Skip to content
BIASED

Sampling unnormalized densities: MALA and HMC

How to sample a density known only up to a constant by following its gradient: the Langevin step and MALA, Hamiltonian Monte Carlo with the leapfrog integrator, why both need only the gradient of the log-density, and where they break.

Densities known up to a constant

The topic The change of variables bought an exact likelihood with a strict architecture: every layer invertible, in the same dimension, with a cheap log-determinant. Now drop normalization altogether. Take any network U:RD→RU: \mathbb R^D \to \mathbb R and declare

p(x)=p~(x)Z,p~(x)=e−U(x),Z=∫e−U(x) dx.p(x) = \frac{\tilde p(x)}{Z}, \qquad \tilde p(x) = e^{-U(x)}, \qquad Z = \int e^{-U(x)}\, dx .

UU is the energy: low energy means high density. Any architecture will do, but ZZ is an integral over all of RD\mathbb R^D, and nobody can compute it. So p(x)p(x) itself cannot be evaluated. Two other quantities can:

p(y)p(x)=eU(x)−U(y),∇xlog⁡p(x)=−∇xU(x).\frac{p(y)}{p(x)} = e^{U(x) - U(y)}, \qquad \nabla_x \log p(x) = -\nabla_x U(x).

In the ratio ZZ cancels. The gradient in xx never sees it, because log⁡Z\log Z does not depend on xx. The gradient of the log-density is called the score, and it costs one backward pass through UU. How do we draw samples of pp with nothing but these two?

Half of the answer exists already. The course Bayesian Methods in Machine Learning builds Markov chains for exactly such targets, posteriors with an unknown evidence (see its topics Monte Carlo and Markov chains and Gibbs sampling and Metropolis–Hastings). Recall Metropolis–Hastings: from the state xx, propose y∼r(y∣x)y \sim r(y \mid x) and move there with probability

A(x,y)=min⁡(1, p~(y) r(x∣y)p~(x) r(y∣x)),A(x, y) = \min\left(1,\ \frac{\tilde p(y)\, r(x \mid y)}{\tilde p(x)\, r(y \mid x)}\right),

otherwise stay at xx. Only a ratio of p~\tilde p enters, and detailed balance makes pp the stationary distribution.

The usual proposal is a random walk, y=x+szy = x + s z with z∼N(0,I)z \sim \mathcal N(0, I). It knows nothing about the target. Its step ss must be about the width of the narrowest direction, or proposals land in low density and get rejected. Independent steps add in variance, so nn steps travel about sns\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.95\rho = 0.95, the axes of the ellipse have variances 1+ρ=1.951 + \rho = 1.95 and 1−ρ=0.051 - \rho = 0.05, so σmax⁡≈1.40\sigma_{\max} \approx 1.40 and σmin⁡≈0.22\sigma_{\min} \approx 0.22: about 3939 steps for one crossing, even if every proposal were accepted.

The Langevin step

The random walk proposes blindly, yet we can evaluate ∇log⁡p~\nabla \log \tilde p, which points uphill. The Langevin update uses it:

xk+1=xk+η2 ∇log⁡p~(xk)+η zk,zk∼N(0,I),x_{k+1} = x_k + \frac{\eta}{2}\, \nabla \log \tilde p(x_k) + \sqrt{\eta}\, z_k, \qquad z_k \sim \mathcal N(0, I),

with a step size η>0\eta > 0. The drift η2∇log⁡p~\tfrac{\eta}{2} \nabla \log \tilde p moves the point uphill in log⁡p\log p. The noise kicks it around, so the chain explores instead of settling on a peak. Without the noise this is gradient ascent, and every chain stops at a mode. The update is one Euler step of the Langevin diffusion, a continuous-time process whose stationary distribution is exactly pp (Roberts and Tweedie, 1996). The drift with factor 12\tfrac12 and noise of variance η\eta are matched for that.

Run as a chain, the update is the unadjusted Langevin algorithm (ULA). "Unadjusted" because a finite step breaks the balance slightly. Take p=N(0,1)p = \mathcal N(0, 1), where ∇log⁡p~(x)=−x\nabla \log \tilde p(x) = -x. Then one step is

xk+1=a xk+η zk,a=1−η2.x_{k+1} = a\, x_k + \sqrt{\eta}\, z_k, \qquad a = 1 - \frac{\eta}{2} .

