Course contents 24 / 34

24 / 34 · Energy-Based Models

Sampling unnormalized densities: MALA, Hamiltonian Monte Carlo and NUTS

How to sample a density known only up to a constant by following its gradient: MALA from the Langevin equation, Hamiltonian Monte Carlo with the leapfrog integrator, and the accept steps that make both exact.

On this page 12

Take a network that maps an image x∈Rdx \in \mathbb R^d to one number U(x)U(x), and declare the density of images to be π(x)=e−U(x)/Z\pi(x) = e^{-U(x)}/Z. The energy-based models of the next note define densities this way, with no architectural restriction of the kind flows need. The normalizer Z=∫e−U(x) dxZ = \int e^{-U(x)}\,dx is an integral over all images, and nobody can compute it. Two other quantities are cheap:

π(y)π(x)=eU(x)−U(y),∇log⁡π(x)=−∇U(x).\begin{aligned} \frac{\pi(y)}{\pi(x)} &= e^{U(x) - U(y)}, \\ \nabla \log \pi(x) &= -\nabla U(x) . \end{aligned}

In the ratio ZZ cancels, and the gradient with respect to xx never sees it, because log⁡Z\log Z does not depend on xx. UU is called the potential energy and ∇log⁡π\nabla \log \pi the score. How do we draw samples of π\pi with nothing but these two quantities?

The starting point: rejection and Metropolis–Hastings#

Two samplers of the probability course already work with ratios. Rejection sampling (Monte Carlo methods) keeps a draw from a proposal qq with probability π(x)/(Mq(x))\pi(x)/(M q(x)), which needs a bound π≤Mq\pi \le M q. It is exact, and it dies with dimension. Take the target N(0,Id)\mathcal N(0, I_d) and the proposal N(0,4Id)\mathcal N(0, 4 I_d). The ratio π/q\pi/q is a product of dd factors 2e−3xi2/82e^{-3x_i^2/8}, each at most 2, so

M=sup⁡xπ(x)q(x)=2d,P(accept)=2−d.\begin{aligned} M &= \sup_x \frac{\pi(x)}{q(x)} = 2^d, \\ P(\text{accept}) &= 2^{-d} . \end{aligned}

That is one proposal in 1,024 kept at d=10d = 10 and one in 103010^{30} at d=100d = 100.

Metropolis–Hastings (Markov chain Monte Carlo) gives up independent draws. From the current state xx it proposes y∼q(⋅∣x)y \sim q(\cdot \mid x) and moves there with probability

α(x,y)=min⁡(1,π(y) q(x∣y)π(x) q(y∣x));\alpha(x, y) = \min\Big(1, \frac{\pi(y)\, q(x \mid y)}{\pi(x)\, q(y \mid x)}\Big) ;

otherwise it stays at xx. With the random-walk proposal y=x+σzy = x + \sigma z, where z∼N(0,I)z \sim \mathcal N(0, I) is fresh noise, qq is symmetric and cancels.

The random walk knows nothing about the target. Its step σ\sigma must be about the width of the narrowest direction, or proposals land in low density and are rejected. Independent steps add in variance, so nn steps travel about σn\sigma\sqrt n, and crossing the widest direction takes about (σmax⁡/σmin⁡)2(\sigma_{\max}/\sigma_{\min})^2 steps. For a bivariate normal with unit variances and correlation 0.950.95 the axes of the ellipse have standard deviations 1.95=1.40\sqrt{1.95} = 1.40 and 0.05=0.22\sqrt{0.05} = 0.22, so a crossing takes about 39 steps even if every proposal were accepted. Dimension adds a second cost, worked out later.

MALA: let the gradient propose#

The Langevin equation#

Picture a particle that drifts uphill on log⁡π\log \pi and is jostled by noise. The Langevin diffusion writes this as

dXt=12∇log⁡π(Xt) dt+dWt,dX_t = \tfrac12 \nabla \log \pi(X_t)\, dt + dW_t ,

where WtW_t is a standard Brownian motion: its increment over a time ε\varepsilon is N(0,εI)\mathcal N(0, \varepsilon I), independent of the past. The drift alone would climb to a mode and stop; the noise alone would spread without limit. With the factor 12\tfrac12 they balance.

The Fokker–Planck equation, derived from one Euler step and a Taylor expansion in the continuous-time diffusion note, makes this balance exact. For dXt=f(Xt) dt+dWtdX_t = f(X_t)\,dt + dW_t (noise scale g=1g = 1 there) the density ptp_t of XtX_t obeys the first line below. The second line writes it as minus the divergence of the flux fpt−12∇ptf p_t - \frac12 \nabla p_t, drift minus diffusion, and the drift f=12∇log⁡πf = \tfrac12 \nabla \log \pi makes that flux zero at pt=πp_t = \pi:

∂tpt=−∇⋅(f pt)+12Δpt=−∇⋅(f pt−12∇pt),f π=12 π∇log⁡π=12∇π,f π−12∇π=0.\begin{aligned} \partial_t p_t &= -\nabla \cdot (f\, p_t) + \tfrac12 \Delta p_t \\ &= -\nabla \cdot \big(f\, p_t - \tfrac12 \nabla p_t\big) , \\ f\, \pi &= \tfrac12\, \pi \nabla \log \pi = \tfrac12 \nabla \pi , \\ f\, \pi - \tfrac12 \nabla \pi &= 0 . \end{aligned}

