Hamiltonian Monte Carlo
Using gradients to take long steps that are still accepted.
Random-walk Metropolis explores a posterior like someone lost in fog, one cautious step at a time, and in dimensions it needs on the order of steps to get anywhere. Hamiltonian Monte Carlo gives the sampler momentum and lets it coast along the posterior's contours, using gradients to make long, directed moves that are still almost always accepted. This lesson shows why that is valid, how to simulate it, how NUTS tunes it automatically, why its cost grows only like , and where it breaks.
What you’ll learn
- Build HMC from Hamiltonian dynamics with an auxiliary momentum, and prove that the exact flow conserves energy and volume and is reversible.
- Prove that the leapfrog integrator is volume-preserving and reversible, that HMC with a Metropolis correction leaves the target invariant, and that leapfrog is stable on a Gaussian only for .
- Explain step-size adaptation, path length and the No-U-Turn criterion, and the role of the mass matrix.
- Derive the identity and use it to explain the step size and the 0.651 optimal acceptance rate.
- Recognize divergences and funnels and fix them by reparameterization, and place MALA, unadjusted Langevin and stochastic-gradient Langevin dynamics relative to HMC.
Physics as a proposal mechanism
Write the target as , with potential energy . Introduce an auxiliary momentum , independent of and Gaussian, with a mass matrix . The joint density is
whose -marginal is the target. Sampling the joint and discarding samples . The Hamiltonian Monte Carlo idea, introduced for lattice field theory as "hybrid Monte Carlo" by Duane, Kennedy, Pendleton & Roweth (1987), is to move through the joint space by following Hamilton's equations:
Energy is conserved. Differentiate along a trajectory and substitute the equations of motion:
Volume is preserved. The velocity field has zero divergence, because each block depends only on the other variable. By Liouville's theorem the flow's Jacobian determinant is 1:
The flow is reversible. If solves the equations, so does : flip the momentum, run for the same time, flip again, and you are back where you started. So "run for time , then flip " is an involution: applying it twice gives the identity.
Together these say that the flow carries the density to itself: a proposal made by the exact flow (with the momentum flipped) would be accepted with probability one, however far it travels. Energy conservation also means a single trajectory never leaves its level set of , so each iteration first resamples the momentum from , a Gibbs step for that changes the energy level and lets the chain reach everything.
Leapfrog and the Metropolis correction
Exact Hamiltonian flows are rarely computable, so HMC uses the leapfrog (Störmer–Verlet) integrator with step size : a half step of momentum, a full step of position, another half step of momentum,
repeated times (consecutive half steps merge into full ones). Each substep is a shear, changing one block by a function of the other, so its Jacobian is block-triangular with identity diagonal blocks and determinant 1. The composition is therefore volume-preserving, and because it is symmetric, it is reversible: leapfrog from returns . It does not conserve exactly.
Let be "leapfrog times, then flip the momentum". It is an involution with . A Metropolis–Hastings move that proposes the deterministic point from satisfies detailed balance with respect to when it accepts with the ratio of densities times the Jacobian, which here is just
Since , the final flip changes neither nor the part, so the flip can be dropped in practice. The momentum refresh is an exact Gibbs update of given , which also preserves . Composing two kernels that preserve the joint preserves it, and marginalizing out leaves :
Leapfrog's error over a fixed integration time is of order , and because it is a symplectic integrator the energy error stays bounded along long trajectories instead of drifting. So long trajectories are still accepted with high probability, which is the whole point.
Stability is another matter. On a one-dimensional Gaussian, with , one leapfrog step is a linear map with determinant 1 and trace . Its eigenvalues lie on the unit circle when , that is when ; beyond that, one eigenvalue exceeds 1 in modulus, iterates grow exponentially and the proposal is rejected. In dimensions the narrowest direction sets the largest stable step, while the widest sets how long trajectories must be, so the cost grows with the ratio of the posterior's largest to smallest standard deviation. That is why samplers adapt the mass matrix: with close to the posterior covariance, every direction looks equally wide.
The widget's Gaussian target has unit variances and correlation 0.9, so its covariance has eigenvalues 1.9 and 0.1. With , above what leapfrog step size does HMC become unstable?
Show the answer
0.63
The narrowest direction has standard deviation , so stability requires . In the widget, HMC accepts over 95% of trajectories up to and about 82% at the default 0.5, and none at all from 0.75.
Tuning: step size, path length and NUTS
HMC has two knobs. A smaller step size means fewer rejections but more gradient evaluations per unit of trajectory; in practice is adapted during warm-up to hit a target average acceptance statistic, using Nesterov's dual averaging (Hoffman & Gelman, 2014). Stan's default target is 0.8. The path length is subtler. Too short, and successive proposals are close: random-walk behavior returns. Too long, and the trajectory curls back toward its start (on a Gaussian with the exact flow is periodic, with period in each direction), so the extra gradient evaluations are wasted.
The No-U-Turn Sampler (NUTS; Hoffman & Gelman, 2014) removes the path length. It grows a trajectory by repeated doubling, each time extending forward or backward in time at random, and stops when the two ends start moving toward each other:
where are the forward and backward ends. A state is then drawn from the trajectory by a scheme that preserves detailed balance. Hoffman & Gelman report that NUTS performs at least as well as a well-tuned standard HMC, without any tuning runs.
HMC-STEP(q, U, grad_U, eps, L, Minv)
p = draw from N(0, M) # fresh momentum
q1, p1 = q, p
p1 = p1 - (eps/2) * grad_U(q1) # half step of momentum
repeat L times:
q1 = q1 + eps * Minv p1 # full step of position
if not last step: p1 = p1 - eps * grad_U(q1)
p1 = p1 - (eps/2) * grad_U(q1) # final half step
dH = [U(q1) + p1^T Minv p1 / 2] - [U(q) + p^T Minv p / 2]
accept q1 with probability min(1, exp(-dH)), else return qgradient evaluations per iteration ( if the gradient at the current point is cached). Production samplers (Stan, PyMC, NumPyro) wrap this in NUTS, adapt by dual averaging and estimate a diagonal (by default) mass matrix from the warm-up draws; Stan (Carpenter et al., 2017) caps each trajectory by default at a tree depth of 10, that is 1,023 leapfrog steps.
Why HMC scales: the d^(1/4) law
Random-walk Metropolis needs order iterations (MCMC: Metropolis–Hastings & Gibbs). HMC does much better, and one identity explains why the analysis looks just like the random walk's.
Let and for a volume-preserving bijection such as leapfrog plus flip. Change variables , whose Jacobian is 1:
If is approximately Gaussian, , then forces : the energy error is biased upward by half its variance. The acceptance rate is then the same function met for the random walk:
For an i.i.d. product target, is a sum of per-coordinate errors, each with standard deviation of order over a fixed integration time, so . A non-degenerate acceptance rate needs bounded:
Beskos, Pillai, Roberts, Sanz-Serna & Stuart (2013) proved this rigorously for i.i.d. product targets: with the acceptance probability stays bounded away from 0 and 1, HMC needs steps to traverse the state space, and balancing the cost of each proposal against the number of proposals gives an asymptotically optimal acceptance probability of 0.651. For comparison, MALA needs (optimal acceptance 0.574) and the random walk .
For an i.i.d. product target, the dimension grows from to . By what factor must the number of leapfrog steps per HMC proposal grow (at fixed integration time and acceptance rate)? For comparison, random-walk Metropolis needs 100 times more iterations.
Show the answer
3.16
, so the factor is . Each step costs one gradient evaluation, which reverse-mode automatic differentiation delivers for a small constant multiple of the cost of one density evaluation; this is why HMC dominates for smooth posteriors in many dimensions.
Divergences, funnels and Langevin cousins
Hierarchical models produce the hardest geometry. In Neal's (2003) funnel, and for . At the funnel's mouth ( large) the 's spread widely; in its neck ( very negative) their scale is minuscule. No single step size works: one adapted to the mouth violates the stability condition in the neck, the leapfrog energy explodes, and the trajectory is rejected. Stan reports such transitions as divergent, and they are a warning that the neck is being under-sampled and estimates may be biased, not just slow.
The cure is usually a change of variables. The non-centered parameterization writes with independent of , so the sampler sees independent standard normals and the funnel disappears; the trade-offs between centered and non-centered forms are analyzed by Papaspiliopoulos, Roberts & Sköld (2007). Riemannian HMC (Girolami & Calderhead, 2011) instead adapts the mass matrix to the local curvature, at extra cost per step.
HMC has a family of relatives driven by the Langevin diffusion , whose stationary distribution is :
- MALA discretizes it, , and corrects with Metropolis–Hastings (Roberts & Tweedie, 1996). It is exactly HMC with a single leapfrog step and . Its step must scale as , so it needs order iterations, with optimal acceptance 0.574 (Roberts & Rosenthal, 1998).
- The unadjusted Langevin algorithm drops the correction. It is biased at any fixed step size and can even fail to converge (Roberts & Tweedie, 1996), but for smooth, log-concave targets it comes with non-asymptotic error bounds (Dalalyan, 2017; Durmus & Moulines, 2017). The law of the diffusion itself is the gradient flow of in the Wasserstein metric (Jordan, Kinderlehrer & Otto, 1998): sampling is optimization in the space of distributions.
- Stochastic-gradient Langevin dynamics (SGLD; Welling & Teh, 2011) replaces the full-data gradient by a minibatch estimate rescaled to the full data size, adds Gaussian noise and skips the accept step, with step sizes decreasing to zero. With such schedules it is consistent and satisfies a central limit theorem, but at a slower rate than standard MCMC (Teh, Thiéry & Vollmer, 2016).
Key takeaways
- HMC augments with Gaussian momentum, , and follows Hamilton's equations: the exact flow conserves energy and volume and is reversible, so it preserves .
- Leapfrog is volume-preserving and reversible but not energy-conserving; a Metropolis step with ratio makes HMC exact. On a Gaussian, leapfrog is stable only for , so the narrowest direction sets the step and the mass matrix should match the posterior's covariance.
- NUTS doubles trajectories until they make a U-turn and adapts by dual averaging, removing hand tuning.
- forces the mean energy error to be half its variance, so acceptance is with : step size , steps per proposal, optimal acceptance 0.651 (Beskos et al., 2013).
- Funnels cause divergences; non-centered parameterizations fix them. MALA is one-step HMC (), the unadjusted Langevin algorithm trades exactness for simplicity, and SGLD trades it for minibatches.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why does HMC still need a Metropolis accept/reject step?
- Because the momentum is random
- Because the leapfrog integrator does not conserve exactly; the correction removes the discretization bias, and volume preservation plus reversibility make the ratio simply
- Because Hamilton's equations do not preserve volume
- It does not: the leapfrog trajectory is exact
Show the answer
B. Because the leapfrog integrator does not conserve exactly; the correction removes the discretization bias, and volume preservation plus reversibility make the ratio simply
The exact flow would conserve and be accepted always, but leapfrog only approximates it. Because leapfrog is volume-preserving and reversible, the Metropolis–Hastings ratio needs no Jacobian, and the correction makes the chain exact for any step size that is stable.
A posterior has standard deviation 0.01 in one direction and 10 in another. With an identity mass matrix, what limits HMC?
- Nothing: HMC is insensitive to scale
- The step size must be at least 10 to explore the wide direction
- The step size must stay below about 0.02, but trajectories must cover a distance of order 10, so each proposal needs on the order of a thousand leapfrog steps; a mass matrix matched to the posterior covariance removes the problem
- The acceptance rate will be too high
Show the answer
C. The step size must stay below about 0.02, but trajectories must cover a distance of order 10, so each proposal needs on the order of a thousand leapfrog steps; a mass matrix matched to the posterior covariance removes the problem
Stability requires , while exploring needs a trajectory length comparable to . The ratio sets the cost. Choosing close to the posterior covariance makes the problem look isotropic.
Stan reports many divergent transitions when fitting a hierarchical model with a group-level scale parameter. What is the most appropriate response?
- Ignore them if
- Run the chains longer
- Increase the maximum tree depth
- Reparameterize, typically to a non-centered form, and possibly raise the target acceptance rate to force smaller steps
Show the answer
D. Reparameterize, typically to a non-centered form, and possibly raise the target acceptance rate to force smaller steps
Divergences mean the integrator is unstable in some region, typically the neck of a funnel, so that region is under-explored and the estimates may be biased. Non-centering removes the funnel; a higher target acceptance shrinks the step size, which helps only partly.
Which statement about Langevin methods is correct?
- MALA is HMC with a single leapfrog step; it needs order iterations, between random-walk Metropolis (order ) and HMC (order leapfrog steps)
- The unadjusted Langevin algorithm is exact for any step size
- SGLD needs a Metropolis–Hastings step on the full data at every iteration
- MALA needs no gradients
Show the answer
A. MALA is HMC with a single leapfrog step; it needs order iterations, between random-walk Metropolis (order ) and HMC (order leapfrog steps)
One leapfrog step from a fresh momentum gives the proposal , the MALA proposal with , and the HMC acceptance equals MALA's. Its proposal variance must shrink like , so its cost sits between the random walk's and full HMC's.
Further reading
- S. Duane, A. D. Kennedy, B. J. Pendleton & D. Roweth, "Hybrid Monte Carlo," Physics Letters B 195(2), 216–222 (1987).
- R. M. Neal, "MCMC using Hamiltonian dynamics," in S. Brooks, A. Gelman, G. L. Jones & X.-L. Meng (eds.), Handbook of Markov Chain Monte Carlo (Chapman & Hall/CRC, 2011).
- M. D. Hoffman & A. Gelman, "The No-U-Turn Sampler: Adaptively setting path lengths in Hamiltonian Monte Carlo," Journal of Machine Learning Research 15, 1593–1623 (2014).
- A. Beskos, N. Pillai, G. Roberts, J.-M. Sanz-Serna & A. Stuart, "Optimal tuning of the hybrid Monte Carlo algorithm," Bernoulli 19(5A), 1501–1534 (2013).
- M. Betancourt, "A conceptual introduction to Hamiltonian Monte Carlo," arXiv:1701.02434 (2017).