Foundations to Frontier
Tests
A. Mathematical Foundations › A5 Statistics › Bayesian statistics

Hamiltonian Monte Carlo and NUTS

Random-walk proposals wander; Hamiltonian Monte Carlo glides. Treat −log posterior as a potential energy, give the parameters a random momentum, and simulate frictionless motion with the leapfrog integrator: the trajectory follows the posterior's geometry and lands far away, yet is accepted with high probability because energy is nearly conserved. You will prove why leapfrog works (reversible, volume-preserving, O(ε²) energy error), tune step size and path length, see NUTS choose the length automatically, and use divergences to diagnose the funnel geometry of hierarchical models, which the non-centred parameterization fixes.

Level 0: Foundation

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

Skating instead of stumbling

Random-walk sampling is like exploring a valley blindfolded with tiny random steps: slow, and you keep going back and forth. Hamiltonian Monte Carlo is like skating. Give yourself a random push and glide frictionlessly over the landscape: you speed up downhill, slow down uphill, and follow the valley’s curves. After a while, stop where you are. That’s your next sample, often very far from the last, and almost always accepted.

The landscape is the (negative log) posterior, so the slope (gradient) tells you which way to glide.

Roll a frictionless puck over −log p: Hamiltonian Monte Carlo
acceptance 100.0% · mean |ΔH| per trajectory 0.025 · gradient evaluations 6000
Dots: samples. Orange: the last 6 leapfrog trajectories. Each follows the posterior's geometry along the banana's curve or the correlated ridge, making large distant moves that are still accepted. Too large an ε makes the energy error ΔH blow up (rejections, or "divergences" in curved regions). Too small an εL takes short, wasteful trajectories. NUTS chooses L automatically by stopping at the U-turn.
Why engineers care

HMC (and its self-tuning version NUTS) is the engine inside Stan, PyMC and NumPyro. It makes Bayesian models with hundreds or thousands of parameters practical: calibration, hierarchical reliability, and Bayesian neural networks. Its diagnostics (“divergences”) point straight at problems in the model’s geometry.

📝 Quick check (Level 0)
0/3 answered
  1. 1. HMC uses the posterior's…
  2. 2. HMC moves are typically…
  3. 3. The 'momentum' in HMC is…

Level 1: Beginner

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

The physics

Define the potential energy U(q)=−log⁡p(q∣x)U(q) = -\log p(q\mid x) and an auxiliary momentum p∼N(0,M)p\sim\mathcal N(0, M), with kinetic energy K=12p⊤M−1pK = \frac12p^\top M^{-1}p. The joint density ∝e−H(q,p)\propto e^{-H(q, p)} with H=U+KH = U + K has the posterior as its qq-marginal. Hamilton’s equations

q˙=M−1p,p˙=−∇U(q)\dot q = M^{-1}p, \qquad \dot p = -\nabla U(q)

conserve HH exactly. Following them moves you along a contour of the joint density.

The algorithm

  1. Draw a fresh momentum p∼N(0,M)p\sim\mathcal N(0, M).
  2. Simulate LL leapfrog steps of size ε\varepsilon: half kick p←p−ε2∇Up\leftarrow p - \frac\varepsilon2\nabla U, then repeat drift q←q+εM−1pq\leftarrow q + \varepsilon M^{-1}p and kick p←p−ε∇Up\leftarrow p - \varepsilon\nabla U, ending with a half kick.
  3. Accept the endpoint with probability min⁡(1,e−ΔH)\min(1, e^{-\Delta H}). With exact dynamics ΔH=0\Delta H = 0, so rejections only come from integration error.
📝 Quick check (Level 1)
0/3 answered
  1. 1. HMC's potential energy is…
  2. 2. The acceptance probability is…
  3. 3. Momentum is redrawn…

Level 2: Intermediate

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

