Simple Algorithm
Machine Learning · Convergence · 28 min

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 dd dimensions it needs on the order of dd 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 d1/4d^{1/4}, 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 ε<2σ\varepsilon<2\sigma.
  • Explain step-size adaptation, path length and the No-U-Turn criterion, and the role of the mass matrix.
  • Derive the identity E[e−ΔH]=1\E[e^{-\Delta H}]=1 and use it to explain the d−1/4d^{-1/4} 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 π(q)∝e−U(q)\pi(\mathbf q)\propto e^{-U(\mathbf q)}, with potential energy U=−log⁡π~U=-\log\tilde\pi. Introduce an auxiliary momentum p∈Rd\mathbf p\in\R^d, independent of q\mathbf q and Gaussian, p∼N(0,M)\mathbf p\sim\mathcal N(\mathbf 0,M) with a mass matrix MM. The joint density is

π(q,p)∝e−H(q,p),H(q,p)=U(q)+12p⊤M−1p,\pi(\mathbf q,\mathbf p)\propto e^{-H(\mathbf q,\mathbf p)},\qquad H(\mathbf q,\mathbf p)=U(\mathbf q)+\tfrac12\mathbf p^\top M^{-1}\mathbf p,

whose q\mathbf q-marginal is the target. Sampling the joint and discarding p\mathbf p samples π\pi. 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:

dqdt=∂H∂p=M−1p,dpdt=−∂H∂q=−∇U(q)\frac{d\mathbf q}{dt}=\frac{\partial H}{\partial\mathbf p}=M^{-1}\mathbf p,\qquad\frac{d\mathbf p}{dt}=-\frac{\partial H}{\partial\mathbf q}=-\nabla U(\mathbf q)
A puck sliding on the surface UU: it speeds up downhill, slows uphill, and its total energy stays constant.
DerivationThree properties of the exact flow
  1. dHdt=∇U(q)⊤q˙+(M−1p)⊤p˙=∇U⊤M−1p−(M−1p)⊤∇U=0\frac{dH}{dt}=\nabla U(\mathbf q)^\top\dot{\mathbf q}+(M^{-1}\mathbf p)^\top\dot{\mathbf p}=\nabla U^\top M^{-1}\mathbf p-(M^{-1}\mathbf p)^\top\nabla U=0

    Energy is conserved. Differentiate HH along a trajectory and substitute the equations of motion:

  2. ∇⋅F=∇q⋅(M−1p)+∇p⋅(−∇U(q))=0+0=0\nabla\cdot F=\nabla_{\mathbf q}\cdot(M^{-1}\mathbf p)+\nabla_{\mathbf p}\cdot\big(-\nabla U(\mathbf q)\big)=0+0=0

    Volume is preserved. The velocity field F(q,p)=(M−1p, −∇U(q))F(\mathbf q,\mathbf p)=(M^{-1}\mathbf p,\,-\nabla U(\mathbf q)) has zero divergence, because each block depends only on the other variable. By Liouville's theorem the flow's Jacobian determinant is 1:

  3. The flow is reversible. If (q(t),p(t))(\mathbf q(t),\mathbf p(t)) solves the equations, so does (q(−t),−p(−t))(\mathbf q(-t),-\mathbf p(-t)): flip the momentum, run for the same time, flip again, and you are back where you started. So "run for time TT, then flip p\mathbf p" is an involution: applying it twice gives the identity.

Together these say that the flow carries the density e−He^{-H} 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 HH, so each iteration first resamples the momentum from N(0,M)\mathcal N(\mathbf 0,M), a Gibbs step for p\mathbf p 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 ε\varepsilon: a half step of momentum, a full step of position, another half step of momentum,

