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 to one number , and declare the density of images to be . The energy-based models of the next note define densities this way, with no architectural restriction of the kind flows need. The normalizer is an integral over all images, and nobody can compute it. Two other quantities are cheap:
In the ratio cancels, and the gradient with respect to never sees it, because does not depend on . is called the potential energy and the score. How do we draw samples of 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 with probability , which needs a bound . It is exact, and it dies with dimension. Take the target and the proposal . The ratio is a product of factors , each at most 2, so
That is one proposal in 1,024 kept at and one in at .
Metropolis–Hastings (Markov chain Monte Carlo) gives up independent draws. From the current state it proposes and moves there with probability
otherwise it stays at . With the random-walk proposal , where is fresh noise, is symmetric and cancels.
The random walk knows nothing about the target. Its step must be about the width of the narrowest direction, or proposals land in low density and are 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 standard deviations and , 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 and is jostled by noise. The Langevin diffusion writes this as
where is a standard Brownian motion: its increment over a time is , independent of the past. The drift alone would climb to a mode and stop; the noise alone would spread without limit. With the factor 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 (noise scale there) the density of obeys the first line below. The second line writes it as minus the divergence of the flux , drift minus diffusion, and the drift makes that flux zero at :
Here is the Laplacian; Isachenko (2025, lecture 10) finds the same drift by setting . Stationarity does not yet say that chains reach , and the discretized chain below does not even keep exactly. For a potential that is -strongly convex with an -Lipschitz gradient, the unadjusted chain forgets its start geometrically and ends within a distance of order of (Dalalyan, 2017, Theorem 1; the bound is below).
The bound
In the notation of the theorem the Euler step below has , and for the distribution of the state after steps satisfies
where 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 per step, because a strongly convex pulls them together. The second is the price of the frozen drift; it does not shrink with but vanishes as .
One Euler step: unadjusted Langevin#
To simulate the diffusion for a time , hold the drift at its value at the start and draw the Brownian increment exactly:
Used as a chain, this is the unadjusted Langevin algorithm (ULA) of the probability course, and the frozen drift makes it slightly wrong. On the score is , one step is with , and a stationary variance must reproduce itself, since and are independent:
The variance is at and at , against the target’s 1; for , where , 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
It is not symmetric: the reverse move from is centred at , with the drift at , so both and enter . Each step costs one new gradient, at .
Why is the chain exact for every ? The probability course proves the general case; here is the core step. A chain leaves invariant if it satisfies detailed balance, . For the chain reaches only by proposing and accepting it, so . Moving the positive factor inside the minimum gives
which is symmetric in and and therefore equals . Rejections form a point mass at , where detailed balance holds trivially (the full kernel is written out in the probability course and in «Байесовские методы в анализе данных», 2026, lecture 4). So is stationary for any step size; a larger costs rejections, never bias.
Worked example: MALA on a standard normal#
Take , so , and write for the factor that maps to the proposal mean . The log-ratio of the two proposal densities is
where the second line expands both squares (the cross terms cancel) and the third uses . Adding leaves
The random walk’s log-ratio for the same pair is ; MALA’s is that times , because the proposal already carries most of the change in density. With and the proposal is . A draw that lands farther out, at , has , so a random walk would accept it with probability . MALA accepts it with : the reverse proposal from has mean , only from , so the move is easy to undo.
The example also suggests why ULA’s bias is small for small steps: a proposal moves by order , so the log-ratio is of order , 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 and a mass matrix (the identity unless said otherwise), and sample the pair from
The density factorizes as , so independently of , and the marginal of is : sample pairs and drop . Think of as the position of a particle with potential energy , kinetic energy and total energy (Neal, 2011, Section 3.1). The particle moves by Hamilton’s equations
The exact flow has three properties, and HMC rests on all three (Neal, 2011, Section 2.2). First, it conserves , by the chain rule and then Hamilton’s equations, with :
Second, it preserves volume in the space (Liouville’s theorem): the velocity field has zero divergence, since its -part does not depend on and its -part does not depend on . Third, it is reversible: run it for a time , negate the momentum, run it again for , and you are back at the start with negated momentum.
If we could follow the exact flow, every proposal would keep its and be accepted however far it went.
The leapfrog integrator#
Euler’s method updates and with the derivatives at the current point. On , where and exact trajectories are circles in the plane, one Euler step maps to , and
Every step multiplies the energy by , and the trajectory spirals outwards. The leapfrog (Störmer–Verlet) method splits the momentum update in two halves around a full position step:
Consecutive steps share a gradient, so steps cost gradients. Leapfrog does not conserve 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
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, , and apply the same three lines:
The first line uses the third leapfrog line, ; the second uses the middle line, ; the third uses the first line. The step returns to .
The energy error stays bounded#
On , where , the three leapfrog lines combine into a linear map. With and it reads and , and substituting it (steps below) shows that it conserves exactly the shadow energy
so along a leapfrog trajectory oscillates and never accumulates. For the coefficient of is no longer positive and trajectories run off to infinity; for a Gaussian with standard deviation the limit is , set by the narrowest direction. In general the error in is of order after one step and of order over a trajectory of fixed length (Neal, 2011, Section 2.3).
Derivation
Substituting the map into , the cross terms cancel:
since . Halving both sides gives .
A toy step on , from , with :
| Quantity | Leapfrog | Euler |
|---|---|---|
| half-step momentum | — | |
| new position | ||
| new momentum | ||
| energy, from | ||
| error |
Leapfrog’s move would be accepted with probability ; Euler’s error, , is nineteen times larger. The shadow energy is before and after the leapfrog step.
One HMC iteration#
An iteration of HMC from the current state has three parts (Neal, 2011, Section 3.2):
- Refresh the momentum: draw , independently of everything else. In the plane this is a vertical move, and it is the only part that changes the energy level.
- Simulate: apply leapfrog steps of size to to get . The trajectory follows a contour of up to the small leapfrog error.
- Accept with probability , where ; otherwise keep . Drop the momentum.
HMC iterations in phase space: leapfrog against Euler
MALA is HMC with a single leapfrog step. From a fresh momentum , one leapfrog step of size moves to : the MALA proposal with . Substituting the leapfrog momenta into the two proposal densities turns them into and , so the MALA ratio is exactly (steps below; Neal, 2011, Section 5.2). Without the test the chain is ULA, and on the shadow energy explains its bias. Leapfrog keeps volume and , and the refresh draws from , its conditional under since separates; both steps leave invariant. Its -marginal has variance , the ULA variance derived above.
Derivation
The momenta match the proposal densities. With and , the leapfrog lines give for the forward move and for the reverse one, so with the same constant
and the MALA ratio equals (Neal, 2011, Section 5.2).
Why the acceptance needs only the energy error#
Write , let be one leapfrog step and the momentum flip, and define the proposal map : run steps, then negate the momentum. Two facts about make the acceptance simple.
- is its own inverse. Reversibility says , so and , the identity.
- preserves volume, , because each leapfrog step and the flip do.
Accept the deterministic proposal with probability . For two regions and of phase space, the probability that the chain is in and moves into is
the probability of the reverse move. The first equality substitutes , allowed because is its own inverse with unit Jacobian; the second uses , which is unchanged when and swap. This is detailed balance, so the accept step leaves invariant. Since , the ratio itself is
and for the same reason the flip is skipped in practice. The refresh draws exactly from its conditional given , a Gibbs step, so it also leaves invariant, and so does the whole iteration.
A proposal map that stretched space would need the factor in the ratio, the change-of-variables term that normalizing flows pay for in their likelihood. Euler’s step on , the linear map with rows and , has determinant , so the factor is , and the plain ratio 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 , counting one gradient as one evaluation. The random walk () accepts 22%. MALA’s drift multiplies the narrow coordinate by , which drops below , so that the drift alone would push the coordinate ever farther out, for . Its step, with factor , sits just below that limit; it accepts 57%. HMC (, , so 300 iterations) accepts 86%.
Three samplers with the same budget on a narrow Gaussian
The effective sample sizes of 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 radians, so the chain tends to land on the other side of the mean, and its autocorrelation after one iteration is .
How the step must shrink with dimension#
Make the target a product of independent copies of one coordinate. Write for the energy error of a proposal, a sum of independent terms . Its mean must stay of order one, or the acceptance rate collapses, so must shrink like . How fast it shrinks with the step decides the rest (Neal, 2011, Sections 4.4 and 5.2):
| Sampler | grows as | step that keeps fixed | proposals per independent sample |
|---|---|---|---|
| random walk, step | |||
| MALA, variance | |||
| HMC, step , fixed trajectory length | leapfrog steps |
For the random walk, the Taylor expansion , averaged over , cancels the linear term and leaves , of order . For MALA and HMC, is the leapfrog energy error: order for one step of size (MALA is one such step), order 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 :
Expanding gives . In the last column the random walk and MALA diffuse, so they need (step length) proposals, while one HMC trajectory crosses the target in leapfrog steps.
The same identity gives the tuning targets. For large the central limit theorem makes , a sum of independent terms, approximately . A Gaussian has , its moment generating function at , and the identity sets this to 1, so : the variance is twice the mean. The acceptance rate splits at :
with the standard normal distribution function (steps below). By the table the cost per independent sample is , with , and . Minimizing it numerically gives the optimal acceptance rates for the random walk, for MALA and for HMC. Every gradient or density value costs order , so the total work per independent sample grows as , and .
Derivation
The first term is . For the second, completing the square shows that times the density of is times the density of , whose probability above zero is again .
Tuning HMC: step size, trajectory length and mass matrix#
The step size must stay below twice the standard deviation of the narrowest direction ( for the target above), and in practice somewhat below, at an acceptance rate of about .
The trajectory length decides how far a proposal goes. Too short a trajectory makes HMC a random walk of small steps (with 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 the leapfrog step is a linear map with determinant 1 and trace , a rotation (after rescaling) by with . In the narrow direction above, gives , and steps make turns, which bring that coordinate back near its start. Drawing or at random in a small range at every iteration breaks such resonances (Neal, 2011, Section 3.2).
Setting the inverse mass matrix to an estimate of the covariance of is equivalent to running HMC with identity mass on the whitened variable , 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 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 : it extends the trajectory until it starts to come back. With identity mass, the squared distance from the start to the current point changes at the rate
by the chain rule and . 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, 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 invariant (Hoffman and Gelman, 2014, Section 3.1). During warm-up, dual averaging tunes towards a target acceptance (Section 3.2). Pyro’s NUTS(potential_fn=...) runs it on any potential, with = target_accept_prob, 0.8 by default (Pyro documentation).
Where it breaks: separated modes#
A particle that starts a trajectory with kinetic energy can climb at most in potential. Take the mixture . Between the modes, at , both components contribute , where is the standard normal density; at a mode the far component is negligible. The barrier is
A chain at a mode crosses only when the fresh momentum supplies that much energy, . A run of 100,000 HMC iterations (, ) started at :
| barrier | crossings of 0 | ||
|---|---|---|---|
| 2 | 1.31 | 0.11 | 21,027 |
| 3 | 3.81 | 0.0058 | 1,903 |
| 4 | 7.31 | 67 | |
| 5 | 11.81 | 0 |
The barrier grows with , and the crossing probability falls roughly like . At 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 as the proposal, with both ways in the test; exact for every .
- HMC: momentum , leapfrog steps, accept with .
- Leapfrog is a composition of shears (volume 1) and is reversible, so no Jacobian enters the test; Euler is neither.
- Steps scale as , , ; target acceptance , , ; leapfrog needs .
- 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 . The notebook has no saved outputs, so it documents procedures only.
- Rejection sampling (cells 4–6): proposal with , which does not bound ; the kept points follow , with variance . The correct constant is .
- Metropolis–Hastings (cells 7–9): a random walk with step , 1000 steps from . It accepts about 84% of proposals in small, correlated steps; a step of gives the one-dimensional optimum of about 44%.
- MALA (cells 10–12):
step_size = 0.1is a standard deviation, so ; 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)andNUTS(model), 500 samples after 100 warm-up steps. Pyro adapts the step size by default, so only the trajectory length stays fixed.
Next#
An energy-based model needs samples from its own density after every update of its parameters, to estimate the gradient of , 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#
- R. M. Neal. MCMC Using Hamiltonian Dynamics. In S. Brooks, A. Gelman, G. Jones, X.-L. Meng (eds.), Handbook of Markov Chain Monte Carlo, Chapter 5, Chapman & Hall/CRC, 2011. Sections 2.2–2.3 (properties of the dynamics, leapfrog), 3.1–3.2 (the HMC algorithm and the proof of invariance), 4.1 (linear transformations), 4.4 (scaling with dimension, optimal acceptance), 5.2 (the Langevin method as one leapfrog step).
- M. D. Hoffman, A. Gelman. The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo. Journal of Machine Learning Research, 15(47), 1593–1623, 2014. arXiv:1111.4246. Sections 3.1 (the U-turn criterion and doubling) and 3.2 (dual averaging).
- R. Isachenko. Deep Generative Models, MIPT and YSDA, 2025. Course repository. Lecture 6 (Langevin dynamics), lecture 10 (the Kolmogorov–Fokker–Planck equation and the Langevin SDE as its stationary case).
- A. S. Dalalyan. Further and stronger analogy between sampling and optimization: Langevin Monte Carlo and gradient descent. COLT, 2017. Theorem 1 (Wasserstein bound for the unadjusted Langevin chain).
- Конспект курса «Байесовские методы в анализе данных», 2026, github.com/bmml-team/bmml_ftda, лекция 4 (rejection sampling, the Metropolis–Hastings kernel and its detailed balance, Gibbs sampling).
- A. Ryzhikov et al. GenAI. Lecture 5: Energy models, MCMC. HSE-LAMBDA Deep Generative Models, 2025:
05_Lecture_MCMC.pdf. - Pyro documentation: MCMC, HMC and NUTS.
- HSE-LAMBDA, Deep Generative Models course repository:
MCMC.ipynb.