A blind random walk needs 400 steps of size 0.5 to get 10 units away. HMC follows the slope of log p, crosses in one trajectory, and still accepts about 99% of its moves.
Pick a sampler and press Run. Each one gets 120 moves on the same stretched target. Watch how much of the long axis each one reaches. Then we build HMC piece by piece: the score, momentum, leapfrog, the energy test, NUTS, and the Langevin family that powers diffusion models.
You need a little Python, what a gradient is, and the Metropolis accept rule from the MCMC lesson. We build the rest from zero.
Part of the Monte Carlo family: Monte Carlo, importance sampling, MCMC, then this lesson. The Field Guide lists the sources.
Illustrative toy, run live in your browser: a 2D normal with correlation 0.9, both chains start in the same corner. Random walk step 0.54; HMC step 0.19 with 11 leapfrog steps per move. Coverage counts which of 12 slices of the long axis the chain has visited.
Chapter 0
See why a blind sampler crawls, and which piece of information it ignores
You fit a Bayesian model with 200 weights. The Metropolis sampler from the MCMC lesson runs for an hour. Its trace plot circles one small region and never reaches the far side of the posterior.
Nothing is broken. A random walk proposes a step of fixed size in a random direction. The directions partly cancel, so the distance covered grows much slower than the number of steps.
Name the parts. Call the step size s and the number of steps N. Call the typical distance from the start after N steps dN, measured as a root mean square over many walkers.
d-N equals s times the square root of N.
Take the square root of the step count N. Multiply it by the step size s. That is how far the walker has typically got, d-N.
With made-up numbers: s = 0.5 and a target 10 units wide. For d-N = 10 you need √N = 10 / 0.5 = 20, so N = 400 steps. After 100 steps, d-N = 0.5 × 10 = 5: half the way for a quarter of the work.
Blue dots are the measured spread of 400 random walkers. Teal is a glider that moves s every step. Press Run, then change the step size.
Illustrative toy: 400 seeded walkers with normal steps of spread s, no target and no rejections. Real Metropolis walkers also reject moves, which makes them slower still.
A sampler that moves s per step in a steady direction crosses the same 10 units in 10 / 0.5 = 20 steps. That is the prize: 20 steps instead of 400.
In d dimensions a random step moves every coordinate, so its squared length is about d × s². To keep the jump from landing in empty space, s must shrink like 1/√d. We checked with seeded numpy on a standard normal: at d = 100, a step of 1 got 0 of 20,000 proposals accepted. A step of 0.1 got 62% accepted, and it crawls.
Roberts, Gelman and Gilks (1997) showed that the best tuned random walk in high dimension accepts about 23.4% of its proposals. Even at that best setting, it still spreads like √N.
The symptom is a trace plot of slow noise with long flat runs. To measure it, compute the effective sample size (Chapter 9). In our race, 10,000 random walk draws held the information of about 340 independent ones. The fix is not a bigger step. It is to stop walking blind and use the slope of log p.
Chapter 1
Compute the slope of log p, and see why the unknown constant drops out
The random walker cannot tell which way is uphill. You can: take the gradient of log p. It is a vector that points toward higher probability.
For most posteriors you know the density only up to a constant. You can compute p̃(x), the unnormalized density, but not the total Z that makes it sum to 1. So log p(x) = log p̃(x) − log Z. Z does not change with x, so its slope is zero.
Name the result. The score s(x) is the gradient of log p at the point x: the direction in which log p rises fastest, with its steepness.
s of x equals grad log p of x, which equals grad log p-tilde of x.
Take the log of the density you can compute, p-tilde. Find its slope along each coordinate. That vector is s of x, and Z never enters.
A normal with mean 2 and variance 4 has log p̃(x) = −(x − 2)² / 8, so s(x) = −(x − 2) / 4. At x = 5: s(5) = −3/4 = −0.75. The minus sign points back toward the mean at 2.
Physics uses the same object with the opposite sign. The potential energy is U(x) = −log p̃(x), so high probability is a low valley. The force −∇U(x) equals the score: it pushes the sample toward the valley floor.
The pink arrow is the score at the teal point. Drag the point anywhere. Then multiply p̃ by a constant c and watch the arrow.
Illustrative toy: a 2D normal with mean (0, 0), unit variances and correlation 0.5. Faint arrows show the score on a grid.
The symptom is a sampler that runs off to infinity. The usual cause is a sign: you returned ∇U, which points uphill in energy, instead of the score. To measure it, compare your gradient with a finite difference at a few points: (log p̃(x + h) − log p̃(x − h)) / (2h) with h = 0.00001. The fix is the sign, or automatic differentiation such as jax.grad.
Chapter 2
Add a velocity to the sample, and define the energy that it keeps
In 1987 Duane, Kennedy, Pendleton and Roweth needed to sample many variables in a lattice physics model. Their method, Hybrid Monte Carlo, treats the sample as a puck on a frictionless surface whose height is U. Statisticians now call it Hamiltonian Monte Carlo (HMC).
Call the puck's position q: it is your parameter vector. Give it a momentum p, drawn fresh from a standard normal. Momentum is a helper variable. You use it to travel, then throw it away.
The puck has two kinds of energy. The potential energy U(q) is its height. The kinetic energy p²/2 is the energy of motion for a unit mass. Their sum is the Hamiltonian H.
H of q and p equals U of q plus p squared over two.
Read the height U at the puck's position q. Add half the square of its momentum p. The total is H, and a frictionless puck keeps H fixed while it moves.
Target a standard normal, so U(q) = q²/2. Start at q = 1 with p = 0: H = 0.5 + 0 = 0.5. The exact motion is q = cos t, p = −sin t. At t = 1.57 (a quarter turn) the puck is at q = 0 with p = −1, so H = 0 + 0.5 = 0.5. The energy moved from height to speed.
Why is the helper allowed? The joint density exp(−H) splits into exp(−U(q)) times exp(−p²/2). The first factor is your target. The second is a standard normal on p. Sample the pair, drop p, and the q values follow your target exactly.
The bowl is U(q) = q²/2. Kick draws a new momentum. Roll runs the exact frictionless motion. The bar splits H into height and speed.
Illustrative toy: the exact motion of a unit mass in the bowl of a standard normal. Each kick is a seeded normal draw.
The symptom is a chain that only visits a ring of points at one energy level. The cause is reusing the old momentum. Exact motion never changes H, so only a fresh p moves the chain between levels. To measure it, plot H at each iteration: a flat line is the bug. The fix is a new standard normal p at the start of every iteration.
Chapter 3
Step the motion forward on a computer without letting the energy leak away
For a real posterior you cannot write the motion down. You step it forward in small time steps. Euler's method updates q and p from the slopes at the start of each step. In a bowl it spirals outward: the energy grows on every step.
The leapfrog step splits each move into three parts. Call the time step ε (epsilon), the slope of the energy at q ∇U(q), and the momentum halfway through the step p½.
p-half equals p minus epsilon over two times grad U of q. q-prime equals q plus epsilon times p-half. p-prime equals p-half minus epsilon over two times grad U of q-prime.
Kick the momentum p by half a step of force. Drift the position q a full step with p-half. Kick again by half a step, using the force at the new position q-prime.
Standard normal, so ∇U(q) = q. Take ε = 0.1 from (q, p) = (1, 1). p-half = 1 − 0.05 × 1 = 0.95. q-prime = 1 + 0.1 × 0.95 = 1.095. p-prime = 0.95 − 0.05 × 1.095 = 0.89525. H goes from 1.0 to 1.00025: an error of 0.00025.
Leapfrog is reversible: flip the momentum, run the same steps, and you land back at the start. It also keeps volume in the (q, p) plane. Together these keep its energy error small and bounded instead of growing. Chapter 4 needs both properties.
The yellow circle is the exact path in the (q, p) plane. Teal dots are leapfrog steps; red is Euler. Move ε and the step count.
Illustrative toy: U(q) = q²/2, start (1, 1). The page computes the read-out live; it matches the numpy check in the text.
The symptom is an acceptance rate that falls as trajectories get longer. The cause is a non-reversible integrator such as Euler. To measure it, track H along one trajectory. On this bowl Euler multiplies H by 1 + ε² every step, so at ε = 0.3 over 20 steps H grows from 1.0 to 5.6. Leapfrog ends within 0.006 of 1.0. The fix is leapfrog.
Chapter 4
Assemble one HMC iteration, and read the energy error as the accept test
One HMC iteration has three moves:
The test is the Metropolis rule from the MCMC lesson, applied to the pair (q, p) with target exp(−H). Leapfrog is reversible and keeps volume, so the proposal terms cancel and only energy is left. Call the energy change ΔH = H(q*, p*) − H(q, p).
alpha equals the minimum of one and e to the minus delta H.
Compute H at the start and at the end of the trajectory. Subtract to get delta H. If the energy went down, accept. If it went up, accept with chance e to the minus delta H.
Standard normal, start (1, 1), ε = 0.1, L = 10. The trajectory ends at (1.3827, −0.3007), so ΔH = 1.00114 − 1.0 = 0.00114 and α = 0.9989. Raise ε to 1.5: ΔH = 0.579 and α = 0.561.
Leapfrog nearly keeps H, so ΔH is near zero and long moves pass. Near is not exact: skip the test and the leftover error biases every sample.
Each Step draws a momentum (warm), rolls a teal trajectory, then accepts (green) or rejects (grey). Push ε past 0.9 to see divergences.
Illustrative toy: a 2D normal with correlation 0.8, so the narrowest standard deviation is 0.447 and leapfrog is stable only for ε below 0.894. Seeded draws.
On a normal with standard deviation σ, leapfrog is stable only while ε < 2σ. Past that, the energy grows on every step. On a standard normal from (1, 1) with L = 10, ε = 1.9 ends with ΔH = −0.18, and ε = 2.1 ends with ΔH = 183,730. Such a blow-up is a divergence. Stan and NumPyro count divergences and warn you.
The symptom is a "divergent transitions" warning and a chain that sticks. To measure it, count divergences per 1,000 iterations and note where they happen. The fix is a smaller ε, or a reshaped target (Chapter 6).
Chapter 5
Grow the trajectory until it starts to turn back, and stop there
HMC has two knobs: the step size ε and the step count L. ε has a target, the acceptance rate. L has none, and it is easy to get wrong.
Too short, and the puck barely leaves the start. Too long, and it orbits back. On a standard normal the puck goes round once every 2π ≈ 6.28 time units. With ε = 0.1, 63 steps from (1, 1) end at (1.02, 0.98): 63 gradients to move almost nowhere.
The No-U-Turn Sampler (NUTS) of Hoffman and Gelman (2014) chooses the length on every iteration. It doubles the trajectory, forward or backward in time at random, until the path starts to turn back. Call the back end q−, the front end q+, and the momentum at the front end p+.
q-plus minus q-minus, dot p-plus, is less than zero.
Draw the span from q-minus to q-plus. Take its dot product with the front momentum p-plus. If the result is below zero, the front is heading back toward the start, so stop.
With made-up numbers: q-minus = −0.5, q-plus = 1.3, p-plus = −0.4. The span is 1.8, and 1.8 × −0.4 = −0.72, below zero: stop. With p-plus = +0.4 the product is +0.72: keep doubling.
The full test also checks the back end with p−. After stopping, NUTS picks one point of the trajectory with a rule that keeps the chain exact. Stan still tunes ε during warmup to reach an average acceptance of 0.8, its default adapt_delta.
Grow doubles the path at one end. The grey arrow is the span; warm arrows are the end momenta. Auto grows until a dot product turns negative.
Illustrative toy: a 2D normal with correlation 0.6, ε = 0.2, a fixed sequence of directions. Real NUTS also checks every sub-tree and picks the sample with a weighted rule.
The symptom of a poor fit is Stan's "maximum treedepth" warning: NUTS hit 10 doublings, 1,023 leapfrog steps. To measure it, look at the tree depth per iteration. The fix is usually geometry, which is the next chapter.
Chapter 6
See why a long thin target costs more, and rescale it with a mass matrix
Suppose the posterior is a long thin oval: standard deviation 10 along one axis and 1 along the other. The limit ε < 2σ holds in every direction. So the narrow direction caps the step: ε < 2.
The puck must still travel the long axis. Half an orbit along an axis with standard deviation σ takes πσ time units. Call the widest standard deviation σmax. The count of leapfrog steps for one crossing is then:
The ratio of the widest to the narrowest standard deviation is the square root of the condition number κ (kappa): the largest variance over the smallest. Here κ = 100 and √κ = 10. The cost grows with √κ, whatever the dimension.
The teal path crosses the long axis once. Stretch the target and push ε. Then switch on the mass matrix.
Illustrative toy: a 2D normal, narrow standard deviation 1. The axes are not to scale, so the oval fits the screen. Leapfrog runs live in your browser.
A mass matrix gives the puck a different mass in each direction. Set to the inverse of the posterior covariance, it equals running HMC on a rescaled target where every standard deviation is 1. Then κ = 1, ε = 1.5 is safe everywhere, and a crossing takes π / 1.5, about 3 steps. Stan and NumPyro estimate this matrix during warmup.
Some targets change shape from place to place. Neal's funnel (Neal, 2003) has a width that changes by orders of magnitude along one axis, so no single ε or mass matrix fits. The usual fix is a non-centered parameterization: sample a standard normal and scale it afterward.
The symptom is divergences in one region plus deep trees. To measure it, scatter the divergent iterations over two parameters: they cluster in the narrow part. The fix is the mass matrix or a reparameterization, not a smaller ε.
Chapter 7
Take a single gradient step with noise, and make it exact with the right accept test
An HMC trajectory costs L gradients. What if you take one? Draw a fresh momentum and run a single leapfrog step. The result is a Langevin step: a nudge along the score plus normal noise.
Call the current point x, the proposal y, the step size ε, and a standard normal draw z.
y equals x plus epsilon over two times s of x, plus the square root of epsilon times z.
Move x along its score by epsilon over two times s of x. Then add noise of variance epsilon. The result is the proposal y.
Standard normal, so s(x) = −x. With ε = 0.5 and x = 0.5, the drift lands at 0.5 − 0.25 × 0.5 = 0.375. With the draw z = 1.732: y = 0.375 + 0.707 × 1.732 = 1.60.
The drift depends on the start point. So proposing y from x is not as likely as proposing x from y, and the test must count both. Call q(y | x) the density of proposing y from x: a normal centered at x's drifted point, with variance ε.
alpha equals the minimum of one and p-tilde of y times q of x given y, over p-tilde of x times q of y given x.
Multiply the target at y by the density of the reverse move. Divide by the target at x times the density of the forward move. Accept with that chance, capped at one. This is the Metropolis-adjusted Langevin algorithm (MALA).
x = 0.5, y = 1.6, ε = 0.5. Log target change: −(1.6² − 0.5²) / 2 = −1.155. Forward: log q(y | x) = −(1.6 − 0.375)² = −1.501. Reverse: y drifts to 1.2, so log q(x | y) = −(0.5 − 1.2)² = −0.490. Log ratio = −1.155 − 0.490 + 1.501 = −0.144, so α = 0.866.
The solid purple bump is q(· | x); the dashed one is q(· | y). Move x, y and ε, or press Propose to draw y.
Illustrative toy: a standard normal target. The normal's constant cancels in the ratio, so the read-out leaves it out.
The symptom of a wrong test is samples with the wrong spread and no warning. The cause is HMC's energy-only rule, which drops the q terms. To measure it, run on a standard normal and check that the variance is near 1. The fix is both q terms, as the Code Lab checks.
Chapter 8
Trade exactness for speed, measure the bias, and find the same step inside diffusion models
The accept test needs log p̃ on the full data. With a billion data points, that is too costly for every step. The unadjusted Langevin algorithm (ULA) keeps the Langevin step and never rejects.
The price is a bias that more samples cannot remove: ULA's long-run distribution is itself wrong. On a standard normal the ULA step is x′ = (1 − ε/2) x + √ε z. In the long run the variance is the same before and after a step. Call that variance v. Then v = (1 − ε/2)² v + ε, and solving gives:
v equals one over one minus epsilon over four.
Divide the step size epsilon by four and subtract it from one. One over the result is v. A bigger epsilon gives a wider, more wrong spread.
ε = 0.1: v = 1 / 0.975 = 1.026, 2.6% too wide. ε = 0.5: v = 1 / 0.875 = 1.143. Halve ε and the excess about halves.
The yellow curve is the true density; the dashed purple curve is ULA's predicted one. Run each sampler and compare its spread.
Illustrative toy: 60,000 seeded steps on a standard normal, the first 2,000 dropped. The sample variance wobbles by about 0.02 from run to run.
Stochastic gradient Langevin dynamics (SGLD), from Welling and Teh (2011), goes further. It uses a score estimated from a small batch of data and no test. It shrinks ε during training so the bias fades.
Image diffusion models run the same step. Add noise of size σ to a clean point x0. The score of the noisy distribution at x is (x0 − x) / σ²: it points from the noisy point back to the clean one.
A network trained to remove noise learns this score. Song and Ermon (2019) sample with Langevin steps at a large σ, then lower σ level by level: annealed Langevin. Like ULA, it skips the test. The diffusion lesson builds that model.
The symptom of ULA bias is a spread that stays too wide no matter how long you run. To measure it, compare with MALA or NUTS on a small problem. The fix is a smaller ε, a decaying schedule, or the test.
Chapter 9
Run a random walk, MALA and HMC on one target, and score them by information, not by count
Neighbouring draws of a chain look alike, so 10,000 draws carry less than 10,000 draws' worth of information. Call the correlation between each draw and the next ρ1, the lag-one autocorrelation. A rough rule gives the effective sample size (ESS): the number of independent draws with the same information.
We ran each sampler for 10,000 iterations on a 2D normal with correlation 0.9 (seeded numpy, first coordinate):
| Sampler | Setting | Accepted | ρ1 | ESS | Work per iteration |
|---|---|---|---|---|---|
| Random walk | step 0.8 | 38% | 0.934 | about 340 | 1 density |
| MALA | ε = 0.3 | 63% | 0.902 | about 516 | 1 gradient |
| HMC | ε = 0.2, L = 10 | 99% | 0.158 | about 7,270 | 10 gradients |
Worked number for the random walk: 10,000 × (1 − 0.934) / (1 + 0.934) = 10,000 × 0.066 / 1.934 ≈ 341. HMC pays 10 gradients per iteration. Per 10,000 units of work it gets 727 effective draws; the walk gets 341. In 2D that is about 2×. The gap grows with dimension: the steps needed grow roughly like d for the random walk, d1/3 for MALA and d1/4 for HMC.
Each pane runs its own chain on the same target. Press Run, then raise the correlation to make the target thinner.
Illustrative toy, seeded. Settings scale with the narrow standard deviation σmin: walk step 1.7σmin, MALA ε = 2σmin², HMC ε = 0.6σmin with enough steps for a quarter orbit. ESS uses the lag-one rule with ρ1 floored at 0, so it never exceeds N.
The rule is rough. When ρ1 is negative it can report more than N, which is why the device floors it. ArviZ's az.ess uses all lags and is the number to report.
Chapter 10
Keep the numbers, the checklist and the code in one place
A random walk spreads like √N. HMC uses the score to push a puck with momentum, steps it with leapfrog, and accepts by the energy change. NUTS picks the length, a mass matrix fixes the shape, and the Langevin family trades the test for speed.
| Term | What it is | Number to remember |
|---|---|---|
| Random walk spread | dN = s√N | s = 0.5, distance 10: 400 steps |
| Score | s(x) = ∇ log p̃(x); Z drops out | N(2, 4) at 5: −0.75 |
| Hamiltonian | H = U(q) + p²/2 | (1, 0) and (0, −1): both 0.5 |
| Leapfrog | half kick, drift, half kick | (1, 1), ε = 0.1: (1.095, 0.89525) |
| Accept test | α = min(1, exp(−ΔH)) | ΔH = 0.00114: α = 0.9989 |
| Stability | ε < 2σmin | ε = 2.1 on N(0, 1): ΔH = 183,730 |
| U-turn | (q+ − q−) · p+ < 0 | 1.8 × −0.4 = −0.72: stop |
| Condition number | κ = largest / smallest variance | κ = 100: √κ = 10 |
| MALA test | target ratio times reverse / forward proposal | x = 0.5, y = 1.6, ε = 0.5: 0.866 |
| ULA variance | v = 1 / (1 − ε/4) | ε = 0.1: 1.026 |
| ESS | N(1 − ρ1) / (1 + ρ1), rough | ρ1 = 0.934: 341 of 10,000 |
pythonimport numpy as np def leapfrog(q, p, grad_U, eps, L): p = p - 0.5 * eps * grad_U(q) # half kick for i in range(L): q = q + eps * p # full drift if i < L - 1: p = p - eps * grad_U(q) # two half kicks merged p = p - 0.5 * eps * grad_U(q) # last half kick return q, p def hmc(U, grad_U, q0, eps, L, n, seed=0): rng = np.random.default_rng(seed) q, out = np.asarray(q0, float), [] for _ in range(n): p = rng.standard_normal(q.shape) # 1. resample H0 = U(q) + 0.5 * p @ p qn, pn = leapfrog(q, p, grad_U, eps, L) # 2. roll dH = U(qn) + 0.5 * pn @ pn - H0 if np.log(rng.random()) < -dH: # 3. accept with min(1, exp(-dH)) q = qn out.append(q.copy()) return np.array(out) # In practice: pm.sample() in PyMC, or numpyro.infer.NUTS, runs NUTS with warmup.
| Method | Test | Use it when |
|---|---|---|
| HMC / NUTS | exp(−ΔH) | the target is smooth and the data fits |
| MALA | full ratio with q terms | one gradient per step, still exact |
| ULA / SGLD | none, bias of order ε | the data is too big for full gradients |
| Annealed Langevin | none, learned score | you generate new data |
| Metropolis / Gibbs | symmetric or conditional | there is no gradient (discrete parameters) |
Gradient samplers need a smooth target. For a model with a discrete index and continuous weights, use HMC moves on the weights and a Metropolis or Gibbs step on the index.
MCMC (the gradient-free base) · Sequential Monte Carlo · Quasi-Monte Carlo · Monte Carlo tree search · Diffusion (annealed Langevin with a learned score) · Score matching · Bayesian estimation · Monte Carlo (the family root).
We recomputed every worked number on this page with seeded numpy.
Explain it back with Teach, or go back to the race in the hero and predict the coverage before you press Run.