Search

Search papers and lessons

MCMC Using Hamiltonian Dynamics

Radford M. Neal · 2012

Neal's review shows how to use Hamiltonian dynamics to make distant, high-acceptance proposals for Metropolis sampling, so high-dimensional distributions can be explored far faster than by random walks.

On this page

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

TL;DR

Neal's review shows how to borrow Hamiltonian dynamics from physics to propose distant new states for a Metropolis sampler. The proposal follows a simulated trajectory through an artificial landscape, so it can move far while still being accepted most of the time. The result is that a Markov chain explores a high-dimensional distribution with far fewer wasted steps than a random walk, which made it a standard tool for Bayesian sampling.

Builds on: Markov Chain Monte Carlo, Hamiltonian Mechanics, Metropolis Algorithm, Verlet Integration · Leads to: Hamiltonian Monte Carlo as a practical sampler

Why it mattered

Bayesian statistics needs samples from posterior distributions over many parameters, and a random-walk sampler becomes very slow once there are more than a few dimensions. Neal's review showed that a sampler which moves along a physical-looking trajectory can keep acceptance high while making large moves, and it gave the theory and the practical rules for doing so. The method is now the default inside widely used probabilistic programming systems. Stan, for example, uses a variant of Hamiltonian Monte Carlo as its default sampler.

The paper also changed how people think about the proposal step. A proposal does not have to be a random guess; it can be the result of a deterministic, reversible, volume-preserving map, and the acceptance rule then needs no Jacobian correction. That idea is useful well beyond this sampler.

The problem

A Metropolis sampler proposes a small random change to the current state and accepts or rejects it. In one dimension this works well. In many dimensions the proposal must be small, or most proposals are rejected, and so the chain takes a random walk through the distribution. Neal's analysis gives the cost: for a target made of dd independent replicas, the potential energy takes of order dd random-walk updates to explore, and the computation grows roughly as d2d^2.

The fix is to propose a state that is far away but still has a similar probability. A physical system does this naturally, since a particle moving under a force follows a trajectory that keeps its total energy nearly constant. The question is how to turn that physics into a valid sampler.

How it works

Each iteration takes the current state qq of the variables of interest and adds a momentum pp that the sampler invents. Then it runs five steps.

  1. Resample the momentum. Draw a new pp from a Gaussian, independently of qq. Check: qq is unchanged, so this step only refreshes the momentum.
  2. Simulate a trajectory. Run Hamiltonian dynamics for LL small steps of size ε\varepsilon using the leapfrog scheme. Check: the total energy HH changes only slightly along the way.
  3. Negate the momentum. Flip the sign of pp at the end. Check: this makes the proposal symmetric, which the acceptance rule needs.
  4. Accept or reject. Accept the new state with probability min⁡[1,exp⁡(−Hnew+Hold)]\min\bigl[1, \exp(-H_{\text{new}} + H_{\text{old}})\bigr]. If it is rejected, keep the old state.
  5. Repeat. Each iteration gives one state of the Markov chain, and the chain's samples approximate the target distribution.

A tiny one-dimensional case shows the mechanics. The target is a Gaussian with variance 1, so U(q)=q2/2U(q) = q^2/2, and the momentum has kinetic energy K(p)=p2/2K(p) = p^2/2. Start at q=0q = 0 with p=1p = 1. Each leapfrog step first moves the momentum a half step, then the position a full step, then the momentum another half step, using the gradient U′(q)=qU'(q) = q. This example is traced in detail in the worked examples below.

flowchart LR
  A["State q, resample p"] --> B["Leapfrog trajectory, L steps"]
  B --> C["Negate p"]
  C --> D{"Accept with min(1, exp of minus change in H)?"}
  D -->|yes| E["Move to new q"]
  D -->|no| F["Keep old q"]
  E --> A
  F --> A

The math

Hamiltonian dynamics operates on positions q∈Rdq \in \mathbb{R}^d and momenta p∈Rdp \in \mathbb{R}^d. The Hamiltonian H(q,p)H(q, p) is the total energy, and Hamilton's equations are

dqdt=∂H∂p,dpdt=−∂H∂q.\frac{dq}{dt} = \frac{\partial H}{\partial p}, \qquad \frac{dp}{dt} = -\frac{\partial H}{\partial q}.

For sampling, the Hamiltonian is split as H(q,p)=U(q)+K(p)H(q, p) = U(q) + K(p). The potential energy is defined as U(q)=−log⁡π(q)U(q) = -\log \pi(q), minus the log of the target density π\pi up to a constant. The kinetic energy is K(p)=∑ipi2/(2mi)K(p) = \sum_i p_i^2 / (2m_i), a Gaussian for the momentum with variances mim_i.

Step 1 in symbols: resampling

The joint distribution of (q,p)(q, p) is proportional to exp⁡(−H(q,p))\exp(-H(q, p)). This factorises, so pp can be drawn from its Gaussian on its own. Refreshing pp leaves the joint distribution invariant, and it is the step that lets the chain move to different energy levels.

Step 2 in symbols: the leapfrog scheme

