Course contents 22 / 22

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.

Prerequisites

Monte Carlo methods

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, p(x)=p~(x)/Zp(x) = \tilde p(x) / Z with ZZ an intractable integral, in many dimensions. The direct methods of the Monte Carlo note need a proposal close to pp, and there is none. Markov chain Monte Carlo turns the ergodic theorem around: build a Markov chain whose stationary distribution is pp, run it, and use its states as samples. The construction needs only ratios p~(y)/p~(x)\tilde p(y)/\tilde p(x), in which ZZ 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. p(x)=p~(x)/Zp(x) = \tilde p(x)/Z is the target; q(y∣x)q(y \mid x) a proposal distribution; X0,X1,…X_0, X_1, \dots the chain. ∇log⁡p(x)\nabla \log p(x) is the score, which does not depend on ZZ.

Detailed balance#

A chain with transition probabilities P(x→y)P(x \to y) satisfies detailed balance with respect to pp if

p(x) P(x→y)=p(y) P(y→x)for all x,y.p(x)\, P(x \to y) = p(y)\, P(y \to x) \quad \text{for all } x, y .

In equilibrium, the flow of probability from xx to yy equals the flow back. Summing over xx shows that pp is stationary:

∑xp(x) P(x→y)=∑xp(y) P(y→x)(detailed balance)=p(y)(the moves out of y sum to 1).\begin{aligned} \sum_x p(x)\, P(x \to y) &= \sum_x p(y)\, P(y \to x) \quad \text{(detailed balance)} \\ &= p(y) \quad \text{(the moves out of } y \text{ sum to 1)} . \end{aligned}

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 pp 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, P(x→x)=1P(x \to x) = 1, satisfies it for every pp. The two-state chain that always switches satisfies it for p=(1/2,1/2)p = (1/2, 1/2), since 12⋅1=12⋅1\frac12 \cdot 1 = \frac12 \cdot 1, yet from a fixed start its distribution alternates between (1,0)(1, 0) and (0,1)(0, 1). Neither chain converges to pp, 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 0.90.9 and stay with probability 0.10.1. Every column of its transition matrix sums to 1, so ∑x13P(x→y)=13\sum_x \frac13 P(x \to y) = \frac13 and the uniform distribution is stationary. The flow from state 1 to state 2 is 13⋅0.9=0.3\frac13 \cdot 0.9 = 0.3, the flow back is 00: 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 xx, propose y∼q(⋅∣x)y \sim q(\cdot \mid x) and accept it with probability

α(x,y)=min⁡(1,p~(y) q(x∣y)p~(x) q(y∣x));\alpha(x, y) = \min\Big(1, \frac{\tilde p(y)\, q(x \mid y)}{\tilde p(x)\, q(y \mid x)}\Big) ;

otherwise stay at xx. The constant ZZ appears in both numerator and denominator and cancels. With a symmetric proposal, such as y=x+σεy = x + \sigma \varepsilon with ε∼N(0,1)\varepsilon \sim N(0, 1), the ratio is simply p~(y)/p~(x)\tilde p(y)/\tilde p(x): moves uphill are always accepted, moves downhill sometimes. This is random-walk Metropolis, the algorithm of Metropolis and colleagues from 1953.

Take p~(x)=e−x2/2\tilde p(x) = e^{-x^2/2} and this random walk, so that q(2∣0)=q(0∣2)q(2 \mid 0) = q(0 \mid 2) and the proposal terms cancel. From x=0x = 0 the proposal y=2y = 2 goes downhill and is accepted with probability α(0,2)=min⁡(1,e−2)=e−2≈0.135\alpha(0, 2) = \min(1, e^{-2}) = e^{-2} \approx 0.135. From x=2x = 2 the proposal y=0y = 0 goes uphill, and α(2,0)=min⁡(1,e2)=1\alpha(2, 0) = \min(1, e^{2}) = 1. The rare move out and the certain move back carry the same flow of probability, because p~(2)=e−2 p~(0)\tilde p(2) = e^{-2}\, \tilde p(0):