If xkx_k has variance vv, then xk+1x_{k+1} has variance a2v+ηa^2 v + \eta, because xkx_k and zkz_k are independent. The chain settles where vv reproduces itself, and that vv is not 11: it exceeds 11 for every η>0\eta > 0. ULA samples a slightly wider distribution than the target, and the error vanishes only as η→0\eta \to 0. Once ∣a∣≥1\lvert a\rvert \ge 1 the chain does not settle at all.

MALA: the Langevin step as a proposal

The bias has a standard cure: keep the Langevin step as a proposal and add the Metropolis–Hastings test. This is the Metropolis-adjusted Langevin algorithm (MALA; Roberts and Tweedie, 1996). The proposal is a Gaussian centred at the drifted point:

r(y∣x)=N(y; x+η2∇log⁡p~(x), ηI).r(y \mid x) = \mathcal N\Big(y;\ x + \frac{\eta}{2} \nabla \log \tilde p(x),\ \eta I\Big).

It is not symmetric. The reverse move from yy is centred at y+η2∇log⁡p~(y)y + \tfrac{\eta}{2} \nabla \log \tilde p(y), with the gradient taken at yy, so both r(y∣x)r(y \mid x) and r(x∣y)r(x \mid y) enter A(x,y)A(x, y). The detailed-balance argument of Metropolis–Hastings works for any proposal, so pp is stationary for every η\eta. A large step costs rejections, never bias. Each step needs one new gradient and one new energy, both at yy.

On p=N(0,1)p = \mathcal N(0, 1) the two proposal densities and the two target values collapse into a short formula. Expand both squares; the cross terms cancel and

log⁡p~(y) r(x∣y)p~(x) r(y∣x)=η8 (x2−y2).\log \frac{\tilde p(y)\, r(x \mid y)}{\tilde p(x)\, r(y \mid x)} = \frac{\eta}{8}\,\big(x^2 - y^2\big).

A random walk gets (x2−y2)/2(x^2 - y^2)/2 for the same pair. MALA's log-ratio is η/4\eta/4 times that, because the proposal already moves the way the density does. Take x=2x = 2 and η=1\eta = 1, so the proposal is N(1,1)\mathcal N(1, 1), and a draw that lands farther out, y=2.8y = 2.8. A random walk would accept this move with probability e−1.92≈0.15e^{-1.92} \approx 0.15. MALA accepts it with e−0.48≈0.62e^{-0.48} \approx 0.62: from 2.82.8 the reverse proposal is centred at 1.41.4, so a way back to 22 is easy to find.

Momentum and energy

MALA forgets its direction after every step. Each move starts from fresh noise, so the chain still diffuses, only with a better local guess. Hamiltonian Monte Carlo (HMC; Duane et al., 1987; Neal, 2011) gives the chain a velocity that persists for many steps.

Add an auxiliary momentum v∈RDv \in \mathbb R^D and sample pairs (x,v)(x, v) from

p(x,v)∝e−H(x,v),H(x,v)=U(x)+12∥v∥2.p(x, v) \propto e^{-H(x, v)}, \qquad H(x, v) = U(x) + \tfrac12 \lVert v\rVert^2 .

The density factorizes into e−U(x)e^{-U(x)} times e−∥v∥2/2e^{-\lVert v\rVert^2/2}. So v∼N(0,I)v \sim \mathcal N(0, I) independently of xx, and the marginal of xx is pp. Sample pairs, then throw vv away.

The physics reading helps. xx is the position of a particle on a landscape of height U(x)U(x), its potential energy. 12∥v∥2\tfrac12 \lVert v\rVert^2 is its kinetic energy, and HH is the total energy. The particle moves by Hamilton's equations:

dxdt=v,dvdt=−∇U(x).\frac{dx}{dt} = v, \qquad \frac{dv}{dt} = -\nabla U(x).

It speeds up going downhill in UU, slows down going uphill, and rolls through a valley and up the other side. The exact flow has three properties:

  • It conserves HH. By the chain rule, dHdt=∇U⋅v+v⋅(−∇U)=0\frac{dH}{dt} = \nabla U \cdot v + v \cdot (-\nabla U) = 0.
  • It preserves volume in the (x,v)(x, v) space. The velocity field (v, −∇U(x))\big(v,\ -\nabla U(x)\big) has zero divergence: its xx-part does not depend on xx, and its vv-part does not depend on vv.
  • It is reversible. Run it for a time tt, negate vv, run it for tt again, and you are back at the start with negated momentum.

If we could follow this flow exactly, the end of a long trajectory would have the same HH as its start, and the Metropolis–Hastings test would accept it however far it went. On a computer the flow must be discretized.

The leapfrog integrator

