You're fitting a model with two parameters that can compensate for each other. Many combinations fit the observations, so their posterior distribution forms a long, narrow region. A sampler taking random steps has to move cautiously across its width, which leaves it slow to explore its length. The Gibbs and slice sampling post showed how severe that slowdown can be. Hamiltonian Monte Carlo uses the slope of the log-density and an added momentum variable to follow a trajectory through the region, making longer proposals possible.
We build a NumPy leapfrog integrator for longer moves through the region. HMC gives 0.391 effective samples per draw, against roughly 0.009 for Metropolis and Gibbs and 0.008 for slice. Charging for work reduces the advantage to 3.6 times; HMC is worst on the uncorrelated target.
The narrowest direction caps step size while the widest sets trajectory length. An 11% step-size increase costs 18x in efficiency. A 60-step trajectory is 1,435 times less efficient than 18 steps. We add Metropolis correction and divergence checks.
Let's Build It
Open this in Google Colab and run it top to bottom. Everything here is small NumPy with gradients derived by hand, measured in seconds.
The whole sampler is the integrator plus an accept step. Here is the integrator.
import numpy as np
def leapfrog(z, p, grad, eps, L):
"""Half a momentum kick, L position drifts, half a kick. Returns the endpoint."""
p = p + 0.5 * eps * grad(z)
for k in range(L):
z = z + eps * p
if k < L - 1:
p = p + eps * grad(z)
p = p + 0.5 * eps * grad(z)
return z, p
And here is everything else.
def hmc(logp, grad, n, eps, L, rng, d=2):
z = np.zeros(d)
out = np.empty((n, d))
accepted = 0
for i in range(n):
p = rng.standard_normal(d) # fresh momentum, every iteration
h0 = -logp(z) + 0.5 * p @ p # potential + kinetic
z_new, p_new = leapfrog(z, p, grad, eps, L)
h1 = -logp(z_new) + 0.5 * p_new @ p_new
if np.log(rng.random()) < h0 - h1: # correct the integrator's error
z, accepted = z_new, accepted + 1
out[i] = z
return out, accepted / n
Run it on the target from the previous post, with . The gradient of a Gaussian log-density is one matrix multiply.
cov = np.array([[1.0, 0.99], [0.99, 1.0]])
prec = np.linalg.inv(cov)
logp = lambda z: -0.5 * z @ prec @ z
grad = lambda z: -prec @ z
draws, acc = hmc(logp, grad, 20000, eps=0.15, L=18, rng=np.random.default_rng(0))
print(f"acceptance {acc:.2f} ESS {ess(draws[:, 0]):.0f} from {len(draws)} draws")
acceptance 0.79 ESS 20000 from 20000 draws
Every number in this post is an effective sample size, so here is the estimator, the initial-positive-sequence one that Stan reports. It sums the autocorrelations in adjacent pairs and stops at the first non-positive pair, which keeps it stable in the tail where those autocorrelations are noise.
def ess(x):
n = len(x)
x = x - x.mean()
f = np.fft.rfft(x, 2 * n)
acf = np.fft.irfft(f * np.conjugate(f))[:n].real
if acf[0] <= 0:
return 0.0 # a chain that never moved is not a well mixed one
acf /= acf[0]
t, total = 1, 0.0
while t + 1 < n and acf[t] + acf[t + 1] > 0:
total += acf[t] + acf[t + 1]
t += 2
return n / (1.0 + 2.0 * total)
Twenty thousand effective samples from twenty thousand draws is the estimator's ceiling rather than a miracle, and the section on trajectory length below is about why that reading needs care.

Each teal path is one proposal. Eighteen leapfrog steps carry the sampler from one end of the ridge to the other, and the endpoint is accepted four times in five. A random-walk proposal large enough to make that move would be rejected almost always, because it would leave the ridge sideways.

Three hundred draws each, both tuned. Metropolis covers a third of the ridge and yields 3 effective samples. HMC covers all of it and yields 117.
What Just Happened?
Momentum, and why it is free
Sampling from is hard. HMC samples from a bigger distribution instead, over and an invented momentum of the same dimension:
is the potential energy, and setting it to the negative log-density is what makes the rest work: the target becomes a surface, and the regions it puts most probability on become its valleys. is ordinary kinetic energy from a standard Gaussian momentum.
The joint factorises, , and that is what makes the momentum free. Draw from the joint, throw the momentum away, and what remains is a draw from exactly. The momentum exists only to carry the sampler somewhere, and it is redrawn from scratch every iteration, which is what stops the chain circling one energy level forever.
The dynamics, and what conserves what
Hamilton's equations move the pair:
Follow them exactly and never changes, so never changes either, and every point on the trajectory is as good a draw as the starting point. That is the promise: move as far as you like for free. Post 78 uses the same conserved quantity for a different purpose, learning from data rather than deriving it from a posterior.
Exactly is the problem. You cannot follow the equations exactly, so you discretise, and the discretisation decides everything.
Leapfrog against Euler
Explicit Euler updates position and momentum from the same old state. Leapfrog interleaves them, half a momentum step around each full position step. Both are first-order pieces of arithmetic and both look equally reasonable written down. They are not equally reasonable.

