Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

pipekit-train — Bayesian inference (1/3): NumPyro SVI

Open In Colab

pipekit-train makes Bayesian inference a first-class TrainingLoop target: you write a probabilistic model once and fit it through the same loop you use for neural nets. This is the first of three short, runnable examples that all fit the same Bayesian linear-regression model with a different inference engine:

#NotebookBackendParadigm
1this onenumpyro-svivariational (a per-step optimizer)
2pipekit_train_numpyro_mcmcnumpyro-mcmcsampling — NUTS (one blocking run)
3pipekit_train_blackjaxblackjaxsampling — NUTS via a sampler library

This notebook covers Stochastic Variational Inference (SVI): it approximates the posterior with a parametric family and maximises a lower bound by gradient ascent — so it really is the per-step TrainingLoop (optimizer config, metric logging, early stopping all apply).

See the design note numpyro_adapter.md (ADR D13) for the full rationale.

/home/user/pipekit/.venv/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm
Python implementation: CPython
Python version       : 3.12.3
IPython version      : 9.10.0

numpy        : 2.4.4
jax          : 0.10.1
numpyro      : 0.21.0
optax        : 0.2.8
pipekit      : 0.0.1
pipekit_train: 0.0.1

Compiler    : GCC 13.3.0
OS          : Linux
Release     : 6.18.5
Machine     : x86_64
Processor   : x86_64
CPU cores   : 4
Architecture: 64bit

1. The problem — Bayesian linear regression

We observe pairs (xi,yi)(x_i, y_i) generated by a noisy line. The generative model places priors on a slope ww, intercept bb, and noise scale σ\sigma, with a Gaussian likelihood:

w∼N(0,5),b∼N(0,5),σ∼HalfNormal(1),w \sim \mathcal{N}(0, 5), \quad b \sim \mathcal{N}(0, 5), \quad \sigma \sim \mathrm{HalfNormal}(1),
yi∣xi,w,b,σ  ∼  N ⁣(w xi+b,  σ2).y_i \mid x_i, w, b, \sigma \;\sim\; \mathcal{N}\!\bigl(w\,x_i + b,\; \sigma^2\bigr).

The target is the posterior p(w,b,σ∣x,y)∝p(y∣x,w,b,σ) p(w) p(b) p(σ)p(w, b, \sigma \mid \mathbf{x}, \mathbf{y}) \propto p(\mathbf{y} \mid \mathbf{x}, w, b, \sigma)\,p(w)\,p(b)\,p(\sigma). We synthesise data from the true line y=2x+1y = 2x + 1 with small noise, so a correct inference should concentrate the posterior near w=2w=2, b=1b=1.

<Figure size 600x300 with 1 Axes>

2. Wrap as a TrainingDataset

IterableDataset is the generic escape hatch — any iterable of (input, target) pairs. The SVI backend is full-batch in v1: it materialises the whole dataset and evaluates the ELBO on all of it each step (minibatch SVI via numpyro.plate(subsample_size=…) is a documented follow-on).

3. The probabilistic model

A NumPyro model is a plain Python callable using numpyro.sample. The obs=y keyword conditions the likelihood site on data when y is given, and leaves it free (for prediction) when y is None.

4. The inference method — SVI / the ELBO

SVI picks a parametric guide qϕ(w,b,σ)q_\phi(w, b, \sigma) and maximises the evidence lower bound

ELBO(ϕ)=Eqϕ ⁣[log⁡p(θ,y∣x)−log⁡qϕ(θ)]  ≤  log⁡p(y∣x),θ=(w,b,σ).\mathrm{ELBO}(\phi) = \mathbb{E}_{q_\phi}\!\bigl[\log p(\theta, \mathbf{y} \mid \mathbf{x}) - \log q_\phi(\theta)\bigr] \;\le\; \log p(\mathbf{y} \mid \mathbf{x}), \qquad \theta = (w, b, \sigma).

Maximising the ELBO minimises KL ⁣(qϕ ∥ p(θ∣x,y))\mathrm{KL}\!\left(q_\phi \,\|\, p(\theta \mid \mathbf{x}, \mathbf{y})\right), so qϕq_\phi converges to the posterior. This is a gradient-ascent loop in ϕ\phi — exactly the per-step TrainingLoop. We use AutoNormal, the mean-field Gaussian guide (a diagonal Normal over the unconstrained parameters — automatic differentiation variational inference, ADVI).

5. Fit through the TrainingLoop

The backend is task-first: the objective is the model’s ELBO, not a carrier-agnostic Loss(pred, target), so we pass a NumpyroTask as loop.task. model_op is required by the loop but ignored here (the task carries the model) — we pass Identity(). The optimizer_config is translated to an optax optimiser and handed to NumPyro’s SVI.

TrainingLoop.run() returns (trained_model_op, artifact). The first call JIT-compiles the per-step svi.update; subsequent steps reuse it.

Backend     : numpyro-svi
Guide       : AutoNormal
Steps       : 800
Final ELBO   : 87.39
Param shapes: {'b_auto_loc': [], 'b_auto_scale': [], 'sigma_auto_loc': [], 'sigma_auto_scale': [], 'w_auto_loc': [], 'w_auto_scale': []}

6. The ELBO curve

The metric writer logged elbo (and loss = -elbo) every step. A rising, plateauing ELBO is the variational analogue of a falling training loss.

<Figure size 600x300 with 1 Axes>

7. The trained operator — posterior predictive

svi_op is an ordinary pipekit_ops.Operator. Calling it returns the posterior-predictive mean of the obs site,

E[y∗∣x∗,data]  ≈  1S∑s=1S(w(s)x∗+b(s)),θ(s)∼qϕ,\mathbb{E}[y^\ast \mid x^\ast, \text{data}] \;\approx\; \frac{1}{S}\sum_{s=1}^{S} \bigl(w^{(s)} x^\ast + b^{(s)}\bigr), \qquad \theta^{(s)} \sim q_\phi,

averaging over SS draws from the fitted guide. We also reach into the wrapped numpyro.infer.Predictive (svi_op.predictive) to draw the full predictive distribution and shade a 95% band — these draws include the observation noise σ\sigma.

<Figure size 600x300 with 1 Axes>

8. The artifact & registry round-trip

TrainingArtifact is the reproducibility record. The trained operator’s weight blob is the variational-parameter PyTree (svi_op.posterior) — serialize_weights() persists it for a ModelRegistry, exactly like a trained neural net (pipekit-jax.JaxModelOp).

Variational params: {'b_auto_loc': (), 'b_auto_scale': (), 'sigma_auto_loc': (), 'sigma_auto_scale': (), 'w_auto_loc': (), 'w_auto_scale': ()}
Weight-blob bytes : 312
Saved svi_artifact.json — the run is reproducible.

What’s next

  • Notebook 2 — numpyro-mcmc: the exact (asymptotically unbiased) posterior via NUTS, with the same NumpyroTask — flip the backend string. It plots the full posterior over w,bw, b that SVI only approximates.

  • Notebook 3 — blackjax: the same NumPyro model sampled by a different engine (BlackJAX NUTS), showing the shared bayes seam.