TExcelTAD
Home › Randomized Algorithms & Probabilistic Analysis › MCMC Sampling: Metropolis and Glauber Dynamics

MCMC Sampling: Metropolis and Glauber Dynamics

How do you pick a uniformly random proper colouring of a graph, or a random independent set weighted by its size, when there are 21002^{100} of them and you cannot even count them? Markov chain Monte Carlo (MCMC) builds a Markov chain whose stationary distribution is the target, using only local moves and ratios of weights, and runs it long enough to mix. The Metropolis rule (Metropolis, Rosenbluth, Rosenbluth, Teller and Teller, 1953; generalised by Hastings, 1970) is the universal recipe; Glauber dynamics, which updates one site at a time, is its most common form. Mixing-time bounds from Coupling and Conductance decide whether the result is an efficient algorithm. This lesson builds the chains, checks them against exact answers on small instances, and states the main mixing results. For Monte Carlo estimation in general, see Monte Carlo Methods.

The Metropolis rule

Let the target be π(x)=w(x)/Z\pi(x) = w(x)/Z on a finite set Ω\Omega, where the weights w(x)>0w(x) > 0 are easy to compute but the normaliser Z=∑xw(x)Z = \sum_x w(x) is not. Choose a symmetric proposal K(x,y)=K(y,x)K(x, y) = K(y, x) (for example: change one coordinate at random) that connects all of Ω\Omega.

text
METROPOLIS-STEP(x)
0  propose y with probability K(x, y)
1  with probability min(1, w(y) / w(x))
2      return y                    // accept
3  return x                        // reject: stay

Theorem. The chain P(x,y)=K(x,y)min⁡(1,w(y)w(x))P(x, y) = K(x, y)\min\bigl(1, \frac{w(y)}{w(x)}\bigr) for y≠xy \ne x is reversible with respect to π\pi, so π\pi is stationary.

Proof. For x≠yx \ne y, π(x)P(x,y)=1ZK(x,y)min⁡(w(x),w(y))\pi(x)P(x, y) = \frac{1}{Z}K(x, y)\min(w(x), w(y)), which is symmetric in xx and yy. So detailed balance π(x)P(x,y)=π(y)P(y,x)\pi(x)P(x, y) = \pi(y)P(y, x) holds, and summing over xx gives ∑xπ(x)P(x,y)=π(y)\sum_x \pi(x)P(x, y) = \pi(y). □\square

Only the ratio w(y)/w(x)w(y)/w(x) is ever needed, so ZZ cancels. That is the whole trick. If the chain is also irreducible and aperiodic (rejections usually make it aperiodic), it converges to π\pi (Ergodic Chains and Stationary Distributions).

The program samples from π(k)∝2−∣k−7∣\pi(k) \propto 2^{-\lvert k - 7 \rvert} on {0,…,20}\{0, \ldots, 20\} with the proposal "move to k±1k \pm 1" and compares long-run frequencies with the exact distribution.

python · try it yourself
import random

N = 20
w = lambda k: 2.0 ** -abs(k - 7)
Z = sum(w(k) for k in range(N + 1))

rng = random.Random(160)
x, counts, steps = 0, [0] * (N + 1), 60000
for _ in range(steps):
    y = x + rng.choice((-1, 1))
    if 0 <= y <= N and rng.random() < min(1.0, w(y) / w(x)):
        x = y
    counts[x] += 1
print(" k   frequency   exact pi(k)")
for k in [0, 3, 6, 7, 8, 12, 20]:
    print(f"{k:2}   {counts[k] / steps:9.4f}   {w(k) / Z:11.4f}")
 k   frequency   exact pi(k)
 0      0.0028        0.0026
 3      0.0199        0.0209
 6      0.1691        0.1671
 7      0.3306        0.3342
 8      0.1650        0.1671
12      0.0112        0.0104
20      0.0000        0.0000

Glauber dynamics for independent sets

The hard-core model on a graph G=(V,E)G = (V, E) with fugacity λ>0\lambda > 0 gives each independent set II (no two vertices adjacent) the weight λ∣I∣\lambda^{\lvert I \rvert}. At λ=1\lambda = 1 it is the uniform distribution on independent sets. Its Glauber dynamics resamples one vertex at a time from its conditional distribution given the rest:

text
HARDCORE-STEP(I)
0  choose a vertex v uniformly at random
1  with probability lambda / (1 + lambda)
2      if no neighbour of v is in I: I = I + {v}
3  else
4      I = I - {v}
5  return I