Tuning ε, L and the mass matrix

  • Step size ε: controls the energy error (and acceptance). Stan adapts it to reach an acceptance target of about 0.8 using dual averaging (Hoffman and Gelman, 2014).
  • Path length εL: too short and HMC degrades to a random walk. Too long and trajectories loop back (wasted gradient evaluations). NUTS builds the trajectory by repeated doubling until it starts to make a U-turn, (q+−q−)⋅p±<0(q^+ - q^-)\cdot p^\pm<0, then samples a point from the trajectory in a way that preserves detailed balance.
  • Mass matrix M: estimate it from the warm-up posterior covariance, so that strongly correlated or differently scaled parameters become isotropic.

Why it scales

To keep acceptance fixed as the dimension dd grows, random-walk MH needs O(d)O(d) steps per effectively independent sample, while HMC needs O(d1/4)O(d^{1/4}) (Beskos et al., 2013; Neal, 2011). On the correlated Gaussian in Exercise 1, HMC gets about 7× the ESS of random-walk MH for the same number of density evaluations.

Divergences: geometry warnings

Where curvature changes sharply, as in the neck of a hierarchical funnel, a fixed ε can’t resolve the dynamics. The energy error explodes and the trajectory “diverges”. Divergent transitions mean the sampler is missing part of the posterior, so the results are biased. The fix is usually to reparameterize, not to shrink ε (Betancourt and Girolami, 2015).

🐍 Exercise 1: leapfrog properties and HMC vs random walk
Implement leapfrog and HMC. Verify the O(ε²) energy error, time-reversibility and volume preservation (det J = 1). Then compare HMC with random-walk Metropolis on a ρ = 0.95 Gaussian for the same number of density evaluations.
📝 Quick check (Level 2)
0/3 answered
  1. 1. NUTS stops a trajectory when…
  2. 2. Divergent transitions indicate…
  3. 3. Stan's default target acceptance is about…

Level 3: Advanced

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

Why HMC is a valid MCMC method

The leapfrog map Φ\Phi is:

  1. Volume-preserving: each kick and drift is a shear, with Jacobian determinant 1.
  2. Reversible: Φ∘F∘Φ=F\Phi\circ F\circ\Phi = F, where FF flips the momentum.

So “run leapfrog, then flip pp” is an involution with unit Jacobian. An MH proposal of that form has acceptance min⁡(1,e−H(q′,p′)/e−H(q,p))\min(1, e^{-H(q', p')}/e^{-H(q, p)}) (no proposal-density terms), and it preserves e−He^{-H}. Redrawing pp is a Gibbs step on the momentum. Together they leave the posterior invariant. ∎

Why the energy error is small

Leapfrog is a symplectic, second-order integrator. Its local error is O(ε3)O(\varepsilon^3) and its global error O(ε2)O(\varepsilon^2). More importantly, it exactly conserves a “shadow” Hamiltonian H~=H+O(ε2)\tilde H = H + O(\varepsilon^2), so the energy error stays bounded over long trajectories instead of drifting. That’s why trajectories can be long and still accepted.

Neal’s funnel

With v∼N(0,9)v\sim\mathcal N(0, 9) and xk∣v∼N(0,ev)x_k\mid v\sim\mathcal N(0, e^v), the scale of xx varies over orders of magnitude. No single step size suits both the mouth and the neck. The non-centred form xk=ev/2zkx_k = e^{v/2}z_k with zk∼N(0,1)z_k\sim\mathcal N(0,1) makes the target an isotropic Gaussian in (v,z)(v, z), which is trivial for HMC. Every hierarchical model with weakly informed group-level variance has this funnel (A5.2-4).

Exercise 3.1: Show that a leapfrog drift has unit Jacobian

The drift (q,p)↦(q+εM−1p,p)(q, p)\mapsto(q + \varepsilon M^{-1}p, p) has Jacobian (IεM−10I)\begin{pmatrix}I & \varepsilon M^{-1}\\0 & I\end{pmatrix}, with determinant 1. A kick (q,p)↦(q,p−ε∇U(q))(q, p)\mapsto(q, p - \varepsilon\nabla U(q)) is lower-triangular with identity blocks, so its determinant is also 1.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Leapfrog's global energy error scales like…
  2. 2. No Jacobian appears in HMC's acceptance because leapfrog is…
  3. 3. The non-centred funnel parameterization uses…

