Search

Search papers and lessons

A Conceptual Introduction to Hamiltonian Monte Carlo

Michael Betancourt · 2017

Betancourt's 2017 review explains why Hamiltonian Monte Carlo explores high-dimensional probability distributions well, using physics intuition, and how to tune and diagnose it in practice.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Classical mechanics
  • Linear algebra
  • Discrete math
  • Sampling
  • ReadReady to readNot yet

TL;DR

Markov chain Monte Carlo estimates an average over a probability distribution by wandering through it, but in many dimensions the wandering is slow. Betancourt's review explains why the important part of a high-dimensional distribution is a thin shell away from its peak, and how Hamiltonian Monte Carlo moves along that shell by borrowing the equations of motion from classical physics. It also covers how the method is tuned and how its failures show up as warnings.

Builds on: Markov Chain Monte Carlo, Metropolis Algorithm, Hamiltonian Mechanics, Verlet Integration · Leads to: Hamiltonian Monte Carlo and the no-U-turn sampler, NUTS

Why it mattered

Hamiltonian Monte Carlo is a sampler used across Bayesian statistics. The review traces its path: Duane and colleagues introduced it in 1987 under the name Hybrid Monte Carlo, Neal adopted it for Bayesian neural networks in the 1990s (his 1995 thesis), and his 2011 review brought it into mainstream statistics. Stan, a widely used probabilistic programming system, implements it, as the paper's appendix describes.

The review matters because it explains the success instead of only reporting it. Before this, the method's performance was a set of empirical facts. The paper gives a geometric account of why it works on hard, high-dimensional problems, and it turns that account into practical rules: how to choose the momentum distribution, how long to integrate, how to tune the step size, and how to recognise a model that the sampler cannot explore.

The problem

The goal is to compute an expectation Eπ[f]\mathbb{E}_{\pi}[f] with respect to a target distribution π\pi on a DD-dimensional space. Exact integration is impossible for realistic targets, so the computer approximates the integral. Every evaluation of the density π(q)\pi(q) costs time, so a good method must spend those evaluations where they count.

The difficulty is geometric. Expectations are integrals of density times volume, and in high dimensions most of the volume is far from the peak. The paper's term for the region that matters is the typical set: the thin shell where density and volume are both large enough to contribute. Grid methods fail because a uniform grid with NN points per axis needs NDN^{D} points, and almost none of them land in the shell.

Random-walk Metropolis, the simplest Markov chain method, proposes a random jump and accepts it with a probability that depends on the density ratio. In high dimensions almost every proposal lands in the tails, where the density is tiny, so it is rejected. Shrinking the jumps raises the acceptance rate, but then the chain moves very slowly. In the worst case it cannot complete one crossing of the typical set in the time available. The method needs transitions that glide along the shell rather than guessing.

How it works

The paper's central move is to turn the probability problem into a physics problem. Here is one tiny instance, with the target a standard normal distribution, so the density is π(q)∝e−q2/2\pi(q) \propto e^{-q^2/2}. Its potential energy is V(q)=q2/2V(q) = q^2/2, and its gradient is dV/dq=qdV/dq = q. The state has a position qq and an auxiliary momentum pp; together they form the phase space. The Hamiltonian energy is H=V(q)+p2/2H = V(q) + p^2/2, the sum of potential energy and kinetic energy.

Start at position q0=1q_0 = 1 with momentum p0=0p_0 = 0. The total energy is H0=0.5H_0 = 0.5. Take one leapfrog step with step size ϵ=0.5\epsilon = 0.5.

  1. Half kick. Update the momentum by half a step along the force: p1/2=p0−ϵ2 dVdq(q0)=0−0.25×1=−0.25p_{1/2} = p_0 - \tfrac{\epsilon}{2}\,\tfrac{dV}{dq}(q_0) = 0 - 0.25 \times 1 = -0.25. The force pulls the momentum toward the peak.
  2. Drift. Move the position with the new momentum: q1=q0+ϵ p1/2=1+0.5×(−0.25)=0.875q_1 = q_0 + \epsilon\, p_{1/2} = 1 + 0.5 \times (-0.25) = 0.875.
  3. Second half kick. Update the momentum at the new position: p1=p1/2−ϵ2 dVdq(q1)=−0.25−0.25×0.875=−0.46875p_1 = p_{1/2} - \tfrac{\epsilon}{2}\,\tfrac{dV}{dq}(q_1) = -0.25 - 0.25 \times 0.875 = -0.46875.
  4. Check the energy. The new energy is H1=0.8752/2+0.468752/2≈0.3828+0.1099=0.4927H_1 = 0.875^2/2 + 0.46875^2/2 \approx 0.3828 + 0.1099 = 0.4927. Compared with H0=0.5H_0 = 0.5, the error is about 0.0070.007. A small error is the sign that the step is good.

The trajectory bends toward the peak and gains speed as it falls, which is exactly the orbit the physical picture predicts. Two checks help you read this. The first step moved the position from 1 to 0.875, a move toward the centre of the distribution. The energy changed by about 1.5 percent, so the path stays close to the same level set.

