Foundations to Frontier
Tests

Probabilistic programming: PyMC, NumPyro and Stan

A probabilistic programming language (PPL) lets you write a statistical model as a short program that says how the data could have been generated. The system then does inference for you. Behind the scenes it turns the program into a log density, maps constrained parameters such as scales and probabilities to the real line with the right Jacobian, differentiates the density automatically, and runs an adaptive Hamiltonian Monte Carlo sampler (NUTS) or variational inference. It reports diagnostics such as R-hat and effective sample size. This page compares the three most used Python-facing systems in 2026: Stan (via CmdStanPy), PyMC (PyTensor backend, with nutpie, NumPyro or BlackJAX samplers) and NumPyro (JAX), alongside ArviZ for diagnostics. Their code is shown as display-only snippets. The exercises rebuild a PPL's core in numpy for one model: unknown mean and scale of 8 thrust measurements. Hand-written random-walk Metropolis and HMC samplers are compared with the exact posterior. HMC with a mass matrix adapted from warm-up, as PPLs do, gave 136 effective draws of μ per 1000 gradient evaluations. Random-walk Metropolis gave 49, and untuned HMC only 26. Dropping the log-Jacobian of σ = exp(η) sampled the wrong posterior, with E[σ] 1.308 instead of 1.458, while R-hat looked perfect (0.999).

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Write the model, let the computer do the inference

In Bayesian statistics the hard part used to be the inference: deriving formulas or hand-coding samplers for every model. A probabilistic programming language separates the two. You write down the model as code: this parameter has that prior, the data are noisy measurements around it. The language turns that into an algorithm that draws samples of the parameters consistent with the data. The same few lines work for a two-parameter model or a hierarchical model with thousands of parameters. The demo shows a sampler exploring a posterior; a PPL tunes such samplers automatically.

Wander the posterior: Metropolis and Gibbs
target: sampler:
acceptance rate 42.5% · ESS for x₁ after burn-in ≈ 16 of 1201 draws · x₁ mean 0.01 (true 0)
Blue shading: the target density. Orange: the chain, starting at the uncoloured dot. A tiny step is almost always accepted but crawls. A huge step is almost always rejected and sits still. Mixing is best near 20–50% acceptance. Gibbs moves along the axes, so a strongly correlated target forces tiny zig-zags. The banana's curved ridge defeats a fixed-size random walk, which motivates Hamiltonian Monte Carlo (next topic).
Why engineers care

Mission analysts fit hierarchical models of component failure rates, sensor biases and orbit-determination errors in Stan or PyMC. Changing an assumption means editing one line of the model, not re-deriving a sampler.

📝 Quick check (Level 0)
0/3 answered
  1. 1. In a PPL you write…
  2. 2. The default sampler in Stan, PyMC and NumPyro is…
  3. 3. A PPL returns…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Stan (Carpenter et al., 2017): its own modelling language compiled to C++; NUTS with adapted step size and mass matrix, ADVI, Pathfinder and optimisation; interfaces CmdStanPy, CmdStanR, BridgeStan. The reference for robust HMC.
  • PyMC (version 5; Abril-Pla et al., 2023): models in Python with the PyTensor graph library; pm.sample runs its own NUTS or, through nuts_sampler=, nutpie (Rust), NumPyro or BlackJAX on JAX. It also offers ADVI, SMC and Pathfinder, plus Bambi for formula-based regression models.
  • NumPyro (Phan, Pradhan and Jankowiak, 2019): Pyro’s syntax on JAX; JIT-compiled, vectorised NUTS on CPU, GPU or TPU; effect handlers for conditioning and reparametrisation; strong for large models and stochastic variational inference.
  • Also: Pyro (PyTorch), Turing.jl (Julia), brms (R, compiles to Stan), TensorFlow Probability, BlackJAX (samplers only).
  • What happens under the hood: constrained parameters are mapped to unconstrained ones (σ = exp η, p = logistic u), adding the log-Jacobian; automatic differentiation gives ∇ log p; warm-up adapts the step size by dual averaging and the mass matrix from warm-up draws; the sampler flags divergences.
  • ArviZ stores draws as InferenceData and computes R-hat, bulk and tail ESS, MCSE, LOO and plots; ArviZ 1.0 splits into arviz-base, arviz-stats and arviz-plots.

The same model in NumPyro and Stan (display only):

import jax, numpyro, numpyro.distributions as dist
from numpyro.infer import MCMC, NUTS
numpyro.set_host_device_count(4)                 # run 4 chains in parallel on CPU