p1/2=p−ε2∇U(q),q′=q+εM−1p1/2,p′=p1/2−ε2∇U(q′),\mathbf p_{1/2}=\mathbf p-\tfrac\varepsilon2\nabla U(\mathbf q),\qquad\mathbf q'=\mathbf q+\varepsilon M^{-1}\mathbf p_{1/2},\qquad\mathbf p'=\mathbf p_{1/2}-\tfrac\varepsilon2\nabla U(\mathbf q'),

repeated LL 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 (q′,−p′)(\mathbf q',-\mathbf p') returns (q,−p)(\mathbf q,-\mathbf p). It does not conserve HH exactly.

DerivationProof
  1. min⁡(1, π(Ψ(z))π(z) ∣det⁡DΨ(z)∣)=min⁡(1, eH(z)−H(Ψ(z)))\min\Big(1,\ \frac{\pi(\Psi(\mathbf z))}{\pi(\mathbf z)}\,\abs{\det D\Psi(\mathbf z)}\Big)=\min\Big(1,\ e^{H(\mathbf z)-H(\Psi(\mathbf z))}\Big)

    Let Ψ\Psi be "leapfrog LL times, then flip the momentum". It is an involution with ∣det⁡DΨ∣=1\abs{\det D\Psi}=1. A Metropolis–Hastings move that proposes the deterministic point Ψ(z)\Psi(\mathbf z) from z=(q,p)\mathbf z=(\mathbf q,\mathbf p) satisfies detailed balance with respect to π(z)\pi(\mathbf z) when it accepts with the ratio of densities times the Jacobian, which here is just

  2. π(q,p) invariant⟹π(q) invariant\pi(\mathbf q,\mathbf p)\ \text{invariant}\quad\Longrightarrow\quad\pi(\mathbf q)\ \text{invariant}

    Since K(p)=K(−p)K(\mathbf p)=K(-\mathbf p), the final flip changes neither HH nor the q\mathbf q part, so the flip can be dropped in practice. The momentum refresh is an exact Gibbs update of p\mathbf p given q\mathbf q, which also preserves π(q,p)\pi(\mathbf q,\mathbf p). Composing two kernels that preserve the joint preserves it, and marginalizing out p\mathbf p leaves π(q)\pi(\mathbf q):

Leapfrog's error over a fixed integration time T=LεT=L\varepsilon is of order ε2\varepsilon^2, 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, U(q)=q2/(2σ2)U(q)=q^2/(2\sigma^2) with M=1M=1, one leapfrog step is a linear map with determinant 1 and trace 2−ε2/σ22-\varepsilon^2/\sigma^2. Its eigenvalues lie on the unit circle when ∣2−ε2/σ2∣<2\abs{2-\varepsilon^2/\sigma^2}<2, that is when ε<2σ\varepsilon<2\sigma; beyond that, one eigenvalue exceeds 1 in modulus, iterates grow exponentially and the proposal is rejected. In dd 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 M−1M^{-1} close to the posterior covariance, every direction looks equally wide.

Predict before you look

The widget's Gaussian target has unit variances and correlation 0.9, so its covariance has eigenvalues 1.9 and 0.1. With M=IM=I, above what leapfrog step size does HMC become unstable?

Show the answer

0.63

The narrowest direction has standard deviation 0.1≈0.316\sqrt{0.1}\approx0.316, so stability requires ε<2×0.316≈0.63\varepsilon<2\times0.316\approx0.63. In the widget, HMC accepts over 95% of trajectories up to ε=0.3\varepsilon=0.3 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 ε\varepsilon means fewer rejections but more gradient evaluations per unit of trajectory; in practice ε\varepsilon 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 LεL\varepsilon 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 M=IM=I the exact flow is periodic, with period 2πσ2\pi\sigma 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:

(q+−q−)⋅p−<0or(q+−q−)⋅p+<0,(\mathbf q^+-\mathbf q^-)\cdot\mathbf p^-<0\qquad\text{or}\qquad(\mathbf q^+-\mathbf q^-)\cdot\mathbf p^+<0,

where (q±,p±)(\mathbf q^\pm,\mathbf p^\pm) 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.

text
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 q

L+1L+1 gradient evaluations per iteration (LL if the gradient at the current point is cached). Production samplers (Stan, PyMC, NumPyro) wrap this in NUTS, adapt ε\varepsilon 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 dd iterations (MCMC: Metropolis–Hastings & Gibbs). HMC does much better, and one identity explains why the analysis looks just like the random walk's.

DerivationThe energy error has mean equal to half its variance
  1. E[e−ΔH]=1Z∫e−H(z) e−H(Ψ(z))+H(z) dz=1Z∫e−H(w) dw=1\E\big[e^{-\Delta H}\big]=\frac1Z\int e^{-H(\mathbf z)}\,e^{-H(\Psi(\mathbf z))+H(\mathbf z)}\,d\mathbf z=\frac1Z\int e^{-H(\mathbf w)}\,d\mathbf w=1

    Let z∼π(z)=e−H(z)/Z\mathbf z\sim\pi(\mathbf z)=e^{-H(\mathbf z)}/Z and ΔH=H(Ψ(z))−H(z)\Delta H=H(\Psi(\mathbf z))-H(\mathbf z) for a volume-preserving bijection Ψ\Psi such as leapfrog plus flip. Change variables w=Ψ(z)\mathbf w=\Psi(\mathbf z), whose Jacobian is 1:

  2. E[min⁡(1,e−ΔH)]=2 Φ(−s2)\E\big[\min(1,e^{-\Delta H})\big]=2\,\Phi\big(-\tfrac s2\big)

    If ΔH\Delta H is approximately Gaussian, N(μ,s2)\mathcal N(\mu,s^2), then E[e−ΔH]=e−μ+s2/2=1\E[e^{-\Delta H}]=e^{-\mu+s^2/2}=1 forces μ=s2/2\mu=s^2/2: the energy error is biased upward by half its variance. The acceptance rate is then the same function met for the random walk:

  3. ε∝d−1/4,L=Tε∝d1/4 leapfrog steps per proposal\varepsilon\propto d^{-1/4},\qquad L=\frac T\varepsilon\propto d^{1/4}\ \text{leapfrog steps per proposal}

    For an i.i.d. product target, ΔH\Delta H is a sum of dd per-coordinate errors, each with standard deviation of order ε2\varepsilon^2 over a fixed integration time, so s2∝d ε4s^2\propto d\,\varepsilon^4. A non-degenerate acceptance rate needs dε4d\varepsilon^4 bounded:

Beskos, Pillai, Roberts, Sanz-Serna & Stuart (2013) proved this rigorously for i.i.d. product targets: with ε=ℓd−1/4\varepsilon=\ell d^{-1/4} the acceptance probability stays bounded away from 0 and 1, HMC needs O(d1/4)\order{d^{1/4}} 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 d1/3d^{1/3} (optimal acceptance 0.574) and the random walk dd.

Predict before you look

For an i.i.d. product target, the dimension grows from d=100d=100 to d=10,000d=10{,}000. 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

L∝d1/4L\propto d^{1/4}, so the factor is 1001/4=10≈3.16100^{1/4}=\sqrt{10}\approx3.16. 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, v∼N(0,32)v\sim\mathcal N(0,3^2) and xi∣v∼N(0,ev)x_i\mid v\sim\mathcal N(0,e^v) for i=1,…,9i=1,\dots,9. At the funnel's mouth (vv large) the xx's spread widely; in its neck (vv very negative) their scale ev/2e^{v/2} is minuscule. No single step size works: one adapted to the mouth violates the stability condition ε<2ev/2\varepsilon<2e^{v/2} 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 xi=ev/2x~ix_i=e^{v/2}\tilde x_i with x~i∼N(0,1)\tilde x_i\sim\mathcal N(0,1) independent of vv, 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 dqt=∇log⁡π(qt) dt+2 dBtd\mathbf q_t=\nabla\log\pi(\mathbf q_t)\,dt+\sqrt2\,d\mathbf B_t, whose stationary distribution is π\pi:

  • MALA discretizes it, q′=q+h2∇log⁡π(q)+h ξ\mathbf q'=\mathbf q+\tfrac h2\nabla\log\pi(\mathbf q)+\sqrt h\,\boldsymbol\xi, and corrects with Metropolis–Hastings (Roberts & Tweedie, 1996). It is exactly HMC with a single leapfrog step and h=ε2h=\varepsilon^2. Its step hh must scale as d−1/3d^{-1/3}, so it needs order d1/3d^{1/3} 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 DKL(ρ ∥ π)\KL(\rho\,\|\,\pi) 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 q\mathbf q with Gaussian momentum, H=U(q)+12p⊤M−1pH=U(\mathbf q)+\frac12\mathbf p^\top M^{-1}\mathbf p, and follows Hamilton's equations: the exact flow conserves energy and volume and is reversible, so it preserves e−He^{-H}.
  • Leapfrog is volume-preserving and reversible but not energy-conserving; a Metropolis step with ratio e−ΔHe^{-\Delta H} makes HMC exact. On a Gaussian, leapfrog is stable only for ε<2σ\varepsilon<2\sigma, 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 ε\varepsilon by dual averaging, removing hand tuning.
  • E[e−ΔH]=1\E[e^{-\Delta H}]=1 forces the mean energy error to be half its variance, so acceptance is 2Φ(−s/2)2\Phi(-s/2) with s2∝dε4s^2\propto d\varepsilon^4: step size d−1/4d^{-1/4}, O(d1/4)\order{d^{1/4}} steps per proposal, optimal acceptance 0.651 (Beskos et al., 2013).
  • Funnels cause divergences; non-centered parameterizations fix them. MALA is one-step HMC (d−1/3d^{-1/3}), 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.

Question 1

Why does HMC still need a Metropolis accept/reject step?

  1. Because the momentum is random
  2. Because the leapfrog integrator does not conserve HH exactly; the correction removes the discretization bias, and volume preservation plus reversibility make the ratio simply e−ΔHe^{-\Delta H}
  3. Because Hamilton's equations do not preserve volume
  4. It does not: the leapfrog trajectory is exact
Show the answer

B. Because the leapfrog integrator does not conserve HH exactly; the correction removes the discretization bias, and volume preservation plus reversibility make the ratio simply e−ΔHe^{-\Delta H}

The exact flow would conserve HH 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.

Question 2

A posterior has standard deviation 0.01 in one direction and 10 in another. With an identity mass matrix, what limits HMC?

  1. Nothing: HMC is insensitive to scale
  2. The step size must be at least 10 to explore the wide direction
  3. 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
  4. 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 ε<2σmin⁡=0.02\varepsilon<2\sigma_{\min}=0.02, while exploring needs a trajectory length comparable to σmax⁡=10\sigma_{\max}=10. The ratio σmax⁡/σmin⁡=1000\sigma_{\max}/\sigma_{\min}=1000 sets the cost. Choosing M−1M^{-1} close to the posterior covariance makes the problem look isotropic.

Question 3

Stan reports many divergent transitions when fitting a hierarchical model with a group-level scale parameter. What is the most appropriate response?

  1. Ignore them if R^<1.01\hat R<1.01
  2. Run the chains longer
  3. Increase the maximum tree depth
  4. 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.

Question 4

Which statement about Langevin methods is correct?

  1. MALA is HMC with a single leapfrog step; it needs order d1/3d^{1/3} iterations, between random-walk Metropolis (order dd) and HMC (order d1/4d^{1/4} leapfrog steps)
  2. The unadjusted Langevin algorithm is exact for any step size
  3. SGLD needs a Metropolis–Hastings step on the full data at every iteration
  4. MALA needs no gradients
Show the answer

A. MALA is HMC with a single leapfrog step; it needs order d1/3d^{1/3} iterations, between random-walk Metropolis (order dd) and HMC (order d1/4d^{1/4} leapfrog steps)

One leapfrog step from a fresh N(0,I)\mathcal N(\mathbf 0,I) momentum gives the proposal q+ε22∇log⁡π+εξ\mathbf q+\frac{\varepsilon^2}2\nabla\log\pi+\varepsilon\boldsymbol\xi, the MALA proposal with h=ε2h=\varepsilon^2, and the HMC acceptance equals MALA's. Its proposal variance must shrink like d−1/3d^{-1/3}, 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).