Over 200 steps at , leapfrog's energy error never exceeds 0.074 and does not trend. Euler's passes . Leapfrog is symplectic: it exactly conserves a slightly wrong energy rather than approximately conserving the right one, so its error oscillates within a bound instead of accumulating. Euler has no such property and spirals off the level set on the first pass.
This matters because the acceptance probability is . A bounded energy error is a bounded rejection rate no matter how long the trajectory. An accumulating one means acceptance decays to zero with trajectory length, which removes the only reason to use the method.
The Metropolis correction
Leapfrog is not exact, so the sampler would target the wrong distribution if it stopped there. The accept step repairs it:
if np.log(rng.random()) < h0 - h1:
Leapfrog is reversible and volume-preserving, so this is an ordinary Metropolis acceptance with a symmetric proposal, and it makes the sampler exact for any step size that does not blow up. The integration error does not bias the answer. It only costs acceptance, and that is the trade the next section prices.
The First Cliff: Step Size
The step size is bounded by the tightest direction in the target, and the bound is sharp. For a Gaussian, leapfrog on the eigendirection with eigenvalue is a harmonic oscillator of frequency , and the integrator is stable only while
For the eigenvalues are 1.99 and 0.01, so the limit is exactly. Sweeping the step size and measuring:

eps acceptance divergent ESS per gradient
0.15 0.829 0.000 0.0304
0.18 0.667 0.000 0.0338
0.20 0.114 0.074 0.0019
0.22 0.031 0.793 0.0001
The best step size in the sweep sits at 0.18, just under the limit. Raise it by 11% to 0.20 and efficiency falls by a factor of 18. Raise it another 10% and four transitions in five are diverging. There is no gentle degradation to warn you, because there is no gentle degradation in the underlying instability: below the threshold the oscillator is integrated stably forever, above it the energy grows geometrically in the number of steps.
A divergence is that instability caught in the act. When comes back enormous or non-finite, the trajectory has fallen off the energy level rather than moved along it, and the transition is reported rather than merely rejected. Stan flags , which is the threshold used here.
The Second Cliff: Trajectory Length
The step size is capped by the tightest direction. The trajectory has to be long enough to cross the loosest. Those are the same two eigenvalues pulling in opposite directions, and their ratio is the condition number, 199 here.
Along the long axis the trajectory is a harmonic oscillator with period in time, which at is leapfrog steps. A quarter of that, 14.8 steps, moves the sampler from one end of the ridge to the middle, which is the most decorrelating move available. A full period returns it to where it started.

The right panel is the mechanism drawn directly. The lag-1 autocorrelation starts at +0.991 for , crosses zero at the predicted quarter period, reaches −0.79 near the half period where consecutive draws land on opposite sides of the target, and returns to +0.994 at , where the trajectory has completed one orbit and handed back the point it was given.
L lag-1 ESS per gradient
18 -0.060 0.052632
40 -0.090 0.024390
60 +0.994 0.000037
Between the best and worst settings there is a factor of 1,435, and the surface is not unimodal: is perfectly good, is seven times worse, is ruinous. You cannot tune this knob by hill-climbing from a bad starting point, because the hill has a comb of resonances in it. That is the argument for the No-U-Turn Sampler, which grows the trajectory until it starts doubling back and so never has to be told a length at all.
Drawing fresh from each iteration is the cheap defence, and it is instructive about what it costs:
acceptance ESS per draw ESS per gradient lag-1
fixed L = 20 0.838 1.000 0.0476 -0.289
L jittered 1-20 0.830 0.391 0.0338 +0.462
Jittering is 29% worse here, because a well chosen fixed produces an antithetic chain whose draws are better than independent. It is worth paying because the alternative is a 1,435x hole one bad guess away. Note also what the fixed- row does to the diagnostic: an ESS of exactly one per draw with a lag-1 autocorrelation of −0.289. The estimator truncates its sum at the first non-positive pair of autocorrelations and so caps at the number of draws, which is correct behaviour and still not what you want to read in a report.
Four Samplers, Two Currencies
Post 62 ran Metropolis, Gibbs and slice on this target at four correlation levels and found all three collapsing together. Adding HMC, with every competitor's own tuning parameter chosen by a pilot sweep so none of them is a strawman:

ESS per draw ESS per target evaluation
ρ=0 ρ=0.9 ρ=0.99 ρ=0 ρ=0.9 ρ=0.99
HMC 1.000 1.000 0.391 0.087 0.087 0.034
MH 0.136 0.036 0.009 0.136 0.036 0.009
Gibbs 0.861 0.095 0.009 0.430 0.048 0.005
slice 1.000 0.110 0.008 0.047 0.009 0.001
Per draw the story is the one the method is sold on. Going from an uncorrelated target to costs HMC a factor of 2.6 and costs slice a factor of 125.
Per unit of work it is more interesting, and less flattering. Each sampler is charged for what it spends: Metropolis one log-density evaluation per proposal, slice one per stepping-out and shrinkage probe, Gibbs two Gaussian draws per cycle, HMC one gradient per leapfrog step. On that axis HMC's win at shrinks to 3.6x over Metropolis, and at HMC is the worst of the four, five times behind Gibbs. Every gradient it spends walking a trajectory is a gradient Gibbs did not need, and on a target with no correlation there was nothing to walk around.
That is the honest summary of when to reach for it. HMC does not buy speed. It buys insensitivity to correlation, and it charges a fixed toll of gradients per draw whether or not there is any correlation to be insensitive to.
A Real Posterior
Toy Gaussians are where the theory is checkable. Here is what the same thing looks like when the correlation arrives on its own. Bayesian logistic regression on the Wisconsin breast-cancer data, 569 rows, using the first four predictors, of which mean radius and mean perimeter correlate at 0.998 because one is very nearly a linear function of the other. Collinear predictors produce a posterior ridge in exactly the way the toy target was constructed to.
def logistic_posterior(X, y, prior_sd=5.0):
def logp(b):
e = X @ b
return float(y @ e - np.logaddexp(0, e).sum() - 0.5 * (b @ b) / prior_sd**2)
def grad(b):
return X.T @ (y - 1.0 / (1.0 + np.exp(-X @ b))) - b / prior_sd**2
return logp, grad

The reference is the posterior mode with a Laplace covariance, computed by optimisation and so independent of both samplers.
Laplace mode HMC mean MH mean MH, 10x budget
mean radius 11.869 12.003 -0.264 7.742
mean perimeter -14.791 -14.920 -3.247 -10.938
HMC agrees with the reference on every coefficient to well within a tenth of a posterior standard deviation. Metropolis, given the same 6,000 post-burn-in draws and its own tuned step size, returns −0.264 for a coefficient whose true value is +11.9. It has the sign wrong. Worse, it reports a standard deviation of 0.394 where the truth is 3.03, so its interval is 7.7 times too narrow and excludes the right answer comfortably. Ten times the budget moves it to +7.742 and it is still not there, with an effective sample size of 4 on the coefficients that matter.
This is the case that should change how you read a trace plot. Metropolis is not slow here in a way that shows up as visible wandering. It is confidently, quietly wrong, and its own uncertainty estimate is the thing most wrong about it.
Two Failure Modes
Neal's funnel
The funnel is the standard counter-example, and it is not artificial: it is the shape every hierarchical model takes in its centred parameterisation. Let and . The width of the distribution varies by a factor of across the plausible range of , so no single step size fits the whole geometry. Large steps are stable in the mouth and unstable in the neck.