def model(y=None):
    mu = numpyro.sample("mu", dist.Normal(0.0, 10.0))
    sigma = numpyro.sample("sigma", dist.HalfNormal(5.0))
    numpyro.sample("y", dist.Normal(mu, sigma), obs=y)

mcmc = MCMC(NUTS(model), num_warmup=1000, num_samples=1000, num_chains=4)
mcmc.run(jax.random.PRNGKey(0), y=y)
mcmc.print_summary()                             # mean, sd, n_eff, r_hat
// thrust.stan — run with CmdStanPy:
//   fit = CmdStanModel(stan_file="thrust.stan").sample(data={"N": len(y), "y": y}, chains=4, seed=0)
data { int<lower=0> N; vector[N] y; }
parameters { real mu; real<lower=0> sigma; }   // Stan adds the log-Jacobian for the lower bound
model {
  mu ~ normal(0, 10);
  sigma ~ normal(0, 5);                          // half-normal because sigma > 0
  y ~ normal(mu, sigma);
}
📝 Quick check (Level 1)
0/3 answered
  1. 1. PyMC 5 builds models on…
  2. 2. NumPyro runs on…
  3. 3. Declaring sigma with a lower bound of 0 in Stan…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

What a PPL does, by hand

Exercise 1.

  • The log posterior on the unconstrained scale (μ, η = log σ), including the log-Jacobian η.
  • Its gradient, checked against finite differences.
  • The leapfrog integrator (reversible, nearly energy-conserving).
  • A vectorised random-walk Metropolis step for several chains.

Practice.

  • Start from the generative story; simulate fake data from the prior and from known parameters before fitting real data.
  • Use the default NUTS with 4 chains and 1000 warm-up and 1000 sampling iterations; check R-hat below 1.01, bulk and tail ESS above about 400, and no divergences.
  • If NUTS struggles, reparametrise (non-centred hierarchies, standardised predictors) before tuning the sampler.
  • Choose by need: Stan for robust, well-documented HMC; PyMC for a Python-native workflow and many backends; NumPyro for speed on accelerators and large or vectorised models.
  • Store results as ArviZ InferenceData so diagnostics and model comparison work the same across libraries.
import pymc as pm, arviz as az
with pm.Model() as model:                       # PyMC 5 (display only)
    mu = pm.Normal("mu", mu=0, sigma=10)
    sigma = pm.HalfNormal("sigma", sigma=5)     # sampled as log(sigma) with its Jacobian
    pm.Normal("y", mu=mu, sigma=sigma, observed=y)
    idata = pm.sample(draws=1000, tune=1000, chains=4, random_seed=0)   # NUTS; try nuts_sampler="nutpie"
print(az.summary(idata, var_names=["mu", "sigma"]))                    # r_hat, ess_bulk, ess_tail
🐍 Exercise 1: log density, gradient, leapfrog and Metropolis
Write the unconstrained log posterior with its Jacobian and its gradient, a leapfrog integrator and a batched Metropolis step.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A common R-hat threshold today is…
  2. 2. pm.sample's tune argument sets…
  3. 3. First fix for divergences in a hierarchical model:

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Change of variables. If σ = e^η, the density of η is p_η(η) = p_σ(e^η) · |dσ/dη| = p_σ(e^η) e^η, so log p_η = log p_σ + η. A sampler that moves in η but evaluates only log p_σ targets p_σ(e^η), a different distribution. Every PPL applies such transforms automatically: log for positive parameters, logit for (0, 1), stick-breaking for simplices, Cholesky factors for correlation matrices.

Why HMC scales. Random-walk Metropolis needs step sizes of order d^(−1/2) and mixes in O(d) steps. HMC with leapfrog steps of size of order d^(−1/4) explores in O(d^(1/4)) gradient evaluations per effective sample for well-conditioned targets (Neal, 2011; Beskos et al., 2013). It needs a good step size and a mass matrix matching the posterior scales: with very different scales, the step must suit the narrowest direction. NUTS (Hoffman and Gelman, 2014) also picks the trajectory length automatically, which avoids the periodic trajectories that a fixed length can produce.

Diagnostics answer one question. Split R-hat compares between-chain and within-chain variance and flags chains that have not mixed or not converged. ESS measures how many independent draws the autocorrelated chain is worth. Neither checks that the model, or its implementation, is the one intended. A missing Jacobian produces perfectly mixed chains from the wrong posterior. Such bugs are caught by simulation-based calibration and by comparison with known answers.

📝 Quick check (Level 3)
0/3 answered
  1. 1. The log density of η = log σ is…
  2. 2. HMC needs a mass matrix because…
  3. 3. R-hat near 1 shows…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