p~(0) q(2∣0) α(0,2)=1⋅q(2∣0)⋅e−2,p~(2) q(0∣2) α(2,0)=e−2⋅q(0∣2)⋅1,\begin{aligned} \tilde p(0)\, q(2 \mid 0)\, \alpha(0, 2) &= 1 \cdot q(2 \mid 0) \cdot e^{-2} , \\ \tilde p(2)\, q(0 \mid 2)\, \alpha(2, 0) &= e^{-2} \cdot q(0 \mid 2) \cdot 1 , \end{aligned}

and the two right-hand sides are equal.

The proposal q(y∣x)q(y \mid x) is the distribution of a candidate, not of the next state. The next state is yy after an acceptance and xx again after a rejection, so the transition kernel, the distribution of Xt+1X_{t+1} given Xt=xX_t = x, has two parts. By the law of total probability over the two outcomes, for a set AA

P(x,A)=∫Aq(y∣x) α(x,y) dy+r(x) 1[x∈A],P(x, A) = \int_A q(y \mid x)\, \alpha(x, y)\, dy + r(x)\, \mathbb 1[x \in A] ,

where

r(x)=1−∫q(y∣x) α(x,y) dyr(x) = 1 - \int q(y \mid x)\, \alpha(x, y)\, dy

is the probability that a proposal from xx is rejected. The first part has a density; the second is a point mass at xx, present even when qq is a smooth density. On a discrete space the integrals become sums.

The kernel satisfies detailed balance. For y≠xy \ne x only the first part acts. Multiplying p(x) q(y∣x)p(x)\, q(y \mid x) into the minimum that defines α\alpha gives an expression symmetric in xx and yy:

p(x) q(y∣x) α(x,y)=min⁡(p(x)q(y∣x), p(y)q(x∣y))=p(y) q(x∣y) α(y,x).\begin{aligned} p(x)\, q(y \mid x)\, \alpha(x, y) &= \min\big(p(x) q(y \mid x),\ p(y) q(x \mid y)\big) \\ &= p(y)\, q(x \mid y)\, \alpha(y, x) . \end{aligned}

The point mass sits at y=xy = x, where detailed balance reads p(x) r(x)=p(x) r(x)p(x)\, r(x) = p(x)\, r(x) and holds for any rr. So pp 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 q(y∣x) α(x,y)/a(x)q(y \mid x)\, \alpha(x, y) / a(x), where a(x)=1−r(x)a(x) = 1 - r(x) is the acceptance probability from xx. Its stationary density is proportional to p(x) a(x)p(x)\, a(x), not to p(x)p(x). Multiplying p(x) a(x)p(x)\, a(x) by this transition density cancels a(x)a(x); then detailed balance (first line) and the definition of aa (second line) give

∫p(x) q(y∣x) α(x,y) dx=∫p(y) q(x∣y) α(y,x) dx=p(y) a(y).\begin{aligned} \int p(x)\, q(y \mid x)\, \alpha(x, y)\, dx &= \int p(y)\, q(x \mid y)\, \alpha(y, x)\, dx \\ &= p(y)\, a(y) . \end{aligned}

States from which most proposals are rejected lose weight. For random-walk Metropolis on N(0,1)N(0, 1) with step 2.42.4, the acceptance probability is a(0)=0.385a(0) = 0.385 at the centre and a(2)=0.534a(2) = 0.534 in the tail, so the moves alone have variance 1.1331.133 instead of 1 (numerical integration). A run of 400,000 steps gives 0.9930.993 with the repeats and 1.1251.125 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 p~(x0)>0\tilde p(x_0) > 0, so that the denominator is positive. A proposal with p~(y)=0\tilde p(y) = 0 gets α=0\alpha = 0, so the chain never leaves the set where p~>0\tilde p > 0. A move that the proposal cannot reverse, q(x∣y)=0q(x \mid y) = 0, also gets α=0\alpha = 0: with y=x+∣ε∣y = x + \lvert \varepsilon \rvert, which only moves right, every proposal is rejected and the chain stays at x0x_0 forever.