Hamilton's equations are discretised with steps of size ε\varepsilon:

p(t+ε/2)=p(t)−ε2∇U(q(t)),q(t+ε)=q(t)+ε p(t+ε/2)/m,p(t+ε)=p(t+ε/2)−ε2∇U(q(t+ε)).\begin{aligned} p(t + \varepsilon/2) &= p(t) - \tfrac{\varepsilon}{2} \nabla U\bigl(q(t)\bigr), \\ q(t + \varepsilon) &= q(t) + \varepsilon\, p(t + \varepsilon/2)/m, \\ p(t + \varepsilon) &= p(t + \varepsilon/2) - \tfrac{\varepsilon}{2} \nabla U\bigl(q(t + \varepsilon)\bigr). \end{aligned}

The scheme preserves volume exactly, and it is reversible, which is what the acceptance rule needs. The paper notes that its local error is of order ε3\varepsilon^3, one order better than the Euler method.

Step 4 in symbols: the acceptance rule

Because the dynamics conserves HH exactly in theory, the acceptance probability is one in theory. Discretisation changes HH slightly, so the rule is

α=min⁡[1, exp⁡(−H(q∗,p∗)+H(q,p))],\alpha = \min\Bigl[1,\ \exp\bigl(-H(q^{*}, p^{*}) + H(q, p)\bigr)\Bigr],

where (q∗,p∗)(q^{*}, p^{*}) is the proposed state. The energy error from discretisation is small when ε\varepsilon is small enough, and it does not grow much with LL, which the paper notes.

Step 5 in symbols: the one-dimensional example

For U(q)=q2/2U(q) = q^2/2 and K(p)=p2/2K(p) = p^2/2, Hamilton's equations give q(t)=q(0)cos⁡t+p(0)sin⁡tq(t) = q(0)\cos t + p(0) \sin t and p(t)=p(0)cos⁡t−q(0)sin⁡tp(t) = p(0) \cos t - q(0) \sin t. The trajectory is a rotation in the (q,p)(q, p) plane, and HH stays fixed along it.

Worked examples

Example
1. The exact rotation (no discretisation)

Start at q=0q = 0, p=1p = 1, so H=0+1/2=1/2H = 0 + 1/2 = 1/2. Run the exact dynamics for time t=π/2t = \pi/2.

  1. q(π/2)=0⋅cos⁡(π/2)+1⋅sin⁡(π/2)=1q(\pi/2) = 0 \cdot \cos(\pi/2) + 1 \cdot \sin(\pi/2) = 1.
  2. p(π/2)=1⋅cos⁡(π/2)−0⋅sin⁡(π/2)=0p(\pi/2) = 1 \cdot \cos(\pi/2) - 0 \cdot \sin(\pi/2) = 0.
  3. New energy: H=12/2+02/2=1/2H = 1^2/2 + 0^2/2 = 1/2.
  4. Check: the energy is unchanged, so the exact proposal is accepted with probability 1.

Interpretation: the exact trajectory moves the sampler from the centre of the Gaussian to q=1q = 1 in one proposal, and the acceptance rule never rejects it. A random-walk proposal of similar size would often be rejected.

Example
2. The standard case: two leapfrog steps

Use the same start, q=0q = 0 and p=1p = 1, with ε=0.5\varepsilon = 0.5 and L=2L = 2. The gradient is ∇U(q)=q\nabla U(q) = q.

  1. Half-step momentum: p=1−0.25×0=1p = 1 - 0.25 \times 0 = 1.
  2. Full-step position: q=0+0.5×1=0.5q = 0 + 0.5 \times 1 = 0.5.
  3. Half-step momentum: p=1−0.25×0.5=0.875p = 1 - 0.25 \times 0.5 = 0.875. Energy now 0.125+0.3828=0.50780.125 + 0.3828 = 0.5078.
  4. Half-step momentum: p=0.875−0.25×0.5=0.75p = 0.875 - 0.25 \times 0.5 = 0.75.
  5. Full-step position: q=0.5+0.5×0.75=0.875q = 0.5 + 0.5 \times 0.75 = 0.875.
  6. Half-step momentum: p=0.75−0.25×0.875=0.53125p = 0.75 - 0.25 \times 0.875 = 0.53125.
  7. Energy: H=0.8752/2+0.531252/2=0.3828+0.1411=0.5239H = 0.875^2/2 + 0.53125^2/2 = 0.3828 + 0.1411 = 0.5239.
  8. Energy change: 0.5239−0.5=0.02390.5239 - 0.5 = 0.0239. Acceptance: min⁡(1,e−0.0239)≈0.976\min(1, e^{-0.0239}) \approx 0.976.

Interpretation: the sampler moves to q=0.875q = 0.875, a large move, and it is accepted with probability about 0.98. Check the step where the energy rose: it went from 0.5 to 0.508 after one step, so the error stays small as long as ε\varepsilon is small.

Example
3. Realistic: a 100-dimensional Gaussian