Level 4: Expert

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

Diagnosing a hierarchical posterior with divergences

In Neal’s 10-D funnel (the shape of every hierarchical model’s group-variance posterior), centred HMC with a step tuned for the bulk produces divergences and never enters the neck: its minimum vv is about −4.6, versus −9.9 for the correct sampler. That means it overestimates the group-level variance. The non-centred model samples the same posterior with no divergences and recovers Var⁡v=9\operatorname{Var}v = 9. In practice, any divergences after warm-up mean: reparameterize (non-centre), use more informative priors on variances, or rescale.

The exact figures differ slightly by platform, because each divergent trajectory amplifies last-bit rounding differences. In the browser, centred HMC diverges on 0.3% of iterations and its minimum v is −4.63, and the non-centred sampler gives Var v ≈ 9.5; desktop CPython gives 2.5%, −4.79 and 9.00. The conclusion is the same on both.

🐍 Exercise 2 (research): divergences in Neal's funnel
Run HMC (with divergence detection) on the centred and non-centred forms of Neal's funnel. Show that the centred sampler diverges and misses the neck (biased v), while the non-centred one explores v ~ N(0, 9) fully with no divergences.

HMC in AI, robotics and aerospace

  • Probabilistic programming: NUTS in Stan, PyMC, NumPyro and Turing, with automatic differentiation for ∇U\nabla U (Carpenter et al., 2017; Phan et al., 2019).
  • Bayesian neural networks: full-batch HMC is the “gold standard” reference for BNN posteriors (Izmailov et al., 2021), and stochastic-gradient HMC scales it to large data (Chen, Fox and Guestrin, 2014).
  • Calibration and inverse problems: HMC over physical parameters of differentiable simulators, such as aerodynamic, thermal and orbital models.
  • Trajectory optimization’s cousin: HMC’s leapfrog is the same symplectic integrator used in orbital mechanics and molecular dynamics, where energy conservation over long horizons matters (Hairer, Lubich and Wanner, 2006).
  • Diffusion and score-based models use Langevin dynamics, the one-step (L = 1) limit of HMC, for sampling (Song and Ermon, 2019).

References

  1. S. Duane, A. Kennedy, B. Pendleton, D. Roweth (1987). “Hybrid Monte Carlo.” Physics Letters B, 195(2).
  2. R. Neal (2011). “MCMC using Hamiltonian dynamics.” In Handbook of Markov Chain Monte Carlo. CRC Press.
  3. M. Hoffman, A. Gelman (2014). “The No-U-Turn Sampler.” JMLR, 15.
  4. M. Betancourt (2017). “A conceptual introduction to Hamiltonian Monte Carlo.” arXiv:1701.02434.
  5. M. Betancourt, M. Girolami (2015). “Hamiltonian Monte Carlo for hierarchical models.” In Current Trends in Bayesian Methodology. CRC Press.
  6. A. Beskos, N. Pillai, G. Roberts, J. Sanz-Serna, A. Stuart (2013). “Optimal tuning of the hybrid Monte Carlo algorithm.” Bernoulli, 19(5A).
  7. E. Hairer, C. Lubich, G. Wanner (2006). Geometric Numerical Integration, 2nd ed. Springer.
  8. T. Chen, E. Fox, C. Guestrin (2014). “Stochastic gradient Hamiltonian Monte Carlo.” ICML.
  9. P. Izmailov, S. Vikram, M. Hoffman, A. G. Wilson (2021). “What are Bayesian neural network posteriors really like?” ICML.
  10. D. Phan, N. Pradhan, M. Jankowiak (2019). “Composable effects for flexible and accelerated probabilistic programming in NumPyro.” arXiv:1912.11554.