Which regions the chain reaches is decided by the accepted moves, not by the proposals. Take a target supported on [−2,−1]∪[1,2][-2, -1] \cup [1, 2] and random-walk steps uniform on [−0.5,0.5][-0.5, 0.5]. Every proposal into the gap (−1,1)(-1, 1) 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 p~\tilde p 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 σ\sigma, but σ\sigma decides how well it works:

Figure

Metropolis with too small, good and too large steps

Three chain tracesA slowly drifting line, a rapidly oscillating line and a step-like line with long flat stretches.step 0.1: tiny moves, almost all accepted · accepted 96%step 2.4: good mixing · accepted 45%step 25: almost all rejected · accepted 6%Three chain tracesA slowly drifting line, a rapidly oscillating line and a step-like line with long flat stretches.step 0.1: tiny moves, almost all acceptedaccepted 96%step 2.4: good mixingaccepted 45%step 25: almost all rejectedaccepted 6%
The first 500 states of three Metropolis chains for a standard normal target. With step 0.1 almost every proposal is accepted (96%), but the chain crawls and does not cover the distribution in 500 steps. With step 25 almost every proposal is rejected (6%) and the chain sits still for long stretches. Step 2.4 accepts 45% of proposals and runs over the whole distribution quickly.

Over 20,000 steps on a standard normal target, a step of 0.10.1 accepts 97% of proposals and is worth only 57 independent samples; a step of 2525 accepts 5% and is worth 708; a step of 2.42.4 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 nn states usually carry less information than nn independent samples. How much less follows from the variance of the chain average gˉn=1n∑t=0n−1g(Xt)\bar g_n = \frac1n \sum_{t=0}^{n-1} g(X_t) in a chain started from pp. Let σ2=Var⁡pg(X)\sigma^2 = \operatorname{Var}_p g(X) and let ρk\rho_k be the autocorrelation of g(Xt)g(X_t) at lag kk. By stationarity a covariance depends only on the lag, and among the n2n^2 ordered pairs (s,t)(s, t) the lag 00 occurs nn times and a lag k≥1k \ge 1 occurs 2(n−k)2(n - k) times:

Var⁡gˉn=1n2∑s=0n−1∑t=0n−1Cov⁡(g(Xs),g(Xt))=σ2n2(n+2∑k=1n−1(n−k) ρk)=σ2n(1+2∑k=1n−1(1−kn)ρk).\begin{aligned} \operatorname{Var} \bar g_n &= \frac{1}{n^2} \sum_{s=0}^{n-1} \sum_{t=0}^{n-1} \operatorname{Cov}\big(g(X_s), g(X_t)\big) \\ &= \frac{\sigma^2}{n^2} \Big( n + 2 \sum_{k=1}^{n-1} (n - k)\, \rho_k \Big) \\ &= \frac{\sigma^2}{n} \Big( 1 + 2 \sum_{k=1}^{n-1} \Big(1 - \frac kn\Big) \rho_k \Big) . \end{aligned}

If ∑k∣ρk∣<∞\sum_k \lvert \rho_k \rvert < \infty, each weight 1−k/n1 - k/n tends to 1 and stays below 1, so by dominated convergence for series the bracket tends to the integrated autocorrelation time

τint=1+2∑k≥1ρk,\tau_{\text{int}} = 1 + 2\sum_{k \ge 1} \rho_k ,

and Var⁡gˉn≈σ2τint/n\operatorname{Var} \bar g_n \approx \sigma^2 \tau_{\text{int}} / n. The effective sample size is

ESS=nτint.\text{ESS} = \frac{n}{\tau_{\text{int}}} .

