Mixing times, spectral gap and perfect sampling
Knowing a chain converges is not enough: we must know how long it takes. Define total-variation mixing times and bound them by coupling, the spectral gap of reversible chains, and conductance through Cheeger's inequality. Study cutoff with card shuffling and conclude with Propp and Wilson's coupling from the past, which produces exact samples from π.
After this lesson you can
- Calculate exact mixing times for small chains and bound them by coupling for the lazy hypercube walk.
- Relate the spectral gap to convergence speed and calculate it numerically.
- Use conductance to diagnose bottlenecks in multimodal chains and understand why MCMC struggles with them.
- Reproduce cutoff in riffle shuffling and the hypercube walk.
- Implement monotone CFTP for the Ising model and verify that the samples are exact.
Before you start
Knowing it converges does not say when
A chain may have the correct limiting distribution yet remain trapped in one mode throughout the available run. For MCMC, the question is not just whether it converges but how long it takes to forget its initial state. A classic example is shuffling: when does the distribution of permutations resemble uniformity?
The figure uses the Gilbert-Shannon-Reeds mathematical model: cut the deck according to a binomial distribution and interleave the piles with probabilities proportional to their remaining sizes. Distance is calculated by grouping permutations by their number of rising sequences, rather than observing a few decks and assuming they represent all of them.
For 52 cards, the table of Bayer and Diaconis gives approximately , , and after five, six, seven and eight shuffles respectively. Seven marks the drop region; with threshold this model requires eight. The conclusion depends on the distance definition and on real shuffling resembling GSR.
Distance and mixing time
For a finite irreducible aperiodic chain with stationary distribution , define
The mixing time is for . The maximum over initial states gives a uniform guarantee; a particular run may appear to mix sooner or later. Threshold conventions should be stated: often abbreviates .
A transition does not increase total variation distance between distributions. For any difference with zero total mass, applying averages its contributions and the triangle inequality bounds the norm . Therefore . Also , by convexity with respect to and the triangle inequality.
For submultiplicativity, take a maximal coupling of and , which disagrees with probability equal to their total variation distance. If it disagrees, maximally couple their distributions after another steps; if it agrees, use the same evolution. The final disagreement probability is at most , so
This result explains why a mixing bound at a fixed threshold can be amplified by repeating blocks, even if the resulting bound is not tight.
Coupling the hypercube
The coupling mixing bound says that if two copies with correct marginals agree from time onward, the distance between their laws at is at most . For the lazy walk on the hypercube , at each step choose a coordinate uniformly and replace it with a fair bit. This is equivalent to staying put with probability and, with probability , flipping a uniformly chosen coordinate.
Couple two copies by choosing the same coordinate and bit at each step. Once chosen, a coordinate stays equal in both forever. When all have been chosen, the copies coincide. By a union bound, the probability that any coordinate remains unchosen after steps is at most . Therefore , and suffices to guarantee distance at most . This is the coupon-collector bound; it need not identify the exact mixing time.
Spectrum and conductance
For a finite reversible chain, the eigenvalues of are real. Order . The spectral gap and relaxation time require distinguishing two quantities: and , with when . A non-lazy chain can have an eigenvalue close to : looking only at would hide a slow oscillation.
For a finite irreducible, reversible and aperiodic chain with , a useful bound for is
The upper bound follows by expanding the initial density in the orthonormal eigenbasis of in and applying Cauchy-Schwarz to pass from to total variation. Each nonconstant component is multiplied by a power of its eigenvalue. The lower bound takes an eigenvector associated with the largest nontrivial modulus and uses the fact that its expectation decays as . These expressions and assumptions appear in Theorems 12.4 and 12.5 of Levin, Peres and Wilmer.
The spectrum quantifies slowness; geometry can explain its origin. For with , the outward stationary flow is . The conductance is
A low-conductance cut retains mass in a region. Cheeger’s inequality for finite irreducible reversible chains says . It refers to the ordinary gap, not automatically the absolute gap. If the chain is lazy with nonnegative spectrum, the two coincide. The upper half follows by testing a centered cut indicator in the Rayleigh quotient; the lower half requires a level-set argument and Cauchy-Schwarz, developed in Theorem 13.10 of the same reference.
Low autocorrelation for one function does not demonstrate that the entire chain has mixed. If that function does not distinguish modes separated by a narrow bridge, it may seem stable while mass from one mode barely reaches the other. Canonical paths, Poincaré inequalities and log-Sobolev inequalities give other bounds; their usefulness depends on each chain’s geometry and assumptions.
Cutoff and exact shuffling
The cutoff phenomenon is a property of a family of chains of increasing size: for every , mixing times at and are asymptotically equivalent. The transition from distance near one to distance near zero occurs in a window small relative to the central time. A single steep curve at finite size suggests the phenomenon but does not prove it.
In GSR, shuffles are equivalent to an -shuffle with . Bayer and Diaconis show that the probability of a permutation with rising sequences is . The number of permutations with sequences is the Eulerian number ; therefore
The formula is exact for the labeled deck and GSR model; numerical calculation requires avoiding overflowing factorials and powers. The paper’s asymptotic result places cutoff around . In the refresh-update hypercube, the location is of order , while the earlier coupon bound guarantees order : a valid bound need not capture cutoff.
Coupling from the past
Coupling from the past (CFTP) generates an exact sample from when the construction coalesces almost surely. Fix a sequence of random transition maps for negative times up to zero. Apply the same maps from every possible state at ; if all images at zero agree, return that image. Otherwise extend the past, for example from to , reusing maps from the interval already generated.
The proof idea first uses a deterministic horizon : start a chain at with law , independent of later maps. Its value at zero has law . On the event that all states coalesce from , this value agrees with the CFTP result because the stationary start is one of the tested states. As grows, the probability of non-coalescence tends to zero and the distance between the returned law and is bounded by that probability. The required time is determined by looking backward with the endpoint fixed at zero; changing or regenerating randomness when extending the past breaks this construction. Under almost-sure coalescence, the returned value has exactly the stationary law. The original work is by Propp and Wilson.
On a partially ordered space, if each map is monotone and minimum and maximum states exist, following those two extremes suffices: all others stay between them. Do not confuse CFTP with advancing all paths from today and stopping when they meet: selecting that time forward can bias the common state.
Lab: exact mixing and bounds
The hypercube has states, but symmetry means it suffices to track Hamming distance from the initial vertex. If the current weight is , refreshing a coordinate increases the weight with probability , decreases it with probability , and leaves it unchanged with probability . The stationary distribution of this weight is . Since all configurations of the same weight have equal probability, total variation between weight laws equals that between the full laws. Translation symmetry makes the distance the same from every vertex.
import numpy as np
from math import comb, exp, log, cos, pi
def hipercubo_pesos(d):
P = np.zeros((d+1, d+1))
for k in range(d+1):
P[k, k] = 0.5
if k < d:
P[k, k+1] = (d-k)/(2*d)
if k > 0:
P[k, k-1] = k/(2*d)
return P
d = 8
P = hipercubo_pesos(d)
estacionaria = np.array([comb(d, k) / 2**d for k in range(d+1)])
mu = np.eye(d+1)[0]
primero = None
for t in range(81):
tv = .5 * np.abs(mu - estacionaria).sum()
if primero is None and tv <= .25:
primero = t
if t in (0, 10, 20, 30):
print('paso, TV exacta, cota cupones:', t, round(tv, 6), round(min(1., d*(1-1/d)**t), 6))
mu = mu @ P
print('tiempo exacto de mezcla a 1/4:', primero)
print('cota por cupones a 1/4:', int(np.ceil(d*log(4*d))))For a cycle of nodes, with probability of staying and of moving to each neighbor, the stationary distribution is uniform and the eigenvalues are . The following search calculates distance from every state without assuming symmetry in advance and compares it with the spectral bound.
N = 20
C = np.zeros((N, N))
for i in range(N):
C[i, i] = .5
C[i, (i-1) % N] = C[i, (i+1) % N] = .25
pi_ciclo = np.ones(N) / N
valores = np.linalg.eigvalsh(C)
gamma = 1 - max(abs(valores[:-1]))
trel = 1 / gamma
potencia = np.eye(N)
tiempo = None
for t in range(501):
distancia = np.max(.5 * np.abs(potencia - pi_ciclo).sum(axis=1))
if tiempo is None and distancia <= .25:
tiempo = t
potencia = potencia @ C
cota = int(np.ceil(trel * (log(1/.5) + .5*log(N))))
print('hueco:', round(gamma, 8), 'relajación:', round(trel, 6))
print('mezcla exacta a 1/4:', tiempo, 'cota espectral:', cota)
print('fórmula del hueco:', round((1-cos(2*pi/N))/2, 8))For small graphs we can calculate conductance exhaustively. The code requires a positive stationary distribution of a reversible chain; enumeration grows exponentially and does not replace approximate cut algorithms on large graphs. Cheeger’s inequality is checked using the ordinary gap .
def conductancia(P, pi):
n = len(pi)
mejor = float('inf')
corte = None
for mascara in range(1, 1 << n):
dentro = np.array([(mascara >> i) & 1 for i in range(n)], dtype=bool)
masa = pi[dentro].sum()
if masa > 0.5 + 1e-12:
continue
flujo = (pi[dentro, None] * P[np.ix_(dentro, ~dentro)]).sum()
valor = flujo / masa
if valor < mejor:
mejor, corte = valor, np.flatnonzero(dentro).tolist()
return mejor, corte
# Paseo perezoso por un camino de 4 estados.
camino = np.array([[.5,.5,0,0],[.25,.5,.25,0],[0,.25,.5,.25],[0,0,.5,.5]])
pi_camino = np.array([1/6, 1/3, 1/3, 1/6])
phi, corte = conductancia(camino, pi_camino)
simetrica = np.sqrt(pi_camino)[:, None] * camino / np.sqrt(pi_camino)[None, :]
gamma_ordinario = 1 - np.linalg.eigvalsh(simetrica)[-2]
print('corte minimizador:', corte, 'conductancia:', round(phi, 6))
print('Cheeger:', round(phi**2/2, 6), '<=', round(gamma_ordinario, 6), '<=', round(2*phi, 6))Lab: Ising by coupling from the past
On a finite grid with spins , ferromagnetic interaction , field and inverse temperature , a single-site heat-bath update uses
If two configurations are ordered componentwise, using the same site and uniform draw preserves the order: the probability of setting increases with the neighbors. It therefore suffices to track the configurations of all and all . The implementation uses free boundaries and retains each site-uniform pair when extending the window. By default it runs CFTP until coalescence. An optional limit returns None if coalescence is not reached: it does not present an approximate configuration as an exact sample. If you impose a limit, the law of results conditional on completion before it may be biased; do not discard failures and present successes as an unconditional Gibbs sample.
The theorem’s exactness assumes ideal probabilities and randomness. On a computer we use floating-point arithmetic and a pseudorandom generator; for extreme parameters, a probability may round to zero or one and destroy positive model transitions. The code explicitly rejects that case, but finite numerical error remains for other values.
from math import exp
def vecinos_libres(L):
resultado = []
for i in range(L*L):
r, c = divmod(i, L)
resultado.append([rr*L+cc for rr, cc in ((r-1,c),(r+1,c),(r,c-1),(r,c+1))
if 0 <= rr < L and 0 <= cc < L])
return resultado
def probabilidad_mas(beta, campo):
z = 2 * beta * campo
if z >= 0:
p = 1 / (1 + exp(-z))
else:
e = exp(z)
p = e / (1 + e)
if p <= 0 or p >= 1:
raise ValueError('probabilidad redondeada a 0 o 1: reduce beta o campo')
return p
def cftp_ising(L, beta, rng, J=1., h=0., max_ventana=None):
if beta < 0 or J < 0:
raise ValueError('se requieren beta y J no negativos para la monotonía')
if L < 1 or (max_ventana is not None and max_ventana < 1):
raise ValueError('L y el límite opcional deben ser positivos')
vecinos = vecinos_libres(L)
sitios = np.empty(0, dtype=int)
uniformes = np.empty(0)
ventana = 1
ultima = 0
while max_ventana is None or ventana <= max_ventana:
ultima = ventana
nuevos = ventana - len(sitios)
sitios = np.concatenate((rng.integers(0, L*L, nuevos), sitios))
uniformes = np.concatenate((rng.random(nuevos), uniformes))
inferior = np.full(L*L, -1, dtype=np.int8)
superior = np.ones(L*L, dtype=np.int8)
for sitio, u in zip(sitios, uniformes):
for estado in (inferior, superior):
campo = J * sum(int(estado[j]) for j in vecinos[sitio]) + h
p_mas = probabilidad_mas(beta, campo)
estado[sitio] = 1 if u < p_mas else -1
if np.array_equal(inferior, superior):
return inferior.reshape(L, L), ventana
ventana *= 2
return None, ultimaFirst validate on , where the states can be enumerated. With free boundaries, each edge is counted once in the energy. Compare mean absolute magnetization of CFTP samples with its exact value and display a Monte Carlo standard error. A statistical comparison can reveal mistakes, but the algorithm’s exactness follows from the coupling argument, not from a table appearing close.
def media_abs_exacta(L, beta):
pesos, observables = [], []
for mascara in range(1 << (L*L)):
s = np.array([1 if mascara & (1 << i) else -1 for i in range(L*L)]).reshape(L,L)
interaccion = int((s[:, :-1]*s[:, 1:]).sum() + (s[:-1, :]*s[1:, :]).sum())
pesos.append(exp(beta * interaccion))
observables.append(abs(s.mean()))
return np.average(observables, weights=pesos)
rng = np.random.default_rng(26041)
beta = .2
muestras = []
for _ in range(400):
s, ventana = cftp_ising(3, beta, rng)
muestras.append(abs(s.mean()))
print('magnetización absoluta exacta:', round(media_abs_exacta(3, beta), 5))
print('media CFTP:', round(np.mean(muestras), 5))
print('error estándar Monte Carlo:', round(np.std(muestras, ddof=1)/np.sqrt(len(muestras)), 5))Finally use the requested grid. To keep this browser demonstration bounded, enable the optional limit and report any censoring; displayed configurations are examples subject to that limit, not an unbiased sample conditional on success. Observed windows are random realizations, not universal execution times; temperature changes dependence and can make coalescence much harder. Comparison with a long chain is an approximate diagnostic, not proof that the chain is exact. To generate exact samples without that conditioning, call cftp_ising without max_ventana and let each run finish.
def gibbs_magnetizacion(L, beta, pasos, rng):
vecinos = vecinos_libres(L)
estado = np.ones(L*L, dtype=np.int8)
sitios = rng.integers(0, L*L, pasos)
uniformes = rng.random(pasos)
for sitio, u in zip(sitios, uniformes):
campo = sum(int(estado[j]) for j in vecinos[sitio])
p = probabilidad_mas(beta, campo)
estado[sitio] = 1 if u < p else -1
return abs(estado.mean())
rng = np.random.default_rng(26042)
for beta in (0.05, 0.15):
s, ventana = cftp_ising(32, beta, rng, max_ventana=65536)
if s is None:
print('beta:', beta, 'sin coalescencia hasta', ventana, 'actualizaciones')
else:
print('beta:', beta, 'ventana CFTP:', ventana, 'magnetización absoluta:', round(abs(s.mean()), 5))
print('una cadena de contraste, magnetización absoluta:', round(gibbs_magnetizacion(32, beta, 30000, rng), 5))To go beyond one path, run independent replications and compare the distribution of windows with magnetization averages from long chains. Each comparison chain first discards 80,000 updates and averages observations separated by 1,000 updates; its two halves are shown as a coarse drift diagnostic, not certification of equilibrium. For CFTP use an explicit limit so each cell finishes: the magnetization comparison is calculated only if no replication was censored and remains a finite experiment, not proof that the limit introduces no bias. For an unconditional estimate use the same protocol without a limit and wait for all replications to coalesce.
def gibbs_resumen(L, beta, rng, calentamiento=80000, intervalo=1000, observaciones=40):
vecinos = vecinos_libres(L)
estado = np.ones(L*L, dtype=np.int8)
total = calentamiento + intervalo * observaciones
sitios = rng.integers(0, L*L, total)
uniformes = rng.random(total)
medidas = []
for t, (sitio, u) in enumerate(zip(sitios, uniformes), 1):
campo = sum(int(estado[j]) for j in vecinos[sitio])
estado[sitio] = 1 if u < probabilidad_mas(beta, campo) else -1
if t > calentamiento and (t-calentamiento) % intervalo == 0:
medidas.append(abs(estado.mean()))
medidas = np.asarray(medidas)
return medidas.mean(), medidas[:observaciones//2].mean(), medidas[observaciones//2:].mean()
def comparar_replicas(beta, seed, replicas=4, limite=65536):
rng = np.random.default_rng(seed)
ventanas, cftp, gibbs = [], [], []
for _ in range(replicas):
s, ventana = cftp_ising(32, beta, rng, max_ventana=limite)
ventanas.append(ventana)
cftp.append(None if s is None else abs(s.mean()))
gibbs.append(gibbs_resumen(32, beta, rng))
return ventanas, cftp, np.array(gibbs)
def mostrar_comparacion(beta, resultado):
ventanas, cftp, gibbs = resultado
fallos = sum(x is None for x in cftp)
print('beta:', beta, 'ventanas:', ventanas, 'censuradas:', fallos)
if fallos == 0:
print('media |magnetización| CFTP, condicionada al límite:', round(np.mean(cftp), 5))
print('media |magnetización| Gibbs:', round(gibbs[:, 0].mean(), 5))
print('mitades Gibbs:', np.round(gibbs[:, 1:].mean(axis=0), 5))comparacion_005 = comparar_replicas(.05, 26043)
mostrar_comparacion(.05, comparacion_005)comparacion_015 = comparar_replicas(.15, 26044)
mostrar_comparacion(.15, comparacion_015)Four replications are a short check, not a precise assessment of the time distribution or proof of Gibbs equilibrium. For a stronger study increase replicas, repeat with longer warmups and runs, compare several chains initialized in opposite states, and estimate uncertainty accounting for autocorrelation. As you approach slowly mixing temperatures, report the censored fraction rather than treating failed runs as nonexistent.
Exercises
More than one answer may be correct.
Step 1 of 3. What happens when P is applied to two distributions?
Step 1 of 3. When do coordinates become equal?
estimate_conductance(P, pi) by exhaustive search in a finite chain with positive pi. Return the minimum of Q(S,Sᶜ)/pi(S) over nonempty sets with mass at most 1/2. There are at most 16 states.import numpy as np
def estimate_conductance(P, pi):
passMixing time measures the worst start in a chosen distance. Coupling, spectrum and conductance give complementary bounds; cutoff describes an asymptotic transition in a family. CFTP fixes the present, preserves randomness and uses coalescence to eliminate dependence on the initial state exactly.