24 / 33 · Energy-Based Models
Sampling unnormalized densities: MALA, Hamiltonian Monte Carlo and NUTS
How to sample a density known only up to its normalizing constant, as an energy-based model defines it: rejection and Metropolis–Hastings in brief, MALA and its gradient-informed proposal, Hamiltonian Monte Carlo with momentum, the leapfrog integrator and an acceptance test on the energy error, tuning the step size, trajectory length and mass matrix, NUTS with its U-turn criterion, doubling and dual averaging, and running the samplers in Pyro.
On this page 17
Flows give an exact density, but only for networks that are invertible and have a cheap Jacobian determinant. An energy-based model drops every restriction on the architecture: any network with a scalar output defines a density
The density is defined when is finite; it is positive automatically, since . The price is , an integral over the whole data space that nobody can compute for images. Without it we cannot evaluate . Its absence alone does not rule out exact sampling: rejection sampling, recalled below, draws exact independent points from an unnormalized density. But direct methods need extra structure, such as an inverse distribution function or an envelope that bounds the density tightly, and on images that structure is missing or useless. What we can compute is a ratio , in which cancels, and the gradient , which does not contain at all. Sampling and training an energy-based model therefore need samplers that use only ratios or gradients of the unnormalized density. This note builds them, from the random walk of Metropolis–Hastings to the gradient-driven samplers that are used in practice: MALA, Hamiltonian Monte Carlo and its adaptive form NUTS. A first reading can follow Metropolis–Hastings, MALA, the leapfrog integrator and one HMC iteration, then tuning, warm-up diagnostics and Pyro; the proof of the acceptance rule and the internals of NUTS are marked as optional. The next note puts them inside training.
Notation. The target is a density on known up to a constant, ; is the potential energy, and for an energy-based model . Its gradient is the score. is a proposal density, an acceptance probability, a normal with covariance (variance as the second argument), and always denotes fresh standard normal noise. In Hamiltonian Monte Carlo is a momentum (never a density), the total energy, a step size and a number of steps. is the dimension.
The starting point: rejection and Metropolis–Hastings#
The probability course has two samplers that already work with an unnormalized density; we only recall what they deliver.
Rejection sampling (Monte Carlo methods) draws from a proposal and keeps it with probability , where . The kept points are exact, independent draws from : a point is drawn and kept with density , which is proportional to . The acceptance rate is for a normalized target, so on average proposals buy one sample; with in place of the bound becomes and the rate . The best constant is , and the proposal must have tails at least as heavy as the target’s, otherwise the supremum is infinite. The bound is also what kills the method in many dimensions. For a target and the proposal , the ratio peaks at , so and half of the proposals are kept. For against the ratio is the product over coordinates, : one proposal in 1024 is kept in ten dimensions, one in in a hundred.
Metropolis–Hastings (Markov chain Monte Carlo) gives up independence. From the current state it proposes and accepts it with
otherwise it stays at . Only the ratio enters, so cancels. The chain satisfies detailed balance, , which makes stationary; if it is also irreducible (it can reach every region of positive density) and aperiodic, it converges to from any start, by the ergodic theorem on finite spaces and its analogue on continuous ones. Its states are correlated, and of them are worth an effective sample size of independent draws, where is the autocorrelation at lag . With the symmetric random-walk proposal the ratio reduces to , and the step decides everything: too small and the chain crawls, too large and it is rejected.
Why a random walk is slow#
A random walk moves by independent steps, so after accepted steps of size it has typically travelled , not . The step is capped by the narrowest direction of the target: a step much longer than the target’s width in some direction lands in low density and is rejected. Crossing the widest direction then takes about steps. For a bivariate normal with unit variances and correlation the standard deviations along the two axes of the ellipse are and , a ratio of and a squared ratio of .
Dimension makes it worse. For a target with independent coordinates, the change in is a sum of terms, and keeping the acceptance rate away from zero requires a proposal variance proportional to . The chain then needs on the order of steps per independent sample, and the optimal acceptance rate tends to as grows, with for standard normal coordinates (Roberts, Gelman and Gilks, 1997). Both problems have the same cause: the proposal knows nothing about where the probability is. The rest of the note feeds it the gradient.
MALA: let the gradient propose#
The Langevin diffusion
with a standard Brownian motion, drifts uphill on and diffuses, and under mild conditions it has as its stationary distribution. Run it for a time with one Euler step and you get the proposal
Used on its own as the update of a chain, this is unadjusted Langevin dynamics (Langevin dynamics), and its stationary distribution is slightly wrong for any finite : on its variance is . The Metropolis-adjusted Langevin algorithm, MALA (Roberts and Tweedie, 1996), uses the same move as a Metropolis–Hastings proposal and corrects the error with the accept test. The proposal is not symmetric, because the drift at differs from the drift at , so both directions enter the Metropolis–Hastings ratio:
Each step needs one new gradient, at ; the gradient at is kept from the previous step. Everything is computed in logarithms: , and the normalizing constants of the two Gaussians are equal and cancel.
Worked example: MALA on a standard normal#
Take , so , and write . The proposal mean from is , and
using and . Adding leaves
The random walk’s log-ratio for the same pair is ; MALA’s is that times . The proposal already carries most of the change in density, and the test only corrects the remainder. With and the proposal is . A draw that lands farther out, at , has , so a random walk would accept it with probability , while MALA accepts it with : the reverse proposal from has mean , only from , so the move is easy to undo.
How the step scales with dimension#
MALA’s errors come only from discretizing a dynamics that keeps invariant, and they are smaller than a random walk’s. For targets with independent coordinates, Roberts and Rosenthal (1998) show that the step can shrink as instead of , so a chain needs on the order of steps per independent sample instead of , and that the optimal acceptance rate tends to , against for the random walk.
A toy check on , each sampler tuned to its asymptotically optimal acceptance rate, counts the effective sample size of per 1000 evaluations of the target (one run of 40,000 evaluations each; Hamiltonian Monte Carlo, introduced below, with trajectories of length about 1 and acceptance about ):
| random walk: | ESS per 1000 | MALA: | ESS per 1000 | HMC: | ESS per 1000 | |
|---|---|---|---|---|---|---|
| 10 | 0.75 | 33 | 1.27 | 316 | 1.05 | 290 |
| 100 | 0.24 | 4.4 | 0.59 | 108 | 0.65 | 126 |
| 1000 | 0.075 | 0.4 | 0.27 | 43 | 0.37 | 66 |
Every tenfold increase in costs the random walk a factor of about ten. MALA’s step follows and its efficiency falls by factors of three and two and a half; the last column is the subject of the next sections.
Two cautions. The step is limited by the stiffest direction of the target, because the drift overshoots where the curvature is large: on a Gaussian with smallest variance the drift alone is stable only for . On a narrow target MALA is therefore limited much as the random walk is (Figure 2 below). A preconditioned proposal with a matrix close to the target’s covariance removes the problem, and a position-dependent gives the Riemann manifold version of Girolami and Calderhead (2011). Second, for targets with tails lighter than Gaussian the unadjusted chain can diverge and MALA can fail to converge geometrically fast (Roberts and Tweedie, 1996).
Hamiltonian Monte Carlo: momentum and energy#
MALA and the random walk both forget their direction after every step. Hamiltonian Monte Carlo (HMC) adds a velocity that persists. Introduce a momentum , independent of and normal, , with a mass matrix (the identity unless said otherwise). The joint density is
and its marginal in is : sampling and dropping samples . In physical language is the position of a particle, its potential energy, its kinetic energy and the total energy (Neal, 2011, Section 3.1). The particle moves by Hamilton’s equations
The momentum carries the particle forward, and the force , which is the score, bends its path towards high probability. The exact flow has three properties, and HMC rests on all three (Neal, 2011, Section 2.2).
- It conserves . By the chain rule, .
- It preserves volume. The vector field has divergence , because the first term does not depend on and the second does not depend on ; a flow with zero divergence keeps the volume of every region (Liouville’s theorem).
- It is reversible. Running the flow for time , negating the momentum and running again for time returns to the start with negated momentum.
If the flow could be computed exactly, a proposal made by following it for some time would have the same and would always be accepted, however far it went. The work is in the integrator.
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:
In a chain of steps the last half step of one and the first of the next use the same gradient, so steps cost gradients. Leapfrog does not conserve , but it keeps the other two properties exactly (Neal, 2011, Section 2.3):
- Volume. Each of the 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 1, and so is the determinant of the composition. This is the same triangular-Jacobian argument that makes coupling layers cheap; here the determinant is not just cheap but equal to one.
- Reversibility. The step is symmetric: negating and applying the same step returns to .
Its energy error stays bounded instead of growing. On the step is the linear map , , and a direct check shows that it conserves exactly the shadow energy
so along any leapfrog trajectory only oscillates. For the coefficient of is no longer positive and the trajectories are no longer bounded; for a Gaussian of standard deviation the limit is , set by the narrowest direction. In general the leapfrog error in is of order after one step and of order over a trajectory of fixed length.
Worked example. On from , with : , , . The energy goes from to , so and the move would be accepted with probability . Euler’s step from the same point gives with , an error , nineteen times larger. The shadow energy is the same before and after the leapfrog step.
One HMC iteration#
An iteration of HMC from the current state has three steps, which the chain then repeats (Neal, 2011, Section 3.2):
HMC iterations in phase space: leapfrog against Euler
- Refresh the momentum. Draw , independently of everything else. In the plane this is a vertical move, and it is the only step 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 or reject. Accept with probability , where ; otherwise keep . Drop the momentum.
- Repeat from step 1 with a new momentum.
In the figure, each fresh momentum puts the chain on a different circle, the leapfrog points stay close to their circle, and Euler’s points drift off. Exploration of different energy levels comes from step 1; long moves at a fixed level come from step 2.
Why the acceptance needs only the energy error#
Optional depth: the proof that the HMC accept step leaves the target invariant. The rest of the note does not depend on it.
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 an involution, . Reversibility says , so and , the identity.
- preserves volume, , because each leapfrog step and the flip do.
Accept the deterministic proposal with probability . For any two regions and of phase space, the probability flow from to is
the flow from to . The first line substitutes , which is allowed because is its own inverse, with unit Jacobian because preserves volume. The second uses , which is symmetric under . This is detailed balance, so the accept step leaves invariant. The ratio itself is
since ; for the same reason the flip changes nothing in practice and is dropped, the momentum being redrawn anyway. The momentum refresh is an exact draw from the conditional of given , a Gibbs step, so it leaves invariant too, and so does the whole iteration (Neal, 2011, Section 3.2).
Volume preservation is what keeps the ratio free of Jacobians. A proposal map that stretched space would need the factor in the ratio, the same change-of-variables term that normalizing flows pay for in their likelihood. With Euler’s method the determinant on is per step, and the plain ratio would sample the wrong distribution.
The three samplers on a narrow Gaussian#
Figure 2 runs a random walk, MALA and HMC on the bivariate normal with correlation from the section on random walks, with the same budget of 3000 evaluations of the target each. The random walk uses and accepts 22%, close to the rule; MALA uses , just below its stability limit , and accepts 57%; HMC uses and , so 300 iterations, and accepts 86%.
Three samplers with the same budget on a narrow Gaussian
The effective sample sizes of are 92, 38 and 300. Three qualifications go with these numbers. The budget counts one gradient as one evaluation, like one density value, although a gradient by reverse-mode differentiation costs a small multiple of a density value; it is one accounting model, not equal wall-clock effort. The estimator sums autocorrelations until the first one below , so for HMC, whose lag-one autocorrelation is negative, it returns exactly the number of iterations, which understates HMC here. Geyer’s initial-sequence estimator, which keeps negative lags, gives 661 on this run (Geyer, 1992). And each number comes from one seed: over 20 seeds the same estimator gives 46 to 107 for the random walk, 21 to 62 for MALA and 299 to 783 (median 482) for HMC. After ten evaluations the autocorrelation of is still for the random walk and for MALA, and for HMC, which has finished one iteration. Each HMC trajectory lasts time units. Along the long axis of the ellipse, whose standard deviation is , ten leapfrog steps advance the oscillation by radians (), so a trajectory tends to end on the other side of the mean; the negative autocorrelation is that swing. On this target the gradient buys MALA nothing, and it does worse than a well-tuned random walk: its step is capped by the narrow direction, and along the long direction it still diffuses. Its advantage is the scaling with dimension in the table above. HMC is different in kind, because its momentum keeps it moving along the long direction for a whole trajectory.
Tuning HMC: step size, trajectory length and mass matrix#
Step size. must stay below the stability limit, about twice the standard deviation of the narrowest direction ( for the target above), and in practice somewhat below, because the acceptance rate falls as the energy error grows. For targets with independent coordinates the step has to shrink as , a trajectory of fixed length then needs on the order of leapfrog steps, and the optimal acceptance rate tends to (Neal, 2011, Section 4.4; Beskos et al., 2013, who give ). Since each gradient costs order , the total cost per independent sample grows like , against for the random walk and for MALA (Neal, 2011, Sections 4.4 and 5.2).
Trajectory length. decides how far a proposal goes. Too short, and HMC degenerates into a random walk of small steps (with it is MALA). Too long, and the trajectory turns back towards its start and the extra gradients are wasted. Worse, a fixed length can resonate with the target’s periods. On the target above, the leapfrog step in the narrow direction is, after rescaling, a rotation by an angle with . With and that is radians per step and turns per trajectory, so the narrow coordinate comes back close to where it started (the cosine of the total angle is ); the effective sample size of drops to between 46 and 78 out of 300 iterations over four runs, while gives 300 in all four. Randomizing or a little at every iteration breaks such resonances (Neal, 2011, Section 3.2), and NUTS removes the choice of altogether.
Mass matrix. With the leapfrog position step becomes . Choosing equal to an estimate of the covariance of is equivalent to running HMC with identity mass on the linearly transformed variable (Neal, 2011, Section 4.1; Betancourt, 2017, Section 4.2), in which the target is roughly isotropic: on a Gaussian the stability limit no longer depends on its correlations, and short trajectories reach nearly independent points. In high dimensions a diagonal , one scale per coordinate, is the usual compromise; it is estimated from the chain during warm-up.
NUTS: stop at the U-turn#
The No-U-Turn Sampler (Hoffman and Gelman, 2014) keeps HMC’s dynamics and removes : it extends the trajectory until it starts to come back.
The U-turn criterion#
With identity mass, the distance from the start of a trajectory to its current point changes at the rate
While this is positive, more simulation moves the proposal further away; once it is negative, the trajectory is turning back (with a mass matrix, is replaced by the velocity ). Simply stopping at the first negative value would break reversibility: the trajectory run back from the stopping point would usually stop somewhere else, so detailed balance would fail (Hoffman and Gelman, 2014, Section 3.1).
Doubling the trajectory#
NUTS builds the trajectory as a balanced binary tree. It starts from the single state after the momentum refresh. At doubling it picks a direction uniformly at random and takes leapfrog steps of size from the corresponding end, forwards or backwards in time, which doubles the number of states. It stops when, for the whole trajectory or for any of its balanced subtrees, the leftmost and rightmost states and satisfy
that is, when continuing in either direction would bring the two ends closer. It also stops if the simulation becomes wildly inaccurate, with an energy error beyond , a divergence (Hoffman and Gelman, 2014, Section 3.1.1). Because the tree is built by random doublings, every state in it could have generated the same tree with the same probability after doublings, and this symmetry, together with volume preservation, replaces the reversibility that a simple stopping rule would lose.
Which state to keep#
Optional depth: how NUTS chooses the next state from its tree. The rest of the note does not depend on it.
NUTS has no single accept/reject step for the end point. It draws the next state from the states of the trajectory, in a way that keeps the joint distribution of position and momentum invariant.
- Slice sampling, the original version: draw and choose uniformly among the trajectory states with , leaving out the states of a final doubling that would have triggered a stop before the whole tree was built (Hoffman and Gelman, 2014, Section 3.1.1). The efficient version stores only states and biases the choice towards the newer half of the tree, so that the next state tends to be far from the current one (Section 3.1.2).
- Multinomial sampling: choose a state with probability proportional to among all states of the trajectory, with no slice variable. Removing the auxiliary variable improves performance by a Rao–Blackwell argument, and this is what Stan and Pyro use by default (Betancourt, 2017, Appendices A.2.2 and A.5).
One iteration of NUTS costs gradients after doublings, and implementations cap the depth of the tree, at 10 doublings by default in Pyro.
Adapting the step size: dual averaging#
Optional depth: the update rule behind automatic step-size tuning. The rest of the note does not depend on it.
NUTS still needs . It is tuned during warm-up so that an acceptance statistic averages to a target . For NUTS, is the average of over the states of the final doubling of iteration , the acceptance HMC would have had for those states. Dual averaging, adapted from Nesterov’s primal–dual method, updates
When the chain accepts less than , grows and the step shrinks; the shrinkage towards favours steps larger than the initial guess , and is a running average that converges. Hoffman and Gelman use , , and, after warm-up, keep fixed at (Hoffman and Gelman, 2014, Section 3.2). They found NUTS efficient for any between 0.45 and 0.65 and suggested , against about for HMC (Section 4.4). Stan and Pyro default to : a smaller step, fewer divergences on difficult geometry, and more leapfrog steps per trajectory.
Warm-up#
The first part of a run, the warm-up, is spent adapting and is discarded. In Pyro, following Stan, it starts with a buffer of 75 iterations in which only the step size adapts, continues with windows of 25, 50, 100, … iterations at the end of each of which the mass matrix is re-estimated from the chain’s states, and ends with a buffer of 50 iterations that adapts the step size to the final mass matrix. When the warm-up is too short for this schedule, the two buffers shrink to 15% and 10% of it. After warm-up the kernel is frozen. A kernel that kept adapting would no longer be a fixed Markov chain, and its stationary distribution would no longer be guaranteed.
Two diagnostics come with every run. Divergences mark trajectories whose energy error exploded; they signal regions of high curvature that the chain cannot explore with its step size, and persistent divergences mean biased estimates (Betancourt, 2017, Section 6.2). The effective sample size and the split across several chains measure mixing as in the probability course.
Running the samplers in Pyro#
Probabilistic programming libraries implement all of this behind two objects: a kernel (HMC or NUTS) that makes one transition, and MCMC, which runs warm-up and sampling. The density can be given as a model, a program that calls pyro.sample:
import torch
import pyro
import pyro.distributions as dist
from pyro.infer import MCMC, NUTS
Sigma = torch.tensor([[1.0, 0.95], [0.95, 1.0]])
def model():
pyro.sample("x", dist.MultivariateNormal(torch.zeros(2), covariance_matrix=Sigma))
mcmc = MCMC(NUTS(model), num_samples=1000, warmup_steps=500)
mcmc.run()
x = mcmc.get_samples()["x"] # tensor of shape (1000, 2)
mcmc.summary() # mean, sd, quantiles, n_eff and r_hat per coordinate
From the model, Pyro builds the potential : the negative log joint density, with each constrained variable mapped to an unconstrained one and the log-Jacobian of that map added to the log density, so that leapfrog moves on all of . Its defaults are the choices described above: step_size is only the initial , adapted by dual averaging to target_accept_prob=0.8; a diagonal mass matrix is adapted during warm-up (adapt_mass_matrix=True, full_mass=False); NUTS uses multinomial sampling and max_tree_depth=10; warmup_steps defaults to num_samples. For plain HMC, HMC(model, step_size=0.1, num_steps=10) fixes the trajectory length , and is recomputed as the integer part of whenever the step size adapts.
For an energy-based model the potential is the energy itself, and it can be passed directly:
energy = ... # a trained network E_theta: a tensor of shape (2,) -> a scalar
def potential(params): # U(x) = E_theta(x); the normalizing constant is never needed
return energy(params["x"])
mcmc = MCMC(NUTS(potential_fn=potential), num_samples=1000, warmup_steps=500,
initial_params={"x": torch.zeros(2)})
mcmc.run()
With potential_fn there is no model to draw a starting point from, so initial_params is required. Gradients of come from automatic differentiation; each leapfrog step is one forward and one backward pass of the network.
What changed#
| Sampler | Proposal | Needs | Accept step | Tuned to | Steps per independent sample, coordinates | Fails when |
|---|---|---|---|---|---|---|
| Rejection | independent draw from | up to a constant, a bound | keep with | the best | about , often exponential in | no tight envelope |
| Random-walk MH | ratios of | acceptance | order | narrow or high-dimensional targets | ||
| MALA | ratios and the score | MH ratio with both ways | acceptance | order | stiff directions, light tails | |
| HMC | leapfrog steps from a fresh momentum | ratios and the score | acceptance ; and by hand | order leapfrog steps | bad , divergences | |
| NUTS | trajectory doubled until a U-turn | ratios and the score | a state of the trajectory, by weight | by dual averaging; in warm-up | as HMC, with chosen per iteration | divergences, several modes |
Limitations#
- Switching between modes can be extremely slow. Nothing forbids a jump across a region of zero density: rejection sampling draws independent points, and a random-walk or MALA proposal can land on the far side of a gap without visiting it. Such a proposal must reach the other mode in one step, though, and with a step tuned to the local width it almost never does. HMC moves along a continuous trajectory whose energy stays nearly constant, so it cannot pass through a region of near-zero density, where the potential is far higher than its energy allows. On a target with separated modes a chain therefore usually stays in the mode it found, as the probability course shows for the random walk; HMC and NUTS are no exception (Neal, 2011, Section 4.2). Tempering and annealing methods address this at extra cost.
- Gradients are required. MALA, HMC and NUTS need a differentiable on a continuous space. Discrete variables must be summed out or updated by other moves, and constrained variables need a change of variables.
- One step size for the whole space. A region of high curvature, such as the neck of a hierarchical model’s funnel, needs a smaller step than the rest; a global either wastes gradients elsewhere or produces divergences there.
- The guarantees are asymptotic. Stationarity, warm-up length and mixing can be checked only through diagnostics, which detect some failures and never all.
- Each gradient is a network pass. For an energy-based model every leapfrog or Langevin step is a forward and a backward pass through , and training needs fresh samples after every parameter update. Chains run to convergence are unaffordable there, which is where the next note starts.
Summary#
- An unnormalized density gives ratios and the score without ; every sampler here uses only these.
- Rejection sampling needs a bound and accepts of the proposals; Metropolis–Hastings needs only ratios but a random walk diffuses, with order steps per independent sample and an optimal acceptance of .
- MALA proposes one Euler step of the Langevin diffusion, , and corrects with an asymmetric Metropolis–Hastings ratio; its step scales as and its optimal acceptance is . On its log-ratio is .
- HMC adds a momentum and follows Hamilton’s equations for with the leapfrog integrator. Leapfrog is volume-preserving and reversible, so the acceptance is with no Jacobian; its energy error stays bounded, while Euler’s method multiplies the energy by per step on a Gaussian.
- HMC’s step must stay below about twice the narrowest standard deviation, scales as and is best at acceptance ; the trajectory length must avoid both random-walk behaviour and resonance; a mass matrix close to the inverse covariance makes the target isotropic.
- NUTS doubles the trajectory in random directions until a U-turn, or , picks the next state from the whole trajectory (slice or multinomial sampling), and tunes by dual averaging during warm-up, together with the mass matrix.
- In Pyro,
MCMC(NUTS(model), num_samples, warmup_steps)runs all of this; for an energy-based model,NUTS(potential_fn=...)takes the energy as the potential.
Notebook#
The MCMC notebook of the HSE-LAMBDA Deep Generative Models repository implements five samplers on one target, the one-dimensional (cell numbers count every cell, markdown included, from 1). It has no saved outputs, so it documents procedures rather than results.
- Cell 1: introduction. Pyro as a probabilistic programming library on PyTorch, and the list of samplers: rejection sampling, Metropolis–Hastings, MALA, HMC and NUTS.
- Cells 2–3: setup. Imports of
torch,pyro,pyro.distributions,pyro.infer.mcmc, matplotlib and seaborn, the seed 42, and a helpertime_samplingthat times a sampler. - Cell 4: rejection sampling, theory. The bound , the proof that accepted points have density , the acceptance rate with a geometric number of draws of mean , the optimal , and the advantages and limitations, including the exponential growth of with the dimension.
- Cells 5–6: rejection sampling, code. Target , proposal (
dist.Normal(0, 2), scale 2), , 1000 samples drawn one proposal at a time, and a histogram with a kernel density estimate. - Cell 7: Metropolis–Hastings, theory. The acceptance ratio, ergodicity and detailed balance, burn-in, the effect of the proposal width, and the random-walk proposal with .
- Cells 8–9: Metropolis–Hastings, code. 1000 steps from with the symmetric ratio ; histogram.
- Cell 10: MALA, theory. The Langevin diffusion, the proposal and the asymmetric ratio, why MALA beats the random walk, and step-size advice. The cell’s step is a standard deviation: its proposal is this note’s with .
- Cells 11–12: MALA, code. Gradients of by autograd at the current and the proposed point, forward and reverse proposal densities, the accept test,
step_size = 0.1, 1000 samples from ; histogram. - Cell 13: HMC, theory. Position, momentum, with , Hamilton’s equations, the leapfrog step, the acceptance , and the effect of and .
- Cells 14–15: HMC in Pyro. A model with one site
x ~ Normal(0, 1),mcmc.HMC(hmc_model, step_size=0.1, num_steps=10),MCMC(..., num_samples=500, warmup_steps=100), samples fromget_samples()["x"]; histogram. - Cell 16: NUTS, theory. Why is hard to set, the U-turn, trajectory doubling, step-size adaptation by dual averaging during warm-up.
- Cells 17–18: NUTS in Pyro. The same model with
mcmc.NUTS(model),MCMC(nuts_kernel, num_samples=500, warmup_steps=100); histogram. - Cell 19: summary and a comparison table of the five methods, which the What changed table above replaces.
Issues, with the correct versions:
- Cell 5: does not bound . The ratio is , with maximum 2 at , and it exceeds 1.5 for . There exceeds 1, every proposal is kept, and the accepted points have density proportional to instead of : a normal with its top cut off, density at zero instead of , variance instead of 1, and acceptance rate instead of the the theory would predict. The correct constant is , with acceptance rate .
- Cell 4: the proposal for heavy tails. A normal proposal cannot cover a heavy-tailed target: is then unbounded in the tails. The proposal needs tails at least as heavy as the target’s (for example a Student-t). The cell’s remark that need not be normalized holds, but then is replaced by in the bound and the acceptance rate is , not .
- Cells 7–8: the random-walk step. The recommended acceptance of 25–50% mixes two results: the optimum is in high dimensions and about in one dimension. With on the stationary acceptance rate is , so the chain takes small, highly correlated steps; gives . The claim that Metropolis–Hastings works for multimodal targets is misleading: it is valid for them but may never cross between modes. Cell 8 also forms the ratio as a quotient of
exp(log_prob); differences of log-densities avoid overflow and underflow on other targets. - Cells 10–11: the MALA step is far too small.
step_size = 0.1means . On the proposal is plus noise of standard deviation , practically every proposal is accepted, and the integrated autocorrelation time is steps, so 1000 steps from are worth two or three independent samples and the histogram cannot resemble . For this one-dimensional target astep_sizebetween 1 and 1.4 accepts 79–92% of the proposals and gives roughly 370 to 780 effective samples per 1000 steps. The rule of thumb of 50% acceptance corresponds to the high-dimensional optimum . “RMSprop MALA” is not an established method: RMSprop preconditioning appears in preconditioned SGLD (Li et al., 2016), which has no accept step, and the preconditioned MALA with a Metropolis correction is the Riemann manifold MALA of Girolami and Calderhead (2011). - Cell 13: energy conservation. The cell attributes the high acceptance to Hamiltonian dynamics preserving volume and energy. The exact dynamics would be accepted always; leapfrog preserves volume and reversibility exactly but energy only approximately, and the acceptance below 1 measures its energy error.
- Cell 14: the HMC settings are adapted away. Pyro’s
HMCadapts the step size by dual averaging towardstarget_accept_prob=0.8and a diagonal mass matrix during warm-up, both on by default.step_size=0.1, num_steps=10therefore only fixes the trajectory length and the initial step; after warm-up is the integer part of for the adapted . To run HMC with exactly these values, passadapt_step_size=Falseandadapt_mass_matrix=False. - Cell 16: how NUTS chooses the next state. The cell describes a Metropolis accept/reject of the trajectory’s end point. NUTS has no such step: it draws the next state from the states of the trajectory, by slice sampling in the original algorithm and by multinomial sampling in Pyro’s default (
use_multinomial_sampling=True). Each doubling extends the trajectory in one randomly chosen direction, not in both. The “acceptance rate of 60–90%” is the adaptation target , 0.8 by default, not a property of the method. - Cell 19: the comparison table. Its acceptance ranges are rules of thumb; the asymptotically optimal values are , and , rejection sampling accepts exactly , and NUTS’s rate is whatever is set to. No sampler in the table handles well-separated modes, and NUTS is the default only for continuous, differentiable targets.
- All cells: one target. On the one-dimensional the five samplers look alike. The correlated two-dimensional Gaussian of Figure 2 separates them.
Next#
The samplers of this note assume a fixed target and enough time to converge. An energy-based model needs samples from its own density after every update of , 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-based models with short Langevin chains, persistent chains and a replay buffer. It also covers the two relatives of these samplers used there: stochastic gradient Langevin dynamics, and annealed importance sampling, which estimates the normalizer to report a likelihood.
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 its invariance), 4.1–4.2 and 4.4 (linear transformations, tuning, scaling with dimension), 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 (U-turn criterion, doubling, slice sampling), 3.2 (dual averaging), 4.4 (choice of ).
- M. Betancourt. A Conceptual Introduction to Hamiltonian Monte Carlo. arXiv, 2017. Sections 4.2 (Euclidean–Gaussian kinetic energies, the mass matrix), 4.3 (integration time), 6.2 (divergences), Appendices A.2.2 and A.5 (multinomial sampling, the current NUTS in Stan).
- G. O. Roberts, R. L. Tweedie. Exponential Convergence of Langevin Distributions and Their Discrete Approximations. Bernoulli, 2(4), 341–363, 1996.
- G. O. Roberts, J. S. Rosenthal. Optimal Scaling of Discrete Approximations to Langevin Diffusions. Journal of the Royal Statistical Society: Series B, 60(1), 255–268, 1998.
- G. O. Roberts, A. Gelman, W. R. Gilks. Weak Convergence and Optimal Scaling of Random Walk Metropolis Algorithms. The Annals of Applied Probability, 7(1), 110–120, 1997.
- A. Beskos, N. Pillai, G. Roberts, J.-M. Sanz-Serna, A. Stuart. Optimal Tuning of the Hybrid Monte Carlo Algorithm. Bernoulli, 19(5A), 1501–1534, 2013. arXiv:1001.4460.
- M. Girolami, B. Calderhead. Riemann Manifold Langevin and Hamiltonian Monte Carlo Methods. Journal of the Royal Statistical Society: Series B, 73(2), 123–214, 2011.
- C. Li, C. Chen, D. Carlson, L. Carin. Preconditioned Stochastic Gradient Langevin Dynamics for Deep Neural Networks. AAAI, 2016. arXiv:1512.07666.
- C. J. Geyer. Practical Markov Chain Monte Carlo. Statistical Science, 7(4), 473–483, 1992.
- Pyro documentation: MCMC, HMC and NUTS.
- HSE-LAMBDA, Deep Generative Models course repository:
MCMC.ipynb.