Hamiltonian Monte Carlo
Hamiltonian Monte Carlo (HMC) is a gradient-informed Metropolis-Hastings sampler whose proposal follows a continuous-time physical trajectory determined by the target . Augment the state with an auxiliary momentum variable and define the Hamiltonian
where is the potential energy, is the kinetic energy, and is a positive-definite mass matrix (default ). The joint target on is , so the -marginal is exactly .One iteration:
- Resample momentum. Draw , independent of the current position .
- Simulate Hamiltonian dynamics. Integrate
for time using leapfrog steps of size :
- Metropolis accept/reject. Let be the leapfrog endpoint. Accept with probability
Why it works. Continuous-time Hamiltonian dynamics exactly preserve , so acceptance would be identically if the integrator were exact. The leapfrog integrator is a symplectic scheme — it preserves phase-space volume exactly and conserves to second order in , so the acceptance probability is nearly even for large numbers of steps . Symplecticity plus time-reversibility of leapfrog (with a momentum flip) is exactly what makes the Metropolis step satisfy detailed balance with respect to .
Mechanical interpretation. HMC is the position-dependent acceleration extension of MALA. MALA evaluates once at the starting position and holds it fixed for the flight time ; HMC updates the acceleration continuously along the trajectory, so the particle “skates” along contours of rather than falling along a single gradient direction. The particle can travel long distances before Metropolis-checking, so HMC takes much larger effective steps than MALA.
Cost and scaling. One HMC iteration costs gradient evaluations ( typically –). In exchange, HMC mixes with step size (versus for MALA and for random-walk Metropolis), and the optimal acceptance rate is roughly . For smooth high-dimensional targets, HMC’s effective-sample-size-per-gradient is dramatically higher than MALA’s, which is why it is the default sampler in modern probabilistic programming systems like Stan, PyMC, and NumPyro. The No-U-Turn Sampler (NUTS) adaptively chooses to avoid hand-tuning the trajectory length.
Prerequisites
- 3.11.3 MALA — the constant-acceleration predecessor; HMC generalizes to position-dependent acceleration.
- 3.11.1 Metropolis-Hastings — HMC is an MH instance whose proposal is the leapfrog endpoint and whose acceptance ratio uses the Hamiltonian.
- 3.11 MCMC — detailed balance, ergodic theorem, effective sample size.
- 5.4 Reversibility — leapfrog with momentum flip is time-reversible, which yields detailed balance.
Intuition
Imagine a frictionless puck sliding across a surface whose height is . Low-posterior regions correspond to tall hills; high-posterior regions are valleys. Give the puck a random push and let it coast: it will speed up sliding into valleys and slow climbing hills, so it naturally spends more time in valleys (high-density regions). If we track its position periodically and record samples, the histogram of positions is . This is exactly what HMC simulates, with kinetic energy playing the role of the puck’s kinetic energy and momentum resampling replacing occasional “shakes” that keep the puck exploring all valleys rather than settling in the first one.
The central insight that makes HMC fast is that the puck’s trajectory stays on a level set of , and level sets stretch across the distribution — a single simulation can traverse a long distance without ever climbing a hill. Compare this to MALA, which takes one gradient step and then pauses for a Metropolis check: MALA’s effective step size is , while HMC’s effective distance traveled per iteration scales with the trajectory length , which can be much larger. The price is that Hamiltonian dynamics have no closed-form solution for general and must be discretized; leapfrog is the numerical scheme that preserves both the structure needed for the Metropolis step (time-reversibility, volume preservation) and the quality needed for high acceptance ( conserved to ).
Properties
(Position-Dependent Acceleration) The acceleration is updated at every leapfrog step, unlike MALA.
The MALA proposal uses a single gradient evaluation at the starting point and pretends the acceleration stays constant for time ; this is accurate only for small . HMC evaluates at every leapfrog half-step, so the trajectory bends along the contours of . The payoff is that HMC can take many small leapfrog steps and cover a long total distance with the acceleration always pointing in the right direction — the chain tracks the geometry of rather than fighting it.
(Symplectic Leapfrog Integrator) Leapfrog preserves phase-space volume exactly and conserves to second order.
The leapfrog update is the canonical symplectic integrator: the Jacobian of one leapfrog step as a map on has determinant exactly , so the measure is preserved. This volume-preservation is necessary for the Metropolis step to have a simple acceptance formula (no Jacobian correction). Additionally, the numerical error in is per step and does not accumulate — leapfrog nearly-conserves a shadow Hamiltonian , so even over long trajectories () the energy error stays bounded.
(Time-Reversibility with Momentum Flip) The leapfrog map is reversed by a momentum flip .
If , then . Combined with symplecticity, this reversibility is exactly the symmetry needed so that the MH acceptance probability satisfies detailed balance with respect to — the proposal is effectively symmetric on the augmented space once the momentum flip is absorbed into the Metropolis step. (Most implementations omit the explicit momentum flip because momentum is resampled at the start of every iteration anyway.)
(Metropolis Acceptance) The accept/reject step uses the change in , with acceptance probability .
If leapfrog were exact, would be conserved and . Discretization makes per leapfrog step, but because the shadow-Hamiltonian error does not accumulate, the total over steps is also . This gives acceptance probabilities in the – range for typical step sizes, compared to for random-walk Metropolis at the same per-iteration cost.
(Optimal Acceptance ≈ 0.65 and ) HMC scales better with dimension than MALA.
For i.i.d. product targets , theory (Beskos, Pillai, Roberts, Sanz-Serna, Stuart 2013) shows the optimal step size scales as with optimal acceptance rate . This is strictly better than MALA’s scaling with acceptance and dramatically better than RWM’s scaling with acceptance. The practical consequence is that HMC remains efficient at dimensions (–) where MALA and RWM become prohibitively slow.
(Momentum Resampling Ensures Ergodicity) Resetting at the start of every iteration is what makes the chain explore the full space.
A single Hamiltonian trajectory is confined to the level set — it cannot reach regions of at different energies. Resampling from its marginal Gaussian changes the Hamiltonian level and lets the chain move between energy shells; after many iterations, the full distribution is explored, and the -marginal is . Without momentum resampling, HMC is not ergodic.
(Mass Matrix Preconditions the Dynamics) A non-identity mass matrix rescales the proposal to match the local geometry of .
The default is the wrong shape when coordinates of live on very different scales. A posterior covariance estimate (from a preliminary run or a Laplace approximation at the MAP) used as equalizes the momentum-induced steps across dimensions. Modern HMC adaptations (warmup phase in Stan, NumPyro) estimate automatically during the tuning phase by running several HMC iterations, computing the sample covariance of the positions, and using its inverse as the mass matrix for the remaining iterations.
(No-U-Turn Sampler (NUTS)) Automatically chooses trajectory length to avoid backtracking.
Choosing too small gives short HMC trajectories that behave like MALA; choosing too large wastes computation on trajectories that loop back to their starting point (called a “U-turn”). The No-U-Turn Sampler (Hoffman & Gelman 2014) detects U-turns on the fly by growing the trajectory doubling each iteration and stopping when the momentum would reverse. NUTS is the default in Stan and PyMC because it removes the most delicate HMC hyperparameter () from the user’s hands.
(Requires Smooth, Gradient-Accessible Targets) HMC breaks on discrete parameters, discontinuities, and heavy tails.
Like MALA, HMC needs to be defined and computable. For discrete parameters, HMC cannot be used directly — collapsed Gibbs or block updates must handle them while HMC handles the continuous parameters. For non-differentiable log-posteriors (e.g., Laplace priors with exact zero, hinge-loss-like terms), HMC behaves erratically at the kinks; reparameterization or smoothing is typically needed. Heavy-tailed targets make the Hamiltonian dynamics unstable at large because the gradient grows without bound, and leapfrog energy errors compound — Riemannian HMC with position-dependent metrics partially addresses this but is rarely used in practice.
Examples
HMC on a 2D Gaussian
Target with . The potential and its gradient are
With mass matrix and step size , run leapfrog steps per iteration. Each leapfrog step is:
The trajectory traces an ellipse in space determined by . Over iterations the effective sample size for each coordinate is typically around — in contrast, random-walk Metropolis gives and MALA on the same target. Setting (the ideal preconditioner) produces exact independent samples after a single iteration because the Hamiltonian becomes rotationally symmetric.
Why leapfrog and not Euler?
The Euler integrator
is not symplectic: the Jacobian determinant is , so volume is not preserved. Worse, energy errors accumulate linearly: grows like , so long trajectories are rejected with probability approaching . Leapfrog
is symplectic (volume-preserving) and keeps the energy error bounded near the shadow Hamiltonian. Running Euler steps vs. leapfrog steps on the 2D Gaussian above gives acceptance rates near for Euler and near for leapfrog with the same step size. Symplectic integration is not a minor implementation detail — it is what makes HMC work.
Hierarchical model with funnel geometry
The Bayesian hierarchical model
produces a “Neal’s funnel” posterior: as , the concentrate near ; as grows, the spread out. HMC with a fixed mass matrix gets stuck near the funnel neck because the local curvature changes dramatically with . The standard fix is a non-centered reparameterization: with a priori. This decouples from and makes the posterior approximately isotropic, at which point vanilla HMC mixes well. Reparameterization is a common HMC workflow step: the sampler exposes geometry problems that are fixed not by tuning HMC but by rewriting the model.
Derivation
Goal. Show that the HMC proposal satisfies detailed balance with respect to the augmented target , hence its -marginal is .
Step 1 — Target augmentation. Define the joint target on by
Because separates additively, and are independent under : marginally, and the -marginal is exactly . Any sampler that preserves as its stationary distribution thus provides samples from by projection.
Step 2 — Momentum resampling preserves . At the start of each iteration, replace the current momentum with a fresh draw , independent of . Because factors and the -conditional is exactly , this Gibbs-style update leaves invariant. (In MH language, this is a full-conditional step with acceptance probability .)
Step 3 — Exact Hamiltonian dynamics preserve and hence . Hamilton’s equations
conserve (classical mechanics: by substitution) and are volume-preserving by Liouville’s theorem. Under an exact Hamiltonian flow, if then as well — the dynamics leave the joint target invariant.
Step 4 — Leapfrog discretization is volume-preserving and time-reversible. The leapfrog map given by
has Jacobian determinant exactly (direct computation: each half-step has a triangular Jacobian with unit diagonal, so the determinant is ). It is also time-reversible in the sense where flips momentum. These two properties — symplecticity and reversibility — are exactly what is needed for the Metropolis step to satisfy detailed balance.
Step 5 — Metropolis correction gives exact detailed balance. Let be the endpoint of leapfrog steps, and accept with probability . The joint kernel is
where is the deterministic leapfrog transition. Because leapfrog is volume-preserving, the Jacobian factor in the density cancels; because it is reversible with a momentum flip, the forward and backward deterministic densities are linked by
Combined with the symmetry , the acceptance rule makes — detailed balance on the augmented state space. Marginalizing over recovers samples from .
Why leapfrog’s energy error stays small. Although does not exactly preserve , symplectic integrators preserve a nearby shadow Hamiltonian exactly. Over steps the true error stays bounded by rather than accumulating to , which is the specific reason HMC can afford long trajectories () with acceptance near .
See Also
- 3.11.3 MALA — constant-acceleration predecessor; HMC generalizes to position-dependent acceleration.
- 3.11.1 Metropolis-Hastings — HMC is an MH sampler on the augmented state space.
- 3.11.2 Gibbs Sampling — alternative when full conditionals are tractable or when parameters are discrete.
- 3.11 MCMC — parent index with tuning, diagnostics, effective sample size.
- 3.9 Laplace Approximation — source of the mass matrix for preconditioning.
- 4.6 Brownian Motion — contrast: MALA’s SDE has a Brownian driving term; HMC’s ODE is deterministic between momentum resets.