Exercise: sampling, temperature and the phase transition
Before this unit: Energy and probability: the Ising model (previous unit); Day 27: Graph cuts.
See also: Day 3: Bit depth and noise.
Goal
By the end of this exercise you should be able to:
- compute the local conditional probability of a pixel given its neighbours,
- carry out one Gibbs and one Metropolis update by hand,
- set up the transition matrix of a two-state chain, find its long-run distribution and check detailed balance,
- describe the phase transition of the 2D Ising model from a simulation, and critical slowing down,
- explain why simulated annealing must cool slowly, and what a quench does.
Do the pen-and-paper part first, then the interactive part. Questions marked (math) are for those who want the derivations; the concept questions do not depend on them.
Background
| Word | Meaning |
|---|---|
| Local field | u_p = J\sum_{q \sim p}s_q + h: the neighbours’ vote for +1 |
| Local conditional | p(s_p = +1 \mid \text{neighbours}) = 1/(1 + e^{-2u_p/T}) |
| Energy change of a flip | \Delta E = 2s_pu_p (s_p = the value before the flip) |
| Gibbs sampler | set s_p = +1 with the local conditional probability, else -1 |
| Metropolis | flip if \Delta E \le 0; otherwise flip with probability e^{-\Delta E/T} |
| Sweep | one update of every pixel |
| Stationary distribution | \boldsymbol\pi with \boldsymbol\pi P = \boldsymbol\pi (row vector, P_{ab} = probability a \to b) |
| Detailed balance | \pi_aP_{ab} = \pi_bP_{ba} for every pair of states |
| Critical temperature | T_c = 2J/\ln(1 + \sqrt2) \approx 2.27 for the square lattice |
Unless stated otherwise: J = 1, h = 0, 4-neighbours.
By hand
B1. A pixel has neighbours (+, +, +, -). (a) Compute u_p and p(s_p = +1 \mid \text{neighbours}) at T = 1, T = 2 and T = 4. (b) The same with neighbours (+, +, -, -), and with (+, +, +, +) at T = 2. (c) Add a field h = 0.5 to (b)’s first case. What changes?
B2. Metropolis. The same pixel is +1 with neighbours (+, +, +, -). (a) What is \Delta E of flipping it to -1? With which probability is the flip accepted at T = 2, and at T = 0.5? (b) The pixel is -1 with the same neighbours. What is \Delta E of flipping it to +1, and the acceptance probability?
B3. Gibbs or Metropolis. For the pixel of B2 at T = 2: (a) After one Gibbs update, what is the probability that it is +1, if it was +1 before? If it was -1 before? (b) The same for one Metropolis update. (c) Which of the two changes the pixel more often? Show that in both cases the long-run fraction of time at +1 (with the neighbours held fixed) is the same, and give it.
B4. A two-state chain. Two states a and b with energies E_a = 0, E_b = 1, T = 1. Metropolis proposes the other state at every step. (a) Write the transition matrix P. (b) Find \boldsymbol\pi = (\pi_a, \pi_b) with \boldsymbol\pi P = \boldsymbol\pi and \pi_a + \pi_b = 1. (c) Check detailed balance, and that \boldsymbol\pi is the Gibbs distribution. (d) Start in a. What is the probability of being in a after 1, 2 and 3 steps? How fast does it approach \pi_a?
B5. Predict. Sketch what a typical state of a large lattice looks like at T = 1, T = 2.27 and T = 5 (h = 0). What is |m| roughly in each case? What does a small field h = 0.05 change at T = 1.8, and at T = 5?
B6. Cooling. (a) A geometric schedule should go from T_0 = 4 to T = 0.5 in 100 sweeps. What is the factor r per sweep? (b) With the logarithmic schedule T_k = 4/\ln(k + 2), after how many sweeps is T = 0.5? And T = 0.1? (c) Why does a quench to T = 0.5 from random spins usually not reach the ground state of a large lattice?
B1. (a) u_p = 1 + 1 + 1 - 1 = 2. T = 1: 1/(1 + e^{-4}) = 0.982; T = 2: 1/(1 + e^{-2}) = 0.881; T = 4: 1/(1 + e^{-1}) = 0.731. (b) (+, +, -, -): u_p = 0, probability \tfrac12 at every T. (+, +, +, +): u_p = 4, at T = 2: 1/(1 + e^{-4}) = 0.982. (c) u_p = 0 + 0.5 = 0.5: 1/(1 + e^{-0.5}) = 0.622 at T = 2. The field breaks the tie.
B2. (a) \Delta E = 2s_pu_p = 2 \cdot 1 \cdot 2 = 4: accepted with e^{-2} = 0.135 at T = 2 and e^{-8} = 0.00034 at T = 0.5. (b) \Delta E = 2 \cdot (-1) \cdot 2 = -4: downhill, always accepted.
B3. (a) Gibbs ignores the old value: +1 with probability 0.881 either way. (b) Metropolis from +1: stays +1 unless the flip is accepted: 1 - 0.135 = 0.865. From -1: always flips to +1: probability 1. (c) Gibbs changes the value with probability 0.119 (from +1) or 0.881 (from -1); Metropolis with 0.135 or 1: Metropolis changes it more often. Long run, Metropolis: balance \pi_+ \cdot 0.135 = \pi_- \cdot 1 gives \pi_+ = 1/(1 + 0.135) = 0.881, the same as Gibbs, and equal to the local conditional.
B4. (a) From a: uphill by 1, accept e^{-1} = 0.368. From b: downhill, always. P = \begin{bmatrix} 0.632 & 0.368 \\ 1 & 0\end{bmatrix}. (b) \pi_a = 0.632\pi_a + \pi_b gives \pi_b = 0.368\pi_a; with \pi_a + \pi_b = 1: \boldsymbol\pi = (0.731, 0.269). (c) \pi_aP_{ab} = 0.731 \cdot 0.368 = 0.269 = \pi_bP_{ba} = 0.269 \cdot 1. Gibbs: e^{0}/(e^0 + e^{-1}) = 0.731. The same. (d) After 1 step: 0.632; after 2: 0.632^2 + 0.368 \cdot 1 = 0.768; after 3: 0.768 \cdot 0.632 + 0.232 \cdot 1 = 0.717. The distance to 0.731 is 0.269 \cdot 0.368^k with alternating sign: -0.099, +0.036, -0.013. It shrinks by a factor 0.368 per step.
B5. T = 1: almost all spins equal; |m| \approx 1 (0.999). T = 2.27: clusters of every size, ragged; |m| fluctuates and is small for a large lattice. T = 5: noise with tiny clusters; |m| \approx 0. At T = 1.8, below T_c, the lattice has to choose a sign; a small field decides which, quickly and for the whole lattice. At T = 5 the field only shifts m slightly towards +.
B6. (a) r = (0.5/4)^{1/100} = 0.125^{0.01} = 0.979. (b) 4/\ln(k + 2) = 0.5: \ln(k + 2) = 8, k = e^8 - 2 = 2979 sweeps. T = 0.1: \ln(k + 2) = 40, k \approx 2.4 \cdot 10^{17} sweeps: hopeless. (c) Domains form everywhere at once. Their walls shrink only by flips that do not raise the energy; a straight wall across the whole (periodic) lattice cannot move without uphill flips, which at T = 0.5 are accepted with tiny probability. The lattice is stuck in a local minimum.
Math questions
B7. (math) Derive the local conditional p(s_p = +1 \mid \text{rest}) = 1/(1 + e^{-2u_p/T}) from the Gibbs distribution, and show that it depends on the rest only through the neighbours of p.
B8. (math) Show that detailed balance \pi_aP_{ab} = \pi_bP_{ba} implies \boldsymbol\pi P = \boldsymbol\pi. Show that the single-pixel Gibbs update satisfies detailed balance with respect to the Gibbs distribution.
B9. (math) For the chain of B4, find both eigenvalues of P and explain the factor 0.368 in B4(d).
B10. (math) In a long 1D chain at temperature T (no field), the fraction of disagreeing neighbour pairs is 1/(1 + e^{2J/T}). Evaluate it at T = 1 and T = 0.5. Use it to argue that a chain has no ordered phase at any T > 0.
B7. States \mathbf s^\pm differ only at p. Terms of E without s_p cancel in E(\mathbf s^-) - E(\mathbf s^+) = 2J\sum_{q \sim p}s_q + 2h = 2u_p. So p(\mathbf s^+)/p(\mathbf s^-) = e^{2u_p/T}, and p(s_p = +1 \mid \text{rest}) = p(\mathbf s^+)/(p(\mathbf s^+) + p(\mathbf s^-)) = 1/(1 + e^{-2u_p/T}). Only u_p appears: the neighbours.
B8. \sum_a\pi_aP_{ab} = \sum_a\pi_bP_{ba} = \pi_b\sum_aP_{ba} = \pi_b. Gibbs update at p: for \mathbf s^+ \ne \mathbf s^- (differing at p), P_{\mathbf s^-\mathbf s^+} = \pi(\mathbf s^+)/(\pi(\mathbf s^+) + \pi(\mathbf s^-)), so \pi(\mathbf s^-)P_{\mathbf s^-\mathbf s^+} = \pi(\mathbf s^-)\pi(\mathbf s^+)/(\pi(\mathbf s^+) + \pi(\mathbf s^-)), which is symmetric in the two states. A sweep is a sequence of such updates, each leaving \boldsymbol\pi stationary.
B9. Rows sum to 1, so \mu_1 = 1 (right eigenvector (1, 1)). The trace is 0.632 + 0 = 0.632, so \mu_2 = 0.632 - 1 = -0.368. Writing the start as \boldsymbol\pi plus a multiple of the other eigenvector, each step multiplies that part by \mu_2 = -0.368: the deviation shrinks by 0.368 and changes sign each step. The closer |\mu_2| is to 1, the slower the chain mixes.
B10. T = 1: 1/(1 + e^2) = 0.119; T = 0.5: 1/(1 + e^4) = 0.018. A chain of n pixels therefore has about 0.018n walls at T = 0.5 and 0.119n at T = 1: domains of typical length 55 and 8. However low T is, a long enough chain contains walls, and the two signs occupy equal shares on average: m = 0 for an infinite chain. (Derivation: with the transfer matrix, \langle s_is_{i+1}\rangle = \mu_2/\mu_1 = \tanh(J/T), and the fraction of disagreeing pairs is (1 - \tanh(J/T))/2 = 1/(1 + e^{2J/T}).)
Explore: sampling the 3 \times 3 lattice
The demo of the previous unit, in sample mode. One step updates one randomly chosen site (circled; dashed if it did not change) by Gibbs or Metropolis. The red dots are the fraction of all steps so far spent in each energy level (or magnetisation), the bars the exact probabilities.
S1. Preset sample: converges (T = 3, Gibbs). Use 1 step a few times: which values does the readout’s “seen” take, and why is it so far from p? Then play at 100 and 1000 steps per frame. After about how many steps do the dots sit on the bars? Compare the dot and the bar of the lowest level after 1000 and after 100 000 steps.
S2. Preset sample: low T, stuck (T = 1, Metropolis, magnetisation tab). Play at 1000 steps per frame. What do the dots show after 100 000 steps? Is the chain wrong? Switch to the energy tab: does the energy histogram look right?
S3. In the same preset, set T = 2 and restart (choose Metropolis again). What changes, and why?
S1. After a few steps “seen” is 0 or a large fraction such as 0.5: the chain has visited only a handful of states. After 100 steps the dots are still far off (the lowest level has 0.19 against 0.377 exact); after 1000 steps 0.346, after 100 000 steps 0.385. Thousands of steps are needed for a few per cent of accuracy: the samples are correlated.
S2. All the mass sits at m = +1 and nearby; m = -1 never appears (the exact bars give both 0.498). The chain is correct but has not mixed: to reach the other ground state it would need to pass through states of much higher energy, starting with a flip of \Delta E = 8 (accepted with e^{-8} = 0.0003). The energy histogram nevertheless looks right (the two ground states have the same energy), which is why checking one statistic can hide a mixing problem.
S3. At T = 2 the chain switches sign every few hundred steps (a run started from all +1 switched 418 times in 100 000 steps), and both sides fill in. Uphill moves are far more likely (e^{-4} = 0.018 for \Delta E = 8).
Explore: a large lattice
A 256 \times 256 periodic lattice (choose 64^2 or 128^2 for speed), animated with Metropolis or Gibbs sweeps. Orange is +1, blue -1. The plots show the magnetisation m and the energy per spin E/n over the last 400 sweeps. Cool to 0.5 lowers T geometrically over the chosen number of sweeps; quench sets T = 0.5 at once. The T-scan tab runs its own 64 \times 64 lattice from T = 4 down to T = 1 and plots the average |m| against T with Onsager’s exact curve.
E1. Presets hot: noise, cold: domains coarsen and at T_c: all scales. Describe each lattice after a few hundred sweeps, and read m and E/n. Compare E/n at T_c with the exact -\sqrt2 = -1.414.
E2. In cold: domains coarsen, watch the domains. Do they all keep their size? What happens to E/n and why?
E3. Preset a small field decides (T = 1.8, h = 0.05). How quickly does m approach its final value? Set h = 0 and press random start: what happens now? Then try h = 0.05 at T = 4.
E4. Open the T-scan tab and run it. Where does \langle|m|\rangle follow Onsager’s curve, and where not? Why is it not 0 above T_c?
E5. Preset critical slowing down (128^2, T = 2.3, start all +1). How does m behave? Restart at T = 3 and at T = 2.5 (button all +1). Compare.
E6. Preset quench, then slow cooling (both 128^2). Compare the final states and their E/n. Which one is a local minimum, and why can it not escape at T = 0.5?
E1. Hot (T = 5): noise, m \approx 0, E/n \approx -0.42. Cold (T = 1.5): domains of each sign that grow; with this seed one sign takes over (m = 0.986 after 1000 sweeps, E/n = -1.95). At T_c: ragged clusters of every size, from single pixels to most of the lattice; m wanders near 0 and E/n is -1.40 after 1000 sweeps, close to -1.414 (the small difference is the finite lattice and the remaining relaxation).
E2. Small domains shrink and vanish, large ones grow (coarsening): a domain wall costs energy per unit length, so the lattice lowers its energy by shortening walls. The number of disagreeing pairs falls from 9740 after 10 sweeps to 3396 after 100 and 1618 after 1000, and E/n falls accordingly (from -1.70 to -1.95).
E3. With h = 0.05: m = 0.82 after 20 sweeps and 0.96 after 50; it stays there. With h = 0 the lattice coarsens without a winner for a long time (m = -0.21 after 400 sweeps). At T = 4 the same field only shifts m to about 0.05 (average over sweeps 100–400): above T_c there is no order for the field to choose.
E4. Below T_c the points lie on Onsager’s curve (e.g. T = 2.0: 0.912 against 0.911; T = 2.2: 0.782 against 0.785). Above T_c the exact value for an infinite lattice is 0, but the 64 \times 64 lattice gives 0.03–0.13: a finite lattice always has some net magnetisation by chance (about 1/\sqrt{\text{cluster count}}), largest close to T_c where clusters are big (0.36 at T = 2.3).
E5. At T = 2.3, m falls from 1 to about 0.5 within 100 sweeps and then lingers there for hundreds of sweeps, although its long-run value is near 0: it reaches |m| < 0.1 only after 1580 sweeps. At T = 3 it takes 6 sweeps, at T = 2.5 29. Near T_c the large clusters must be taken apart pixel by pixel.
E6. Quench: domains form and coarsen, but with this seed the lattice ends in two stripes across the whole torus (m \approx 0.1, E/n \approx -1.966) and stays there. Slow cooling (from 3.5 to 0.5 over 300 sweeps): one domain, m = -1 (a ground state, apart from rare thermal flips). The stripes are a local minimum: their straight walls can only move by flips that raise the energy by 4 first (accepted with e^{-8} = 0.0003 at T = 0.5), so they effectively never do. With other seeds a quench may also reach one domain, and slow cooling may also end in stripes; slower cooling makes stripes rarer.
Code
Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in ising/src/mcmc/exercise.rs. The lattice is an image of spins \pm 1 and is periodic: the right neighbour of the last column is the first column, and likewise for rows.
C1. local_field(s, x, y, J, h): the neighbours’ vote u = J \cdot (\text{sum of the 4
neighbouring spins}) + h, with wrap-around at the edges. The check is B1.
C2. gibbs_sweep(s, J, h, T, rng): one sweep of the Gibbs sampler, changing s in place:
for every pixel (x, y), row by row:
u = local field at (x, y)
p = 1 / (1 + e^(−2u/T))
s(x, y) = +1 if random() < p, else −1
C3. metropolis_sweep(s, J, h, T, rng): one sweep of Metropolis; returns the number of accepted flips:
for every pixel (x, y), row by row:
ΔE = 2 · s(x, y) · (local field at (x, y))
if ΔE ≤ 0 or random() < e^(−ΔE/T):
s(x, y) = −s(x, y)
C4. energy_and_magnetisation(s, J, h): the energy per spin E/n (each pair of neighbours once: pair every pixel with its right neighbour and the one below, with wrap-around) and the magnetisation m.
The checks for C2 and C3 run each sampler for 40 000 sweeps on the 3 \times 3 torus at T = 3, and compare the fraction of sweeps spent at each energy level with the exact probabilities of the Ising unit (E2). A second check is B2(b): a lone -1 among +1 neighbours flips back even at T = 0.01, and nothing else flips.
C5. anneal(s, J, T0, T1, sweeps, rng): simulated annealing with a geometric schedule; returns the temperatures used:
r = (T1 / T0)^(1 / (sweeps − 1))
T = T0
repeat sweeps times:
one Metropolis sweep at temperature T
T = T · r
The check is B6(a): from 4 to 0.5 in 100 steps, r = 0.979.
Then cargo run -p ising -- mcmc and open the pictures in out/mcmc/. The program draws samples of a 128 \times 128 lattice at three temperatures, scans the temperature on 64 \times 64, measures critical slowing down, and compares a quench with slow cooling for 8 random starts.
C6. Compare sample-cold.png, sample-critical.png and sample-hot.png with the printed E/n and m. Which picture has clusters of every size? The program also prints how often a pixel changes per sweep with Gibbs and with Metropolis at T = 2: which changes more often, and does that agree with B3?
C7. Read the T-scan. Where does \langle|m|\rangle agree with Onsager’s curve, and where not? The scan starts every temperature from all +1: what could go wrong at low T if it started from random spins instead? (Look at quench.png.)
C8. How many sweeps does it take from all +1 until |m| < 0.1 at T = 4, 3, 2.5, 2.3? How many of the 8 quenches, and how many of the 8 slow coolings, end in one domain?
The model solution is ising/src/mcmc/solution.rs in the download.
C6. Cold (T = 1.5): one sign has taken over, with scattered single flipped spins (E/n = -1.950, m = -0.986). Critical (T = 2.27): clusters of every size, from single pixels to blobs tens of pixels across (E/n = -1.399, close to -\sqrt2; m = 0.51 after 300 sweeps, still wandering). Hot (T = 5): fine-grained noise (E/n = -0.422, m = 0.01). Per sweep, Gibbs changed 10.4 % of the pixels and Metropolis 11.3 %: Metropolis changes more often, as in B3(c), and both sample the same distribution.
C7. Below T_c the averages lie on Onsager’s curve (0.980 at T = 1.6, 0.912 against 0.911 at T = 2, 0.778 against 0.785 at T = 2.2). Above T_c they are small but not 0 (0.12 at T = 2.4, 0.04 at T = 3.2): a finite lattice always has some net magnetisation by chance, most near T_c. From random spins, a cold lattice can freeze into stripes that span the torus (as in quench.png), with |m| far below the equilibrium value for hundreds of sweeps: the scan would show dips that have nothing to do with the model.
C8. 2, 6, 31 and 3416 sweeps: near T_c the large clusters must be taken apart one pixel at a time (critical slowing down). Only 2 of the 8 quenches end in one domain; the other 6 stay in stripes (E/n \approx -1.90); all 8 slow coolings end in one domain (E/n = -2).
Where this leads
So far the field h was the same for every pixel. In the next unit the field comes from a noisy image: the Ising model becomes a prior for the clean image, and sampling, annealing and the exact minimum cut become tools for Bayesian denoising. Much later, the sampler of a diffusion model adds the same kind of random-walk correction steps (Langevin steps, sampling from diffusion models, day 45).