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 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 on a finite set , where the weights are easy to compute but the normaliser is not. Choose a symmetric proposal (for example: change one coordinate at random) that connects all of .
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: stayTheorem. The chain for is reversible with respect to , so is stationary.
Proof. For , , which is symmetric in and . So detailed balance holds, and summing over gives .
Only the ratio is ever needed, so cancels. That is the whole trick. If the chain is also irreducible and aperiodic (rejections usually make it aperiodic), it converges to (Ergodic Chains and Stationary Distributions).
The program samples from on with the proposal "move to " and compares long-run frequencies with the exact distribution.
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 with fugacity gives each independent set (no two vertices adjacent) the weight . At it is the uniform distribution on independent sets. Its Glauber dynamics resamples one vertex at a time from its conditional distribution given the rest:
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 IIt is reversible with respect to (the same detailed-balance check). Mixing results, stated: if has maximum degree and , a path coupling argument (two sets differing at one vertex meet with probability per step and drift apart with probability at most ) gives mixing in steps. The chain mixes in polynomial time for all below the uniqueness threshold (Anari, Liu and Oveis Gharan, 2020, by spectral independence), and above it approximate sampling is hard for general graphs of maximum degree unless (Sly, 2010; Sly and Sun, 2014).
The program runs the chain on the grid at and compares the average size of the sampled sets with the exact value, computed by enumerating all independent sets.
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 -colourings, pick a vertex and a colour uniformly, and recolour with if no neighbour of has colour . 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 has maximum degree and , this chain satisfies
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 and spreads with probability at most . Vigoda (1999) lowered the condition to with a different chain, and Chen, Delcourt, Moitra, Perarnau and Postle (2019) slightly below that; the conjecture is that suffices.
The program checks the colouring chain on a cycle with (, so ): 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, .
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 grid in C++ (fixed-seed std::mt19937), at a fugacity below the path-coupling threshold for () and at . 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.
#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 is , 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 ?
- Because
- Because the acceptance probability uses only the ratio
- Because the chain computes on the way
- Because the proposal is uniform
Which property of the Metropolis chain proves that is stationary?
- Irreducibility
- Detailed balance:
- Aperiodicity
- Laziness
Jerrum's theorem guarantees mixing of the colouring chain under which condition?
- Always
How can an approximate sampler for independent sets be used to approximately count them?
- It cannot
- Write the count as a telescoping product of ratios , each a probability that the sampler estimates
- Run the sampler until it repeats
- Count distinct samples