The paper's test distribution is a 100-dimensional Gaussian with independent variables and standard deviations 0.01,0.02,…,1.000.01, 0.02, \ldots, 1.00. The leapfrog stepsize has to be small for the narrowest direction, so the paper uses ε\varepsilon near 0.0130.013 and L=150L = 150.

  1. Trajectory length: εL≈0.013×150=1.95\varepsilon L \approx 0.013 \times 150 = 1.95, which is long enough to cross the widest direction, whose standard deviation is 1.
  2. Rejection rate for HMC: 0.13, so acceptance is 1−0.13=0.871 - 0.13 = 0.87.
  3. Rejection rate for random-walk Metropolis, with its best proposal size: 0.75, so acceptance is 0.25.
  4. Check: both rates are reported for near-optimal tuning, so the comparison is fair.

Interpretation: HMC accepts most of its long proposals, while the random walk rejects three quarters of its short ones. Per unit of computation the difference is large in 100 dimensions.

Try it. How many times higher is the HMC acceptance rate than the random-walk acceptance rate in this example? Answer: 0.87/0.25=3.480.87 / 0.25 = 3.48, about 3.5 times higher.

Results

The review reports three kinds of result, each with its numbers from the paper.

ResultWhat the paper reports
Optimal acceptance, random-walk MetropolisAbout 23 percent, at the optimal mean energy change μ=2.8\mu = 2.8
Optimal acceptance, HMCAbout 65 percent, at μ=0.41\mu = 0.41
100-dimensional GaussianHMC rejection 0.13, random-walk rejection 0.75, with L=150L = 150
Exploring the potential energyRandom walk needs of order dd updates; the paper argues HMC may need only a few iterations to reach a nearly independent point

The 23 percent figure for random walks matches a more formal analysis by Roberts and colleagues, and the 65 percent figure for HMC is consistent with earlier empirical results on high-dimensional problems. The paper's arguments about exploration rest on the fact that the momentum resampling changes the kinetic energy by an amount that grows with d\sqrt{d}, which lets a single proposal move the potential energy a comparable amount.

The paper also states its limits. The stepsize must be small compared with the narrowest scale in the target, otherwise the energy error grows and acceptance falls. Trajectories can be periodic, which stops the chain from exploring, so the paper suggests choosing ε\varepsilon or LL at random within a small range. Distributions with isolated modes need extra methods, such as tempering during a trajectory, which the review describes. HMC also needs the gradient of the log density, which is not always available.

Reading guide

  1. Introduction (Section 1). Read for the motivation: random-walk proposals diffuse, and Hamiltonian dynamics can make distant proposals. Needs Markov Chain Monte Carlo and Metropolis Algorithm.
  2. Hamiltonian dynamics (Section 2). Read Hamilton's equations, the properties of volume preservation and reversibility, and the leapfrog scheme. Needs Hamiltonian Mechanics and Verlet Integration. The one-dimensional rotation example is a good place to check the reasoning.
  3. MCMC from Hamiltonian dynamics (Section 3). Read the canonical distribution and the HMC algorithm. Needs Probability Density Function for the target and Detailed Balance for the proof of invariance. The 2D and 100-dimensional illustrations follow.
  4. HMC in practice and theory (Section 4). Read the tuning rules, the effect of the mass matrix, and the scaling with dimension. Needs Kinetic Energy, Potential Energy and the Gaussian (Normal) Distribution that the momentum follows.
  5. Variations (Section 5). Skim unless you need them; these cover windows of states, tempering and short-cut methods.

Check yourself

QuestionRecall: why must the momentum be resampled at the start of each iteration, rather than kept from the previous trajectory?Show answer

Without resampling, a trajectory keeps the total energy H=U+KH = U + K almost fixed, so the chain would stay on one energy level and could not move to states of different probability. Resampling the momentum changes KK, and therefore HH, letting the chain move between energy levels. It also keeps the joint distribution invariant.

QuestionComputation: with ε=0.2\varepsilon = 0.2 and L=50L = 50, what is the trajectory length εL\varepsilon L?Show answer

The trajectory length is 0.2×50=100.2 \times 50 = 10.

QuestionWhy: why does the negation of the momentum at the end of the trajectory matter, if the momentum is resampled anyway in the next iteration?Show answer

The acceptance rule assumes the proposal is symmetric: the probability of moving from one state to another must equal the probability of the reverse move. Negating the momentum makes the reverse of the trajectory land back on the start, so the proposal is symmetric. In practice the negation can be skipped, because K(p)=K(−p)K(p) = K(-p) and the momentum is resampled before it is used again, but it is part of the algorithm's correctness argument.

QuestionApplied: a model has 10,000 parameters and the gradient is cheap to compute. A colleague proposes random-walk Metropolis with a tuned step size. Should you use HMC instead?Show answer

Probably yes. The paper's analysis shows that random-walk Metropolis needs work that grows with the dimension, while HMC's proposals move far with high acceptance. Before committing, check that the target is smooth enough for the leapfrog scheme, tune ε\varepsilon and LL to get an acceptance rate near the 65 percent the paper reports, and compare effective samples per second with the random walk on a short run.

Sources

Read the full paper

Radford M. Neal, 2012. arXiv:1206.1901