Sequential Monte Carlo

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.

Find both peaks

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

Why One Leap Cannot Reach a Rare Event

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.

Reach the tail in stages

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.

The failure

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.

The road

  1. Weights and ESS: what a swarm of weighted particles is worth.
  2. Resampling: clone heavy particles, drop light ones.
  3. The ladder: a path of easier targets from base to target.
  4. The incremental weight: what one rung costs each particle.
  5. Moves: spread the clones without changing the weights.
  6. The evidence: the area under the target, which MCMC cannot give.
  7. AIS: SMC without resampling, and the averaging trap.
  8. Cross the valley: the full sampler on two peaks, the hero's engine.
  9. The Bayes factor: score two models by their evidence.
  10. Field guide: terms, numbers, checklist, code.
You estimate a tail chance of 0.0000317 with 10,000 plain samples. Why is the answer usually exactly 0?

Chapter 1

Weighted Particles and the Effective Sample Size

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.

Watch one particle take over

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.

1.0

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.

Say it aloud

ESS equals one over the sum over i of W-i squared.

ESS
E S S the effective sample size: how many equal-weight particles the swarm is worth, from 1 to N.
Σi
the sum over i add one term for each of the N particles.
Wi
W-i the share of particle i. All shares add to 1.
2
squared multiply the share by itself, so big shares count much more.
In plain words

Square each share W-i. Add the squares. One over that sum is the ESS.

With numbers

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.

The failure

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).

1,000 particles have ESS = 3. What does that mean?

Chapter 2

Resampling: Clone the Heavy, Drop the Light

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.

SchemePointersChildren of particle i
MultinomialN independent random pointsany count; a heavy particle can get none
Systematicone random offset u0, then steps of 1/Nalways N·Wi rounded down or up

Run the lottery

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.

A worked lottery

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:

  1. 0.025 lands in segment 0.
  2. 0.275 and 0.525 land in segment 1, the heavy particle.
  3. 0.775 lands in segment 2.

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.

The failure

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).

Why do most SMC codes use systematic resampling?

Chapter 3

The Tempering Ladder

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 πβ.

Say it aloud

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.

πβ(x)
pi-beta of x the bridge at rung beta, evaluated at position x.
∝
is proportional to equal up to a constant factor. The sampler never needs that factor.
p0(x)
p-zero of x the base density, here N(0, 9): easy to sample.
pT(x)
p-T of x the target density, here N(0, 1). We can evaluate it up to a constant, not sample it.
β
beta the inverse temperature, from 0 to 1.
In plain words

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.

With numbers

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.

Slide up the ladder

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.

0.50

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.

The failure

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.

Base N(0, 9), target N(0, 1), geometric bridge at beta 0.5. What is the bridge variance?

Chapter 4

The Incremental Weight: What One Rung Costs

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.

Say it aloud

log w-inc equals delta beta times, log p-T of x minus log p-zero of x.

log winc
log w-inc the log of the factor that multiplies this particle's weight at this rung.
Δβ
delta beta the rung step, beta-t minus beta-t-minus-one, for example 0.25.
log pT(x)
log p-T of x how much the target likes position x, in logs, up to a constant.
log p0(x)
log p-zero of x how much the base likes x, in logs, up to a constant.
In plain words

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.

With numbers

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.

Price one rung

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.

1.50
0.25

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.

The failure

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.

You double the number of rungs on an evenly spaced ladder. What happens to each particle's log incremental weight?

Chapter 5

Moves Between Rungs

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.

Say it aloud

a equals the minimum of one and e to the minus beta times delta U.

a
a the chance of accepting the proposed move, from 0 to 1.
min
the minimum of the smaller of the two values, so a downhill move is always accepted.
β
beta the current rung. Small beta flattens the landscape.
ΔU
delta U energy at the proposal minus energy now. Positive means uphill.
In plain words

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.

With numbers

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.

Cross the hill when it is warm

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.

0.25

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.

The failure

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.

Why does the same uphill move pass more often at beta 0.25 than at beta 1?

Chapter 6