It belongs to a quantity of interest g(Xt)g(X_t), not to the chain as a whole, and it measures how many independent samples the nn states are worth for estimating Ep[g(X)]E_p[g(X)]. The error of the average of gg over the chain is then about σ/ESS\sigma / \sqrt{\text{ESS}}, not σ/n\sigma/\sqrt n, with σ2=Var⁡pg(X)\sigma^2 = \operatorname{Var}_p g(X). 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 nn; negative ones can make it larger: a chain whose autocorrelations are ρk=(−0.5)k\rho_k = (-0.5)^k has ESS=3n\text{ESS} = 3n. The ESS values quoted in this note come from a simple estimator that stops summing where the autocorrelations drop below 0.050.05; they are illustrative, and production tools use more careful estimators.

A chain whose numbers are all known checks the formula. The chain Xt+1=aXt+1−a2 εtX_{t+1} = a X_t + \sqrt{1 - a^2}\, \varepsilon_t, with εt∼N(0,1)\varepsilon_t \sim N(0, 1) independent of the past, keeps N(0,1)N(0, 1) stationary; the draws of X1X_1 in the Gibbs sampler below form such a chain with a=ρ2a = \rho^2. For g(x)=xg(x) = x we have σ2=1\sigma^2 = 1. The noise is independent of XtX_t, so Cov⁡(Xt+k,Xt)=aCov⁡(Xt+k−1,Xt)\operatorname{Cov}(X_{t+k}, X_t) = a \operatorname{Cov}(X_{t+k-1}, X_t), hence ρk=ak\rho_k = a^k, and the geometric series gives τint=(1+a)/(1−a)\tau_{\text{int}} = (1 + a)/(1 - a). For a=0.7a = 0.7 and n=50n = 50:

QuantityValue
τint=1.7/0.3\tau_{\text{int}} = 1.7 / 0.35.6675.667
finite-nn formula above0.10710.1071
limit σ2τint/n\sigma^2 \tau_{\text{int}} / n0.11330.1133
variance of 200,000 simulated averages0.10710.1071

The weights 1−k/n1 - k/n matter when nn is only a few times τint\tau_{\text{int}}.

The variance formula assumed a start from pp. Then every XtX_t has distribution pp, and by linearity Egˉn=EpgE \bar g_n = E_p g at every nn: the average is unbiased. From a fixed start it is biased. In the same chain, taking expectations of the update gives EXt+1=a EXtE X_{t+1} = a\, E X_t, so EXt=atx0E X_t = a^t x_0, and summing the geometric series,

Egˉn=x0 (1−an)n (1−a),E \bar g_n = \frac{x_0\, (1 - a^n)}{n\, (1 - a)} ,

which is 0.6670.667 for x0=10x_0 = 10, n=50n = 50, against the true mean 00. Discarding an initial burn-in removes the early terms that carry this bias. No length suits every chain. From x0=10x_0 = 10 the bias atx0a^t x_0 drops below 0.010.01 after 20 steps for a=0.7a = 0.7 and after 688 steps for a=0.99a = 0.99, and the required tt, which is log⁡(0.01/∣x0∣)/log⁡a\log(0.01 / \lvert x_0 \rvert) / \log a rounded up, grows without bound as a→1a \to 1 or ∣x0∣→∞\lvert x_0 \rvert \to \infty. 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 R^\hat R 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:

Figure

A chain stuck in one mode

Two traces for a two-mode targetThe top line stays near −3; the bottom one jumps between −3 and 3.step 0.5: 0% of the time in the right mode-33step 4: 56% of the time in the right mode-33Two traces for a two-mode targetThe top line stays near −3; the bottom one jumps between −3 and 3.step 0.5: 0% of the time in the right mode-33step 4: 56% of the time in the right mode-33
The target is an equal mixture of two normals centred at −3 and 3. Both chains start at −3. With step 0.5 the chain never reaches the second mode in 2,000 steps, and its samples look like draws from a single normal: nothing in them reveals that half of the probability is missing. With step 4 proposals jump the gap between the modes, and the chain spends about half its time in each.

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 ρ\rho, the conditionals are X1∣X2=x2∼N(ρx2,1−ρ2)X_1 \mid X_2 = x_2 \sim N(\rho x_2, 1 - \rho^2) and symmetrically.

