Hamiltonian and Langevin Monte Carlo

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.

Race a walker against a glider

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

The Random Walk That Never Arrives

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.

Say it aloud

d-N equals s times the square root of N.

dN
d-N the typical distance from the start after N steps.
s
s the step size: the spread of one proposed move.
√N
the square root of N N is the step count. Four times the steps gives only twice the distance.
In plain words

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 numbers

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.

Watch 400 walkers spread out

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.

0.50

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.

High dimension makes it worse

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 failure, as symptom, measurement and fix

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.

The road

  1. The score: the slope of log p, and why the unknown constant drops out.
  2. Momentum: give the sample a velocity and an energy to keep.
  3. Leapfrog: step the motion on a computer without leaking energy.
  4. Resample, roll, accept: one HMC move and its energy test.
  5. NUTS: let the path choose its own length.
  6. Shape: why a thin target costs more, and the mass matrix fix.
  7. Langevin: one step of drift and noise, made exact by MALA.
  8. No check: ULA's bias, SGLD, and the diffusion model link.
  9. The race: random walk, MALA and HMC, scored by effective samples (the hero's full version).
  10. Field Guide: numbers, code, checklist and sources.
A random walk takes steps of size 0.5. About how many steps does it need to get 10 units from its start?

Chapter 1

The Score Points Toward Mass

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.

Say it aloud

s of x equals grad log p of x, which equals grad log p-tilde of x.

s(x)
s of x the score at point x: a vector with one entry per parameter.
∇
grad the gradient: the direction in which a function rises fastest, and how fast.
log p(x)
log p of x the log of the true, normalized density.
∇
grad the same gradient, now of the part you can compute.
log p̃(x)
log p-tilde of x the log of the unnormalized density. It differs from log p(x) by the constant log Z.
In plain words

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.

With numbers

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.

Drag the point, then scale the density

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.

1.0

Illustrative toy: a 2D normal with mean (0, 0), unit variances and correlation 0.5. Faint arrows show the score on a grid.

The failure, as symptom, measurement and fix

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.

Why can you compute the score of a posterior whose constant Z is unknown?

Chapter 2

Give the Sample Momentum

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.

Say it aloud

H of q and p equals U of q plus p squared over two.

H(q, p)
H of q and p the total energy of the puck at position q with momentum p.
U(q)
U of q the potential energy: minus log p-tilde at q.
p²/2
p squared over two the kinetic energy. With many parameters, add the squares of all momentum entries, then halve.
In plain words

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.

With numbers

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.

Kick the puck, let it roll

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 failure, as symptom, measurement and fix

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.

Why can HMC add a momentum p and still sample the right target for q?

Chapter 3

Leapfrog Keeps the Energy Close

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½.

Say it aloud

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.

p½
p-half the momentum after the first half kick.
ε
epsilon the step size in time.
∇U(q)
grad U of q the slope of the energy at the old position. Minus this is the score.
q′
q-prime the new position after a full drift.
p′
p-prime the new momentum after the second half kick.
∇U(q′)
grad U of q-prime the slope at the new position.
In plain words

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.

With numbers

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.

Integrate the bowl two ways

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.

0.30
20

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 failure, as symptom, measurement and fix

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.

What makes leapfrog the right integrator for HMC?

Chapter 4

Resample, Roll, Accept

Assemble one HMC iteration, and read the energy error as the accept test

One HMC iteration has three moves:

  1. Resample. Draw a fresh momentum p from a standard normal.
  2. Roll. Run L leapfrog steps from (q, p) to a proposal (q*, p*).
  3. Accept or reject. Keep q* or stay at q.

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).

Say it aloud

alpha equals the minimum of one and e to the minus delta H.

α
alpha the chance of accepting the proposal.
min(1, ·)
the minimum of one and caps the chance at 1.
exp(−ΔH)
e to the minus delta H where delta H is the energy at the proposal minus the energy at the start.
In plain words

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.

With numbers

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.

Run the HMC loop, then break it

Each Step draws a momentum (warm), rolls a teal trajectory, then accepts (green) or rejects (grey). Push ε past 0.9 to see divergences.

0.20
12

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.

The step size has a hard limit

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).

Why is HMC's acceptance usually close to 1, even for long moves?

Chapter 5

Let the Path Choose Its Length

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+.

Say it aloud

q-plus minus q-minus, dot p-plus, is less than zero.

q+
q-plus the front end of the trajectory.
q−
q-minus the back end of the trajectory.
( · − · )
the span the vector from the back end to the front end.
·
dot the dot product: multiply matching entries and add. It is negative when two vectors point in opposite directions.
p+
p-plus the momentum at the front end.
< 0
less than zero the stop condition.
In plain words

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 numbers

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.

Double the path until it U-turns

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.

What does NUTS choose for you, and how does it know when to stop?

Chapter 6

