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 and declare
is the energy: low energy means high density. Any architecture will do, but is an integral over all of , and nobody can compute it. So itself cannot be evaluated. Two other quantities can:
In the ratio cancels. The gradient in never sees it, because does not depend on . The gradient of the log-density is called the score, and it costs one backward pass through . How do we draw samples of 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 , propose and move there with probability
otherwise stay at . Only a ratio of enters, and detailed balance makes the stationary distribution.
The usual proposal is a random walk, with . It knows nothing about the target. Its step must be about the width of the narrowest direction, or proposals land in low density and get rejected. Independent steps add in variance, so steps travel about , and crossing the widest direction takes about steps. For a bivariate normal with unit variances and correlation , the axes of the ellipse have variances and , so and : about steps for one crossing, even if every proposal were accepted.
The Langevin step
The random walk proposes blindly, yet we can evaluate , which points uphill. The Langevin update uses it:
with a step size . The drift moves the point uphill in . 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 (Roberts and Tweedie, 1996). The drift with factor and noise of variance 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 , where . Then one step is
If has variance , then has variance , because and are independent. The chain settles where reproduces itself, and that is not : it exceeds for every . ULA samples a slightly wider distribution than the target, and the error vanishes only as . Once 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:
It is not symmetric. The reverse move from is centred at , with the gradient taken at , so both and enter . The detailed-balance argument of Metropolis–Hastings works for any proposal, so is stationary for every . A large step costs rejections, never bias. Each step needs one new gradient and one new energy, both at .
On the two proposal densities and the two target values collapse into a short formula. Expand both squares; the cross terms cancel and
A random walk gets for the same pair. MALA's log-ratio is times that, because the proposal already moves the way the density does. Take and , so the proposal is , and a draw that lands farther out, . A random walk would accept this move with probability . MALA accepts it with : from the reverse proposal is centred at , so a way back to 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 and sample pairs from
The density factorizes into times . So independently of , and the marginal of is . Sample pairs, then throw away.
The physics reading helps. is the position of a particle on a landscape of height , its potential energy. is its kinetic energy, and is the total energy. The particle moves by Hamilton's equations:
It speeds up going downhill in , slows down going uphill, and rolls through a valley and up the other side. The exact flow has three properties:
- It conserves . By the chain rule, .
- It preserves volume in the space. The velocity field has zero divergence: its -part does not depend on , and its -part does not depend on .
- It is reversible. Run it for a time , negate , run it for 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 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 and with the derivatives at the current point. On , where , the exact trajectories are circles in the plane. One Euler step of size maps to , and
Every step multiplies by , and the trajectory spirals outwards.
The leapfrog integrator (Störmer–Verlet) splits the momentum update into two halves around a full position step:
The last gradient of one step is the first gradient of the next, so steps cost gradients. Leapfrog does not conserve 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 . That is the argument behind coupling layers in The change of variables. And running the three lines from returns exactly , so leapfrog is reversible.
One step on from , with . Leapfrog first halves the momentum update, , then:
| leapfrog | Euler | |
|---|---|---|
| new position | ||
| new momentum | ||
| energy, from | ||
| error |
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 , leapfrog is stable for ; beyond that, trajectories run off to infinity.
One HMC iteration
One HMC iteration from the current state has three parts (Neal, 2011, Section 3.2):
- Refresh the momentum: draw , independently of everything else. This is the only part that changes the energy level.
- Simulate: leapfrog steps of size take to .
- Accept with probability , where ; otherwise keep . Drop the momentum.
Why is the whole test? Once is drawn, the proposal is deterministic: 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, . The flip does not change , so in practice it is skipped. The refresh draws from its exact conditional given , a Gibbs step, so it also leaves invariant.
Volume preservation is load-bearing. A proposal map that stretched space would need the factor in the ratio, the same change-of-variables term that flows pay in their likelihood. Euler's step on has determinant , so a chain built on Euler with the plain test would sample the wrong distribution.
is only the integration error, so a good integrator keeps acceptance high even for long trajectories that travel far. MALA is the special case . One leapfrog step from a fresh moves to : the MALA proposal with , and its MALA acceptance ratio equals exactly (Neal, 2011, Section 5.2).
Comparison and tuning
Compare the three samplers on the narrow Gaussian from the first block, , with the same budget: evaluations of the target, a gradient counted as one. The random walk uses ; MALA uses ; HMC uses and , so it gets iterations. Averaged over runs:
| sampler | accepted | ESS of |
|---|---|---|
| random walk | ||
| MALA | ||
| HMC |
The gradient alone buys MALA nothing here. Along the narrow direction its drift multiplies the coordinate by , which drops below for , 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 , 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 independent coordinates, the step must shrink as 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 | |||
| MALA | |||
| HMC | leapfrog steps |
HMC has three knobs. The step stays below and is tuned to about acceptance. The trajectory length 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 and moves along ; with close to the covariance of , the target looks round to the sampler. The No-U-Turn Sampler (NUTS; Hoffman and Gelman, 2014) removes the choice of 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 can climb at most that much in . Take the mixture . Between the modes the energy rises by a barrier
A chain in one mode crosses only when the fresh momentum supplies that much energy. With , the chance falls roughly like :
| barrier | ||
|---|---|---|
At , an HMC chain (, ) started in the right mode crosses less than once per iterations, while accepting 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 and , and for a network is one backward pass. That makes a new kind of model possible: a network that outputs a single number, an energy , and defines 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 , 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.
Answers are saved on the server and tied to this browser until you sign in.