It is reversible with respect to π(I)∝λ∣I∣\pi(I) \propto \lambda^{\lvert I \rvert} (the same detailed-balance check). Mixing results, stated: if GG has maximum degree Δ\Delta and λ<1Δ−1\lambda < \frac{1}{\Delta - 1}, a path coupling argument (two sets differing at one vertex vv meet with probability 1n\frac1n per step and drift apart with probability at most Δn⋅λ1+λ\frac{\Delta}{n}\cdot\frac{\lambda}{1 + \lambda}) gives mixing in O(nlog⁡n)O(n \log n) steps. The chain mixes in polynomial time for all λ\lambda below the uniqueness threshold λc(Δ)=(Δ−1)Δ−1(Δ−2)Δ≈eΔ\lambda_c(\Delta) = \frac{(\Delta - 1)^{\Delta - 1}}{(\Delta - 2)^{\Delta}} \approx \frac{e}{\Delta} (Anari, Liu and Oveis Gharan, 2020, by spectral independence), and above it approximate sampling is hard for general graphs of maximum degree Δ\Delta unless NP=RP\text{NP} = \text{RP} (Sly, 2010; Sly and Sun, 2014).

The program runs the chain on the 4×44 \times 4 grid at λ=1\lambda = 1 and compares the average size of the sampled sets with the exact value, computed by enumerating all independent sets.

python · try it yourself
import random
from itertools import product

side = 4
n = side * side
nbrs = [[] for _ in range(n)]
for r, c in product(range(side), repeat=2):
    for dr, dc in ((0, 1), (1, 0)):
        if r + dr < side and c + dc < side:
            a, b = r * side + c, (r + dr) * side + c + dc
            nbrs[a].append(b)
            nbrs[b].append(a)

def exact(lam):
    """Enumerate all independent sets by backtracking over the vertices 0 .. n-1."""
    Z = total = 0.0
    def extend(v, chosen, k):
        nonlocal Z, total
        if v == n:
            Z += lam ** k
            total += k * lam ** k
            return
        extend(v + 1, chosen, k)                              # leave v out
        if not any(u in chosen for u in nbrs[v]):
            extend(v + 1, chosen | {v}, k + 1)                # put v in
    extend(0, frozenset(), 0)
    return total / Z, Z

