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 (3/3): BlackJAX (NUTS)

Open In Colab

Last of three examples. Notebooks 1–2 fit a Bayesian linear regression with NumPyro’s own engines (SVI, NUTS). Here we sample the same NumPyro model with a different sampler library — BlackJAX.

#NotebookBackendEngine
1pipekit_train_numpyro_svinumpyro-sviNumPyro SVI
2pipekit_train_numpyro_mcmcnumpyro-mcmcNumPyro NUTS
3this oneblackjaxBlackJAX NUTS

Why a separate backend? NumPyro is a probabilistic programming language (a modelling DSL plus built-in engines). BlackJAX is a sampler library, not a PPL — it operates on a bare logdensity_fn(position) -> float. The blackjax backend bridges a NumpyroTask to a log-density (via numpyro.infer.util.initialize_model) and reuses the shared bayes seam, so the same model swaps engines by flipping the backend string. It also fits the per-step loop more naturally: BlackJAX exposes kernel.step(rng, state) -> (state, info) — one sample per step. See blackjax_adapter.md (ADR D14).

/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
blackjax     : 1.5
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 model to notebooks 1–2: 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 from y=2x+1y = 2x + 1.

2. The inference method — BlackJAX NUTS on a bridged log-density

BlackJAX samples a target π(θ)∝exp⁡(ℓ(θ))\pi(\theta) \propto \exp(\ell(\theta)) known only through its (unnormalised) log-density ℓ\ell. The bridge turns our NumPyro model into exactly that: initialize_model returns the model’s potential function U(z)=−log⁡p~(z∣x,y)U(z) = -\log \tilde p(z \mid \mathbf{x}, \mathbf{y}) over unconstrained parameters zz, and a constrain map postprocess_fn back to the model’s sites. The seam builds

ℓ(z)=−U(z),θ=constrain(z),\ell(z) = -U(z), \qquad \theta = \text{constrain}(z),

then runs NUTS like notebook 2 — Hamiltonian dynamics on H(z,p)=−ℓ(z)+12p⊤M−1pH(z, p) = -\ell(z) + \tfrac12 p^\top M^{-1} p — but each transition is one explicit kernel.step. A window_adaptation warmup tunes the step size and mass matrix MM; then the per-step loop records one draw per step, streaming acceptance / divergence diagnostics to the metric writer. The unconstrained draws {z(s)}\{z^{(s)}\} are mapped through the constrain map to {θ(s)}\{\theta^{(s)}\} before the posterior predictive — essential for the transformed HalfNormal scale σ\sigma.

3. Fit through the TrainingLoop

A BlackjaxTask wraps the NumpyroTask (the bridge source) and selects the sampler. max_steps is the number of posterior draws; num_warmup is the window_adaptation budget. We attach a JSONLWriter to capture the per-step diagnostics that BlackJAX — unlike NumPyro’s single blocking mcmc.run — exposes.

The per-step kernel.step is JIT-compiled once (calling it un-jitted in a Python loop would re-trace every iteration). The first step pays the compile; the rest are fast.

Backend      : blackjax
Sampler      : nuts
Warmup/draws : 400 / 500
Divergences  : 0
BlackJAX ver : 1.5

4. Per-step diagnostics

Because each draw is a loop step, the writer logged the acceptance rate and divergence flag per sample — diagnostics a single blocking sampler can only report in aggregate.

<Figure size 600x300 with 1 Axes>

5. Posterior & predictive

The bridged NUTS path constrains the samples back to the model’s sites, so bj_op.posterior holds draws of {w,b,σ}\{w, b, \sigma\} — directly comparable to notebook 2’s NumPyro-NUTS posterior (same model, different engine).

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

6. The artifact

The trained operator is the same NumpyroPredictiveOp the NumPyro adapters return (the shared bayes seam) — its weight blob is the constrained posterior-samples PyTree, round-tripping through the model registry like any other trained model.

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

Recap — one model, three engines

Across the three notebooks the model never changed — only the backend:

  • numpyro-svi — fast variational approximation (per-step optimiser).

  • numpyro-mcmc — exact NUTS posterior (one blocking run).

  • blackjax — exact NUTS posterior from a separate sampler library, with per-step diagnostics, via the shared model→log-density bridge.

All three return an ordinary pipekit_ops.Operator + TrainingArtifact that compose into inference pipelines and round-trip through the model registry.