What does a PPL’s machinery buy, and which mistakes can diagnostics not see?

History.

  • D. Lunn et al. (2000) WinBUGS made Gibbs-sampling PPLs popular; M. Plummer (2003) JAGS.
  • M. Hoffman and A. Gelman (2014) NUTS; B. Carpenter et al. (2017) “Stan: a probabilistic programming language”.
  • J. Salvatier, T. Wiecki and C. Fonnesbeck (2016) PyMC3; D. Phan, N. Pradhan and M. Jankowiak (2019) NumPyro; O. Abril-Pla et al. (2023) PyMC 5.

Exercise 2. Unknown mean and scale of 8 thrust measurements, y ~ N(3, 2²).

  • Model: μ ~ N(0, 10²), σ ~ HalfNormal(5), sampled as (μ, η = log σ).
  • Exact posterior by quadrature on a 400 × 400 grid.
  • Chains: four, started far apart, with the first half discarded as warm-up. Random-walk Metropolis: 4000 iterations, step 0.5. Untuned HMC: identity mass matrix, step 0.05, 1–20 leapfrog steps. Adapted HMC: diagonal mass matrix from warm-up draws, step 0.5, 1–8 steps. The adapted HMC is run once more without the log-Jacobian. Short chains: 200 iterations with step 0.05.
sampler E[μ] E[σ] R-hat (μ) ESS μ / σ ESS of μ per 1000 evaluations
exact 3.693 1.458
random-walk Metropolis 3.703 1.454 1.009 389 / 960 48.6
HMC, untuned 3.701 1.467 1.001 615 / 1342 26.4
HMC, adapted mass matrix 3.688 1.465 1.001 1549 / 1565 135.6
HMC, adapted, no Jacobian 3.702 1.308 0.999 2000 / 1420 181.0
short chains, tiny steps 2.520 3.765 33.1 2 / 2 5.1
  • Adaptation is what makes HMC pay off. Untuned HMC accepted every proposal, because its step was sized for the narrow η direction, and was less efficient than random-walk Metropolis. With the mass matrix estimated from warm-up, it was 2.8 times more efficient than Metropolis per evaluation. In two dimensions Metropolis is competitive; HMC’s advantage grows with dimension.
  • A missing Jacobian is silent. Without it the chains targeted p_σ(e^η) instead of the right density, giving E[σ] 1.308, close to that wrong density’s exact mean of 1.327 and far from 1.458. R-hat and ESS were excellent.
  • R-hat catches non-convergence. Short chains with tiny steps had not left their starting points: R-hat 33.
  • ESS ceiling: our estimator caps ESS at the number of draws (2000) when draws are anticorrelated; ArviZ would report more.
  • Seeds 1 and 2: adapted HMC 168 and 180 effective draws per 1000 evaluations, Metropolis 30.0 and 20.4, untuned HMC 17.0 and 6.4. Without the Jacobian E[σ] was 1.679 and 2.812 against exact 1.821 and 3.035. Short chains gave R-hat 40.2 and 23.2.
🐍 Exercise 2 (research): what does a PPL's machinery buy, and which mistakes can diagnostics not see?
Sample a two-parameter posterior with hand-written random-walk Metropolis and HMC, with and without a warm-up mass matrix and with and without the log-Jacobian; compare with exact quadrature and with R-hat and ESS.

Probabilistic programming in AI, robotics and aerospace

  • Reliability engineering: hierarchical failure-rate models across a satellite fleet share information between rare-failure components; Stan and PyMC are standard tools.
  • Sensor calibration and system identification: Bayesian models of bias, scale factor and noise for IMUs and star trackers give posterior uncertainty that feeds Kalman filters.
  • Scientific ML: NumPyro and BlackJAX sample Bayesian neural network heads and physical-model parameters on GPUs; amortised and simulation-based inference extends this to simulators.

References

  1. B. Carpenter et al. (2017). “Stan: a probabilistic programming language.” Journal of Statistical Software.
  2. M. D. Hoffman and A. Gelman (2014). “The No-U-Turn sampler.” JMLR.
  3. D. Phan, N. Pradhan and M. Jankowiak (2019). “Composable effects for flexible and accelerated probabilistic programming in NumPyro.” arXiv.
  4. O. Abril-Pla et al. (2023). “PyMC: a modern and comprehensive probabilistic programming framework in Python.” PeerJ Computer Science.
  5. A. Vehtari, A. Gelman, D. Simpson, B. Carpenter and P.-C. Bürkner (2021). “Rank-normalization, folding, and localization: an improved R-hat.” Bayesian Analysis.