The Normalizing Constant MCMC Cannot Give

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.

Say it aloud

Z-T-hat over Z-zero equals the product over t of the sum over i of W-i times w-t-i.

ẐT
Z-T-hat the estimate of the target's area. The hat means estimate.
Z0
Z-zero the base's area, known exactly: we chose the base for that.
Πt
the product over t multiply one factor per rung, t = 1 to T.
Σi
the sum over i add over the N particles.
Wi
W-i particle i's share just before rung t. After a resample every share is 1/N.
wt,i
w-t-i particle i's incremental weight at rung t, from Chapter 4.
In plain words

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.

With numbers

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.

Measure the area

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.

20

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).

The failure

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.

Why can a Metropolis chain sample a posterior well but never estimate its normalizing constant?

Chapter 7

Annealed Importance Sampling and the Averaging Trap

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.

Say it aloud

log of Z-T-hat over Z-zero equals the log of one over N times the sum over i of w-i.

log(ẐT/Z0)
log of Z-T-hat over Z-zero the estimated log area ratio.
1/N
one over N divide by the number of climbers, N.
Σi
the sum over i add over climbers.
wi
w-i climber i's final weight: e to its summed log incremental weights.
In plain words

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.

With numbers

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.

Pool the climbers two ways

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.

5
24

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.

The failure

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.

AIS climbers end with log weights −0.5, −0.3, −0.8 and −0.4. Which pooled value is right?

Chapter 8

Cross the Valley

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:

  1. Reweight every particle by its incremental weight (Chapter 4), and update the area estimate (Chapter 6).
  2. Resample if ESS is under the threshold (Chapter 2).
  3. Move each particle with three Metropolis steps on the current bridge (Chapter 5).

The particles split between the peaks while the valley is still shallow. When the valley deepens, each one is already on a side.

Race the swarm and the chain

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.

±5.0
50
500
0.50 N

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

Score Two Models With Their Evidence

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.

Say it aloud

log B-F equals log Z-A minus log Z-B.

log BF
log B-F the log Bayes factor. Positive favours model A.
log ZA
log Z-A the log evidence of model A: how likely the five readings are under A, averaged over its prior.
log ZB
log Z-B the same for model B.
In plain words

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.

With numbers

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.

Score both models

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.

10

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.

The failure

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.

log Z-A = −6.795 and log Z-B = −8.434. What is the Bayes factor for A over B?

Chapter 10

Field Guide

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.

Terms and numbers

TermWhat it isThis page's number
ESS1 / sum of squared shares4 shares of 0.25 → 4; after one observation → 1.16
Systematic resamplingone offset, pointers 1/N apartW = (0.1, 0.6, 0.2, 0.1) → children (1, 2, 1, 0)
Bridgep01−β pTβvariance 1.8 at beta 0.5, not 5
Incremental weightexp(Δβ × log gap)x = 1.5, Δβ = 0.25 → 0.779
Tempered acceptancemin(1, e−βΔU)hill of 4: 0.018 at beta 1, 0.368 at beta 0.25
Area ratioproduct of weighted rung averages0.334 ± 0.006 against 1/3
AIS poolinglogsumexp(log w) − log N−0.483, not the mean of logs −0.500
Bayes factorZA / ZB5.15 for the five readings

Same engine, other jobs

MethodSequence of distributionsGives Z?
Importance samplingnone: one proposalyes, with one jump; collapses when proposal and target differ
MCMCnone: one fixed targetno
Particle filterstate posteriors over time, set by the datayes, the data likelihood
SMC samplera ladder you choose, ending at one fixed targetyes
AISthe same ladder, no resamplingyes

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.

Checklist

The core loop

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.

Keep going

The one idea: a hard distribution becomes a chain of easy ones. Keep the weights honest at every rung and the swarm hands you both samples and the area.

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.

Sequential Monte Carlo: A Weighted Swarm Up a Tempering Ladder
The Monte Carlo family · Del Moral, Doucet and Jasra (2006) · Neal, Annealed Importance Sampling · Back to Gleams