Turning this trajectory into a Markov transition takes three moves. First, lift the position into phase space by sampling a momentum from its conditional distribution. Second, integrate Hamilton's equations for a time TT. Third, project back to position by dropping the momentum. Because the trajectory conserves energy, the proposed point is almost always accepted, and a Metropolis correction (below) fixes the small error that remains.

The visual that matters is the phase-space picture: a level set of HH, all the points that share one energy, is a closed curve, and each trajectory traces that level set rather than jumping randomly between points.

flowchart LR
  A[Position q] -->|sample momentum p| B[Phase space q, p]
  B -->|leapfrog steps for time T| C[New phase-space point]
  C -->|drop momentum| D[New position q]
  C -->|accept or reject with energy| D

The math

The paper's formal core fits in a few equations. Each one matches a step above.

The expectation and the typical set

The expectation is Eπ[f]=∫π(q) f(q) dq\mathbb{E}_{\pi}[f] = \int \pi(q)\, f(q)\, \mathrm{d}q, and the volume element dq\mathrm{d}q is what makes the typical set matter. Cut each axis into three equal pieces, so the space splits into 3D3^{D} boxes with the mode in the centre box. That centre box holds 1/31/3 of the volume in one dimension, 1/91/9 in two and 1/271/27 in three, that is 1/3D1/3^{D} in general. The neighbouring boxes dominate the volume, and they lie away from the mode.

The Hamiltonian and its two parts

Phase space adds one momentum pp for each position qq. The canonical distribution is π(q,p)=π(p∣q) π(q)\pi(q, p) = \pi(p \mid q)\,\pi(q), and up to a normalising constant it can be written as π(q,p)∝e−H(q,p)\pi(q,p) \propto e^{-H(q,p)} with

H(q,p)=K(p,q)+V(q),V(q)=−log⁡π(q),K(p,q)=−log⁡π(p∣q).H(q,p) = K(p,q) + V(q), \qquad V(q) = -\log \pi(q), \qquad K(p,q) = -\log \pi(p \mid q).

Here VV is the potential energy, fixed by the target, and KK is the kinetic energy, chosen by the user. The Gaussian choice π(p∣q)=N(p∣0,M)\pi(p \mid q) = \mathcal{N}(p \mid 0, M) gives K(p,q)=12pTM−1p+constK(p,q) = \tfrac{1}{2} p^{\mathsf{T}} M^{-1} p + \text{const}, where MM is the mass matrix and sets how each momentum direction is spread.

Hamilton's equations

The trajectory follows the ordinary differential equations

dqdt=∂K∂p,dpdt=−∂K∂q−∂V∂q.\frac{\mathrm{d}q}{\mathrm{d}t} = \frac{\partial K}{\partial p}, \qquad \frac{\mathrm{d}p}{\mathrm{d}t} = -\frac{\partial K}{\partial q} - \frac{\partial V}{\partial q}.

The energy HH is constant along the exact solution, so every trajectory stays on one level set.

The leapfrog update (steps 1 to 3 above)

The leapfrog update with step size ϵ\epsilon is

pn+12=pn−ϵ2 ∂V∂q(qn),qn+1=qn+ϵ pn+12,pn+1=pn+12−ϵ2 ∂V∂q(qn+1).p_{n+\frac{1}{2}} = p_n - \tfrac{\epsilon}{2}\,\tfrac{\partial V}{\partial q}(q_n), \qquad q_{n+1} = q_n + \epsilon\, p_{n+\frac{1}{2}}, \qquad p_{n+1} = p_{n+\frac{1}{2}} - \tfrac{\epsilon}{2}\,\tfrac{\partial V}{\partial q}(q_{n+1}).

It is symplectic: it preserves phase-space volume exactly, so its energy error oscillates instead of growing steadily. That is why it can be run for long trajectories.

The Metropolis correction (step 4 above)

Integrating only approximately makes the proposal slightly biased. Flip the momentum after the trajectory to make the proposal reversible, and accept it with probability

a=min⁡ ⁣(1,exp⁡ ⁣(H(q0,p0)−H(qL,−pL))).a = \min\!\left(1, \exp\!\left(H(q_0, p_0) - H(q_L, -p_L)\right)\right).

For the example above, H(q0,p0)−H(q1,−p1)≈0.5−0.4927=0.0073H(q_0,p_0) - H(q_1, -p_1) \approx 0.5 - 0.4927 = 0.0073, so a=1a = 1. The proposal is accepted.

Mixing: how many draws the chain is worth

The estimator's standard error is MCMC SE=Varπ[f]/ESS\mathrm{MCMC\,SE} = \sqrt{\mathrm{Var}_{\pi}[f] / \mathrm{ESS}}, where the effective sample size is

ESS=N1+2∑l=1∞ρl,\mathrm{ESS} = \frac{N}{1 + 2\sum_{l=1}^{\infty} \rho_{l}},

and ρl\rho_l is the lag-ll autocorrelation. The effective sample size counts how many independent draws the chain is worth.

Results

