Hamiltonian Monte Carlo (HMC) is a Markov chain Monte Carlo method that proposes new samples by simulating the motion of a particle across the negative log-density surface of a target distribution, using gradient information to make long, well-directed moves. Among probabilistic models, it is a standard tool for drawing samples from posterior distributions in Bayesian inference, especially when the posterior has many continuous parameters. The method is also known as hybrid Monte Carlo, its original name from lattice physics.
Compared with random-walk samplers, HMC explores high-dimensional spaces with far less autocorrelation per sample. The price is that it needs a differentiable log-density and careful tuning of two parameters, which is why modern libraries pair it with automatic differentiation and adaptive schemes.
How Hamiltonian Monte Carlo generates proposals
HMC generates proposals by treating the parameters as the position of a particle and adding an auxiliary momentum variable of the same dimension. The potential energy is the negative log posterior density, and the kinetic energy is a quadratic function of the momentum, so the total energy forms a Hamiltonian function.
- Resample momentum from a Gaussian distribution, usually with a mass matrix as covariance.
- Simulate Hamiltonian dynamics for L steps of size epsilon with the leapfrog integrator.
- Compute the energy change between the start and the end of the trajectory.
- Accept or reject the endpoint with a Metropolis probability based on that energy change.
The leapfrog integrator alternates half steps in momentum with full steps in position. It is volume-preserving and time-reversible, two properties that keep the Metropolis correction valid. Because exact dynamics would conserve energy, the acceptance rate stays high when the integration error is small, even for proposals far from the starting point.
Tuning parameters and diagnostics
HMC performance depends mainly on step size, trajectory length and the mass matrix. Poor values either waste gradient evaluations or produce chains that reject most proposals.
The table below summarizes the key tuning parameters, their typical settings and what happens when each is set badly. Exact values depend on the geometry of the specific posterior.
| Parameter | Role | Typical setting | Effect of a poor choice |
|---|---|---|---|
| Step size (epsilon) | Resolution of the leapfrog integrator | Adapted to reach about 0.65 to 0.8 acceptance | Too large causes rejections and divergences |
| Number of steps (L) | Length of each trajectory | Tens to hundreds of steps | Too short behaves like a random walk |
| Mass matrix | Rescales parameter dimensions | Diagonal or dense, estimated in warm-up | Poor scaling forces a tiny step size |
| Warm-up length | Period for adaptation | Often 500 to 1,000 iterations | Too short leaves parameters untuned |
HMC also offers unusually informative diagnostics. A divergent transition occurs when the simulated energy explodes, which signals a region of high curvature that the sampler cannot explore reliably. Practitioners also monitor the split R-hat statistic, the effective sample size and the energy Bayesian fraction of missing information.
How HMC compares with other MCMC methods
HMC differs from older MCMC methods by using gradients to move coherently instead of proposing blind local steps. The comparison below places it alongside its neighbors in the same family of samplers.
| Method | Proposal mechanism | Needs gradients | Scaling with dimension |
|---|---|---|---|
| Random-walk Metropolis-Hastings | Small random perturbation | No | Poor, steps shrink as dimension grows |
| Gibbs sampling | Draws each block from its conditional | No | Slow with strongly correlated parameters |
| Hamiltonian Monte Carlo | Simulated physical trajectory | Yes | Good, cost grows roughly as d to the 5/4 |
| No-U-Turn Sampler | HMC with automatic trajectory length | Yes | Good, with less manual tuning |
| Langevin methods (MALA) | One gradient-informed step | Yes | Better than random walk, worse than HMC |
The No-U-Turn Sampler is an extension of HMC that chooses the trajectory length automatically by stopping when the path starts to double back. It is the default sampler in Stan and PyMC, so most practitioners who use HMC today actually run this variant. Variational inference offers a faster but approximate alternative when exact sampling is too expensive.
When to use Hamiltonian Monte Carlo
HMC is the preferred choice for Bayesian models with many continuous parameters and a smooth, differentiable posterior. It is less suitable when the model contains discrete latent variables or when the data set is so large that each full gradient is costly.
| Situation | Recommended approach | Reason |
|---|---|---|
| Hierarchical regression, hundreds of parameters | HMC or NUTS | Efficient exploration of correlated posteriors |
| Discrete latent variables | Marginalize them, or use Gibbs steps | HMC cannot move on discrete spaces |
| Millions of observations | Stochastic variational inference | Full-batch gradients become too expensive |
| Multimodal posterior | HMC with tempering or multiple chains | Trajectories rarely cross deep energy barriers |
| Funnel-shaped hierarchical prior | HMC with non-centered parameterization | Removes the curvature that causes divergences |
Limitations and common mistakes
The main limitation of HMC is its dependence on posterior geometry. Regions of sharply varying curvature, such as the neck of a hierarchical funnel, force a single step size to be either too large for one region or too small for another.
- Ignoring divergent transitions, which indicate that some posterior regions were not explored and the estimates may be biased.
- Constrained parameters without transformation: variances and probabilities must be mapped to an unconstrained space before sampling.
- Running one chain only, which hides convergence problems that several chains would reveal.
- Assuming HMC handles multimodality: it explores a single mode well but seldom jumps between separated modes.
- Expensive gradients: each leapfrog step needs a full gradient, so models with costly likelihoods can become slow.
Most of these problems are reparameterization issues rather than sampler failures. Rewriting the model, for example with non-centered priors or better scaling, usually resolves them more reliably than adjusting tuning parameters.
Explained without jargon
Imagine a landscape of hills and valleys. The low valleys are where the most likely answers lie. A statistician wants to visit places in proportion to how likely they are.
A simple method takes small random steps. It wanders slowly and often walks back over the same ground. Hamiltonian Monte Carlo works like a frictionless skateboard. It gives the board a random push and lets it roll along the slopes. The board travels far but still spends most time in the deep valleys.
The result is a faster and more reliable picture of uncertainty. The method needs to know the slope everywhere, so it works best when the landscape is smooth.
A typical use case
A public health team models hospital admission rates across 150 counties with a hierarchical Bayesian model. Each county has its own rate, and the rates share a common prior with an unknown spread. The model has more than 300 continuous parameters, and many of them are strongly correlated.
The team first tried a random-walk Metropolis sampler, which needed hundreds of thousands of iterations and still produced effective sample sizes below 50 for some parameters. They switched to the No-U-Turn variant of HMC with four chains of 2,000 iterations each. The first run reported several divergent transitions in the spread parameter, so they rewrote the county effects in a non-centered form.
After that change, the sampler finished in a few minutes with no divergences and R-hat values close to 1.00. The team could report credible intervals for each county with confidence that the posterior had been explored properly.