Here Δ=∇⋅∇\Delta = \nabla \cdot \nabla is the Laplacian; Isachenko (2025, lecture 10) finds the same drift by setting ∂tpt=0\partial_t p_t = 0. Stationarity does not yet say that chains reach π\pi, and the discretized chain below does not even keep π\pi exactly. For a potential UU that is mm-strongly convex with an MM-Lipschitz gradient, the unadjusted chain forgets its start geometrically and ends within a distance of order εd\sqrt{\varepsilon d} of π\pi (Dalalyan, 2017, Theorem 1; the bound is below).

The bound

In the notation of the theorem the Euler step below has h=ε/2h = \varepsilon/2, and for h≤2/(m+M)h \le 2/(m + M) the distribution νK\nu_K of the state after KK steps satisfies

W2(νK,π)≤(1−mh)K W2(ν0,π)+1.82 Mmhd,\begin{aligned} W_2(\nu_K, \pi) \le{}& (1 - m h)^K\, W_2(\nu_0, \pi) \\ &+ 1.82\, \frac{M}{m} \sqrt{h d} , \end{aligned}

where W2W_2 is the Wasserstein-2 distance. The first term is the start being forgotten: two copies of the chain driven by the same noise approach each other by the factor 1−mh1 - mh per step, because a strongly convex UU pulls them together. The second is the price of the frozen drift; it does not shrink with KK but vanishes as h→0h \to 0.

One Euler step: unadjusted Langevin#

To simulate the diffusion for a time ε\varepsilon, hold the drift at its value at the start and draw the Brownian increment exactly:

y=x+ε2∇log⁡π(x)+ε z.y = x + \frac{\varepsilon}{2} \nabla \log \pi(x) + \sqrt{\varepsilon}\, z .

Used as a chain, this is the unadjusted Langevin algorithm (ULA) of the probability course, and the frozen drift makes it slightly wrong. On π=N(0,1)\pi = \mathcal N(0, 1) the score is −x-x, one step is y=ax+ε zy = a x + \sqrt\varepsilon\, z with a=1−ε/2a = 1 - \varepsilon/2, and a stationary variance vv must reproduce itself, since xx and zz are independent:

v=a2v+εv=ε1−a2=εε−ε2/4=11−ε/4.\begin{aligned} v &= a^2 v + \varepsilon \\ v &= \frac{\varepsilon}{1 - a^2} \\ &= \frac{\varepsilon}{\varepsilon - \varepsilon^2/4} \\ &= \frac{1}{1 - \varepsilon/4} . \end{aligned}

The variance is 1.141.14 at ε=0.5\varepsilon = 0.5 and 1.331.33 at ε=1\varepsilon = 1, against the target’s 1; for ε≥4\varepsilon \ge 4, where ∣a∣≥1|a| \ge 1, the chain diverges.

The Metropolis correction#

The Metropolis-adjusted Langevin algorithm (MALA) keeps the Euler step as a proposal and adds the Metropolis–Hastings test (Neal, 2011, Section 5.2). The proposal density is

q(y∣x)=N(y; x+ε2∇log⁡π(x), εI).q(y \mid x) = \mathcal N\Big(y;\ x + \frac{\varepsilon}{2} \nabla \log \pi(x),\ \varepsilon I\Big) .

It is not symmetric: the reverse move from yy is centred at y+ε2∇log⁡π(y)y + \frac{\varepsilon}{2}\nabla\log\pi(y), with the drift at yy, so both q(y∣x)q(y \mid x) and q(x∣y)q(x \mid y) enter α\alpha. Each step costs one new gradient, at yy.

Why is the chain exact for every ε\varepsilon? The probability course proves the general case; here is the core step. A chain leaves π\pi invariant if it satisfies detailed balance, π(x)P(x→y)=π(y)P(y→x)\pi(x) P(x \to y) = \pi(y) P(y \to x). For y≠xy \ne x the chain reaches yy only by proposing and accepting it, so P(x→y)=q(y∣x) α(x,y)P(x \to y) = q(y \mid x)\, \alpha(x, y). Moving the positive factor π(x)q(y∣x)\pi(x) q(y \mid x) inside the minimum gives

π(x) P(x→y)=π(x) q(y∣x) α(x,y)=min⁡(π(x) q(y∣x), π(y) q(x∣y)),\begin{aligned} \pi(x)\, P(x \to y) &= \pi(x)\, q(y \mid x)\, \alpha(x, y) \\ &= \min\big(\pi(x)\, q(y \mid x),\ \pi(y)\, q(x \mid y)\big) , \end{aligned}

which is symmetric in xx and yy and therefore equals π(y)P(y→x)\pi(y) P(y \to x). Rejections form a point mass at xx, where detailed balance holds trivially (the full kernel is written out in the probability course and in «Байесовские методы в анализе данных», 2026, lecture 4). So π\pi is stationary for any step size; a larger ε\varepsilon costs rejections, never bias.

Worked example: MALA on a standard normal#

Take π=N(0,1)\pi = \mathcal N(0, 1), so ∇log⁡π(x)=−x\nabla \log \pi(x) = -x, and write a=1−ε/2a = 1 - \varepsilon/2 for the factor that maps xx to the proposal mean axa x. The log-ratio of the two proposal densities is

log⁡q(x∣y)q(y∣x)=(y−ax)2−(x−ay)22ε=(1−a2)(y2−x2)2ε=(1−ε4)y2−x22,\begin{aligned} \log \frac{q(x \mid y)}{q(y \mid x)} &= \frac{(y - a x)^2 - (x - a y)^2}{2\varepsilon} \\ &= \frac{(1 - a^2)(y^2 - x^2)}{2\varepsilon} \\ &= \Big(1 - \frac{\varepsilon}{4}\Big)\frac{y^2 - x^2}{2} , \end{aligned}