eps divergent recovered sd of v deepest v reached
0.60 7.150% 1.983 -2.71
0.30 0.037% 2.135 -3.52
0.15 0.000% 2.258 -4.77
0.05 0.000% 2.434 -6.95
(The figure annotates a separate 6,000-draw run at the same step size, which stopped at −2.16.) Two things to take from that table. The divergences do what they are supposed to: at they fire on 7% of transitions and they cluster in the neck, which is precisely where the answer is wrong. And the harder lesson, zero divergences is not a clean bill of health. At nothing diverges at all and the recovered standard deviation is 2.26 against a true 3.00, because the sampler simply never reaches the neck to have trouble there. A diagnostic that fires tells you something is wrong. A diagnostic that stays silent tells you nothing.
The real fix is not a smaller step size but a different parameterisation. Sample and set , and the funnel becomes a product of independent standard normals with no neck in it at all. Every practical treatment of hierarchical models in PyMC reaches for that reparameterisation for this reason.
Discrete parameters
The gradient is the whole method, so a parameter with no gradient has no HMC. A mixture-component indicator, a variable-selection flag, a change point on a discrete grid: none of them can be moved by Hamiltonian dynamics. PyMC dispatches such variables to a different sampler and runs the two in alternation, which is why the earthquake mixture model needs Metropolis or Gibbs somewhere in the loop no matter what the continuous parameters get. The standard alternative is to integrate the discrete variable out analytically where the model allows it, leaving a fully continuous target.
Going Deeper
The two knobs are one number
Both cliffs come from the same place. The step size is capped by and the useful trajectory length is about a quarter period, . Put the cap into the length:
The number of gradient evaluations per independent draw grows with the square root of the condition number. For that predicts about 11 leapfrog steps, and the measured optimum was 18. Random-walk Metropolis on the same target needs steps rather than , which is the whole advantage stated in one line, and it is an advantage that disappears as .
The practical reading is that HMC pays for correlation with a square root instead of a linear factor, and that a mass matrix which whitens the target reduces directly. That is what Stan's warmup is doing when it estimates a diagonal or dense metric: it is not tuning the sampler so much as changing the geometry the sampler has to walk.
Acceptance rate targets
The optimal acceptance rate for HMC is about 0.65, from Beskos and colleagues, against 0.234 for random-walk Metropolis. The two numbers come from opposite pressures. A random walk wants a large step and pays in rejection; HMC's step is capped by stability instead, so it should be run near the cap and there is no benefit in rejecting more. The sweep above is consistent with that: the best setting sat at 0.667 acceptance, and everything above it fell off the cliff.
A frozen chain scores perfectly
One implementation warning, because it cost a run here. At on the logistic posterior the sampler rejected every proposal and the chain never moved. A constant chain has zero variance and no autocorrelation to measure, so an autocorrelation-based ESS estimator will happily report one effective sample per draw. A naive tuning sweep that maximises ESS therefore picks the step size that breaks the sampler completely.
if acf[0] <= 0:
return 0.0 # a chain that never moved is not a perfectly mixed one
Guard the tuning objective on acceptance and divergence as well as on ESS, and read the acceptance rate before you read anything else.
Split conformal for the variance, HMC for the shape
The samplers here all report a posterior. If what you need is an interval with a coverage guarantee rather than a posterior, the assumptions are different and so is the method: see the conformal prediction post, which gets a coverage rate out of any model with no distributional assumption at all, and no gradient.
Where This Comes From
Duane, Kennedy, Pendleton and Roweth introduced the algorithm as "Hybrid Monte Carlo" in a 1987 Physics Letters B paper, combining molecular dynamics with a Metropolis accept step for lattice field theory. The statistics literature took roughly a decade to notice, and the name drifted to Hamiltonian Monte Carlo along the way.
Neal's chapter "MCMC using Hamiltonian dynamics" (2011) is the reference treatment and the source of most of what is above: the leapfrog analysis, the stability threshold verified numerically here, the against scaling, and the recommendation to randomise the trajectory length to avoid exactly the resonance measured in this post.
Hoffman and Gelman's "The No-U-Turn Sampler" (2014) removes the trajectory-length knob by doubling the trajectory until it starts to double back, and adds dual averaging to tune the step size during warmup. It is the reason a modern probabilistic programming language asks you for neither number.
Betancourt's "A Conceptual Introduction to Hamiltonian Monte Carlo" (2017) is the geometric account, and the source of the modern reading of divergences: they are not a numerical nuisance but a signal that the target's curvature has outrun the integrator, which is why they concentrate in the funnel's neck rather than scattering at random.
Neal's "Slice Sampling" (2003) supplies both the funnel used above and the slice sampler measured against HMC, and Beskos, Pillai, Roberts, Sanz-Serna and Stuart's "Optimal tuning of the hybrid Monte Carlo algorithm" (2013) is where the 0.65 acceptance target comes from.
Interactive Tools
- Markov Chain Simulator: watch a chain's transition structure decide how fast it forgets where it started, which is what effective sample size measures.
- Distribution Explorer: the Gaussian momentum, the target's marginals, and the shape of the funnel's log-normal conditional.
- Gradient Descent Visualizer: the same gradient field HMC rolls across, used for the other purpose, and the same step-size instability.
Related Posts
- Gibbs and Slice Sampling: Two Cures for Random-Walk MCMC: the post that measured the collapse this one escapes, on the same target, and promised this sequel.
- MCMC Island Hopping: A Metropolis-Hastings Guide: where the accept step comes from, in its original random-walk setting.
- Sampling Methods Compared: Inverse-CDF, Rejection, Importance: what to reach for when the target is simple enough not to need a chain.
- Hamiltonian Neural Networks: Physics as Inductive Bias: the same conserved quantity, learned from data instead of derived from a posterior.
- Approximate Inference: From MCMC to Variational Bayes: the other direction to go when gradients are available and exactness is negotiable.
- Hierarchical Bayesian Regression with PyMC: When Groups Share Strength: the models whose centred parameterisation produces the funnel measured above.






