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 (2/3): NumPyro MCMC / NUTS

Open In Colab

Second of three examples (see notebook 1 for numpyro-svi). Here we fit the same Bayesian linear-regression model with MCMC — the No-U-Turn Sampler (NUTS). Where SVI approximates the posterior with a parametric guide, MCMC draws asymptotically exact samples from it: it is the oracle, at higher cost.

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

The headline: the NumpyroTask is identical to notebook 1’s — only the backend string changes. SVI and MCMC are two engines for one model. See numpyro_adapter.md (ADR D13).

/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
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 & model

Identical to notebook 1: priors w∼N(0,5)w \sim \mathcal{N}(0,5), b∼N(0,5)b \sim \mathcal{N}(0,5), σ∼HalfNormal(1)\sigma \sim \mathrm{HalfNormal}(1), Gaussian likelihood yi∼N(wxi+b,σ2)y_i \sim \mathcal{N}(w x_i + b, \sigma^2), data drawn from y=2x+1y = 2x + 1.

2. The inference method — NUTS

The No-U-Turn Sampler (Hoffman & Gelman, 2014) is adaptive Hamiltonian Monte Carlo. It augments the parameters θ\theta with a momentum p∼N(0,M)p \sim \mathcal{N}(0, M) and simulates Hamiltonian dynamics on

H(θ,p)=−log⁡p(θ∣x,y)+12 p⊤M−1p,H(\theta, p) = -\log p(\theta \mid \mathbf{x}, \mathbf{y}) + \tfrac{1}{2}\, p^\top M^{-1} p,

using gradients of the log-posterior; NUTS picks each trajectory length automatically (no U-turns). A warmup phase adapts the leapfrog step size (dual averaging) and the mass matrix MM. The result is a set of correlated draws {θ(s)}s=1S∼p(θ∣x,y)\{\theta^{(s)}\}_{s=1}^{S} \sim p(\theta \mid \mathbf{x}, \mathbf{y}).

Crucially this is not a per-gradient-step optimiser: it is a single blocking run of warmup + sampling over the full likelihood — so unlike SVI, optimizer_config / max_steps / per-step eval do not apply. The numpyro-mcmc backend fires only on_train_begin / on_train_end.

3. Fit through the TrainingLoop

The NumpyroTask is the same kind of object as notebook 1 — here we set the MCMC controls (num_warmup, num_samples). The backend materialises the full dataset into single (X, y) arrays and calls mcmc.run once.

Backend        : numpyro-mcmc
Warmup / draws : 500 / 500
Chains         : 1
Divergences    : 0
Sampled sites  : ['b', 'sigma', 'w']

Divergences are NUTS’s built-in health check: a divergent transition signals the sampler failed to integrate the dynamics (often a too-tight posterior geometry). Zero (or very few) divergences over the run is the green light here.

4. The full posterior

Because MCMC samples the parameters directly, oracle_op.posterior is a dict of draws {w(s),b(s),σ(s)}\{w^{(s)}, b^{(s)}, \sigma^{(s)}\} — the full posterior that SVI only approximated with a Gaussian. We plot the marginal histograms against the truth w=2w=2, b=1b=1.

<Figure size 700x300 with 2 Axes>
w: 2.013 ± 0.016   (truth 2.0)
b: 0.991 ± 0.010   (truth 1.0)

5. Posterior predictive

As in notebook 1, the trained Operator returns the posterior-predictive mean of the obs site, marginalised over the posterior draws:

p(y∗∣x∗,data)≈1S∑s=1Sp ⁣(y∗∣x∗,θ(s)).p(y^\ast \mid x^\ast, \text{data}) \approx \frac{1}{S}\sum_{s=1}^{S} p\!\bigl(y^\ast \mid x^\ast, \theta^{(s)}\bigr).
<Figure size 600x300 with 1 Axes>

6. The artifact

The weight blob is the posterior-samples PyTree (oracle_op.posterior); it persists through serialize_weights() for the model registry, just like the variational params in notebook 1.

Posterior sites: {'b': (500,), 'sigma': (500,), 'w': (500,)}
Weight-blob bytes: 6188
Saved mcmc_artifact.json — the run is reproducible.

What’s next

  • Notebook 3 — blackjax: sample the same NumPyro model with a different engine — BlackJAX’s NUTS — via the shared bayes bridge. “Same model, flip the engine” extends one step further, to a separate sampler library.