def glauber(lam, steps, rng):
    I = [False] * n
    size_sum = size = 0
    for t in range(steps):
        v = rng.randrange(n)
        if rng.random() < lam / (1 + lam):
            if not I[v] and not any(I[u] for u in nbrs[v]):
                I[v], size = True, size + 1
        elif I[v]:
            I[v], size = False, size - 1
        if t >= steps // 10:               # discard a burn-in period
            size_sum += size
    return size_sum / (steps - steps // 10)

mean_exact, Z = exact(1.0)
rng = random.Random(161)
print(f"4x4 grid: {int(Z)} independent sets, exact mean size {mean_exact:.4f}")
print(f"Glauber dynamics, 100000 steps: mean size {glauber(1.0, 100000, rng):.4f}")
4x4 grid: 1234 independent sets, exact mean size 4.0648
Glauber dynamics, 100000 steps: mean size 4.0953

Glauber dynamics for colourings

For proper qq-colourings, pick a vertex vv and a colour cc uniformly, and recolour vv with cc if no neighbour of vv has colour cc. The proposal is symmetric and every allowed move has the same weight, so the uniform distribution on proper colourings is stationary.

Theorem (Jerrum, 1995), stated. If GG has maximum degree Δ\Delta and q>2Δq > 2\Delta, this chain satisfies

tmix(ε)≤q−Δq−2Δ nln⁡nε.t_{\text{mix}}(\varepsilon) \le \frac{q - \Delta}{q - 2\Delta}\, n \ln\frac{n}{\varepsilon} .

The proof is a path coupling: for two colourings differing at one vertex, the chosen colour is coupled so that the disagreement disappears with probability about q−Δqn\frac{q - \Delta}{qn} and spreads with probability at most Δqn\frac{\Delta}{qn}. Vigoda (1999) lowered the condition to q>116Δq > \frac{11}{6}\Delta with a different chain, and Chen, Delcourt, Moitra, Perarnau and Postle (2019) slightly below that; the conjecture is that q≥Δ+2q \ge \Delta + 2 suffices.

The program checks the colouring chain on a cycle C8C_8 with q=5q = 5 (Δ=2\Delta = 2, so q>2Δq > 2\Delta): it estimates the probability that two opposite vertices get the same colour and compares it with the exact value from the colouring count of a cycle, (q−1)n+(−1)n(q−1)(q - 1)^n + (-1)^n (q - 1).

python · try it yourself
import random

def cycle_colourings(n, q):
    return (q - 1) ** n + (-1) ** n * (q - 1)

def path_colourings_same_ends(length, q):
    # proper colourings of a path with `length` edges whose two ends have a given equal colour
    same, diff = 1, 0
    for _ in range(length):
        same, diff = diff, same * (q - 1) + diff * (q - 2)
    return same

n, q = 8, 5
total = cycle_colourings(n, q)
# vertices 0 and 4 equal: fix their colour (q ways), each of the two 4-edge arcs is a path with equal ends
same = q * path_colourings_same_ends(4, q) ** 2
exact = same / total

rng = random.Random(162)
col = [i % 2 for i in range(n)]               # a proper starting colouring
hits, steps, burn = 0, 100000, 10000
for t in range(steps):
    v, c = rng.randrange(n), rng.randrange(q)
    if col[(v - 1) % n] != c and col[(v + 1) % n] != c:
        col[v] = c
    if t >= burn:
        hits += col[0] == col[4]
print(f"C_{n} with q = {q}: {total} proper colourings")
print(f"Pr[colour(0) = colour(4)]: exact {exact:.4f}, Glauber estimate {hits / (steps - burn):.4f}")
C_8 with q = 5: 65540 proper colourings
Pr[colour(0) = colour(4)]: exact 0.2063, Glauber estimate 0.2057

In C++

The hard-core Glauber dynamics on a 30×3030 \times 30 grid in C++ (fixed-seed std::mt19937), at a fugacity below the path-coupling threshold for Δ=4\Delta = 4 (λ<13\lambda < \frac13) and at λ=1\lambda = 1. It reports the density of the sampled independent sets, averaged after a burn-in period. There is no exact value to compare with here; the point is the sampler itself.

cpp · try it yourself
#include <cstdio>
#include <random>
#include <vector>

int main() {
    const int side = 30, n = side * side;
    std::vector<std::vector<int>> nb(n);
    for (int r = 0; r < side; ++r)
        for (int c = 0; c < side; ++c) {
            int v = r * side + c;
            if (c + 1 < side) { nb[v].push_back(v + 1); nb[v + 1].push_back(v); }
            if (r + 1 < side) { nb[v].push_back(v + side); nb[v + side].push_back(v); }
        }
    std::mt19937 rng(163);
    for (double lam : {0.25, 1.0}) {
        std::vector<char> in(n, 0);
        long long size = 0, sum = 0;
        const long long steps = 4000000, burn = 400000;
        for (long long t = 0; t < steps; ++t) {
            int v = rng() % n;
            double u = rng() / 4294967296.0;
            if (u < lam / (1 + lam)) {
                bool free = !in[v];
                for (int w : nb[v]) free = free && !in[w];
                if (free) { in[v] = 1; ++size; }
            } else if (in[v]) { in[v] = 0; --size; }
            if (t >= burn) sum += size;
        }
        std::printf("lambda = %.2f: mean density of the independent set %.4f\n", lam, double(sum) / (steps - burn) / n);
    }
}
lambda = 0.25: mean density of the independent set 0.1234
lambda = 1.00: mean density of the independent set 0.2299

From sampling to counting

For self-reducible problems, approximate sampling and approximate counting are equivalent up to polynomial factors (Jerrum, Valiant and Vazirani, 1986). For example, the number of independent sets of GG is Z(G)Z(G−v1)⋅Z(G−v1)Z(G−v1−v2)⋯\frac{Z(G)}{Z(G - v_1)} \cdot \frac{Z(G - v_1)}{Z(G - v_1 - v_2)} \cdots, and each ratio is the probability that a uniform independent set avoids a vertex, which a sampler estimates. Jerrum, Sinclair and Vigoda (2004) used this route, with a carefully analysed chain, to approximate the permanent of a nonnegative matrix in polynomial time, a problem whose exact version is #P-complete.

Test yourself

Why does the Metropolis rule never need the normalising constant ZZ?

  1. Because Z=1Z = 1
  2. Because the acceptance probability uses only the ratio w(y)/w(x)w(y)/w(x)
  3. Because the chain computes ZZ on the way
  4. Because the proposal is uniform

Which property of the Metropolis chain proves that π\pi is stationary?

  1. Irreducibility
  2. Detailed balance: π(x)P(x,y)=π(y)P(y,x)\pi(x)P(x,y) = \pi(y)P(y,x)
  3. Aperiodicity
  4. Laziness

Jerrum's theorem guarantees O(nlog⁡n)O(n \log n) mixing of the colouring chain under which condition?

  1. q≥Δq \ge \Delta
  2. q>2Δq > 2\Delta
  3. q>Δ2q > \Delta^2
  4. Always

How can an approximate sampler for independent sets be used to approximately count them?

  1. It cannot
  2. Write the count as a telescoping product of ratios Z(Gi)/Z(Gi+1)Z(G_{i})/Z(G_{i+1}), each a probability that the sampler estimates
  3. Run the sampler until it repeats
  4. Count distinct samples