Hamiltonian Monte Carlo and diagnostics
Use auxiliary momentum and reversible integration while interpreting divergences, rank diagnostics, ESS, and Monte Carlo error.
On this page
The question for today
What you’ll understand
- Explain why auxiliary momentum leaves the target position marginal unchanged.
- Calculate one leapfrog proposal and its energy correction.
- Interpret HMC diagnostics as evidence rather than a proof of convergence.
Random-walk proposals can waste effort taking small, directionless steps through a high-dimensional posterior. Hamiltonian Monte Carlo adds an auxiliary momentum and uses gradients to construct longer coordinated proposals. Its mathematical foundation combines an augmented target, structured numerical integration, and a probability correction. Good performance still depends on posterior geometry and tuning. A smooth-looking trajectory or reassuring acceptance rate cannot establish that all relevant regions were explored, so computation must be accompanied by diagnostics targeted at both numerical and statistical failure.
Augment without changing the position target
For a positive differentiable target on unconstrained coordinates , define potential and introduce Gaussian momentum with positive-definite mass matrix . The joint density is proportional to , where kinetic energy is quadratic in momentum. Integrating momentum leaves the desired position marginal because its Gaussian normalizer is constant in position. Constraints require valid coordinate transforms and the associated Jacobian terms; gradients of an incorrectly transformed density faithfully explore the wrong target.
For a twice continuously differentiable potential, exact Hamiltonian flow conserves energy and phase-space volume along trajectories that exist within its domain. It moves along an energy surface, so flow alone does not sample the entire augmented distribution. Momentum refreshment and a valid trajectory proposal rule are essential parts of a sampler. A nontrivial mass matrix changes movement through differently scaled directions without changing the intended position marginal when incorporated consistently. Multimodality, narrow necks, and strongly varying curvature can remain difficult even with exact gradients.
Leapfrog needs a correction
Leapfrog alternates half a momentum update, a full position update, and another half momentum update. For differentiable potential and constant mass, the exact-arithmetic map is reversible after momentum reversal and preserves volume. It does not conserve the Hamiltonian exactly. A standard fixed-length HMC proposal therefore receives a Metropolis acceptance probability based on the change in Hamiltonian. Ignoring this correction generally leaves discretization bias. Floating-point computation also calls for numerical checks rather than interpreting the exact-arithmetic derivation as an implementation guarantee.
Large step sizes can cause inaccurate trajectories or numerical divergence, especially where curvature changes rapidly. Very small step sizes cost more gradient evaluations for the same travel time. Integration length also matters: repeatedly returning near a starting point wastes proposals. The No-U-Turn Sampler adapts trajectory construction using a valid sampling procedure; it is not equivalent to stopping an arbitrary trajectory whenever a picture looks close to a turn. Warmup adaptation learns scales and step sizes, after which retained sampling follows the specified algorithm.
Read several diagnostics together
Divergent transitions warn that the numerical trajectory encountered problematic geometry and can indicate biased exploration; inspecting where they occur can suggest reparameterization or stronger modeling constraints. Maximum tree-depth warnings primarily indicate potentially inefficient trajectory truncation and need separate interpretation. Rank-normalized split R-hat compares multiple chains and parts of chains; values near one support agreement for examined quantities but cannot reveal every shared failure, such as all chains remaining in one missed-mode basin.
Bulk and tail effective sample sizes address different summaries, and Monte Carlo standard error should be small enough for the intended decision. A posterior standard deviation measures substantive uncertainty, not simulation accuracy. Inspect parameter combinations and scientifically relevant predictions in addition to individual coordinates, since a hard-to-explore direction can hide in a projection. Diagnostics should be interpreted with traces, initialization, model structure, and numerical warnings. Finite diagnostic success is evidence about the run, not a mathematical proof that the chain converged or that the model is calibrated for reality.
Work it through
One leapfrog step for a standard normal
Let U(q)=q²/2, mass M=1, initial q=1 and momentum p=0. Take one leapfrog step of size 0.5. Calculate the new state, energy change, and acceptance probability.
The initial potential gradient is one. The first half momentum step gives p_half=0−0.25 times 1=−0.25. The full position step gives q_new=1+0.5 times (−0.25)=0.875.
The new gradient is 0.875. The final half momentum step gives p_new=−0.25−0.25 times 0.875=−0.46875. The initial Hamiltonian is 0.5.
The new Hamiltonian is (0.875²+0.46875²)/2=0.49267578125. The energy change is −0.00732421875, so exp(H_old−H_new) exceeds one and the Metropolis acceptance probability is one. This particular downward energy error does not mean leapfrog is exact.
The proposal is (q,p)=(0.875,−0.46875), with a nonzero energy error and acceptance one for this step. A valid HMC transition also includes its momentum and proposal construction rules.
The living notebook
Explore the model
Interactive lab · oscillator
Hamiltonian position motion versus damping
Pause and Reset, then set both controls to damping ratio ζ=0 and natural frequency ω₀=1. The position is cos(t), starting at one with zero velocity; predict cos(1)≈0.5403 after two Steps. Reset and set ζ=0.50 and ω₀=1, then compare later oscillation amplitudes. The damped curve loses energy and is not Hamiltonian target-preserving flow. This instrument is an exact oscillator illustration, not an HMC sampler.
- Displacement x(t)
- 1
- Velocity v(t)
- 0
- Regime
- underdamped
Unit mass, x(0) = 1 and v(0) = 0. The analytic solution includes underdamped, critically damped and overdamped cases; time is measured in seconds. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.
Look forConservative dynamics inspire HMC proposals; damping toward a mode would not itself preserve a posterior distribution.
Pause & reason
Check your understanding
Your turn
Try it yourself
For the same standard-normal potential and unit mass, start at q=0, p=1 and use one leapfrog step with size 1. Find the proposal energy change and acceptance probability.
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
The first position gradient is zero, but the gradient after the position update is not. Compare total potential plus kinetic energies.
Compare with the solution
The first half momentum update leaves p_half=1. The position becomes q_new=0+1 times 1=1. The final momentum is p_new=1−0.5 times 1=0.5. Initial energy is (0²+1²)/2=0.5; final energy is (1²+0.5²)/2=0.625. The increase is 0.125, so acceptance is exp(−0.125), approximately 0.8825. Rejecting with the complementary probability is part of preserving the augmented target, rather than a nuisance to erase from the recorded chain.
Keep the idea
Take it with you
- Auxiliary Gaussian momentum preserves the target position marginal.
- Reversible volume-preserving integration still needs energy correction for discretization error.
- R-hat, ESS, Monte Carlo error, and numerical warnings provide complementary finite-run evidence.
Read further
Original sources and deeper explanations to follow at your own pace.
Optional progress, saved in this browser when available. Revisit any lesson at any time.
Lesson not marked complete.