22 / 22 · Random Processes and Sampling
Markov chain Monte Carlo
How to sample from a distribution known only up to a constant by running a Markov chain whose stationary distribution is the target, how to tell how much such correlated samples are worth, and how the gradient-following Langevin sampler connects to score-based generative models.
On this page 6
The posterior of a real model, a distribution over molecular configurations or an energy-based model of images has a density that can be evaluated only up to a constant, with an intractable integral, in many dimensions. The direct methods of the Monte Carlo note need a proposal close to , and there is none. Markov chain Monte Carlo turns the ergodic theorem around: build a Markov chain whose stationary distribution is , run it, and use its states as samples. The construction needs only ratios , in which cancels. This last note of the course derives the Metropolis–Hastings algorithm, shows how it fails, and ends with Langevin dynamics, which follows the gradient of the log-density and supplies the score that diffusion models reuse.
Notation. is the target; a proposal distribution; the chain. is the score, which does not depend on .
Detailed balance#
A chain with transition probabilities satisfies detailed balance with respect to if
In equilibrium, the flow of probability from to equals the flow back. Summing over shows that is stationary:
With a density the sum becomes an integral. Detailed balance is a local condition that is easy to arrange, and if the chain is also irreducible and aperiodic, the Markov chains note guarantees convergence to from any start for finite state spaces; continuous spaces need the conditions of general state spaces.
Detailed balance gives invariance and nothing more. The chain that never moves, , satisfies it for every . The two-state chain that always switches satisfies it for , since , yet from a fixed start its distribution alternates between and . Neither chain converges to , so irreducibility and aperiodicity are checked separately.
The condition is sufficient but not necessary. Put three states on a circle and let the chain step forward with probability and stay with probability . Every column of its transition matrix sums to 1, so and the uniform distribution is stationary. The flow from state 1 to state 2 is , the flow back is : detailed balance fails. This one-directional chain is the simplest non-reversible sampler. A Gibbs sampler that updates coordinates in a fixed order is another chain that keeps its target invariant without detailed balance (Gibbs sampling note).
Metropolis–Hastings#
From the current state , propose and accept it with probability
otherwise stay at . The constant appears in both numerator and denominator and cancels. With a symmetric proposal, such as with , the ratio is simply : moves uphill are always accepted, moves downhill sometimes. This is random-walk Metropolis, the algorithm of Metropolis and colleagues from 1953.
Take and this random walk, so that and the proposal terms cancel. From the proposal goes downhill and is accepted with probability . From the proposal goes uphill, and . The rare move out and the certain move back carry the same flow of probability, because :
and the two right-hand sides are equal.
The proposal is the distribution of a candidate, not of the next state. The next state is after an acceptance and again after a rejection, so the transition kernel, the distribution of given , has two parts. By the law of total probability over the two outcomes, for a set
where
is the probability that a proposal from is rejected. The first part has a density; the second is a point mass at , present even when is a smooth density. On a discrete space the integrals become sums.
The kernel satisfies detailed balance. For only the first part acts. Multiplying into the minimum that defines gives an expression symmetric in and :
The point mass sits at , where detailed balance reads and holds for any . So is stationary for the full kernel, rejections included.
A rejection therefore repeats the current state, and the repeat counts as a draw. Dropping repeats keeps only the moves. They form a chain with transition density , where is the acceptance probability from . Its stationary density is proportional to , not to . Multiplying by this transition density cancels ; then detailed balance (first line) and the definition of (second line) give
States from which most proposals are rejected lose weight. For random-walk Metropolis on with step , the acceptance probability is at the centre and in the tail, so the moves alone have variance instead of 1 (numerical integration). A run of 400,000 steps gives with the repeats and without them. The Bayesian Methods course shows the same effect on a posterior.
Two rules about the support follow from the ratio. Start at a point with , so that the denominator is positive. A proposal with gets , so the chain never leaves the set where . A move that the proposal cannot reverse, , also gets : with , which only moves right, every proposal is rejected and the chain stays at forever.
Which regions the chain reaches is decided by the accepted moves, not by the proposals. Take a target supported on and random-walk steps uniform on . Every proposal into the gap is rejected, and a jump across it would need a step longer than 1, so the chain stays in the interval where it starts. A proposal density that is positive and continuous everywhere, with finite, avoids both problems: the chain is then irreducible in the sense of general state spaces and aperiodic (Roberts and Rosenthal, 2004, Section 3.2).
The chain is valid for any step size , but decides how well it works:
Metropolis with too small, good and too large steps
Over 20,000 steps on a standard normal target, a step of accepts 97% of proposals and is worth only 57 independent samples; a step of accepts 5% and is worth 708; a step of accepts 44% and is worth 4,815. For random-walk Metropolis in many dimensions, theory suggests tuning the step to an acceptance rate of about 0.23; in one dimension, about 0.44.
Mixing and diagnostics#
Successive states of a chain are correlated, so states usually carry less information than independent samples. How much less follows from the variance of the chain average in a chain started from . Let and let be the autocorrelation of at lag . By stationarity a covariance depends only on the lag, and among the ordered pairs the lag occurs times and a lag occurs times:
If , each weight tends to 1 and stays below 1, so by dominated convergence for series the bracket tends to the integrated autocorrelation time
and . The effective sample size is
It belongs to a quantity of interest , not to the chain as a whole, and it measures how many independent samples the states are worth for estimating . The error of the average of over the chain is then about , not , with . This needs a chain that has reached stationarity, autocorrelations whose sum converges, and a central limit theorem for the chain, which holds for well-behaved chains but not for every one. Positive correlations make the ESS smaller than ; negative ones can make it larger: a chain whose autocorrelations are has . The ESS values quoted in this note come from a simple estimator that stops summing where the autocorrelations drop below ; they are illustrative, and production tools use more careful estimators.
A chain whose numbers are all known checks the formula. The chain , with independent of the past, keeps stationary; the draws of in the Gibbs sampler below form such a chain with . For we have . The noise is independent of , so , hence , and the geometric series gives . For and :
| Quantity | Value |
|---|---|
| finite- formula above | |
| limit | |
| variance of 200,000 simulated averages |
The weights matter when is only a few times .
The variance formula assumed a start from . Then every has distribution , and by linearity at every : the average is unbiased. From a fixed start it is biased. In the same chain, taking expectations of the update gives , so , and summing the geometric series,
which is for , , against the true mean . Discarding an initial burn-in removes the early terms that carry this bias. No length suits every chain. From the bias drops below after 20 steps for and after 688 steps for , and the required , which is rounded up, grows without bound as or . The burn-in is set for each problem from diagnostics: run several chains from dispersed starting points, and compare the variance between chains with the variance within them (the statistic).
No diagnostic can detect what a chain has never visited. For a target with two separated modes, a chain with a small step stays in the mode it starts in:
A chain stuck in one mode
In 20,000 steps the small-step chain spends 0% of its time in the right mode, the large-step chain 50%. No burn-in removes the bias of the first chain, since it never leaves the left mode. Its samples look perfectly healthy; only a second chain started in the other mode, or knowledge of the target, reveals the problem. Multimodality is one of the main practical failures of MCMC, and tempering methods, which run chains on flattened versions of the target, exist to cross the barriers.
Gibbs sampling#
When the conditional distribution of each coordinate given the others is easy to sample, Gibbs sampling updates one coordinate at a time from its conditional. It is Metropolis–Hastings with the conditional as the proposal, and the acceptance probability is always 1. For the bivariate normal of the multivariate Gaussian note with unit variances and correlation , the conditionals are and symmetrically.
Gibbs sampling moves in a zigzag
Strong correlation makes Gibbs slow: each move is along an axis, and the conditional variance is small. Successive draws of have correlation , which is for and for ; 20,000 sweeps are then worth about 2,300 and 190 independent samples. Reparametrizing to remove the correlation, or updating correlated coordinates in blocks, fixes it. Gibbs sampling is the workhorse for models with conjugate conditionals, such as topic models and many hierarchical Bayesian models; the Gibbs sampling note of the Bayesian Methods course proves that each update leaves the target invariant and builds samplers for such models.
Langevin dynamics#
Random-walk proposals ignore where the probability is. Langevin dynamics uses the score to push each step uphill and adds noise to keep exploring:
This is the unadjusted Langevin algorithm (ULA). For a smooth target and small enough steps its stationary distribution tends to as ; for a finite step it is biased, and for too large a step, or a score that grows quickly in the tails, the chain can be unstable and have no stationary distribution at all. On a standard normal target, whose score is , the update is , which is stable only for ; then the stationary variance is : for , for . For the chain diverges. Adding a Metropolis–Hastings acceptance step removes the discretization bias (MALA): is then exactly stationary for every step size, and the chain converges to it under the usual conditions, although a large step gets few acceptances; simulating Hamiltonian dynamics with a momentum variable gives Hamiltonian Monte Carlo, which in its adaptive NUTS form is the default sampler of modern probabilistic programming systems such as Stan. With minibatch gradients, the same update is stochastic gradient Langevin dynamics, which turns noisy gradient descent into approximate posterior sampling for neural networks.
The score needs neither nor the density itself, only the gradient of its logarithm, and this is the bridge to generative models. The bridge carries the score, not the whole sampler, and three procedures should be kept apart:
- Equilibrium Langevin and MALA, this note: one fixed target , a chain run long enough to forget its start, samples from (approximately, or for MALA exactly) its stationary distribution .
- Annealed Langevin dynamics (Song and Ermon, 2019): a network learns the scores of the data blurred by Gaussian noise of several sizes , and a few Langevin steps are run at each level, from the largest to the smallest. Every level has its own target, the chain is not run to equilibrium at any of them, and the result is not an MCMC sample of the data distribution (score matching note).
- Reverse diffusion (DDPM, score-based SDEs, Song et al., 2021): generation simulates the time reversal of a noising process, from pure noise at the final time back to data, in a fixed number of steps. Its drift contains the score of the noised data at time , so the transition rule changes from step to step; it is a time-inhomogeneous Markov chain with no stationary target (DDPM sampling). Langevin steps can be added at each time as a corrector, but the reverse process itself is not MCMC.
What changed#
| Direct Monte Carlo | Markov chain Monte Carlo | |
|---|---|---|
| Needs | samples from or a close proposal | up to a constant (or its score) |
| Samples | independent | correlated; count the effective sample size |
| High dimensions | proposals degrade exponentially | local moves still work, at the cost of mixing time |
| Typical algorithms | inversion, rejection, importance sampling | Metropolis–Hastings, Gibbs, Langevin, HMC |
| Main failure | infinite-variance weights | slow mixing, chains stuck in one mode |
Limitations#
- Convergence is asymptotic and hard to verify. A chain can look stationary while it has explored only part of the target; diagnostics detect some failures, never all.
- Tuning matters. Step sizes, proposal shapes, parametrizations and the number of chains change efficiency by orders of magnitude.
- It is expensive for big data and big models. Every step evaluates the target, often on the whole dataset; for neural networks variational inference, ensembles or stochastic-gradient MCMC are cheaper approximations.
What you should remember#
- Detailed balance makes stationary.
- Metropolis–Hastings: propose , accept with ; only ratios of are needed.
- Too small a step crawls, too large a step is rejected; aim for acceptance of roughly 0.23 in many dimensions.
- For a quantity of a stationary chain, correlated samples are worth an effective sample size , usually less than ; run several chains; beware of modes a chain never visits.
- Gibbs sampling updates coordinates from their conditionals; strong correlation makes it slow.
- Langevin dynamics follows the score plus noise; without a correction it is biased by the step size and can be unstable ( on a standard normal), MALA removes the bias, and HMC uses the same score. Annealed Langevin and reverse diffusion reuse learned scores of noised data, but with targets that change across noise levels or time, so they are not equilibrium MCMC.
Code#
Random-walk Metropolis with three step sizes, a two-mode target, Gibbs sampling and unadjusted Langevin dynamics:
import numpy as np, math
rng = np.random.default_rng(0)
def metropolis(logp, x0, step, n):
"""Random-walk Metropolis: propose x + step * N(0, 1), accept with probability min(1, p(y) / p(x))."""
x, lp, chain, accepted = x0, logp(x0), np.empty(n), 0
for t in range(n):
y = x + step * rng.normal()
ly = logp(y)
if math.log(rng.random()) < ly - lp:
x, lp, accepted = y, ly, accepted + 1
chain[t] = x
return chain, accepted / n
def ess(chain):
"""A rough effective sample size for illustration: autocorrelations summed until they drop below 0.05 (production tools use more careful estimators)."""
c = chain - chain.mean()
f = np.fft.rfft(c, 2 * len(c))
ac = np.fft.irfft(f * np.conj(f))[: len(c)]
ac /= ac[0]
cut = np.argmax(ac < 0.05)
return len(c) / (1 + 2 * ac[1:cut].sum())
# a standard normal target with three step sizes, 20,000 steps each: acceptance rate and effective sample size
for step in (0.1, 2.4, 25):
chain, rate = metropolis(lambda x: -x * x / 2, 0.0, step, 20_000)
print(step, round(rate, 3), round(ess(chain)))
# 0.1 0.971 57 | 2.4 0.443 4815 | 25 0.053 708
# two modes at -3 and 3: the share of time in the right mode with a small and a large step
mix = lambda x: math.log(0.5 * math.exp(-(x + 3) ** 2 / 0.72) + 0.5 * math.exp(-(x - 3) ** 2 / 0.72))
for step in (0.5, 4.0):
chain, rate = metropolis(mix, -3.0, step, 20_000)
print(step, round(float((chain > 0).mean()), 3))
# 0.5 0.0 | 4.0 0.502
# Gibbs for a bivariate normal: successive draws of x1 have correlation rho^2
for rho in (0.5, 0.9, 0.99):
x1 = x2 = 0.0
s, xs = math.sqrt(1 - rho ** 2), np.empty(20_000)
for t in range(20_000):
x1 = rho * x2 + s * rng.normal()
x2 = rho * x1 + s * rng.normal()
xs[t] = x1
print(rho, round(float(np.corrcoef(xs[:-1], xs[1:])[0, 1]), 3), round(ess(xs)))
# 0.5 0.264 12075 | 0.9 0.807 2292 | 0.99 0.978 188
# unadjusted Langevin on N(0, 1), whose score is -x: the step size biases the stationary variance to 1 / (1 - eps / 4)
for eps in (0.1, 0.5):
x, xs = 0.0, np.empty(200_000)
for t in range(200_000):
x = x + eps / 2 * (-x) + math.sqrt(eps) * rng.normal()
xs[t] = x
print(eps, round(float(xs[1000:].var()), 3), round(1 / (1 - eps / 4), 3))
# 0.1 1.026 1.026 | 0.5 1.13 1.143
# the chain x' = a x + sqrt(1 - a^2) eps: finite-n variance of the mean, and the bias from a fixed start
a, n = 0.7, 50
formula = (1 + 2 * sum((1 - k / n) * a ** k for k in range(1, n))) / n
X, S = rng.normal(size=200_000), np.zeros(200_000) # 200,000 chains started from N(0, 1)
for t in range(n):
S += X
X = a * X + math.sqrt(1 - a * a) * rng.normal(size=200_000)
print(round(formula, 4), round((1 + a) / (1 - a) / n, 4), round(float((S / n).var()), 4))
print(round(10 * (1 - a ** n) / (n * (1 - a)), 3), [math.ceil(math.log(0.01 / 10) / math.log(r)) for r in (0.7, 0.99)])
# 0.1071 0.1133 0.1071 | 0.667 [20, 688]
Next#
This is the last note of the course. It started from coins, dice and the question of what a probability is, and ends with the samplers behind Bayesian statistics and the score that diffusion models reuse. The Machine Learning course builds on the whole course, and two later courses use this last section directly. The Bayesian Methods course turns Bayesian inference, the multivariate Gaussian and these samplers into methods for real models, with variational inference beside sampling. The generative models course builds on almost every note here: maximum likelihood and KL divergence, the multivariate Gaussian, the change-of-variables formula, Monte Carlo estimates of expectations, and Langevin dynamics with the score it follows.
References#
- N. Metropolis, A. W. Rosenbluth, M. N. Rosenbluth, A. H. Teller, E. Teller. Equation of State Calculations by Fast Computing Machines. The Journal of Chemical Physics, 21(6), 1953.
- W. K. Hastings. Monte Carlo Sampling Methods Using Markov Chains and Their Applications. Biometrika, 57(1), 1970.
- S. Geman, D. Geman. Stochastic Relaxation, Gibbs Distributions, and the Bayesian Restoration of Images. IEEE Transactions on Pattern Analysis and Machine Intelligence, 6(6), 1984.
- G. O. Roberts, J. S. Rosenthal. General State Space Markov Chains and MCMC Algorithms. Probability Surveys, 1, 2004. Section 2.1 (the Metropolis–Hastings kernel), Section 3.2 (irreducibility and aperiodicity of Metropolis–Hastings).
- 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), 1997.
- R. M. Neal. MCMC Using Hamiltonian Dynamics. In Handbook of Markov Chain Monte Carlo, CRC Press, 2011.
- M. Welling, Y. W. Teh. Bayesian Learning via Stochastic Gradient Langevin Dynamics. ICML, 2011.
- Y. Song, S. Ermon. Generative Modeling by Estimating Gradients of the Data Distribution. NeurIPS, 2019. Annealed Langevin dynamics.
- Y. Song, J. Sohl-Dickstein, D. P. Kingma, A. Kumar, S. Ermon, B. Poole. Score-Based Generative Modeling through Stochastic Differential Equations. ICLR, 2021. Reverse-time SDEs and predictor–corrector sampling.