- Year
- 1987
- Type
- Gradient-based Markov chain Monte Carlo sampler
What does it do?
Hamiltonian Monte Carlo (HMC) is a Markov chain Monte Carlo algorithm that uses the gradient of the log-posterior to propose distant, high-probability moves through parameter space, instead of the small random steps of classical random-walk samplers.
Duane, Kennedy, Pendleton, and Roweth (1987) introduced it for lattice field theory under the name Hybrid Monte Carlo, and Neal (2011) brought it into mainstream statistics. An adaptive extension, the No-U-Turn Sampler (NUTS), is the default sampler in Stan and is also implemented in PyMC.
The intuition behind the method
Imagine a ball rolling on a surface whose height represents the negative log-posterior: valleys are high-probability regions and peaks are low-probability regions. Random-walk MCMC moves the ball by small random nudges, so it wanders slowly and rarely crosses a wide valley in a few moves. HMC instead gives the ball a random push (the auxiliary momentum variable), lets it roll under Hamiltonian dynamics for several steps, and then proposes the position where it ends up. Because the ball travels along contours of nearly constant energy, a single proposal can cover a long distance while keeping a high probability of acceptance. The practical consequence is that successive draws are typically less correlated than those from a random-walk sampler, so each gradient evaluation tends to buy more independent information.
History
HMC was introduced by Duane, Kennedy, Pendleton, and Roweth (1987) as Hybrid Monte Carlo, in the context of lattice field theory and simulations with dynamical fermions. Neal's 2011 chapter in the Handbook of Markov Chain Monte Carlo presented the method, its theory, and practical guidance for statisticians. The No-U-Turn Sampler, an adaptive extension that automates the choice of trajectory length, is implemented in Stan and PyMC.
When to use it
Choose HMC when (1) the posterior is continuous and differentiable with respect to all parameters, which is required to compute the gradients; (2) the parameter space is moderate to high dimensional, where random-walk proposals explore slowly; and (3) the posterior geometry is complicated, for example strongly correlated parameters or strongly curved regions. Do not use HMC when the model has discrete parameters, since they have no gradient, unless they can be marginalised out or re-parameterised. For low-dimensional or easily factored posteriors, simpler samplers are usually adequate and cheaper per iteration. The No-U-Turn Sampler (NUTS), the default in Stan, removes the need to hand-tune the number of leapfrog steps L, which makes HMC practical without expert tuning.
Limitations and considerations
- Requires a continuous, differentiable log-posterior; models with discrete latent variables need marginalisation, re-parameterisation, or a hybrid sampler.
- Each leapfrog step requires a gradient of the full log-posterior, which is expensive for large datasets. Stochastic (mini-batch) gradients break the exact Metropolis correction and need specialised treatment.
- Performance depends strongly on the mass matrix M and the step size ε. Poorly scaled posteriors, such as strongly correlated or funnel-shaped geometries, often need re-parameterisation or better adaptation.
- The warm-up phase, in which ε and M are adapted, can be long for difficult geometries and can take a substantial share of the sampling budget.
Source conditions do not replace independent scientific review or validation by an analysis engine.
Strengths
- Gradient-guided proposals travel long distances through the posterior, which typically gives lower autocorrelation between draws than random-walk moves (The Elements of Statistical Learning, 2009, Sec. 11.9, p. 411).
- Because the Metropolis correction removes integration error, the chain targets the exact posterior regardless of the step size ε used in the leapfrog integrator.
- NUTS adapts the trajectory length automatically while keeping the same target distribution as HMC, so users do not need to tune L by hand.
- The random-walk problem becomes more severe as dimension grows, and gradient guidance is the mechanism that mitigates it, which is why HMC is widely used for high-dimensional models.
- Implemented and used in Stan, PyMC, NumPyro, and TensorFlow Probability, with convergence diagnostics such as R-hat and effective sample size available in common workflows.
Applications
- Hierarchical and multilevel models with correlated group-level parameters, where random-walk moves mix slowly.
- Latent variable and structural equation models with continuous latent factors.
- Pharmacokinetic and pharmacodynamic modelling with continuous, differentiable likelihoods.
- Gaussian process models with continuous hyperparameters, and posterior inference over Bayesian neural network weights.
- Parameter inference for physical models with differentiable likelihoods, wherever gradients of the log-likelihood are available.
- Compartmental epidemic models with continuous rate parameters fitted to case data.
How it works
How it works
HMC augments the target parameter vector θ with an auxiliary momentum vector r, drawn independently from a zero-mean Gaussian with mass matrix M. The joint density of (θ, r) corresponds to a Hamiltonian H = U(θ) + K(r), where the potential energy U(θ) = −log p(θ|y) is the negative log-posterior and the kinetic energy K(r) = ½ r⊤M⁻¹r is quadratic. Integrating out r leaves the original posterior on θ unchanged.
Formula
H(\theta, r) = U(\theta) + K(r) = -\log p(\theta \mid y) + \frac{1}{2}r^\top M^{-1} rA proposal (θ*, r*) is generated by numerically integrating Hamilton's equations with the leapfrog (Störmer–Verlet) integrator. The first half-step updates the momentum using the gradient of U at the current position. This gradient is the only derivative of the log-posterior needed per step.
Formula
r_{t+\epsilon/2} = r_t - \frac{\epsilon}{2}\,\nabla_\theta U(\theta_t)The second sub-step of the leapfrog integrator advances the position by a full step ε in the direction of the current momentum, scaled by the inverse mass matrix. Repeating the half-momentum and full-position updates for L steps traces a trajectory over the energy surface.
Formula
\theta_{t+\epsilon} = \theta_t + \epsilon\, M^{-1} r_{t+\epsilon/2}The leapfrog cycle closes with a final half-step momentum update using the gradient at the newly proposed position. Leapfrog integration is time-reversible and volume-preserving, which are the properties that make the proposal map suitable for detailed balance. Exactness, however, comes from the accept step below, because the integrator is only approximate and its numerical error must be corrected.
Formula
r_{t+\epsilon} = r_{t+\epsilon/2} - \frac{\epsilon}{2}\,\nabla_\theta U(\theta_{t+\epsilon})After L leapfrog steps, the proposal (θ*, r*) is accepted or rejected with a Metropolis probability that corrects for the integration error. When ε is small the Hamiltonian is nearly conserved and acceptance is high; in practice ε and L (or the equivalent tree depth in NUTS) are adapted during warm-up so that the average acceptance rate is high but the trajectories remain long enough to explore efficiently.
Formula
\alpha = \min\!\left(1,\; \exp\!\bigl[-H(\theta^*, r^*)\bigr + H(\theta_t, r_t)\bigr]\right)
Common pitfalls
- Ignoring convergence diagnostics. R-hat values above 1.01, or low bulk or tail effective sample sizes, indicate that the chains have not mixed and that posterior summaries are unreliable.
- Skipping posterior predictive checks. HMC gives valid draws from the posterior it is given, but if the model is misspecified the posterior is wrong no matter how well the sampler performs.
- Running chains with too little warm-up, especially when the mass matrix is far from the posterior covariance.
- Applying HMC to models with discrete parameters without marginalising them out or re-parameterising, which breaks the gradient computation.
- Treating divergent transitions as a bug to suppress rather than a signal. Divergences usually mean that the step size is too large for a high-curvature region of the posterior, which calls for a change in parameterisation, not only a smaller step size.
Frequently asked questions
What is the difference between HMC and the Metropolis–Hastings algorithm?
Both are MCMC algorithms that build a Markov chain converging to the target posterior, and both use a Metropolis acceptance step. They differ in how proposals are generated. A basic Metropolis–Hastings sampler proposes a random-walk move around the current state, which in high dimensions gives slow, diffusive exploration and high autocorrelation. HMC uses the gradient of the log-posterior to guide proposals along near-constant-energy trajectories, producing distant proposals that are still likely to be accepted. The acceptance step in HMC corrects for numerical integration error, so it targets the exact posterior.
What is NUTS and how does it relate to HMC?
The No-U-Turn Sampler (NUTS) is an adaptive extension of HMC. It chooses the number of leapfrog steps automatically by building a binary tree of trajectory segments and stopping when the trajectory starts to double back on itself, the so-called U-turn condition. This removes the need to set the number of steps L by hand, which is the most sensitive HMC tuning choice. NUTS is the default sampler in Stan.
What do divergent transitions mean and what should I do about them?
A divergent transition occurs when the leapfrog integrator makes a large numerical error, usually because the trajectory enters a region of very high curvature in the posterior. This means the step size is too large for the local geometry, and the sampler may not be exploring that part of the posterior faithfully. Reducing the step size can hide the symptom, but the underlying geometric problem usually remains. A more reliable remedy is to re-parameterise the model, for example with a non-centred parameterisation for hierarchical models.
Can HMC be used with discrete parameters?
Standard HMC requires gradients and so cannot be applied directly to discrete parameters. The usual approach is to marginalise discrete parameters out of the model analytically before sampling, which Stan requires. Some frameworks combine discrete updates, such as Gibbs steps, with NUTS for the continuous parameters. PyMC supports this kind of mixed sampling.
How do I judge whether a run has converged?
Check the convergence diagnostics before interpreting any posterior summary. R-hat values above 1.01 indicate that the chains have not mixed, so the run should be extended or reconsidered. Check that bulk and tail effective sample sizes are large enough for the quantities you report, particularly tail quantiles and credible interval endpoints. Count divergent transitions and treat any non-zero count as a signal to investigate rather than a number to ignore. Adaptation aims for a high average acceptance rate during warm-up; if adaptation has not settled, lengthen warm-up or revisit the parameterisation, since poorly scaled or strongly correlated posteriors are the usual cause. Posterior predictive checks then assess whether the fitted model is adequate for the data.
Related methods
Sources
Duane, S., Kennedy, A. D., Pendleton, B. J., & Roweth, D. (1987). Hybrid Monte Carlo. Physics Letters B, 195(2), 216–222.
Open DOI referenceNeal, R. M. (2011). MCMC using Hamiltonian dynamics. In S. Brooks, A. Gelman, G. L. Jones, & X.-L. Meng (Eds.), Handbook of Markov Chain Monte Carlo (pp. 116–162). Chapman and Hall/CRC.
Open publication reference ISBN: 978-1420079418Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., & Rubin, D. B. (2013). Bayesian Data Analysis (3rd ed.). CRC Press.
ISBN: 978-1439840955The Elements of Statistical Learning (2009), Sec. 11.9, p. 411