A swarm of 500 weighted particles walks down a ladder of 50 easier targets. It lands on both peaks of a two-peak target, about half on each, and it measures the target's area on the way.
Press Run with the swarm, then switch to One chain and run again. Count how much of each histogram sits on the left peak. Then we build the machine piece by piece: weights, resampling, the ladder, moves and the area.
You need a probability density and a little Python. Importance sampling and MCMC help. We rebuild what we use.
Part of the Monte Carlo family (hub). For tracking a moving state over time, see the particle filter lesson. This lesson uses the same engine to sample one fixed target.
Illustrative toy: target with equal peaks at −5 and +5, base N(0, 9), three Metropolis steps per particle per rung. Both samplers get the same 75,000 moves. Each run uses a new seed, so the chain sometimes crosses; run it a few times.
Chapter 0
See plain sampling miss a one in thirty thousand event, and see a swarm reach it in three easy stages
You need the chance that a standard normal draw lands above 4. The true value is 0.0000317, about 1 in 31,600. You draw 10,000 samples and count the ones above 4.
You expect 10,000 × 0.0000317 = 0.32 hits. So 73% of the time you see zero hits, and your estimate is exactly 0. A stable answer needs about 3 million draws. Each step further into the tail costs ten times more.
Now split the climb. First ask what share of draws pass 2. Then, among those, what share pass 3. Then what share of those pass 4. Each share is a few percent, so a swarm of 1,000 particles sees dozens of hits at every stage.
The curve is the normal density. Press Run. In plain mode, count the dots past 4. In staged mode, the swarm keeps the dots past each bar, clones them, moves them, and climbs.
1,000 particles per stage. After each cut the swarm clones the survivors and runs ten Metropolis steps that stay above the bar. Each run uses a new seed.
The three true shares are 0.02275, 0.05934 and 0.02346. Their product is 0.0000317, the tail itself, because a chain of conditional chances multiplies to the joint chance. Over 200 seeded runs of this swarm, the mean estimate was 0.0000318, with a spread of 37% of the true value. Plain sampling with the same budget is wrong by 100% most of the time.
That is the idea of Sequential Monte Carlo (SMC): reach a hard distribution through a sequence of easy ones, with a swarm of weighted particles (sample points that each carry a weight). This staged tail hunt is called multilevel splitting. The rest of the lesson builds the general sampler.
Symptom: a rare-event estimate of exactly 0, or one that jumps by orders of magnitude between seeds. Measure: count the hits; under 10 hits, the estimate is noise. Fix: stage the event, so each stage has a share of a few percent.
Chapter 1
Give each particle a weight, then measure how many particles the swarm is worth
You cannot sample the target, but you can sample an easy proposal q. So you draw from q and give each draw x an importance weight w = target(x) / q(x). The importance sampling lesson derives this. With target N(0, 1) and proposal N(3, 1), a draw at x = 2 gets w = 0.0540 / 0.2420 = 0.223.
One weight alone means nothing. Only its share of the total counts: the normalized weight Wi = wi / (sum of all w). Multiply every weight by 1,000 and every share stays the same.
Now apply weights again and again. Four particles start with shares 0.25 each. One observation multiplies them by 2, 0.1, 0.05 and 0.01. The new shares are 0.926, 0.046, 0.023 and 0.005. One particle now carries almost everything. This is weight degeneracy.
Each bar is one particle's share. Press Observe to multiply in a new random factor. Raise the sharpness and watch the ESS meter fall.
Illustrative: each factor is exp(sharpness × z) with z a standard normal draw, a stand-in for a likelihood.
How many equal particles is a weighted swarm worth? Call each particle's share Wi, for particles i = 1 to N. Call the answer the ESS.
ESS equals one over the sum over i of W-i squared.
Square each share W-i. Add the squares. One over that sum is the ESS.
Four shares of 0.25: the squares add to 0.25, so ESS = 4. After the observation, shares 0.926, 0.046, 0.023, 0.005: the squares add to 0.860, so ESS = 1.16. Four particles now do the work of about one.
Symptom: an estimate that jumps from seed to seed although N is large. Measure: print the ESS after every update. Fix: when ESS falls under N/2, resample (Chapter 2).
Chapter 2
Replace a lopsided swarm with an equal-weight one, and choose the lottery that adds the least noise
A swarm with ESS near 1 spends its work on particles that count for nothing. Resampling fixes that. Draw N new particles from the old ones, each with chance equal to its share Wi. Heavy particles get several copies, light ones get none. Then set every weight to 1/N.
Picture the shares laid end to end on a ruler from 0 to 1. Each particle owns a segment as long as its share. Drop N pointers on the ruler. The particle under each pointer gets one child.
| Scheme | Pointers | Children of particle i |
|---|---|---|
| Multinomial | N independent random points | any count; a heavy particle can get none |
| Systematic | one random offset u0, then steps of 1/N | always N·Wi rounded down or up |
Top: the shares. Middle: the ruler with pointers. Bottom: children per particle, with the expected count N·W as an outline. Press Throw several times in each scheme.
Eight illustrative particles. Both schemes give each particle N·Wi children on average.
Take shares W = (0.1, 0.6, 0.2, 0.1). The ruler boundaries are 0.1, 0.7, 0.9 and 1.0. Systematic with u0 = 0.1 puts pointers at (0.1 + k)/4 for k = 0 to 3:
The children are (1, 2, 1, 0). The expected counts were (0.4, 2.4, 0.8, 0.4), and each count is one of the two whole numbers next to it. Multinomial with points 0.05, 0.30, 0.50 and 0.95 gives (1, 2, 0, 1): particle 2, share 0.2, got nothing by bad luck.
Resampling adds noise on the spot, because clones replace distinct particles. So resample only when ESS drops under a threshold, usually N/2, and prefer the systematic scheme. In code it is one searchsorted into the running sum of the shares.
Symptom: the swarm turns into a few distinct points. Measure: count unique particle positions after each step. Fix: resample only below the ESS threshold, and follow every resample with a move (Chapter 5).
Chapter 3
Bend an easy distribution into the hard target in small steps, so no step is a cliff
The hard target is a sharp posterior. A broad Gaussian is easy to sample. One importance jump from broad to sharp gives a collapsed ESS. So build a ladder of in-between targets, each close to the one before.
Call the easy start the base p0 and the hard target pT. Call the rung position β (beta), the inverse temperature, from 0 at the base to 1 at the target. Call the rung's distribution the bridge πβ.
pi-beta of x is proportional to p-zero of x to the power one minus beta, times p-T of x to the power beta.
Pick beta. Raise the base p-zero to the power one minus beta and the target p-T to the power beta. Multiply. At beta 0 you have the base; at beta 1 you have the target.
For two zero-mean Gaussians, the precisions (one over the variance) blend: 1/9 and 1. At beta 0.5 the precision is 0.5/9 + 0.5 = 0.556. The variance is 1.8 and the spread is 1.34, not the average variance of 5.
Blue is the base, yellow the target, purple the bridge at this rung. Drag beta. Then switch to two peaks and watch one blob split.
Base N(0, 9). One-peak target N(0, 1); two-peak target with equal peaks at ±3. The page normalizes each curve to area 1.
The spread at beta 0, 0.25, 0.5, 0.75 and 1 is 3.00, 1.73, 1.34, 1.13 and 1.00. It falls fast early and slowly late. The geometric path is a product, not a mixture: a 50/50 mixture of the two Gaussians would keep a broad shoulder and never narrow into the target.
Symptom: ESS collapses at one rung. Measure: plot ESS against beta. Fix: add rungs where ESS drops, or choose each next beta so that ESS lands at a set fraction, such as N/2. That rule is adaptive tempering.
Chapter 4
Reweight each particle as the ladder moves up one rung, with one multiply and one exponential
The swarm stands on rung beta-t-minus-one. The ladder moves to rung beta-t. Each particle fits the old bridge, so it needs a correction weight for the new one: new bridge over old bridge, at the particle's spot. This is the incremental weight.
Write both bridges in logs. Each is (1 − β) log p0 + β log pT. Subtract, and only the change in beta survives. Call the change Δβ = βt − βt−1 and the incremental weight winc.
log w-inc equals delta beta times, log p-T of x minus log p-zero of x.
At the particle's position x, take the gap: log p-T minus log p-zero. Multiply the gap by delta beta. Exponentiate to get w-inc.
Base kernel exp(−x²/18), target kernel exp(−x²/2). Take x = 1.5 and delta beta = 0.25. Then log p-zero = −0.125, log p-T = −1.125, so the gap is −1.0. log w-inc = 0.25 × −1.0 = −0.25, and w-inc = 0.779.
Blue is log p-zero, yellow is log p-T. Drag the particle and the rung step. The pink bar is the incremental weight; the line at 1 means no change.
Kernels of N(0, 9) and N(0, 1), as in the worked example.
Halve the rung step and every log weight halves. So a finer ladder keeps each factor near 1, and the ESS falls slowly per rung. That is the knob that fights degeneracy without touching any particle.
The weight uses the particle's position before the move of Chapter 5. Reweight first, then move.
Symptom: ESS drops to a handful in one rung. Measure: print the spread of the log incremental weights; a spread above about 1 is too big. Fix: a smaller rung step there.
Chapter 5
Spread the clones with a Metropolis step that targets the current rung, and let warm rungs cross barriers
After resampling, the heavy particle has three copies on the same spot. Three copies explore no better than one. So after each rung, every particle takes a few Metropolis steps aimed at the current bridge. The copies drift apart.
Write the target as an energy U: pT(x) ∝ exp(−U(x)), so low energy means high density. With a flat base, the bridge is exp(−βU). A proposed move from x to x′ changes the energy by ΔU. Call the chance of accepting it a.
a equals the minimum of one and e to the minus beta times delta U.
Find the energy change delta U. Multiply by beta. If the result is downhill, accept. If uphill, accept with chance e to the minus beta times delta U.
Double well U(x) = (x² − 4)²/4: valleys at ±2, a hill of height 4 at 0. A jump from x = 2 to the top has delta U = 4. At beta 1, a = e−4 = 0.018. At beta 0.25, a = e−1 = 0.368, twenty times more likely.
Grey is the true energy. Purple is what the particle feels at this rung, beta times U. Press Run 2,000 steps at a low beta, then at beta 1.
Illustrative: Gaussian proposal with step 0.4 on a flat base. A crossing is a move from one valley side (|x| above 1) to the other.
The move targets the bridge it stands on, so it leaves that bridge unchanged. That is why the move adds nothing to the weight. Reweight anneals; the move explores. Mixing the two counts the same correction twice and breaks the area estimate of Chapter 6.
Symptom: many identical particles at the end. Measure: the move acceptance rate per rung. Fix: shrink the step if acceptance is under about 20%; grow it above about 60%, or add steps.
Chapter 6
Multiply the average incremental weight of each rung, and read off the area under the target
Your target is known only up to a constant: f(x), with area Z = ∫ f(x) dx. In Bayesian work, Z is the evidence, the chance of the data under a model. A Metropolis chain cannot give it. Its acceptance rule uses f(x′) / f(x), and Z cancels in that ratio.
SMC keeps Z. At each rung, the weighted average of the incremental weights estimates how much the area changed. Multiply those averages and you get the area ratio. Call the known area of the base Z0 and the estimated area of the target ẐT.
Z-T-hat over Z-zero equals the product over t of the sum over i of W-i times w-t-i.
At each rung t, average the incremental weights w-t-i, weighted by the shares W-i. Multiply these averages over all rungs. Multiply by Z-zero to get the target's area.
Base kernel exp(−x²/18) has area √(18π) = 7.52. Target kernel exp(−x²/2) has area √(2π) = 2.51. The true ratio is 1/3. Twenty seeded runs with 1,000 particles and 20 rungs gave a mean of 0.334 and a spread of 0.006. Then 0.334 × 7.52 = 2.51.
Orange is the running product, rung by rung. Yellow is the true ratio, 1/3. Press Run a few times at each rung count; each run leaves a dot at the right.
1,000 particles, base N(0, 9), target N(0, 1), resample below ESS N/2, three Metropolis steps per rung. Each run uses a new seed.
The rung averages telescope: each new bridge's area cancels the old one's, so only ZT/Z0 is left. The product itself is unbiased for the ratio, even with resampling. That is the result of SMC samplers (Del Moral, Doucet and Jasra, 2006).
Symptom: an area off by a large factor with healthy-looking particles. Measure: check the weights used in the average are the shares from before the rung. Fix: average with those shares. An older version of this page averaged plain incremental weights over particles left at the base, and its code returned 0.020, not 0.333.
Chapter 7
Run each particle up the ladder alone, then pool the weights in the right space
Remove resampling from SMC and each particle becomes a lone climber. It starts in the base, moves at every rung, and adds each rung's log incremental weight to its total. This is annealed importance sampling (AIS), from Radford Neal (2001). The climbers never interact, so they run in parallel.
Each climber ends with one log weight log wi. Pool N climbers into the estimate of log(ZT/Z0) by averaging the weights themselves, not their logs.
log of Z-T-hat over Z-zero equals the log of one over N times the sum over i of w-i.
Exponentiate each climber's log weight to get w-i. Average the w-i. Take the log. In code this is logsumexp of the log weights minus log N, which never overflows.
Four climbers with log weights −0.5, −0.3, −0.8, −0.4. The weights are 0.607, 0.741, 0.449 and 0.670. They add to 2.467; divided by 4 that is 0.617, and its log is −0.483. The mean of the logs is −0.500, which is lower.
Each teal line is one climber's running log weight. At the right: orange is log of the mean weight, red is the mean of the logs, yellow is the truth, log(1/3). Try 3 rungs, then 50.
Base N(0, 9), target N(0, 1), three Metropolis steps per rung, no resampling. Each climb uses a new seed.
Why is the mean of the logs low? The log bends down, so the average of logs is never above the log of the average. This is Jensen's inequality. In 200 seeded runs with 100 climbers and 3 rungs, the mean of logs averaged −2.64, the log of the mean −1.11, and the truth is −1.10.
The average weight is unbiased for the area ratio. Its log is a little low too, by an amount that shrinks as N grows. An older version of this page called the log of the average unbiased; it is not.
Symptom: a model's log likelihood looks far worse than a rival's. Measure: check whether the code averages log weights. Fix: use logsumexp minus log N, and add rungs until the ESS of the final weights is healthy.
Chapter 8
Run the full sampler on two far-apart peaks and set every knob yourself
The target has two equal peaks with a deep valley between them. A Metropolis chain started on the right peak samples that peak well. To reach the left peak it must climb the valley one small step at a time, and that run of uphill steps is rare.
The full SMC sampler starts warm, where the base N(0, 9) covers both peaks. It cools rung by rung. At each rung it does three things, in this order:
The particles split between the peaks while the valley is still shallow. When the valley deepens, each one is already on a side.
Top: the swarm (teal) under the current bridge (purple), with the target in yellow. Bottom: one chain with the same number of moves. Widen the gap and run again.
Illustrative toy. Target: equal Gaussian peaks of spread 1 at ±gap. Its area over the base kernel's area is exactly 2/3 for every gap. Move step 0.6.
Our seeded checks match what you see. At gap 5, with 500 particles and 50 rungs, 20 runs put 51% of the swarm on the left peak (spread 3%), with an area ratio of 0.66 against the true 0.667. Four of five seeded chains of 75,000 steps never left the right peak. The fifth spent 78% of its time on the left. The chain's answer depends on luck; the swarm's does not.
The bridge mass between the peaks explains it. Above x = 2, the base N(0, 9) holds 25% of its mass. The target's spread-1 peak at 0 would hold 2.3% there. Warm rungs have eleven times more mass in the gap, so particles cross while it is cheap.
Chapter 9
Walk each model's ladder from its prior up to its posterior, read off its evidence, and compare the two
Five sensor readings arrive: 1.2, 0.4, 1.9, 0.8 and 1.6. Each is the true offset μ plus noise of spread 1. Model A says μ is near 0, with prior spread 1. Model B says μ could be anything, with prior spread 10. Which model do the data prefer?
Use the prior as the base and prior times likelihood as the target. The bridge is then the prior times the likelihood raised to beta:
πβ(μ) ∝ prior(μ) · L(μ)β, so log winc = Δβ · log L(μ)
Here L(μ) is the likelihood: the chance of the five readings if the offset is μ. The prior has area 1, so the swarm's area estimate is the evidence Z itself. Call the two evidences ZA and ZB, and their ratio the Bayes factor BF.
log B-F equals log Z-A minus log Z-B.
Run SMC once per model to get log Z-A and log Z-B. Subtract. Exponentiate to get BF, the odds that the data give model A over model B.
The exact values for this toy are log Z-A = −6.795 and log Z-B = −8.434. So log BF = 1.639 and BF = 5.15: the readings favour A at about 5 to 1.
Blue is the chosen model's prior, yellow its posterior, teal the swarm. The rows below compare each estimate (orange dot) with the exact log evidence (yellow tick). Drop the rungs to 1, then raise them.
Illustrative data. 500 particles per model, resample below ESS N/2, three Metropolis steps per rung. Exact evidence from the Gaussian marginal of the five readings.
Why does the broad model lose, when both posteriors sit near 1.0? Model B spreads its prior over a range about 20 wide. Most of that range predicts the readings badly, and the evidence averages over all of it. This built-in penalty for vague models is often called the Occam factor.
Model B is also harder to score. Its posterior is about 22 times narrower than its prior, so a coarse ladder collapses: with one rung, its smallest ESS averaged 31 of 500 in our seeded runs. Model A's averaged 162.
Symptom: the Bayes factor changes sign between runs. Measure: repeat each evidence run with five seeds and report the spread of log Z. Fix: more rungs or particles for the model whose posterior is much narrower than its prior.
Chapter 10
Keep the terms, the numbers, the checklist and the core loop in one place
An SMC sampler walks a weighted swarm from an easy base to a hard target along a ladder of bridges. At each rung it reweights, resamples when ESS falls, and moves. The product of rung averages gives the target's area.
| Term | What it is | This page's number |
|---|---|---|
| ESS | 1 / sum of squared shares | 4 shares of 0.25 → 4; after one observation → 1.16 |
| Systematic resampling | one offset, pointers 1/N apart | W = (0.1, 0.6, 0.2, 0.1) → children (1, 2, 1, 0) |
| Bridge | p01−β pTβ | variance 1.8 at beta 0.5, not 5 |
| Incremental weight | exp(Δβ × log gap) | x = 1.5, Δβ = 0.25 → 0.779 |
| Tempered acceptance | min(1, e−βΔU) | hill of 4: 0.018 at beta 1, 0.368 at beta 0.25 |
| Area ratio | product of weighted rung averages | 0.334 ± 0.006 against 1/3 |
| AIS pooling | logsumexp(log w) − log N | −0.483, not the mean of logs −0.500 |
| Bayes factor | ZA / ZB | 5.15 for the five readings |
| Method | Sequence of distributions | Gives Z? |
|---|---|---|
| Importance sampling | none: one proposal | yes, with one jump; collapses when proposal and target differ |
| MCMC | none: one fixed target | no |
| Particle filter | state posteriors over time, set by the data | yes, the data likelihood |
| SMC sampler | a ladder you choose, ending at one fixed target | yes |
| AIS | the same ladder, no resampling | yes |
The bootstrap particle filter of Gordon, Salmond and Smith (1993) runs this engine forward in time to track a hidden state. The particle filter lesson and the Monte Carlo localization lesson cover that job. Pierre Del Moral's book Feynman-Kac Formulae (2004) gives the theory behind both.
pythonimport numpy as np from scipy.special import logsumexp def smc_sampler(logp0, logpT, sample0, N=500, T=50, step=0.6, seed=0): rng = np.random.default_rng(seed) betas = np.linspace(0, 1, T + 1) lp = lambda b, x: (1 - b) * logp0(x) + b * logpT(x) # log bridge x = sample0(rng, N) # shape (N,) logw, logZ = np.zeros(N), 0.0 # logZ = log(Z_T / Z_0) for t in range(1, T + 1): b = betas[t] inc = lp(b, x) - lp(betas[t - 1], x) # 1. reweight logW = logw - logsumexp(logw) # shares before the rung logZ += logsumexp(logW + inc) # weighted rung average logw += inc W = np.exp(logw - logsumexp(logw)) if 1 / np.sum(W**2) < N / 2: # 2. resample on low ESS u = (rng.random() + np.arange(N)) / N idx = np.minimum(np.searchsorted(np.cumsum(W), u), N - 1) x, logw = x[idx], np.zeros(N) for _ in range(3): # 3. move, targets the bridge xp = x + step * rng.standard_normal(N) ok = np.log(rng.random(N)) < lp(b, xp) - lp(b, x) x = np.where(ok, xp, x) return x, np.exp(logw - logsumexp(logw)), logZ # the hero: equal peaks at +-5, base N(0, 9); area ratio is 2/3 logp0 = lambda x: -x**2 / 18 logpT = lambda x: np.logaddexp(-(x - 5)**2 / 2, -(x + 5)**2 / 2) x, W, logZ = smc_sampler(logp0, logpT, lambda r, n: r.normal(0, 3, n)) print(np.sum(W * (x < 0)), np.exp(logZ)) # about 0.5 and about 0.667
Libraries ship this loop: PyMC's pm.sample_smc, BlackJAX's tempered SMC, and Nicolas Chopin's particles package.
Now press Present or Teach and explain from memory: ESS, the systematic lottery, the bridge, the incremental weight, why moves leave weights alone, and how the rung averages give Z. Then go back to the hero and run the chain three times. Say why its answer changes and the swarm's does not.