The review is conceptual and reports no new benchmark. Its quantitative statements are these, with the paper's own values.

  • Volume. The centre box holds 1/31/3, 1/91/9 and 1/271/27 of the volume in one, two and three dimensions. A 3×3×33 \times 3 \times 3 grid has 26 neighbouring boxes around its centre.
  • Step size. The automatic tuning procedure adapts the step size during warm-up to reach an average Metropolis acceptance probability between 0.6 and 0.8.
  • Energy diagnostic. The energy Bayesian fraction of missing information (E-BFMI) measures the mismatch between the energy's overall distribution and the energy changes the chain actually makes. A poorly chosen kinetic energy shows up as a low value. Empirically, values below 0.3 have proven problematic, though the paper says no exact threshold has been established.
  • Heavy tails. For the family πβ(q)∝e−∣q∣β\pi_\beta(q) \propto e^{-|q|^{\beta}}, the optimal integration time scales with the energy as H(2−β)/(2β)H^{(2-\beta)/(2\beta)}. For a Gaussian, β=2\beta = 2, the exponent is zero, so one static time works everywhere. For heavy tails, β\beta below 2, the optimal time grows with the energy, so a fixed time fails in the tails.
  • Divergences. Divergent trajectories are a warning that the posterior has regions of high curvature. The paper says divergences can be removed by a smaller step size when the pathology is mild, and that severe cases need the model itself changed, for example with stronger priors or an alternative parameterisation.

Limits. The paper states its own gaps. Proving geometric ergodicity, which guarantees valid estimates, is extremely difficult in general, and the diagnostics are necessary but not sufficient. The empirical threshold of 0.3 is not a theorem. The higher-order integrators it discusses need automated tuning procedures that do not yet exist, and the theory for the more sophisticated implementations is still being developed.

Reading guide

  • Section 1 (expectations and typical sets). This needs Markov Chain Monte Carlo only in outline and Probability Density Function for the density. Read the volume argument slowly; everything else depends on it.
  • Section 2 (Markov chain Monte Carlo). Uses Metropolis Algorithm and the efficiency measures Effective Sample Size and Autocorrelation Function. The Metropolis-Hastings rule of Section 2.4 is the acceptance step the final correction reuses.
  • Section 3 (the foundations). Relies on Hamiltonian Mechanics, with Kinetic Energy and Potential Energy as the two terms of the Hamiltonian.
  • Section 4 (efficient implementations). Covers the choice of the mass matrix, with a position-dependent Riemannian version that uses Riemannian Geometry, and the integration time, which leads to the no-U-turn criterion in the NUTS paper.
  • Section 5 (implementation). The leapfrog integrator is the Verlet method of Verlet Integration. The warm-up that tunes the step size to an acceptance rate between 0.6 and 0.8 is in Section 5.3. The acceptance correction is the Metropolis-Hastings step from Section 2.4, which relies on the same Detailed Balance reasoning as Metropolis Algorithm.
  • Section 6 (robustness). Read it last. It turns the theory into diagnostics you can run on your own model.

Check yourself

QuestionWhy does a random-walk Metropolis chain accept almost no proposals in high dimensions, and why does shrinking the jumps not fully fix it?Show answer

In high dimensions most of the volume lies in the tails, so a random jump almost always lands where the density is tiny, and the Metropolis ratio rejects it. Shrinking the jump keeps proposals inside the typical set and raises the acceptance rate, but each jump then moves a tiny distance, so the chain explores very slowly and its estimates have large autocorrelation.

QuestionUsing the worked example, the start is q0=1q_0 = 1, p0=0p_0 = 0, ϵ=0.5\epsilon = 0.5. After one leapfrog step, the position is q1=0.875q_1 = 0.875 and the momentum is p1=−0.46875p_1 = -0.46875. What is the energy error, and why is that error small?Show answer

The energy at the start is H0=12/2+0=0.5H_0 = 1^2/2 + 0 = 0.5. At the end, H1=0.8752/2+0.468752/2≈0.4927H_1 = 0.875^2/2 + 0.46875^2/2 \approx 0.4927. The error is about 0.00730.0073. It is small because the leapfrog update is symplectic: it preserves phase-space volume, so the energy error oscillates rather than drifting. Because the error is so small, the Metropolis ratio is close to one and the proposal is accepted.

QuestionWhy does a warning about a divergent transition matter more than an ordinary low acceptance rate?Show answer

A divergence means the numerical trajectory shot off toward extreme energies, which happens when the posterior has a region of high curvature that the step size cannot resolve. Such a region is one the chain can miss, which biases the estimates, so a divergence is a warning about the estimates themselves. The paper recommends a smaller step size for mild cases and changing the model for severe ones.

QuestionFor a heavy-tailed target with β\beta below 2, why can a single fixed integration time fail?Show answer

The optimal integration time grows with the energy of the trajectory as H(2−β)/(2β)H^{(2-\beta)/(2\beta)}, which increases when β\beta is below 2. Trajectories in the bulk need short paths, but trajectories that reach the tails need much longer ones. A fixed time suits one energy level and is too short in the tails, so the chain slows to a crawl there. The no-U-turn criterion is designed to choose the length dynamically.

Sources

Read the full paper

Michael Betancourt, 2017. arXiv:1701.02434