where the second line expands both squares (the cross terms −2axy-2axy cancel) and the third uses 1−a2=ε−ε2/41 - a^2 = \varepsilon - \varepsilon^2/4. Adding log⁡π(y)−log⁡π(x)=(x2−y2)/2\log \pi(y) - \log \pi(x) = (x^2 - y^2)/2 leaves

log⁡π(y) q(x∣y)π(x) q(y∣x)=ε8 (x2−y2).\log \frac{\pi(y)\, q(x \mid y)}{\pi(x)\, q(y \mid x)} = \frac{\varepsilon}{8}\,(x^2 - y^2) .

The random walk’s log-ratio for the same pair is (x2−y2)/2(x^2 - y^2)/2; MALA’s is that times ε/4\varepsilon/4, because the proposal already carries most of the change in density. With x=2x = 2 and ε=1\varepsilon = 1 the proposal is N(1,1)\mathcal N(1, 1). A draw that lands farther out, at y=2.8y = 2.8, has π(y)/π(x)=e−1.92=0.15\pi(y)/\pi(x) = e^{-1.92} = 0.15, so a random walk would accept it with probability 0.150.15. MALA accepts it with e−0.48=0.62e^{-0.48} = 0.62: the reverse proposal from 2.82.8 has mean 1.41.4, only 0.60.6 from x=2x = 2, so the move is easy to undo.

The example also suggests why ULA’s bias is small for small steps: a proposal moves xx by order ε\sqrt\varepsilon, so the log-ratio ε8(x−y)(x+y)\frac{\varepsilon}{8}(x - y)(x + y) is of order ε3/2\varepsilon^{3/2}, and ULA differs from the exact MALA only in the rare rejections. This is an intuition; the bound is the second term of Dalalyan’s inequality above.

Hamiltonian Monte Carlo: momentum and energy#

MALA forgets its direction after every step. Hamiltonian Monte Carlo (HMC) adds a velocity that persists. Introduce a momentum p∈Rdp \in \mathbb R^d and a mass matrix MM (the identity unless said otherwise), and sample the pair (x,p)(x, p) from

π(x,p)∝e−H(x,p),H(x,p)=U(x)+K(p),K(p)=12 p⊤M−1p.\begin{aligned} \pi(x, p) &\propto e^{-H(x, p)} , \\ H(x, p) &= U(x) + K(p) , \\ K(p) &= \tfrac12\, p^\top M^{-1} p . \end{aligned}

The density factorizes as e−U(x)e−K(p)e^{-U(x)} e^{-K(p)}, so p∼N(0,M)p \sim \mathcal N(0, M) independently of xx, and the marginal of xx is π\pi: sample pairs and drop pp. Think of xx as the position of a particle with potential energy UU, kinetic energy KK and total energy HH (Neal, 2011, Section 3.1). The particle moves by Hamilton’s equations

dxdt=∂H∂p=M−1p,dpdt=−∂H∂x=−∇U(x).\begin{aligned} \frac{dx}{dt} &= \frac{\partial H}{\partial p} = M^{-1} p , \\ \frac{dp}{dt} &= -\frac{\partial H}{\partial x} = -\nabla U(x) . \end{aligned}

The exact flow has three properties, and HMC rests on all three (Neal, 2011, Section 2.2). First, it conserves HH, by the chain rule and then Hamilton’s equations, with ∇K=M−1p\nabla K = M^{-1} p:

dHdt=∇U⋅dxdt+∇K⋅dpdt=∇U⋅M−1p−M−1p⋅∇U=0.\begin{aligned} \frac{dH}{dt} &= \nabla U \cdot \frac{dx}{dt} + \nabla K \cdot \frac{dp}{dt} \\ &= \nabla U \cdot M^{-1} p - M^{-1} p \cdot \nabla U \\ &= 0 . \end{aligned}

Second, it preserves volume in the (x,p)(x, p) space (Liouville’s theorem): the velocity field (M−1p, −∇U(x))(M^{-1}p,\ -\nabla U(x)) has zero divergence, since its xx-part does not depend on xx and its pp-part does not depend on pp. Third, it is reversible: run it for a time tt, negate the momentum, run it again for tt, and you are back at the start with negated momentum.

If we could follow the exact flow, every proposal would keep its HH and be accepted however far it went.

The leapfrog integrator#

Euler’s method updates xx and pp with the derivatives at the current point. On N(0,1)\mathcal N(0, 1), where H=x2/2+p2/2H = x^2/2 + p^2/2 and exact trajectories are circles in the (x,p)(x, p) plane, one Euler step maps (x,p)(x, p) to (x+εp, p−εx)(x + \varepsilon p,\ p - \varepsilon x), and

(x+εp)2+(p−εx)2=(1+ε2)(x2+p2).(x + \varepsilon p)^2 + (p - \varepsilon x)^2 = (1 + \varepsilon^2)(x^2 + p^2) .

Every step multiplies the energy by 1+ε21 + \varepsilon^2, and the trajectory spirals outwards. The leapfrog (Störmer–Verlet) method splits the momentum update in two halves around a full position step:

p1/2=p−ε2∇U(x),x′=x+ε M−1p1/2,p′=p1/2−ε2∇U(x′).\begin{aligned} p_{1/2} &= p - \tfrac{\varepsilon}{2} \nabla U(x) , \\ x' &= x + \varepsilon\, M^{-1} p_{1/2} , \\ p' &= p_{1/2} - \tfrac{\varepsilon}{2} \nabla U(x') . \end{aligned}

Consecutive steps share a gradient, so LL steps cost LL gradients. Leapfrog does not conserve HH exactly, but it keeps the other two properties exactly (Neal, 2011, Section 2.3).

Why leapfrog keeps volume#

Each line is a shear: it changes one block of variables by an amount that depends only on the other block. The first line has the Jacobian

∂(x,p1/2)∂(x,p)=(I0−ε2∇2U(x)I),\frac{\partial (x, p_{1/2})}{\partial (x, p)} = \begin{pmatrix} I & 0 \\ -\tfrac{\varepsilon}{2} \nabla^2 U(x) & I \end{pmatrix} ,

block-triangular with identity blocks on the diagonal, so its determinant is 1; the same holds for the other two lines and for their composition. This is the triangular-Jacobian argument of coupling layers.

Why leapfrog is reversible#

Start from the end point with the momentum negated, (x′,−p′)(x', -p'), and apply the same three lines:

p~1/2=−p′−ε2∇U(x′)=−p1/2,x~=x′+εM−1p~1/2=x,p~=p~1/2−ε2∇U(x)=−p.\begin{aligned} \tilde p_{1/2} &= -p' - \tfrac{\varepsilon}{2} \nabla U(x') = -p_{1/2} , \\ \tilde x &= x' + \varepsilon M^{-1} \tilde p_{1/2} = x , \\ \tilde p &= \tilde p_{1/2} - \tfrac{\varepsilon}{2} \nabla U(x) = -p . \end{aligned}

The first line uses the third leapfrog line, p′=p1/2−ε2∇U(x′)p' = p_{1/2} - \frac{\varepsilon}{2}\nabla U(x'); the second uses the middle line, x′−εM−1p1/2=xx' - \varepsilon M^{-1} p_{1/2} = x; the third uses the first line. The step returns to (x,−p)(x, -p).

The energy error stays bounded#

On N(0,1)\mathcal N(0, 1), where ∇U(x)=x\nabla U(x) = x, the three leapfrog lines combine into a linear map. With c=1−ε2/2c = 1 - \varepsilon^2/2 and k=1−ε2/4k = 1 - \varepsilon^2/4 it reads x′=cx+εpx' = c x + \varepsilon p and p′=cp−εkxp' = c p - \varepsilon k x, and substituting it (steps below) shows that it conserves exactly the shadow energy

H~(x,p)=p22+(1−ε24)x22,\tilde H(x, p) = \frac{p^2}{2} + \Big(1 - \frac{\varepsilon^2}{4}\Big)\frac{x^2}{2} ,

so along a leapfrog trajectory H−H~=ε2x2/8H - \tilde H = \varepsilon^2 x^2/8 oscillates and never accumulates. For ε≥2\varepsilon \ge 2 the coefficient of x2x^2 is no longer positive and trajectories run off to infinity; for a Gaussian with standard deviation σ\sigma the limit is ε<2σ\varepsilon < 2\sigma, set by the narrowest direction. In general the error in HH is of order ε3\varepsilon^3 after one step and of order ε2\varepsilon^2 over a trajectory of fixed length (Neal, 2011, Section 2.3).

Derivation

Substituting the map into p′2+kx′2p'^2 + k x'^2, the cross terms ±2ckε xp\pm 2 c k \varepsilon\, x p cancel:

p′2+kx′2=(c2+kε2) p2+k (kε2+c2) x2=p2+kx2,\begin{aligned} p'^2 + k x'^2 &= (c^2 + k \varepsilon^2)\, p^2 + k\,(k \varepsilon^2 + c^2)\, x^2 \\ &= p^2 + k x^2 , \end{aligned}

since c2+kε2=1−ε2+ε44+ε2−ε44=1c^2 + k\varepsilon^2 = 1 - \varepsilon^2 + \tfrac{\varepsilon^4}{4} + \varepsilon^2 - \tfrac{\varepsilon^4}{4} = 1. Halving both sides gives H~(x′,p′)=H~(x,p)\tilde H(x', p') = \tilde H(x, p).

A toy step on N(0,1)\mathcal N(0, 1), from x=1x = 1, p=0.5p = 0.5 with ε=0.5\varepsilon = 0.5:

QuantityLeapfrogEuler
half-step momentum p1/2p_{1/2}0.5−0.25⋅1=0.250.5 - 0.25 \cdot 1 = 0.25—
new position x′x'1+0.5⋅0.25=1.1251 + 0.5 \cdot 0.25 = 1.1251.251.25
new momentum p′p'0.25−0.25⋅1.125=−0.031250.25 - 0.25 \cdot 1.125 = -0.0312500
energy, from H=0.625H = 0.6250.633300.633300.781250.78125
error ΔH\Delta H0.00830.00830.1560.156

Leapfrog’s move would be accepted with probability e−0.0083=0.992e^{-0.0083} = 0.992; Euler’s error, ε2H\varepsilon^2 H, is nineteen times larger. The shadow energy is 0.593750.59375 before and after the leapfrog step.

One HMC iteration#

An iteration of HMC from the current state xx has three parts (Neal, 2011, Section 3.2):

  1. Refresh the momentum: draw p∼N(0,M)p \sim \mathcal N(0, M), independently of everything else. In the (x,p)(x, p) plane this is a vertical move, and it is the only part that changes the energy level.
  2. Simulate: apply LL leapfrog steps of size ε\varepsilon to (x,p)(x, p) to get (x′,p′)(x', p'). The trajectory follows a contour of HH up to the small leapfrog error.
  3. Accept x′x' with probability min⁡(1,e−ΔH)\min(1, e^{-\Delta H}), where ΔH=H(x′,p′)−H(x,p)\Delta H = H(x', p') - H(x, p); otherwise keep xx. Drop the momentum.