Figure

Gibbs sampling moves in a zigzag

The Gibbs zigzag inside a narrow ellipseA staircase path of horizontal and vertical segments along a diagonal ellipse.startx₁x₂The Gibbs zigzag inside a narrow ellipseA staircase path of horizontal and vertical segments along a diagonal ellipse.startx₁x₂
A bivariate normal with correlation 0.95 (ellipses of distance 1 and 2) and the first 40 full sweeps of Gibbs sampling from (−2.4, −2.4). Each update changes one coordinate, drawn from its conditional distribution given the other, so the chain only moves along the axes. The narrow diagonal ellipse allows only short moves, and the chain crawls along the diagonal: successive values are strongly correlated (ρ² = 0.90 per sweep).

Strong correlation makes Gibbs slow: each move is along an axis, and the conditional variance 1−ρ21 - \rho^2 is small. Successive draws of X1X_1 have correlation ρ2\rho^2, which is 0.810.81 for ρ=0.9\rho = 0.9 and 0.980.98 for ρ=0.99\rho = 0.99; 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:

xt+1=xt+ε2∇log⁡p(xt)+ε zt,zt∼N(0,I).x_{t+1} = x_t + \frac{\varepsilon}{2} \nabla \log p(x_t) + \sqrt{\varepsilon}\, z_t, \qquad z_t \sim N(0, I) .

This is the unadjusted Langevin algorithm (ULA). For a smooth target and small enough steps its stationary distribution tends to pp as ε→0\varepsilon \to 0; 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 −x-x, the update is xt+1=(1−ε/2) xt+ε ztx_{t+1} = (1 - \varepsilon/2)\, x_t + \sqrt{\varepsilon}\, z_t, which is stable only for 0<ε<40 < \varepsilon < 4; then the stationary variance is 1/(1−ε/4)1/(1 - \varepsilon/4): 1.0261.026 for ε=0.1\varepsilon = 0.1, 1.1431.143 for ε=0.5\varepsilon = 0.5. For ε≥4\varepsilon \ge 4 the chain diverges. Adding a Metropolis–Hastings acceptance step removes the discretization bias (MALA): pp 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 ZZ 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 pp, a chain run long enough to forget its start, samples from (approximately, or for MALA exactly) its stationary distribution pp.
  • Annealed Langevin dynamics (Song and Ermon, 2019): a network learns the scores ∇log⁡pσ\nabla \log p_\sigma of the data blurred by Gaussian noise of several sizes σ\sigma, 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 ∇log⁡pt\nabla \log p_t of the noised data at time tt, 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 CarloMarkov chain Monte Carlo
Needssamples from pp or a close proposalp~\tilde p up to a constant (or its score)
Samplesindependentcorrelated; count the effective sample size
High dimensionsproposals degrade exponentiallylocal moves still work, at the cost of mixing time
Typical algorithmsinversion, rejection, importance samplingMetropolis–Hastings, Gibbs, Langevin, HMC
Main failureinfinite-variance weightsslow 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 p(x)P(x→y)=p(y)P(y→x)p(x) P(x \to y) = p(y) P(y \to x) makes pp stationary.
  • Metropolis–Hastings: propose y∼q(⋅∣x)y \sim q(\cdot \mid x), accept with min⁡(1,p~(y)q(x∣y)/(p~(x)q(y∣x)))\min\big(1, \tilde p(y) q(x \mid y) / (\tilde p(x) q(y \mid x))\big); only ratios of p~\tilde p 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 g(Xt)g(X_t) of a stationary chain, correlated samples are worth an effective sample size n/(1+2∑ρk)n/(1 + 2\sum \rho_k), usually less than nn; 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 (0<ε<40 < \varepsilon < 4 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#