The Narrowest Direction Sets the Step

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:

steps = π × σmax / ε = 3.14 × 10 / 1.5 ≈ 21

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.

Stretch the target, then rescale it

The teal path crosses the long axis once. Stretch the target and push ε. Then switch on the mass matrix.

10
1.50

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.

The fix: a mass matrix

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 ε.

A target has standard deviations 1 and 10. Why does HMC need many leapfrog steps per crossing?

Chapter 7

One Step of Drift and Noise

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.

Say it aloud

y equals x plus epsilon over two times s of x, plus the square root of epsilon times z.

y
y the proposed next point.
x
x the current point.
ε
epsilon the step size. It is also the variance of the noise.
s(x)
s of x the score at x, from Chapter 1.
√ε z
root epsilon z normal noise with variance epsilon.
In plain words

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.

With numbers

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 ε.

Say it aloud

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.

α
alpha the chance of accepting y.
p̃(y)
p-tilde of y the unnormalized target at the proposal.
q(x | y)
q of x given y the density of the reverse move, from y back to x.
p̃(x)
p-tilde of x the unnormalized target at the current point.
q(y | x)
q of y given x the density of the forward move.
In plain words

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).

With numbers

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.

Weigh the forward and reverse moves

The solid purple bump is q(· | x); the dashed one is q(· | y). Move x, y and ε, or press Propose to draw y.

0.50
1.60
0.50

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.

Why does MALA's test include q(x | y) and q(y | x)?

Chapter 8

Drop the Check: ULA, SGLD and Diffusion

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:

Say it aloud

v equals one over one minus epsilon over four.

v
v the variance that ULA's samples settle at. The true variance is 1.
1 − ε/4
one minus epsilon over four where epsilon is the step size. It is below 1, so v is above 1.
In plain words

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.

With numbers

ε = 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.

Measure the bias of skipping the test

The yellow curve is the true density; the dashed purple curve is ULA's predicted one. Run each sampler and compare its spread.

0.50

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.

SGLD and diffusion

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.

score = (x0 − x) / σ² = (0 − 3) / 2² = −0.75

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.

ULA on a standard normal with ε = 0.1 gives a variance near 1.026 after a very long run. What fixes it?

Chapter 9

Race Three Samplers

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.

ESS ≈ N × (1 − ρ1) / (1 + ρ1)

We ran each sampler for 10,000 iterations on a 2D normal with correlation 0.9 (seeded numpy, first coordinate):

SamplerSettingAcceptedρ1ESSWork per iteration
Random walkstep 0.838%0.934about 3401 density
MALAε = 0.363%0.902about 5161 gradient
HMCε = 0.2, L = 1099%0.158about 7,27010 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.

Race three samplers

Each pane runs its own chain on the same target. Press Run, then raise the correlation to make the target thinner.

0.90

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.

HMC's ESS per iteration is about 21 times the random walk's here. Why is the real advantage smaller in this 2D race?

Chapter 10

Field Guide

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.

TermWhat it isNumber to remember
Random walk spreaddN = s√Ns = 0.5, distance 10: 400 steps
Scores(x) = ∇ log p̃(x); Z drops outN(2, 4) at 5: −0.75
HamiltonianH = U(q) + p²/2(1, 0) and (0, −1): both 0.5
Leapfroghalf 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+ < 01.8 × −0.4 = −0.72: stop
Condition numberκ = largest / smallest varianceκ = 100: √κ = 10
MALA testtarget ratio times reverse / forward proposalx = 0.5, y = 1.6, ε = 0.5: 0.866
ULA variancev = 1 / (1 − ε/4)ε = 0.1: 1.026
ESSN(1 − ρ1) / (1 + ρ1), roughρ1 = 0.934: 341 of 10,000

Checklist before you trust a run

  1. Check the gradient against a finite difference at three points.
  2. Run four chains from spread-out starts. Compare them with R-hat.
  3. Report ESS per parameter, not the draw count.
  4. Count divergences. If there are any, find where they cluster.
  5. Watch tree depth. Many trees at the limit point to bad geometry.
  6. Reparameterize funnels; let warmup fit the mass matrix.

The core, in numpy

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.

Where it sits

MethodTestUse it when
HMC / NUTSexp(−ΔH)the target is smooth and the data fits
MALAfull ratio with q termsone gradient per step, still exact
ULA / SGLDnone, bias of order εthe data is too big for full gradients
Annealed Langevinnone, learned scoreyou generate new data
Metropolis / Gibbssymmetric or conditionalthere 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.

Keep going

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).

Sources

We recomputed every worked number on this page with seeded numpy.

The takeaway. The slope of log p is the information a random walk throws away. HMC turns it into long moves that pass an energy test.

Explain it back with Teach, or go back to the race in the hero and predict the coverage before you press Run.

Hamiltonian and Langevin Monte Carlo
Back to Gleams