Figure

HMC iterations in phase space: leapfrog against Euler

Three HMC iterations and the Euler spiralLeft: the (x, p) plane with three leapfrog arcs on circles of different radius, joined by vertical momentum-refresh arrows, and a red Euler spiral. Right: the energy error per step, almost zero for leapfrog and growing for Euler.−202−202x (position)p (momentum)p ~ N(0, 1)leapfrogEulerΔH = −0.003acceptednew x1234energy error H − H₀ on the first trajectory00.5101234567stepEuler: +1.15leapfrog: |ΔH| ≤ 0.025Three HMC iterations and the Euler spiralLeft: the (x, p) plane with three leapfrog arcs on circles of different radius, joined by vertical momentum-refresh arrows, and a red Euler spiral. Right: the energy error per step, almost zero for leapfrog and growing for Euler.−202−202x (position)p (momentum)p ~ N(0, 1)leapfrogEulerΔH = −0.003acceptednew x1234energy error H − H₀ on the first trajectory00.5101234567stepEuler: +1.15leapfrog: |ΔH| ≤ 0.025
Three HMC iterations on a standard normal in the (x, p) plane, where exact trajectories are circles. Each draws a fresh momentum (vertical arrow), takes 7 leapfrog steps of size ε = 0.3 (blue dots) and is accepted. Euler's method from the same point (red dashes) spirals outwards; right: energy error along the first trajectory.