Euler's method updates xx and vv with the derivatives at the current point. On p=N(0,1)p = \mathcal N(0, 1), where U=x2/2U = x^2/2, the exact trajectories are circles in the (x,v)(x, v) plane. One Euler step of size hh maps (x,v)(x, v) to (x+hv, v−hx)(x + hv,\ v - hx), and

(x+hv)2+(v−hx)2=(1+h2) (x2+v2).(x + hv)^2 + (v - hx)^2 = (1 + h^2)\,(x^2 + v^2).

Every step multiplies HH by 1+h21 + h^2, and the trajectory spirals outwards.

The leapfrog integrator (Störmer–Verlet) splits the momentum update into two halves around a full position step:

v1/2=v−h2∇U(x),x′=x+h v1/2,v′=v1/2−h2∇U(x′).v_{1/2} = v - \frac{h}{2} \nabla U(x), \qquad x' = x + h\, v_{1/2}, \qquad v' = v_{1/2} - \frac{h}{2} \nabla U(x').

The last gradient of one step is the first gradient of the next, so LL steps cost LL gradients. Leapfrog does not conserve HH exactly, but it keeps the other two properties exactly. Each of its three lines is a shear: it changes one block of variables by an amount that depends only on the other block. Its Jacobian is block-triangular with identity blocks on the diagonal, so its determinant is 11. That is the argument behind coupling layers in The change of variables. And running the three lines from (x′,−v′)(x', -v') returns exactly (x,−v)(x, -v), so leapfrog is reversible.

One step on N(0,1)\mathcal N(0, 1) from x=1x = 1, v=0.5v = 0.5 with h=0.5h = 0.5. Leapfrog first halves the momentum update, v1/2=0.5−0.25⋅1=0.25v_{1/2} = 0.5 - 0.25 \cdot 1 = 0.25, then:

leapfrog Euler
new position x′x' 1.1251.125 1.251.25
new momentum v′v' −0.03125-0.03125 00
energy, from H=0.625H = 0.625 0.63330.6333 0.781250.78125
error ΔH\Delta H 0.00830.0083 0.1560.156

Leapfrog's energy error is nineteen times smaller, and over a trajectory it oscillates instead of accumulating. That holds only while the step is small compared with the narrowest direction of the target. For a Gaussian with standard deviation σ\sigma, leapfrog is stable for h<2σh < 2\sigma; beyond that, trajectories run off to infinity.

One HMC iteration

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

  1. Refresh the momentum: draw v∼N(0,I)v \sim \mathcal N(0, I), independently of everything else. This is the only part that changes the energy level.
  2. Simulate: LL leapfrog steps of size hh take (x,v)(x, v) to (x′,v′)(x', v').
  3. Accept x′x' with probability min⁡(1,e−ΔH)\min\big(1, e^{-\Delta H}\big), where ΔH=H(x′,v′)−H(x,v)\Delta H = H(x', v') - H(x, v); otherwise keep xx. Drop the momentum.

Why is e−ΔHe^{-\Delta H} the whole test? Once vv is drawn, the proposal is deterministic: LL leapfrog steps followed by a flip of the momentum. Reversibility makes this map its own inverse, and the shears make it keep volume. For such a map the Metropolis–Hastings ratio is just the ratio of target densities, p(x′,v′)/p(x,v)=e−ΔHp(x', v')/p(x, v) = e^{-\Delta H}. The flip does not change HH, so in practice it is skipped. The refresh draws vv from its exact conditional given xx, a Gibbs step, so it also leaves p(x,v)p(x, v) invariant.

Volume preservation is load-bearing. A proposal map that stretched space would need the factor ∣det⁡J∣\lvert\det J\rvert in the ratio, the same change-of-variables term that flows pay in their likelihood. Euler's step on N(0,1)\mathcal N(0, 1) has determinant 1+h21 + h^2, so a chain built on Euler with the plain e−ΔHe^{-\Delta H} test would sample the wrong distribution.

ΔH\Delta H is only the integration error, so a good integrator keeps acceptance high even for long trajectories that travel far. MALA is the special case L=1L = 1. One leapfrog step from a fresh vv moves xx to x+hv−h22∇U(x)x + hv - \tfrac{h^2}{2} \nabla U(x): the MALA proposal with η=h2\eta = h^2, and its MALA acceptance ratio equals e−ΔHe^{-\Delta H} exactly (Neal, 2011, Section 5.2).

Comparison and tuning

Compare the three samplers on the narrow Gaussian from the first block, ρ=0.95\rho = 0.95, with the same budget: 30003000 evaluations of the target, a gradient counted as one. The random walk uses s=1s = 1; MALA uses η=0.17\eta = 0.17; HMC uses h=0.3h = 0.3 and L=10L = 10, so it gets 300300 iterations. Averaged over 20002000 runs:

sampler accepted ESS of x1x_1
random walk 24%24\% ≈80\approx 80
MALA 58%58\% ≈45\approx 45
HMC 84%84\% >300> 300

The gradient alone buys MALA nothing here. Along the narrow direction its drift multiplies the coordinate by 1−η/(2σmin⁡2)1 - \eta/(2\sigma_{\min}^2), which drops below −1-1 for η>4σmin⁡2=0.2\eta > 4\sigma_{\min}^2 = 0.2, so the step is capped by that direction, and along the long one the chain still diffuses. HMC carries its momentum along the long axis. Consecutive states tend to land on opposite sides of the mean, their lag-one autocorrelation is about −0.3-0.3, and the ESS exceeds the number of iterations, as negative correlations allow (see Monte Carlo and Markov chains).

Dimension sharpens the difference. For a target made of dd independent coordinates, the step must shrink as dd grows, or the acceptance rate collapses. The cost of one independent sample then grows at different rates (Roberts, Gelman and Gilks, 1997; Roberts and Rosenthal, 1998; Neal, 2011, Section 4.4):

sampler step proposals per independent sample best acceptance
random walk s∝d−1/2s \propto d^{-1/2} ∝d\propto d 0.2340.234
MALA η∝d−1/3\eta \propto d^{-1/3} ∝d1/3\propto d^{1/3} 0.5740.574
HMC h∝d−1/4h \propto d^{-1/4} ∝d1/4\propto d^{1/4} leapfrog steps ≈0.65\approx 0.65

HMC has three knobs. The step hh stays below 2σmin⁡2\sigma_{\min} and is tuned to about 65%65\% acceptance. The trajectory length hLhL decides how far a proposal goes: too short and HMC becomes MALA again, too long and the trajectory turns back and wastes gradients. A mass matrix draws v∼N(0,M)v \sim \mathcal N(0, M) and moves xx along M−1vM^{-1} v; with M−1M^{-1} close to the covariance of pp, the target looks round to the sampler. The No-U-Turn Sampler (NUTS; Hoffman and Gelman, 2014) removes the choice of LL by extending each trajectory until it starts to turn back, and it is the default sampler in Stan and PyMC.

Where the samplers break

All these samplers move locally, and that has a price. A trajectory that starts with kinetic energy 12∥v∥2\tfrac12 \lVert v\rVert^2 can climb at most that much in UU. Take the mixture p=12N(−m,1)+12N(m,1)p = \tfrac12 \mathcal N(-m, 1) + \tfrac12 \mathcal N(m, 1). Between the modes the energy rises by a barrier

ΔU=U(0)−U(m)≈m22−log⁡2.\Delta U = U(0) - U(m) \approx \frac{m^2}{2} - \log 2 .

A chain in one mode crosses only when the fresh momentum supplies that much energy. With v∼N(0,1)v \sim \mathcal N(0, 1), the chance falls roughly like e−ΔUe^{-\Delta U}:

mm barrier ΔU\Delta U P(v2/2>ΔU)P\big(v^2/2 > \Delta U\big)
22 1.311.31 0.110.11
33 3.813.81 0.00580.0058
44 7.317.31 1.3⋅10−41.3 \cdot 10^{-4}
55 11.8111.81 1.2⋅10−61.2 \cdot 10^{-6}

At m=5m = 5, an HMC chain (h=0.2h = 0.2, L=25L = 25) started in the right mode crosses less than once per 100 000100\,000 iterations, while accepting 99.7%99.7\% of its proposals. Its acceptance rate and ESS look healthy; it has simply sampled half of the distribution. Only several chains started in different places and compared with each other reveal the second mode. Langevin and MALA are stuck in the same way. Tempering methods, which run chains on flattened versions of the target, can cross such barriers at extra cost.

Within these limits, we can now sample any density we can differentiate. MALA and HMC need only UU and ∇U\nabla U, and for a network ∇U\nabla U is one backward pass. That makes a new kind of model possible: a network that outputs a single number, an energy Eθ(x)E_\theta(x), and defines pθ(x)∝e−Eθ(x)p_\theta(x) \propto e^{-E_\theta(x)} with no invertibility and no normalizer. Training it is the open problem. Maximum likelihood for such a model turns out to need samples from the model itself after every update of θ\theta, and the samplers of this topic, run for a few steps at a time, are what supply them. That is the next topic, Energy-based models.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.