MALA is HMC with a single leapfrog step. From a fresh momentum p=zp = z, one leapfrog step of size hh moves xx to x+hz−h22∇U(x)x + h z - \frac{h^2}{2}\nabla U(x): the MALA proposal with ε=h2\varepsilon = h^2. Substituting the leapfrog momenta into the two proposal densities turns them into e−K(p)e^{-K(p)} and e−K(p′)e^{-K(p')}, so the MALA ratio is exactly e−ΔHe^{-\Delta H} (steps below; Neal, 2011, Section 5.2). Without the test the chain is ULA, and on N(0,1)\mathcal N(0, 1) the shadow energy explains its bias. Leapfrog keeps volume and H~\tilde H, and the refresh draws pp from N(0,1)\mathcal N(0, 1), its conditional under e−H~e^{-\tilde H} since H~\tilde H separates; both steps leave e−H~e^{-\tilde H} invariant. Its xx-marginal has variance 1/(1−h2/4)=1/(1−ε/4)1/(1 - h^2/4) = 1/(1 - \varepsilon/4), the ULA variance derived above.

Derivation

The momenta match the proposal densities. With y=x′y = x' and ε=h2\varepsilon = h^2, the leapfrog lines give y−x+ε2∇U(x)=hpy - x + \frac{\varepsilon}{2}\nabla U(x) = h p for the forward move and x−y+ε2∇U(y)=−hp′x - y + \frac{\varepsilon}{2}\nabla U(y) = -h p' for the reverse one, so with the same constant

q(y∣x)∝e−∥hp∥2/(2h2)=e−K(p),q(x∣y)∝e−K(p′),\begin{aligned} q(y \mid x) &\propto e^{-\lVert h p\rVert^2/(2h^2)} = e^{-K(p)} , \\ q(x \mid y) &\propto e^{-K(p')} , \end{aligned}

and the MALA ratio π(y) q(x∣y)/(π(x) q(y∣x))\pi(y)\, q(x \mid y)/\big(\pi(x)\, q(y \mid x)\big) equals e−U(y)−K(p′)+U(x)+K(p)=e−ΔHe^{-U(y) - K(p') + U(x) + K(p)} = e^{-\Delta H} (Neal, 2011, Section 5.2).

Why the acceptance needs only the energy error#

Write z=(x,p)z = (x, p), let Λ\Lambda be one leapfrog step and F(x,p)=(x,−p)F(x, p) = (x, -p) the momentum flip, and define the proposal map Ψ=F∘ΛL\Psi = F \circ \Lambda^L: run LL steps, then negate the momentum. Two facts about Ψ\Psi make the acceptance simple.

  • Ψ\Psi is its own inverse. Reversibility says F∘Λ∘F=Λ−1F \circ \Lambda \circ F = \Lambda^{-1}, so FΛLF=Λ−LF \Lambda^L F = \Lambda^{-L} and Ψ∘Ψ=FΛLFΛL=Λ−LΛL\Psi \circ \Psi = F \Lambda^L F \Lambda^L = \Lambda^{-L} \Lambda^L, the identity.
  • Ψ\Psi preserves volume, ∣det⁡∂Ψ/∂z∣=1\lvert \det \partial\Psi / \partial z \rvert = 1, because each leapfrog step and the flip do.

Accept the deterministic proposal Ψ(z)\Psi(z) with probability α(z)=min⁡(1,π(Ψ(z))/π(z))\alpha(z) = \min\big(1, \pi(\Psi(z))/\pi(z)\big). For two regions AA and BB of phase space, the probability that the chain is in AA and moves into BB is

∫Aπ(z) α(z) 1[Ψ(z)∈B] dz=∫Bπ(Ψ(w)) α(Ψ(w)) 1[Ψ(w)∈A] dw=∫Bπ(w) α(w) 1[Ψ(w)∈A] dw,\begin{aligned} &\int_A \pi(z)\, \alpha(z)\, \mathbf 1[\Psi(z) \in B]\, dz \\ &\quad = \int_B \pi(\Psi(w))\, \alpha(\Psi(w))\, \mathbf 1[\Psi(w) \in A]\, dw \\ &\quad = \int_B \pi(w)\, \alpha(w)\, \mathbf 1[\Psi(w) \in A]\, dw , \end{aligned}

the probability of the reverse move. The first equality substitutes z=Ψ(w)z = \Psi(w), allowed because Ψ\Psi is its own inverse with unit Jacobian; the second uses π(z) α(z)=min⁡(π(z),π(Ψ(z)))\pi(z)\, \alpha(z) = \min\big(\pi(z), \pi(\Psi(z))\big), which is unchanged when zz and Ψ(z)\Psi(z) swap. This is detailed balance, so the accept step leaves π(x,p)\pi(x, p) invariant. Since K(−p′)=K(p′)K(-p') = K(p'), the ratio itself is

π(Ψ(z))π(z)=e−H(x′,−p′)+H(x,p)=e−ΔH,\frac{\pi(\Psi(z))}{\pi(z)} = e^{-H(x', -p') + H(x, p)} = e^{-\Delta H} ,

and for the same reason the flip is skipped in practice. The refresh draws pp exactly from its conditional given xx, a Gibbs step, so it also leaves π(x,p)\pi(x, p) invariant, and so does the whole iteration.

A proposal map that stretched space would need the factor ∣det⁡∂Ψ/∂z∣\lvert \det \partial\Psi/\partial z \rvert in the ratio, the change-of-variables term that normalizing flows pay for in their likelihood. Euler’s step on N(0,1)\mathcal N(0, 1), the linear map with rows (1,ε)(1, \varepsilon) and (−ε,1)(-\varepsilon, 1), has determinant 1+ε21 + \varepsilon^2, so the factor is (1+ε2)L(1 + \varepsilon^2)^L, and the plain ratio e−ΔHe^{-\Delta H} would sample the wrong distribution.

The three samplers on a narrow Gaussian#

The figure gives a random walk, MALA and HMC 3000 evaluations each of the bivariate normal with correlation 0.950.95, counting one gradient as one evaluation. The random walk (σ=1\sigma = 1) accepts 22%. MALA’s drift multiplies the narrow coordinate by 1−ε/(2σmin⁡2)1 - \varepsilon/(2\sigma_{\min}^2), which drops below −1-1, so that the drift alone would push the coordinate ever farther out, for ε>4σmin⁡2=0.2\varepsilon > 4\sigma_{\min}^2 = 0.2. Its step, ε=0.17\varepsilon = 0.17 with factor −0.7-0.7, sits just below that limit; it accepts 57%. HMC (ε=0.3\varepsilon = 0.3, L=10L = 10, so 300 iterations) accepts 86%.

Figure

Three samplers with the same budget on a narrow Gaussian

Paths and autocorrelations of three samplersTop: three panels with the same diagonal ellipse and the chain paths: zigzag lines for the random walk and MALA, and a few HMC states scattered along the ellipse. Bottom: three autocorrelation curves: HMC drops below zero after one iteration, the random walk decays within about fifty evaluations, MALA most slowly.Random-walk Metropolisaccepted 22%ESS of x₁: 92MALAaccepted 57%ESS of x₁: 38Hamiltonian Monte Carloaccepted 86%ESS of x₁: 300autocorrelation of x₁ over the whole budget−0.500.51050100150200lag in target evaluationsrandom walkMALAHMCPaths and autocorrelations of three samplersTop: three panels with the same diagonal ellipse and the chain paths: zigzag lines for the random walk and MALA, and a few HMC states scattered along the ellipse. Bottom: three autocorrelation curves: HMC drops below zero after one iteration, the random walk decays within about fifty evaluations, MALA most slowly.Random walkaccepted 22%ESS of x₁: 92MALAaccepted 57%ESS of x₁: 38HMCaccepted 86%ESS of x₁: 300budget: 3000 evaluationsof the targetstart (−2, −2)autocorrelation of x₁ over the whole budget−0.500.51050100150200lag in target evaluationsrandom walkMALAHMC
Random walk (σ = 1), MALA (ε = 0.17) and HMC (ε = 0.3, L = 10), each with 3000 target evaluations on a bivariate normal with correlation 0.95, started at (−2, −2). Top: the first 300 evaluations; faint lines are HMC's leapfrog trajectories. Bottom: autocorrelation of x₁ against the lag in evaluations.

The effective sample sizes of x1x_1 are 92, 38 and 300 (for HMC the estimator is capped at the number of iterations and understates it). The gradient buys MALA nothing here: its step is capped by the narrow direction, and along the long one it still diffuses. Along the long axis, ten HMC leapfrog steps advance the oscillation by 2.152.15 radians, so the chain tends to land on the other side of the mean, and its autocorrelation after one iteration is −0.41-0.41.

How the step must shrink with dimension#

Make the target a product of dd independent copies of one coordinate. Write Δ=−log⁡(acceptance ratio)\Delta = -\log(\text{acceptance ratio}) for the energy error of a proposal, a sum of dd independent terms Δ1\Delta_1. Its mean must stay of order one, or the acceptance rate collapses, so E[Δ1]\mathbb E[\Delta_1] must shrink like 1/d1/d. How fast it shrinks with the step decides the rest (Neal, 2011, Sections 4.4 and 5.2):

SamplerE[Δ1]\mathbb E[\Delta_1] grows asstep that keeps E[Δ]\mathbb E[\Delta] fixedproposals per independent sample
random walk, step σ\sigmaσ2\sigma^2σ∝d−1/2\sigma \propto d^{-1/2}σ−2∝d\sigma^{-2} \propto d
MALA, variance ε\varepsilonε3\varepsilon^3ε∝d−1/3\varepsilon \propto d^{-1/3}ε−1∝d1/3\varepsilon^{-1} \propto d^{1/3}
HMC, step ε\varepsilon, fixed trajectory lengthε4\varepsilon^4ε∝d−1/4\varepsilon \propto d^{-1/4}ε−1∝d1/4\varepsilon^{-1} \propto d^{1/4} leapfrog steps

For the random walk, the Taylor expansion U(x+c)−U(x)=c U′(x)+12c2U′′(x)+O(c3)U(x + c) - U(x) = c\, U'(x) + \tfrac12 c^2 U''(x) + O(c^3), averaged over c=±σc = \pm\sigma, cancels the linear term and leaves 12σ2U′′(x)\tfrac12 \sigma^2 U''(x), of order σ2\sigma^2. For MALA and HMC, Δ1\Delta_1 is the leapfrog energy error: order h3h^3 for one step of size h=εh = \sqrt\varepsilon (MALA is one such step), order ε2\varepsilon^2 over a fixed-length trajectory. Squared errors give the mean, through an identity that holds for any Metropolis–Hastings proposal made from a state distributed as π\pi:

E[e−Δ]=∬π(x) q(y∣x) π(y) q(x∣y)π(x) q(y∣x) dx dy=∬π(y) q(x∣y) dx dy=1.\begin{aligned} \mathbb E\big[e^{-\Delta}\big] &= \iint \pi(x)\, q(y \mid x)\, \frac{\pi(y)\, q(x \mid y)}{\pi(x)\, q(y \mid x)}\, dx\, dy \\ &= \iint \pi(y)\, q(x \mid y)\, dx\, dy = 1 . \end{aligned}

Expanding e−Δ≈1−Δ+Δ2/2e^{-\Delta} \approx 1 - \Delta + \Delta^2/2 gives E[Δ]≈E[Δ2]/2\mathbb E[\Delta] \approx \mathbb E[\Delta^2]/2. In the last column the random walk and MALA diffuse, so they need (step length)−2^{-2} proposals, while one HMC trajectory crosses the target in 1/ε1/\varepsilon leapfrog steps.

The same identity gives the tuning targets. For large dd the central limit theorem makes Δ\Delta, a sum of dd independent terms, approximately N(μ,s2)\mathcal N(\mu, s^2). A Gaussian has E[e−Δ]=e−μ+s2/2\mathbb E[e^{-\Delta}] = e^{-\mu + s^2/2}, its moment generating function at −1-1, and the identity sets this to 1, so s2=2μs^2 = 2\mu: the variance is twice the mean. The acceptance rate Emin⁡(1,e−Δ)\mathbb E \min(1, e^{-\Delta}) splits at Δ=0\Delta = 0:

a(μ)=P(Δ<0)+E[e−Δ 1[Δ>0]]=2 Φ(−μ/2),\begin{aligned} a(\mu) &= P(\Delta < 0) + \mathbb E\big[e^{-\Delta}\, \mathbf 1[\Delta > 0]\big] \\ &= 2\,\Phi\big(-\sqrt{\mu/2}\big) , \end{aligned}

with Φ\Phi the standard normal distribution function (steps below). By the table the cost per independent sample is 1/(a(μ) μk)1/(a(\mu)\,\mu^k), with k=1k = 1, 1/31/3 and 1/41/4. Minimizing it numerically gives the optimal acceptance rates 0.2340.234 for the random walk, 0.5740.574 for MALA and 0.6510.651 for HMC. Every gradient or density value costs order dd, so the total work per independent sample grows as d2d^2, d4/3d^{4/3} and d5/4d^{5/4}.

Derivation

The first term is Φ(−μ/s)=Φ(−μ/2)\Phi(-\mu/s) = \Phi(-\sqrt{\mu/2}). For the second, completing the square shows that e−Δe^{-\Delta} times the density of N(μ,s2)\mathcal N(\mu, s^2) is e−μ+s2/2=1e^{-\mu + s^2/2} = 1 times the density of N(μ−s2,s2)=N(−μ,2μ)\mathcal N(\mu - s^2, s^2) = \mathcal N(-\mu, 2\mu), whose probability above zero is again Φ(−μ/2)\Phi(-\sqrt{\mu/2}).

Tuning HMC: step size, trajectory length and mass matrix#

The step size must stay below twice the standard deviation of the narrowest direction (0.450.45 for the target above), and in practice somewhat below, at an acceptance rate of about 0.650.65.

The trajectory length εL\varepsilon L decides how far a proposal goes. Too short a trajectory makes HMC a random walk of small steps (with L=1L = 1 it is MALA); too long a one turns back and wastes gradients; a fixed length can resonate with a period of the target. On a Gaussian direction of variance σ2\sigma^2 the leapfrog step is a linear map with determinant 1 and trace 2−ε2/σ22 - \varepsilon^2/\sigma^2, a rotation (after rescaling) by θ\theta with cos⁡θ=1−ε2/(2σ2)\cos\theta = 1 - \varepsilon^2/(2\sigma^2). In the narrow direction above, ε=0.25\varepsilon = 0.25 gives θ=1.19\theta = 1.19, and L=10L = 10 steps make 1.891.89 turns, which bring that coordinate back near its start. Drawing ε\varepsilon or LL at random in a small range at every iteration breaks such resonances (Neal, 2011, Section 3.2).

Setting the inverse mass matrix M−1M^{-1} to an estimate Σ\Sigma of the covariance of π\pi is equivalent to running HMC with identity mass on the whitened variable Σ−1/2x\Sigma^{-1/2} x, in which the target is roughly isotropic and the stability limit no longer depends on the correlations (Neal, 2011, Section 4.1). In high dimensions a diagonal MM estimated during warm-up is the usual compromise.

NUTS: stop at the U-turn#

The No-U-Turn Sampler (Hoffman and Gelman, 2014) removes the choice of LL: it extends the trajectory until it starts to come back. With identity mass, the squared distance from the start xx to the current point x~\tilde x changes at the rate

ddt ∥x~−x∥22=(x~−x)⋅p~,\frac{d}{dt}\, \frac{\|\tilde x - x\|^2}{2} = (\tilde x - x) \cdot \tilde p ,

by the chain rule and dx~/dt=p~d\tilde x/dt = \tilde p. While this is positive, more simulation moves the proposal farther away.

Stopping at the first negative value would break reversibility, since a trajectory run back from the stopping point would usually stop elsewhere. NUTS instead doubles the trajectory, 1,2,4,…1, 2, 4, \dots leapfrog steps, each time forwards or backwards at random, until its two ends start to approach each other, and draws the next state from the whole trajectory with weights that keep π(x,p)\pi(x, p) invariant (Hoffman and Gelman, 2014, Section 3.1). During warm-up, dual averaging tunes ε\varepsilon towards a target acceptance δ\delta (Section 3.2). Pyro’s NUTS(potential_fn=...) runs it on any potential, with δ\delta = target_accept_prob, 0.8 by default (Pyro documentation).

Where it breaks: separated modes#

A particle that starts a trajectory with kinetic energy KK can climb at most KK in potential. Take the mixture π=12N(−m,1)+12N(m,1)\pi = \tfrac12 \mathcal N(-m, 1) + \tfrac12 \mathcal N(m, 1). Between the modes, at x=0x = 0, both components contribute 12φ(m)\tfrac12\varphi(m), where φ\varphi is the standard normal density; at a mode the far component is negligible. The barrier is

U(0)−U(m)≈log⁡12φ(0)φ(m)=m22−log⁡2.\begin{aligned} U(0) - U(m) &\approx \log \frac{\tfrac12 \varphi(0)}{\varphi(m)} \\ &= \frac{m^2}{2} - \log 2 . \end{aligned}

A chain at a mode crosses only when the fresh momentum supplies that much energy, p2/2>U(0)−U(m)p^2/2 > U(0) - U(m). A run of 100,000 HMC iterations (ε=0.2\varepsilon = 0.2, L=25L = 25) started at x=mx = m:

mmbarrierP(p2/2>barrier)P(p^2/2 > \text{barrier})crossings of 0
21.310.1121,027
33.810.00581,903
47.311.3⋅10−41.3 \cdot 10^{-4}67
511.811.2⋅10−61.2 \cdot 10^{-6}0

The barrier grows with m2m^2, and the crossing probability falls roughly like e−barriere^{-\text{barrier}}. At m=5m = 5 the chain never leaves its starting mode while accepting 99.7% of its proposals, and every diagnostic computed from it looks healthy. Only chains started in different places, compared as in the probability course, reveal the second mode; tempering methods, which run chains on flattened versions of the target, cross it at extra cost.

What you should remember#

  • MALA: Euler step of dX=12∇log⁡π dt+dWdX = \frac12\nabla\log\pi\,dt + dW as the proposal, with qq both ways in the test; exact for every ε\varepsilon.
  • HMC: momentum p∼N(0,M)p \sim \mathcal N(0, M), LL leapfrog steps, accept with min⁡(1,e−ΔH)\min(1, e^{-\Delta H}).
  • Leapfrog is a composition of shears (volume 1) and is reversible, so no Jacobian enters the test; Euler is neither.
  • Steps scale as d−1/2d^{-1/2}, d−1/3d^{-1/3}, d−1/4d^{-1/4}; target acceptance 0.2340.234, 0.5740.574, 0.650.65; leapfrog needs ε<2σmin⁡\varepsilon < 2\sigma_{\min}.
  • No sampler here crosses a high energy barrier between modes.

Notebook#

The MCMC notebook of the HSE-LAMBDA Deep Generative Models course runs five samplers on the one-dimensional N(0,1)\mathcal N(0, 1). The notebook has no saved outputs, so it documents procedures only.

  • Rejection sampling (cells 4–6): proposal N(0,22)\mathcal N(0, 2^2) with M=1.5M = 1.5, which does not bound π/q=2e−3x2/8\pi/q = 2e^{-3x^2/8}; the kept points follow min⁡(π,1.5 q)\min(\pi, 1.5\,q), with variance 1.1071.107. The correct constant is M=2M = 2.
  • Metropolis–Hastings (cells 7–9): a random walk with step 0.50.5, 1000 steps from x=0x = 0. It accepts about 84% of proposals in small, correlated steps; a step of 2.42.4 gives the one-dimensional optimum of about 44%.
  • MALA (cells 10–12): step_size = 0.1 is a standard deviation, so ε=0.01\varepsilon = 0.01; the integrated autocorrelation time is then about 400 steps, and 1000 steps are worth two or three independent samples.
  • HMC and NUTS in Pyro (cells 13–18): HMC(model, step_size=0.1, num_steps=10) and NUTS(model), 500 samples after 100 warm-up steps. Pyro adapts the step size by default, so only the trajectory length εL=1\varepsilon L = 1 stays fixed.

Next#

An energy-based model needs samples from its own density after every update of its parameters, to estimate the gradient of log⁡Z\log Z, and cannot afford converged chains. The next note derives that gradient, with its negative phase that needs model samples, and trains energy networks with short Langevin chains and a replay buffer.

References#