SStatistics, Built

Stage III · Master's

Part 27 of 65

Bayesian Computation

Master'sstarts at this level53 min of film15 chaptersprerequisites: Part 7, Part 26

How do you compute an integral you cannot do, in a hundred dimensions?

Los Alamos, 1953: Metropolis, the Rosenbluths and the Tellers move forty hard disks at random, reject the moves that overlap, and the lattice melts. The part builds the samplers that grew from that walk. Importance sampling reweights draws and fails quietly when the proposal's tails are too light; Metropolis-Hastings and Gibbs are exact in the limit but crawl, the Gibbs zigzag at correlation 0.95 earning 33 effective draws from 2,000 sweeps. Hamiltonian Monte Carlo sends a puck across the surface of minus the log posterior by leapfrog steps, and NUTS chooses the path length itself. The turn is Neal's funnel: the centred sampler never enters the neck, on the eight schools it reports 47 divergences, and writing each effect as mu plus tau times a standard normal fixes it. The samplers are assembled into statkit.ppl, a small probabilistic programming language on AI, Built's autodiff, checked against closed forms. The part ends with the approximations and what each gives up: particle filters and tempering, variational inference, Laplace and INLA, ABC, and coupling from the past, which is exact.

What you need. Part 7's Markov chains (stationary laws, detailed balance) and Part 26's posteriors; gradients and a little classical mechanics for the Hamiltonian chapters.

Hook
Los Alamos, 1953
Mathematics
importance sampling, MH, Gibbs, HMC, NUTS, diagnostics, SMC, VI, ABC, SBC
Built
a tiny probabilistic programming language

What you will be able to do

Bachelor's

  • Explain why accepting uphill moves always and downhill moves sometimes makes a random walk visit each region in proportion to its probability.
  • Read a trace plot and an acceptance rate, and say what a step that is too small or too large does to both.

Master's

  • Prove detailed balance for Metropolis-Hastings and show that a leapfrog step preserves volume and is reversible.
  • Derive the effective sample size of Gibbs sampling on a correlated normal, and the ELBO identity.
  • Implement random-walk Metropolis and HMC for a log density, with the Jacobian of a log transform.

PhD

  • State the assumptions behind the 0.234 and 0.574 acceptance guidelines and why they are not universal.
  • Explain why coupling from the past returns an exact draw and why monotonicity is needed to run it.

Practice

  • Diagnose a fit from rank-normalized split R-hat, bulk and tail ESS and divergences, knowing that they detect failures and prove nothing.
  • Recognise a funnel in a hierarchical model and remove it by a non-centred parametrization.
  • Check an importance-sampling or variational approximation with the Pareto k-hat diagnostic.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 10 min · Master's 49 min · PhD 53 min · Practice 20 min.

  1. 0Hard disks, 1953Bachelor's3 min
  2. 1Importance samplingMaster's4 min
  3. 2Metropolis-HastingsBachelor's4 min
  4. 3Gibbs samplingMaster's3 min
  5. 4DiagnosticsPractice3 min
  6. 5Hamiltonian Monte CarloMaster's4 min
  7. 6NUTSMaster's3 min
  8. 7Neal's funnel and the eight schoolsPractice4 min
  9. 8Built: a probabilistic programming languagePractice4 min
  10. 9Sequential Monte CarloMaster's4 min
  11. 10Variational inferenceMaster's4 min
  12. 11Laplace and INLAMaster's3 min
  13. 12Likelihood-free inferenceMaster's4 min
  14. 13Exact samplingPhD4 min
  15. Recap, problems, and the road aheadAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

Hard disks, 1953Bachelor's3 min

In 1953, at Los Alamos, Nicholas Metropolis, Arianna and Marshall Rosenbluth, and Augusta and Edward Teller wanted the equation of state of a fluid, modelled as hard disks in a box. It needed an average over every possible arrangement of the disks. With two hundred and twenty-four disks that is an integral in four hundred and forty-eight dimensions: no grid could touch it. Their idea, run on the MANIAC computer, was a random walk through arrangements that spends its time in proportion to their probability.

Here is a seeded forty-disk illustration, with hard walls rather than the original periodic boundaries. Start them on a lattice. Pick a disk and propose moving it a small random distance. If it would overlap another, reject the move: the disk stays where it is, and that position is counted again. Otherwise accept it, provided it also stays inside the walls. Sweep after sweep, the lattice melts into a typical arrangement, and averages over the walk become averages over all arrangements, each weighted by its probability.

In general: from the current point, propose a random step. Accept it with probability the ratio of the target densities, capped at one: always move uphill, sometimes downhill. For hard disks every legal arrangement is equally likely, so the rule is simply 'accept unless they overlap'. And because only ratios appear, the normalizing constant is never needed, which is exactly what Bayesians lack: the posterior up to a constant, likelihood times prior.

Why averages over a walk work: the ergodic theorem, Part 6's law of large numbers for Markov chains, says they converge to target expectations when the chain is ergodic and the quantity is integrable. Under further conditions there is a central limit theorem too, with variance multiplied by the integrated autocorrelation time. Positive correlation inflates it; antithetic correlation can reduce it. The price of a random walk is that S draws are worth only S over tau independent ones; chapter four turns this into the effective sample size.

The same walk on a curved two-parameter posterior, its contours in gold. Start somewhere unlikely. The walk drifts in, then wanders along the curved ridge. About half the proposals are accepted. Thousands of steps later, the cloud of visited positions approximates the posterior with correlated draws, and any average over it is an estimate of a posterior expectation.

Part 26 integrated over tau on a grid, which works in one dimension. With a hundred parameters and only ten grid points each, a grid needs ten to the hundred evaluations. A well-behaved posterior can be explored without an exponential grid, but multimodality and poor geometry can still make sampling exponentially difficult. The questions of this part are which sampler, how to know it worked, and what to do when it doesn't.

Numbers: 36% of moves accepted; 53% on the banana

1Importance samplingMaster's4 min

The simplest Monte Carlo trick for a distribution you can't sample: sample from one you can, covering the target support, and correct. Multiply and divide by a proposal density q. Draw from q, weight each draw by the ratio of target to proposal, and take a weighted average; normalizing by the sum of the weights means the target's constant cancels. Kish's effective sample size summarizes weight concentration. It is a heuristic, not the accuracy of every integrand. The danger: if the proposal has lighter tails than the target, a rare draw far out gets an enormous weight, and the estimator's variance can be infinite.

Three proposals for a standard normal target, two thousand draws each; each stick is one draw's weight. A proposal narrower than the target, standard deviation a half, almost never reaches the tails, so when it does the weight is huge: one draw carries eleven percent of the total. A wide normal wastes draws far out, but its weights are bounded. A Student t, with heavier tails than the target, gives nearly even weights: the best of the three.

Estimating the variance, whose true value is one. The narrow proposal gives one point three one, thirty percent wrong. Worse, its effective sample size of sixty-two looks respectable, because the ESS is computed from the same unreliable weights. The wide normal and the t give about one point oo five and one point oo three, much closer in this run. The last column is the honest alarm: the Pareto shape k-hat, next.

Importance sampling can also beat sampling from the target itself. For ordinary importance sampling with a normalized target, the minimum-variance proposal is proportional to the absolute value of f times pi. It has zero variance when f has one sign. The self-normalized estimator has a different optimum. Take the rare event that a standard normal exceeds three, probability point oo one three five. Sampling the normal directly, two thousand draws see about three such events, and the estimate's standard deviation is point oo oo nine, nearly as large as the answer. Proposing from a normal centred just beyond three, many more draws reach the event, and the error is sixteen times smaller. Rare-event simulation, in engineering and finance, is built on this.

Importance sampling also recycles draws you already have. Suppose you sampled a posterior under one prior. To see the posterior under another, weight each draw by the ratio of the new prior to the old: a sensitivity analysis without refitting. Weighting each draw by one over the likelihood of a single observation gives the posterior with that observation left out, the trick behind Part 28's fast cross-validation. Both are only as good as the weights, so both are checked by k-hat.

Pareto-smoothed importance sampling, from Aki Vehtari and colleagues, fits a generalized Pareto distribution to the largest weights. Its estimated shape diagnoses the weight tail. For a positive population shape k, moments of order below one over k exist; a shape at least a half implies infinite variance. A fitted k-hat is a noisy diagnostic, not proof of that property. Below a sample-size-dependent threshold capped at point seven, Pareto smoothing can stabilize the estimate. Low k-hat alone does not guarantee accuracy. Above it, as for the narrow proposal's point nine three, the estimate is unreliable; improving the proposal, collecting more effective draws or refitting may be necessary. Part 28 uses it for cross-validation, and chapter ten to check variational approximations.

Numbers: 1.309 with k̂ 0.93; tail SD 16× smaller

2Metropolis-HastingsBachelor's4 min

Wilfred Hastings generalized the rule in 1970. Propose a new point from any distribution q you can sample. Accept with probability the target ratio times the ratio of the proposal densities in reverse, which corrects for proposals that favour some directions. On rejection, the chain stays put, and the current point counts again; dropping repeats would bias the answer. For a symmetric proposal, the correction cancels, leaving the 1953 rule.

Why it works is Part 7's detailed balance: the flow of probability from x to x prime equals the flow back. Multiply out: the flow from x to x prime is the smaller of two products, and that expression is symmetric, so the flows match. Integrating shows the target is stationary: a chain started from it stays there. If the chain can reach everywhere and doesn't cycle, it converges to the target from anywhere, and long-run averages converge to posterior expectations.

The step size matters enormously. Six hundred iterations of the first coordinate of a twenty-dimensional normal. Tiny steps are almost always accepted, but the chain creeps, and neighbouring draws are nearly identical. Steps tuned to accept about a quarter of proposals explore quickly. Huge steps are almost always rejected, and the chain sits still for long stretches.

Measure it. For a range of step sizes, the acceptance rate against the effective sample size per iteration. Efficiency rises and then falls. The peak is near an acceptance rate of a quarter, where the chain gives about one point six effective draws per hundred iterations. For a smooth product-target limit and an isotropic random walk, Gareth Roberts, Andrew Gelman and Wally Gilks proved an optimal acceptance rate tending to point two three four, with the step shrinking like one over the square root of the dimension.

The trouble is scaling. In that product-target limit, the proposal SD shrinks like one over root d, and a random walk's distance grows only like the square root of the number of steps, so crossing the posterior takes a number of iterations proportional to d. With correlated parameters it's worse: the step is limited by the narrowest direction, and the chain crawls along the widest. The way out is to stop guessing directions and follow the gradient, chapter five's Hamiltonian Monte Carlo.

Other proposals fill the gap. An independence sampler proposes from a fixed distribution, chapter one's proposal turned into a chain, and works only when that distribution resembles the target. The Metropolis-adjusted Langevin algorithm drifts each proposal up the gradient of the log density before adding noise. For smooth product targets, its limiting optimal acceptance is point five seven four. The squared noise scale shrinks like d to the minus one third, so the noise SD epsilon shrinks like d to the minus one sixth. For HMC on suitable product targets at fixed integration time, the leapfrog step scales like d to the minus one quarter. These rules describe particular asymptotic settings, not every posterior or a universal cost ranking.

Numbers: 88 / 24 / 0.3% acceptance; peak near 0.23

3Gibbs samplingMaster's3 min

Stuart and Donald Geman's Gibbs sampler of 1984, brought to statistics by Alan Gelfand and Adrian Smith in 1990, updates one coordinate at a time, drawing it from its distribution given all the others. Then the next coordinate, using the newest values. Each update is a Metropolis–Hastings step whose proposal is the conditional itself, so its acceptance probability is exactly one. It needs full conditionals you can sample, which is where Part 26's conjugate pairs earn their keep: inside a big model, each piece is often conjugate given the rest.

Gibbs sampling's weakness shows on a correlated target: a normal with correlation point nine five. Every move is parallel to an axis, so the chain zigzags. Each step can only be as large as the ridge is wide, while the ridge is long. Two thousand sweeps are worth thirty-three independent draws. The cure is to reparametrize, or to update correlated parameters together, a block, so that moves can run along the ridge.

Gibbs sampling becomes powerful with data augmentation. James Albert and Siddhartha Chib wrote probit regression as a latent threshold: each binary outcome records whether a hidden normal variable exceeds zero, Part 24's tolerance distribution. Given the coefficients, each hidden variable is a normal truncated to the side its outcome says. Given the hidden variables, the coefficients are an ordinary least-squares posterior. Neither conditional is hard, though the posterior of beta alone has no closed form: add latent variables until every conditional is easy.

On Bliss's beetles from Part 24, four hundred and eighty-one of them, the Gibbs sampler for the probit model. The posterior mean slope is nineteen point eight, beside the maximum likelihood estimate of nineteen point seven three, with similar uncertainty, consistent with the regular large-sample approximation. This finite sample has no automatic Bernstein–von Mises guarantee. But the trace wanders: two thousand five hundred iterations are worth about two hundred and thirty independent draws, because beta and the hidden z's are strongly dependent and each conditional update can only move a little.

Three standard cures for slow Gibbs samplers. Block: update strongly correlated parameters together, drawing them jointly from their conditional. Collapse: integrate a parameter out analytically, so the remaining ones move more freely. Reparametrize, so that the coordinates are nearly independent, chapter seven's trick. Part 26's numerical-grid sampler for the eight schools used a useful factorization: given tau, it drew mu and every effect jointly, collapsing the whole problem to one dimension.

The BUGS project, from 1989, automated this: describe a graphical model, and the software derives and samples every conditional. Pieces that aren't conjugate get Metropolis steps inside the sweep. Its weakness is dependence between parameters. In the eight schools, when tau is small the effects are pinned near mu, and when the effects are close together tau stays small: each conditional traps the other, the geometry chapter seven returns to.

Numbers: ESS 33 of 2,000; probit slope 19.80 vs 19.73

4DiagnosticsPractice3 min

Two questions after every run. First: how much information do the draws carry? Under a Markov-chain central limit theorem, correlation multiplies an average's variance by one plus twice the autocorrelation sum. This factor depends on the reported quantity and can be below one for antithetic draws. Dividing the number of draws by that factor gives the effective sample size. The Monte Carlo standard error of a posterior mean is the posterior SD over the root of the ESS. Aki Vehtari and colleagues recommend two versions: a bulk ESS computed on ranks, for the centre of the distribution, and a tail ESS for the quantiles that make intervals.

The second question: did the chains find the posterior at all? Run several chains from deliberately scattered starts. Andrew Gelman and Donald Rubin's R-hat compares the variance between the chains' means with the variance within each chain. If every chain has explored the same distribution, R-hat is close to one. The modern version splits each chain in half, so a chain that drifts disagrees with itself, uses rank normalization to improve robustness to heavy tails, and also checks folded deviations for differences in spread; it should be below one point oh one.

A rank plot shows the same thing at a glance. Rank all the draws from all the chains together, and histogram each chain's ranks. For the stuck chains, three have only low ranks and one only high ones. For mixing chains, every histogram is flat: each chain has seen the same distribution. Rank plots can reveal differences that a dense trace plot hides; neither display guarantees convergence.

The routine, then. Run four or more chains from dispersed starting points. Require R-hat below one point oh one for everything you report, and bulk and tail effective sample sizes above about four hundred. Look at the traces. And remember that diagnostics can show a run failed; they can never prove one succeeded.

Three more habits. Discard the warmup: early draws still remember where the chain began, and for NUTS they are also when the tuning happens. Don't thin to improve accuracy: keeping every tenth draw throws away information, and usually reduces precision per generated transition. This is a practical recommendation, not a theorem about every possible autocorrelation pattern or estimated ESS. Thin only to save storage or downstream computation. And report the Monte Carlo standard error, so readers know how many digits of a posterior mean are real.

Numbers: R̂ 1.53 (stuck) vs 1.008

5Hamiltonian Monte CarloMaster's4 min

Hamiltonian Monte Carlo, invented by Simon Duane and colleagues in 1987 for lattice physics and brought to statistics by Radford Neal, turns the posterior into a landscape: the potential energy is minus the log density, low where the posterior is high. Give the position a random momentum, and add its kinetic energy. Then let physics run: Hamilton's equations, the position moving with the momentum and the momentum pushed by the slope. The exact flow conserves energy, preserves volume and runs backwards as well as forwards, exactly the properties a valid proposal needs, so a puck sent sliding across the landscape lands somewhere far away that is still probable.

The computer can't follow the exact flow, so it takes leapfrog steps: half a kick to the momentum from the gradient, a full step of the position, and another half kick. After L steps, accept the end point with the Metropolis probability of the change in total energy. The integrator is volume-preserving and reversible, so this correction is exact, and because its energy error stays small the acceptance rate stays high.

Why leapfrog, and not the obvious method? A spring, whose exact orbits in position and momentum are circles. Euler's method, update both from the old values, spirals outwards: after sixty steps its energy has grown from a half to eighty-eight. For this stable harmonic oscillator, leapfrog stays on a slightly squashed orbit, its absolute energy error staying below about point oh one one over these sixty steps. Symplectic methods often keep energy error controlled for long times under suitable stability conditions; they do not exactly conserve a nearby energy for every nonlinear model.

Here is the picture to keep in mind. The surface is the potential energy of a strongly correlated normal posterior: a long, narrow valley. Each iteration flicks the puck in a random direction and lets it slide for twenty-five leapfrog steps. It climbs the valley walls, falls back, and travels along the floor, covering in one iteration a distance a random walk would need hundreds of steps to cover. Every trajectory here was accepted.

Radford Neal's demonstration: a hundred-dimensional normal whose coordinates have scales from point oh one to one. The traces show the widest coordinate, The displayed traces have different subsampling and are illustrative. The efficiency figures below count retained-run work, excluding warmup, and distinguish density evaluations from gradients. The random walk, its step held small by the narrowest coordinate, crawls: about point oh five effective draws per thousand evaluations. HMC gives six point three. Counting a gradient as one evaluation, that's about a hundred and forty times the efficiency, for this coordinate in these runs. Short-run ESS estimates are uncertain, and the ratio is not a universal dimension-dependent speedup.

The mass matrix is HMC's preconditioner. Set its inverse to the posterior covariance, and the landscape the puck sees becomes round. A diagonal one, Stan's default, rescales each parameter to unit spread. A dense one also removes linear correlations, at a cost of d squared. Mark Girolami and Ben Calderhead's Riemannian HMC lets it vary with position, adapting to curvature that changes from place to place, as in a funnel, at a higher cost per step.

The catch is tuning. Too large a step size, and the energy errors cause rejections. Too few steps, and HMC degenerates into a random walk. Too many, and the puck, on its periodic orbit, comes back to where it started, wasting every gradient in between. With the kinetic-energy convention used here, the inverse mass matrix should approximate the posterior covariance, so that Gaussian dynamics have similar frequencies. Choosing all three automatically is what NUTS does.

Numbers: Euler 0.5 → 88; leapfrog ±0.011; 140× in 100-D

6NUTSMaster's3 min

Matthew Hoffman and Andrew Gelman's No-U-Turn Sampler removes the number of steps. From the current point it builds a trajectory both forwards and backwards in time, doubling its length each round: one step, two, four, eight. It stops when the path starts to turn back on itself, when either end's momentum points back towards the other end. The next point is then drawn from the trajectory in a way that keeps detailed balance, the subtle part of the algorithm. The path length responds to local geometry, with a maximum-depth safeguard. A U-turn is a stopping rule, not proof that an iteration did all the exploration needed.

Three NUTS iterations on a correlated normal. The first builds a trajectory of seven leapfrog steps, both ways from the start, until it has swept along the valley and begun to turn. The second, starting from the chosen point, needs fifteen, the third seven again. The ringed dots are the points chosen: each far from where its iteration began.

The step size and mass matrix are learned during warmup. The step size by dual averaging, an optimization method that adjusts it until the average acceptance probability is point eight. The inverse mass matrix is estimated from draw variances in expanding windows. Statkit uses a simplified schedule inspired by Stan, with initial and terminal buffers proportional to warmup length; it is not Stan's exact production implementation. Then both are frozen for ordinary Markov-chain sampling. Continuing adaptation requires additional adaptive-MCMC conditions; it is not automatically invalid. Warmup draws are discarded.

On the eight schools, written in the non-centred form chapter seven explains, four chains of a thousand. Most iterations need a tree of depth three, seven leapfrog steps, about eight on average. The caption reports the average adapted step size of these four chains. R-hat for log tau is one point oo two, the effective sample size about eighteen hundred, and there are no divergences: a clean run.

HMC has one more gift: it reports its own failures. If the energy along a trajectory suddenly explodes, the trajectory has diverged. That happens where the posterior's curvature changes faster than the step size can follow, in a narrow neck or a sharp ridge. The sampler then can't enter that region properly, and finite-run estimates may be biased, sometimes without another obvious warning. So a divergence is never to be ignored. Usually the fix is to change the parametrization, as the next chapter shows.

One limitation of all gradient-based samplers: standard HMC needs differentiable continuous coordinates in the region it explores, often after transforming constrained parameters. Discrete unknowns, like which component of a mixture each observation came from, or the time of a change point, have no gradient. The standard remedy is to sum them out of the likelihood, which for a mixture gives the familiar weighted sum of densities. Their posterior can then be recovered afterwards, one draw at a time.

Numbers: 7 / 15 / 7 steps; ε 0.42; ESS 1,830

7Neal's funnel and the eight schoolsPractice4 min

Radford Neal's funnel is the hierarchical model's geometry, distilled. A scale parameter v is normal, and nine further parameters are normal with standard deviation e to the v over two. When v is very negative, the x's are squeezed into a tiny neck; when it is large, they spread across a wide mouth. No single step size suits both, and the curvature in the neck is so extreme that HMC's trajectories diverge before they can enter it.

Two thousand NUTS draws of v against the first x. The grey lines mark two standard deviations of x at each height. Sampling v and x directly, the centred form, the draws stop at v of about minus two: the neck, below, is never visited. The true five percent point of v is minus four point nine; the sampler's is minus two point one, a badly biased answer with only one divergence to warn of it. Now sample v and standard normals z instead, and set x to e to the v over two times z: the non-centred form. Now the coordinates are independent normals, with v's different scale handled by adaptation, and the draws fill the whole funnel, neck included.

The eight schools are a funnel: log tau controls the width, and the eight effects play x. Sampled directly, as Part 26 wrote the model, against a numerical-grid reference, using a normal prior with SD five on mu and a half-Cauchy prior with scale five on tau. These are proper priors, different from Part 26's opening flat-prior fit, NUTS gives forty-seven divergences in four thousand iterations, all at small tau, where the neck is. The histogram misses the left tail: the five percent point of tau is point nine instead of about point two five. R-hat is one point oh five and the effective sample size sixty: the diagnostics are worried, and right to be.

Now write each effect as mu plus tau times a standard normal z, and sample the z's. It is the same model: only the coordinates the sampler moves in have changed. No divergences, R-hat of one point oh oh three, and an effective sample size of nineteen hundred. The histogram lies on the exact curve: five percent point point two five, median two point six nine, against the grid's about point two five and two point seven five.

A tempting response to divergences is to force a smaller step size by raising the target acceptance rate. At point nine nine the divergences fall from forty-seven to four, the run costs about three point two times the original gradients, and the five percent point of tau is still point five five, not about point two five: the problem is hidden, not solved. The non-centred run agrees closely with the reference at about half the original gradient count. Reparametrization helps this weak-data example more than just increasing effort.

Non-centring is one of a family of reparametrizations. In regression, factor the design matrix as Q times R and sample the rotated coefficients, which are nearly uncorrelated. Standardize predictors, so that parameters live on similar scales. Sample positive quantities on the log scale, which the transforms already do. The common principle is to find coordinates in which the posterior looks like a standard normal, the shape HMC handles best.

Which form to use depends on the data. When groups carry little information, as here, non-centre. When each group has lots of data, the likelihood pins each effect down and the centred form is better; the funnel appears in the other coordinates instead. Omiros Papaspiliopoulos, Gareth Roberts and Martin Sköld worked out the theory. Either way, a divergence is information about your model's geometry, not noise to be suppressed.

Numbers: v: −2.12 vs −4.93; τ 5%: 0.90 / 0.55 / 0.25 vs 0.25

8Built: a probabilistic programming languagePractice4 min

Everything so far assembles into a probabilistic programming language, the design of Stan and PyMC, and statkit now has a small one. A model is just a function returning the log density. Its gradient comes from the reverse-mode automatic differentiation that AI, Built's fourth part wrote: no derivative is ever worked out by hand. Parameters with constraints, like a positive standard deviation, are transformed to the whole real line, and the transform's Jacobian is added to the log density. NUTS with a simplified Stan-inspired warmup runs on the transformed space, with several chains run sequentially here, and the output supports R-hat, effective sample sizes and divergence checks.

This is the whole of chapter seven's non-centred eight schools model in statkit. The function adds up the log densities of the priors and the likelihood, written exactly as the model is written on paper. The model declares each parameter's size and support: tau is positive, so the sampler works with its logarithm. One call samples four chains with adaptation.

The transforms deserve a moment. A positive parameter becomes the exponential of an unconstrained u, a probability the logistic of one. The sampler works with u, so the log density must include the log of the transform's derivative, the change-of-variables rule. Forget it, and you have silently changed the prior; it is a common sampler bug. Part 26's simulation-based calibration can detect many such errors, though a passing check is not proof of correctness.

Why gradients are affordable. The forward pass computes the log density and records each operation in a graph. The backward pass runs the chain rule from the output back to every input, accumulating each parameter's derivative. Its cost is a small constant multiple of one evaluation of the density, however many parameters there are. That single fact is why gradient-based samplers scale to thousands of dimensions, and why the same machinery trains neural networks.

A sampler must be checked against answers known in closed form. A normal mean, a proportion with its logistic transform, a Poisson rate with its log transform, and the eight schools against a numerical grid using this chapter's proper priors. The displayed comparisons are numerical smoke checks; Monte Carlo standard errors are shown for the first and third means. The test suite independently checks several conjugate posteriors, gradients and diagnostics, with explicit tolerances.

When building or using such a system, a checklist. Simulate fake data from the model, fit it, and see whether the parameters come back. Check gradients against finite differences, as statkit's tests do. Compare with an exact answer on a simplified case. Run simulation-based calibration. And read every warning the sampler gives.

The real systems: Stan, with its own modelling language compiled to C++, is the standard. PyMC, NumPyro and Turing bring the same ideas to Python and Julia. BUGS and JAGS were the Gibbs-sampling generation before them. Statkit's is about seven hundred lines, slow and readable: meant for understanding what the real ones do.

Numbers: numerical comparisons with explicit test tolerances

9Sequential Monte CarloMaster's4 min

When data arrive one at a time, posteriors must be updated one at a time. Take Part 17's local-level model: a hidden level that wanders, observed with noise. A particle filter keeps a cloud of guesses for the level. Move each by the model's dynamics. Weight each by how well it predicts the new observation: chapter one's importance sampling. Then resample: copy the heavily weighted particles and drop the light ones, so the cloud doesn't degenerate. This bootstrap filter is Neil Gordon, David Salmond and Adrian Smith's, from 1993.

Sixty noisy observations of a wandering level, whose true path is in gold. For this linear Gaussian model the exact answer is Part 38's Kalman filter, in blue with its two-standard-deviation band. The particle filter, a thousand particles, dashed green, lies on top of it. The particle-filter idea extends beyond linear Gaussian models when transitions can be simulated and observation weights evaluated; the model-specific code must change.

The filter also estimates the likelihood of the whole series, as a product of each observation's average weight. With fifty particles the estimate's log varies by one point two from run to run; with two hundred, by point six six; with a thousand, by point two. The nonnegative likelihood estimate is unbiased for the specified model; Jensen's inequality makes its log downward biased in expectation, and it converges on the Kalman filter's exact value. Christophe Andrieu and Gareth Roberts showed that Metropolis–Hastings run with a nonnegative unbiased likelihood estimate still targets the exact posterior when the auxiliary randomness is part of the state and the current estimate is retained on rejection: pseudo-marginal MCMC, for models whose likelihood can only be simulated.

Particle methods have their own pathologies. Without resampling, after a few steps one particle carries nearly all the weight. With resampling, the particles' histories coalesce, so the distant past is represented by a single ancestor. To learn the model's fixed parameters too, particle MCMC wraps the filter inside Metropolis–Hastings. And in high dimensions the number of particles needed grows very quickly: particle filters suit small hidden states, not large ones.

The same machinery reaches static posteriors by tempering. Build a ladder of distributions from the prior, at temperature zero, to the posterior, at one, raising the likelihood to a power that climbs step by step. Particles drawn from the prior are reweighted from one rung to the next, with each new temperature chosen so the effective sample size falls to half; then they are resampled and moved by a few Metropolis steps. And the average weights along the way multiply up to the evidence, the hard integral behind Part 26's Bayes factors.

Part 26's twenty points from a cubic, whose evidence we could compute exactly. Tempered SMC with two thousand particles, five to seven rungs, finds each log evidence within about point one five of the truth, and picks the same winner, degree three. With no closed form, it would be the way to compute a Bayes factor.

Numbers: log-lik SD 1.20 / 0.66 / 0.21; evidence within 0.15

10Variational inferenceMaster's4 min

Variational inference trades sampling for optimization: find, within a simple family of distributions, the one closest to the posterior in Kullback–Leibler divergence. The log evidence splits into a lower bound plus that divergence, so maximizing the evidence lower bound, the ELBO, minimizes the divergence without ever computing the normalizing constant. But note the direction: the divergence from q to the posterior punishes q for putting mass where the posterior has little, and not the reverse. A restricted family and this divergence often favour concentrated approximations, but under-dispersion is not a universal theorem.

The classic failure. The posterior is a correlated normal, its two-standard-deviation contour in gold. The purple ellipse is a stochastic ADVI fit with independent normal coordinates. The exact optimum in this family has SD root one minus rho squared, about point four four; the finite optimization has additional error. Its standard deviations are about point four, where the true ones are one: mean field recovers the conditional spread, the square root of one minus rho squared, and reports far too much certainty about each coordinate.

For conditionally conjugate models the optimization has closed-form steps. A normal sample with unknown mean and precision, approximated by independent factors. The best factor for the mean, holding the other fixed, is the expected log joint under it, which is again normal, and the precision's is a gamma; alternate until they stop changing: coordinate ascent variational inference. It converges in a few iterations, and its standard deviation for the mean, point two seven six, is below the exact posterior's point two eight nine: under-dispersed in this example.

On the eight schools, mean-field ADVI against NUTS. NUTS puts tau's ninety percent interval between point two six and ten point three. ADVI says point six five to six point seven: far too narrow, cutting off both the small values near the funnel's neck and the large ones. Chapter one's Pareto k-hat, using the approximation as a proposal for the posterior, comes out at point six two: below the alarm level, but not by much. Variational inference is fast and often good for means; for uncertainty, check it.

Richer families help. A full-rank Gaussian captures correlations, at the cost of d squared parameters. Normalizing flows learn an invertible transformation of a normal, flexible enough for curved posteriors. Forward KL often favours covering mass. Expectation propagation uses local moment matching and tilted-distribution projections; it does not generally minimize one global forward KL. Each remains an approximation whose error has to be checked rather than assumed.

Variational inference wins on scale: millions of parameters, streaming data, topic models and neural networks, where sampling is out of reach. Automatic differentiation variational inference, ADVI, is the generic version built here: transform every parameter to the real line, fit a Gaussian by stochastic gradients. It loses on uncertainty, on funnels and on multiple modes. So check it, with Yuling Yao and colleagues' Pareto k-hat, or with Part 26's simulation-based calibration, remembering that a passing diagnostic is not proof of accuracy.

Numbers: SD 0.41 vs 1; τ [0.65, 6.66] vs [0.26, 10.3]; k̂ 0.62

11Laplace and INLAMaster's3 min

The oldest approximation is Laplace's: find the posterior mode, and replace the posterior by a normal there whose covariance is the inverse of the curvature. One optimization and one Hessian, with no sampling at all. It is as good as the posterior is normal, so regular fixed-dimensional asymptotics can justify it with growing data. Skewness, boundaries and multiple modes can make it inaccurate.

A logistic regression with a normal prior, fitted both ways. With twenty observations, the posterior for the slope is skewed: its upper tail stretches to five point five five, while Laplace's symmetric normal has a ninety-fifth percentile of four point seven seven. With four hundred observations the two curves coincide, and the two methods give similar answers in this example.

Laplace's method also approximates the evidence: the joint density at the mode, times the volume of the normal fitted there, computed from the determinant of the Hessian. Under regular fixed-dimensional assumptions and a suitable fixed prior, retaining the leading terms gives BIC. Order-one prior and curvature terms remain in Laplace's expression. It is also how Part 25 integrated each school's random effect in the mixed logistic model. When it isn't accurate enough, adaptive quadrature in low dimensions, or chapter nine's tempered SMC, do better.

Håvard Rue, Sara Martino and Nicolas Chopin's INLA pushes Laplace's idea far. It targets latent Gaussian models, Part 25's generalized linear mixed models and their spatial cousins: thousands of Gaussian latent effects and a handful of hyperparameters. It approximates the hyperparameters' posterior by dividing the joint density by a Gaussian approximation to the latent field, evaluated at its mode, integrates over a small grid of hyperparameter values, and applies Laplace again for each latent effect: integrated nested Laplace approximation. For suitable sparse latent-Gaussian models with few hyperparameters, it can be much faster than MCMC. Accuracy and speed depend on the model; Part 39 returns to these methods.

The whole toolkit on one page. Grids, importance sampling, Gibbs, NUTS and SMC are exact in the limit of more computation; Laplace, INLA and a fixed variational family retain approximation error. ABC at fixed summaries and tolerance does too, but sufficient summaries and vanishing tolerance can recover the full posterior under regularity conditions. Each has its domain and its characteristic failure, and its own warning sign. Most applied work today starts with NUTS, and reaches for the others when the model is too big, too slow or has no likelihood.

Numbers: 95% point 5.55 vs 4.77 (n = 20); 2.18 vs 2.14 (n = 400)

12Likelihood-free inferenceMaster's4 min

Some models can be simulated but their likelihood can't be written down: population genetics, epidemics, agent-based economies. Approximate Bayesian computation needs only the simulator. Draw a parameter from the prior and simulate a data set. Keep the parameter if the simulated data's summaries are within epsilon of the real ones. As epsilon shrinks, the kept parameters approach the posterior given the summaries. That is the posterior given the data only if the summaries are sufficient.

A test case with a known answer: fifteen Poisson counts, a gamma prior, and the sample mean as the summary, which is sufficient. The exact posterior is in gold. With a loose tolerance of one, ABC's posterior is too wide. With point oh five it matches the exact one closely, but only one simulation in eighty is kept: ABC's accuracy is bought with simulations.

Now the same data with the median as the summary, which throws information away. Even at the tightest tolerance, ABC's posterior has mean two point one and standard deviation point four nine, where the exact answer is two point five six and point four. It isn't merely wider; it is in the wrong place, because conditioning on this discrete median gives a different posterior from conditioning on all the counts. A low value in this dataset is not a universal downward-bias property of Poisson medians. No tolerance can fix a poor summary: choosing summaries is the heart of ABC.

Rejection is wasteful: at small tolerances almost every simulation is thrown away. ABC-MCMC moves a Metropolis chain through parameter space, accepting a proposal only if its simulated data land close enough. ABC-SMC passes a population of particles through a sequence of shrinking tolerances, as chapter nine's tempering did with temperatures. All target the same approximate posterior; they differ in how many simulations it costs.

Better versions keep more of the simulations: Mark Beaumont's regression adjustment corrects each kept draw for how far its summaries missed. Simon Wood's synthetic likelihood fits a normal to simulated summaries. And neural posterior estimation trains a network to map simulated data straight to a posterior, after which inference on new datasets within the training model and design can be fast. Out-of-distribution data require additional checks. All of them approximate, so all of them need checking, by Part 26's simulation-based calibration: the Board.

The Board tests computation itself. Draw the eight schools' parameters from the prior, simulate eight estimates, and compute each school's ninety percent interval; a hundred times. If the computation is right, the intervals cover ninety percent of the true effects, averaged over the prior. The numerical grid draws cover ninety point four percent. NUTS on the non-centred model, eighty-seven point nine. NUTS on the centred model, ninety point eight. Its coverage is close to nominal in this noisy run, despite the observed-data tau distortion in chapter seven. Mean-field ADVI covers eighty-four point eight percent, a visible shortfall, although still inside the Board's coarse three-standard-error margin. Uncertainty is computed across one hundred independent datasets, each contributing eight correlated intervals. Calibration can pass while a particular data set's answer is still biased; it checks the computation on average, not case by case.

Numbers: mean summary 2.58; median summary 2.10 vs exact 2.56

13Exact samplingPhD4 min

Every chain in this part reaches its target only in the limit. After any finite run it is approximately there, and chapter four's diagnostics can only warn when it isn't. How long is long enough? In 1996 James Propp and David Wilson showed that for some chains the question has an exact answer, and a sampler can stop knowing its draw is perfect.

Imagine running the chain from time minus T to zero, from every possible starting state at once, all driven by the same random numbers. If every copy has merged into one state by time zero, that state doesn't depend on where the chain began, so it is what a chain started infinitely long ago would show: an exact draw from the stationary distribution. If they haven't merged, go further back, doubling T and reusing the same random numbers for the most recent times; running forwards until coalescence instead would bias the result. For monotone chains we needn't track every state: only the highest and the lowest, since every other copy is trapped between them.

Propp and Wilson's showcase was the Ising model of Part 22: spins on a grid, plus or minus one, preferring to agree with their neighbours, more strongly as beta grows. The Gibbs update sets one spin to plus with a probability that rises with the sum of its neighbours. Using one shared uniform for every copy, a configuration with more plus spins stays above one with fewer: the coupling is monotone. So it is enough to run two chains, from all plus and all minus.

A sixteen-by-sixteen grid. In green, the magnetization of the chain started from all plus; in red, from all minus. At beta of point three the two meet within thirty-two sweeps, and the state they share at time zero, shown below, is an exact draw from the Ising distribution. At point four two, closer to the infinite square lattice's critical inverse temperature of about point four four. This finite torus has no sharp phase transition; in this seeded run, they need a hundred and twenty-eight: near criticality the chain mixes slowly, and the observed coalescence horizon is a random computational cost, not the exact mixing time.

The coupling idea has recently returned in a practical form. Pierre Jacob, John O'Leary and Yves Atchadé couple two copies of an ordinary Markov chain, one lagged behind the other. Once they meet, a simple correction turns finite runs into unbiased estimates of posterior expectations, under appropriate coupling, meeting-time and moment conditions. The unbiased object is an expectation estimator, not an exact posterior draw. The distribution of meeting times bounds how far the chain is from stationarity, under the relevant coupling and integrability assumptions. And it works for Metropolis–Hastings, Gibbs and HMC, without needing monotonicity.

The price: the method needs monotonicity, or some other way to bound all starting states. Its running time is random, and can be long. Most posteriors offer no such structure, so in practice we rely on the diagnostics. But coupling from the past makes precise what we mean when we hope a chain has converged.

Numbers: T = 32 (β 0.3), 128 (β 0.42)

Recap, problems, and the road aheadAll tracks3 min

Part twenty-seven in fourteen lines. A random walk over hard disks integrated what no grid could. Importance sampling reweights a proposal, and Pareto's k-hat says when not to trust it. Metropolis–Hastings needs only density ratios, with a quarter-acceptance guideline in a specific smooth high-dimensional product-target limit. Gibbs updates one coordinate at a time, helped by latent variables. R-hat and effective sample sizes caught stuck chains. Hamiltonian Monte Carlo follows the gradient, a hundred and forty times more efficient in a hundred dimensions. NUTS stops each trajectory at its U-turn and tunes itself. Neal's funnel defeats it until the model is non-centred. Statkit's probabilistic programming language reproduces exact answers. Particle filters track hidden states, and tempered SMC found the evidence. Variational inference can scale well but may understate uncertainty. Laplace and INLA put normals at the mode. ABC needs only a simulator, and lives or dies by its summaries. And coupling from the past samples exactly.

Where it comes back. Part 28 uses Pareto-smoothed importance sampling for leave-one-out cross-validation. Part 32 fits sparsity priors with NUTS. Part 38 builds the Kalman filter the particles matched. Part 39 fits Gaussian processes and spatial models with INLA. Part 41 imputes missing data by MCMC. Part 44 proves when Markov chains converge and how fast. Part 50 studies stochastic approximation, the theory behind adaptation. And Part 53 proves Bernstein–von Mises.

Six problems, with full solutions in the README. Detailed balance for Metropolis–Hastings; consistency of self-normalized importance sampling; the Gibbs sampler on a correlated normal as an autoregression; why leapfrog preserves volume and reverses; the ELBO identity; and the Jacobian of the log transform. Pause here if you want to try them.

The books this part follows: Robert and Casella's Monte Carlo Statistical Methods, the Handbook of Markov Chain Monte Carlo, the computational chapters of Bayesian Data Analysis, and Doucet, de Freitas and Gordon on sequential Monte Carlo; with the papers from Metropolis to Propp and Wilson.

Twenty-seven parts of sixty-five. We now have tools to fit and check many models, alongside limits from geometry, identifiability and computational cost. Which makes the next question unavoidable: which model should we believe? In 1983 David Freedman regressed pure noise on fifty columns of noise, kept the columns that looked significant, refitted, and found a highly significant regression. Part 28: which model?

Where it goes next. PSIS becomes leave-one-out cross-validation in Part 28; NUTS fits the shrinkage priors of Part 32; the particle and Kalman filters return with state-space models in Part 38, INLA with Gaussian processes in Part 39, and the chains' mixing times are studied in Part 44.

Key results

The part's results in one place, for revision.

Self-normalized importance sampling\(\displaystyle \hat{\operatorname{E}}_\pi f=\frac{\sum_s w_sf(x_s)}{\sum_s w_s},\quad\allowbreak w_s=\frac{\pi(x_s)}{q(x_s)},\qquad\allowbreak \mathrm{ESS}=\frac{(\sum_s w_s)^2}{\sum_s w_s^2}\)
The Hastings ratio\(\displaystyle \alpha(x,x')=\min\Bigl\{1,\ \frac{\pi(x')\,q(x\mid x')}{\pi(x)\,q(x'\mid x)}\Bigr\}\ \Longrightarrow\ \pi(x)K(x\to x')=\pi(x')K(x'\to x)\)
Gibbs on a correlated normal\(\displaystyle x_1^{(t+1)}=\rho^2x_1^{(t)}+\text{noise},\qquad\allowbreak \frac{\mathrm{ESS}}{n}=\frac{1-\rho^2}{1+\rho^2}\)
Leapfrog\(\displaystyle p\leftarrow p-\tfrac{\varepsilon}{2}\nabla U(q),\quad\allowbreak q\leftarrow q+\varepsilon M^{-1}p,\quad\allowbreak p\leftarrow p-\tfrac{\varepsilon}{2}\nabla U(q),\qquad\allowbreak U=-\log\pi\)
Non-centring\(\displaystyle \theta_j=\mu+\tau z_j,\qquad\allowbreak z_j\sim N(0,1)\)
The ELBO\(\displaystyle \log p(y)=\operatorname{E}_q\log\frac{p(y,\theta)}{q(\theta)}+\operatorname{KL}\bigl(q\,\|\,p(\theta\mid y)\bigr)\)

Try it

Lab 27 · Three samplers, one correlated normal

Sample a bivariate normal with correlation 0.95 by Gibbs, by random-walk Metropolis and by Hamiltonian Monte Carlo (statkit.ppl on autodiff), check Gibbs's effective sample size against (1 - rho^2)/(1 + rho^2), and check that leapfrog keeps the spring's energy while Euler's grows like (1 + eps^2)^steps.

Figure produced by Lab 27: Three samplers, one correlated normal
Produced by the lab below, seed 0, in 1.5 s.
python -m videos.stats.labs 27 needs numpy, scipy, matplotlib · download lab27.py · source on GitHub
spring, 60 steps of 0.3: Euler's energy  0.5 -> 88.0   (theory 0.5 (1 + eps^2)^60 = 88.0)
spring: leapfrog's largest energy error  0.0112   (bound eps^2/8 = 0.0112)
Gibbs: sd of x1, correlation             1.02, 0.952   (truth 1, 0.95)
Gibbs: ESS per iteration                 0.047   (theory 0.051)
random walk: sd of x1, correlation       0.98, 0.947   (truth 1, 0.95)
random walk: ESS per iteration           0.015
HMC: sd of x1, correlation               0.97, 0.953   (truth 1, 0.95)
HMC: ESS per iteration                   0.761   (0.063 per gradient)
acceptance: random walk, HMC             44%, 97%

All three chains have the right stationary law, but each Gibbs sweep or random-walk step is worth a few hundredths of an independent draw, while one HMC trajectory is worth most of one.
The code (115 lines; it asserts its own result)
"""Lab 27: run Gibbs, random-walk Metropolis and HMC on one correlated normal, and count effective draws."""

import numpy as np

from videos.coursekit import labs
from explainer.stats.kit import ppl

TITLE = "Three samplers, one correlated normal"
GOAL = ("Sample a bivariate normal with correlation 0.95 by Gibbs, by random-walk Metropolis and by Hamiltonian Monte "
        "Carlo (statkit.ppl on autodiff), check Gibbs's effective sample size against (1 - rho^2)/(1 + rho^2), and "
        "check that leapfrog keeps the spring's energy while Euler's grows like (1 + eps^2)^steps.")
TASKS = [
    "Set RHO = 0.99. Gibbs's ESS per sweep should fall to about 0.01: does HMC, with EPS and L retuned, suffer as much?",
    "Sweep the random walk's scale over 0.05, 0.3 and 3 and record acceptance and ESS. Where is the ESS highest?",
    "Replace the target by Neal's funnel (v ~ N(0, 9), x ~ N(0, e^v)) and run ppl.sample on it centred and "
    "non-centred. Compare the 5% point of v with -4.93.",
]

RHO, EPS, L = 0.95, 0.18, 12


def gibbs(n, rng):
    x, s, out = np.zeros(2), np.sqrt(1 - RHO ** 2), np.empty((n, 2))
    for i in range(n):
        x[0] = RHO * x[1] + s * rng.standard_normal()
        x[1] = RHO * x[0] + s * rng.standard_normal()
        out[i] = x
    return out


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    # 1. The integrator.  A unit spring is a standard normal target: H = q^2/2 + p^2/2 = 0.5 at (1, 0).
    spring = ppl.Model({"q": (1, "real")}, lambda p: (p["q"] * p["q"] * -0.5).sum())
    eps, steps = 0.3, 60
    q, p = np.array([1.0]), np.array([0.0])
    lp, g = spring.logp_grad(q)
    leap = [0.5]
    for _ in range(steps):
        q, p, lp, g = ppl.leapfrog(spring, q, p, g, eps, np.ones(1))
        leap.append(float(-lp + 0.5 * p @ p))
    qe, pe, euler = 1.0, 0.0, [0.5]
    for _ in range(steps):
        qe, pe = qe + eps * pe, pe - eps * qe
        euler.append(0.5 * (qe * qe + pe * pe))
    leap, euler = np.array(leap), np.array(euler)
    lab.row("spring, 60 steps of 0.3: Euler's energy", f"0.5 -> {euler[-1]:.1f}   (theory 0.5 (1 + eps^2)^60 = {0.5 * 1.09 ** 60:.1f})")
    lab.row("spring: leapfrog's largest energy error", f"{np.abs(leap - 0.5).max():.4f}   (bound eps^2/8 = {eps ** 2 / 8:.4f})")
    assert abs(euler[-1] - 0.5 * (1 + eps ** 2) ** steps) < 1e-6 and 87 < euler[-1] < 89
    assert np.abs(leap - 0.5).max() <= eps ** 2 / 8 + 1e-9, "leapfrog's energy error stays bounded"

    # 2. Three samplers on the same target.
    n_g = 20000
    G = gibbs(n_g, rng).reshape(4, n_g // 4, 2)
    log_density = lambda x: -0.5 * (x[0] ** 2 - 2 * RHO * x[0] * x[1] + x[1] ** 2) / (1 - RHO ** 2)
    n_r = 20000
    rw = ppl.rwm(log_density, np.zeros(2), 0.5, n_r, rng)
    R = rw["draws"].reshape(4, n_r // 4, 2)
    target = ppl.Model({"a": (1, "real"), "b": (1, "real")},
                       lambda p: ppl.normal_lpdf(p["a"], 0.0, 1.0) + ppl.normal_lpdf(p["b"], p["a"] * RHO, np.sqrt(1 - RHO ** 2)))
    n_h = 800
    hm = ppl.hmc(target, np.zeros(2), EPS, L, n_h, rng, record=True)
    H = hm["draws"].reshape(4, n_h // 4, 2)

    theory = (1 - RHO ** 2) / (1 + RHO ** 2)
    res = {}
    for name, D, cost in (("Gibbs", G, 1), ("random walk", R, 1), ("HMC", H, L)):
        flat = D.reshape(-1, 2)
        e = ppl.ess_basic(D[..., 0])
        res[name] = dict(ess=e / len(flat), sd=flat[:, 0].std(), corr=np.corrcoef(flat.T)[0, 1], rhat=ppl.rhat(D[..., 0]))
        r = res[name]
        lab.row(f"{name}: sd of x1, correlation", f"{r['sd']:.2f}, {r['corr']:.3f}   (truth 1, {RHO})")
        lab.row(f"{name}: ESS per iteration", f"{r['ess']:.3f}" + (f"   (theory {theory:.3f})" if name == "Gibbs" else "")
                + (f"   ({r['ess'] / cost:.3f} per gradient)" if name == "HMC" else ""))
    lab.row("acceptance: random walk, HMC", f"{rw['accept'].mean():.0%}, {hm['accept'].mean():.0%}")
    lab.note = ("All three chains have the right stationary law, but each Gibbs sweep or random-walk step is worth a "
                "few hundredths of an independent draw, while one HMC trajectory is worth most of one.")
    for name, r in res.items():
        tol = 0.12 if name == "Gibbs" else 0.2
        assert abs(r["sd"] - 1) < tol and abs(r["corr"] - RHO) < 0.03, f"{name} samples the target"
    assert abs(res["Gibbs"]["ess"] / theory - 1) < 0.3, "Gibbs's x1 is an AR(1) with coefficient rho^2"
    assert res["HMC"]["ess"] > 5 * res["Gibbs"]["ess"] and res["HMC"]["ess"] > 5 * res["random walk"]["ess"]
    assert hm["accept"].mean() > 0.9

    fig, ax = labs.figure(2, size=(11, 4.2))
    t = np.linspace(0, 2 * np.pi, 200)
    for r in (1, 2):
        ex = r * np.cos(t)
        ey = r * (RHO * np.cos(t) + np.sqrt(1 - RHO ** 2) * np.sin(t))
        ax[0].plot(ex, ey, color=labs.GRID, lw=1)
    gz = G.reshape(-1, 2)[:25]
    stairs = np.column_stack([np.repeat(gz[:, 0], 2)[1:], np.repeat(gz[:, 1], 2)[:-1]])
    ax[0].plot(stairs[:, 0], stairs[:, 1], color=labs.RED, lw=1, label="Gibbs: 25 sweeps")
    for k, path in enumerate(hm["paths"][:6]):
        ax[0].plot(path[:, 0], path[:, 1], color=labs.GOLD, lw=1.4, label="HMC: 6 trajectories" if k == 0 else None)
        ax[0].plot(path[-1, 0], path[-1, 1], "o", color=labs.GOLD, ms=4)
    ax[0].set(title="The same target, two ways to move", xlabel="x1", ylabel="x2", xlim=(-3, 3), ylim=(-3, 3))
    ax[0].legend(loc="upper left")
    lags = np.arange(41)

    def acf(D):
        x = D[..., 0] - D[..., 0].mean()
        return np.array([1.0] + [np.mean(x[:, :-k] * x[:, k:]) / np.mean(x * x) for k in lags[1:]])

    ax[1].plot(lags, acf(G), color=labs.RED, label="Gibbs")
    ax[1].plot(lags, RHO ** (2 * lags), color=labs.MUTED, ls="--", label="theory: rho^(2 lag)")
    ax[1].plot(lags, acf(R), color=labs.BLUE, label="random walk")
    ax[1].plot(lags, acf(H), color=labs.GOLD, label="HMC")
    ax[1].axhline(0, color=labs.GRID, lw=1)
    ax[1].set(title="Autocorrelation of x1", xlabel="lag (iterations)", ylabel="autocorrelation")
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Set RHO = 0.99. Gibbs's ESS per sweep should fall to about 0.01: does HMC, with EPS and L retuned, suffer as much?
  2. Sweep the random walk's scale over 0.05, 0.3 and 3 and record acceptance and ESS. Where is the ESS highest?
  3. Replace the target by Neal's funnel (v ~ N(0, 9), x ~ N(0, e^v)) and run ppl.sample on it centred and non-centred. Compare the 5% point of v with -4.93.

Problems, with solutions

Try each problem before opening its solution.

1. Detailed balance for Metropolis–Hastings. Show that the Metropolis–Hastings kernel satisfies detailed balance with respect to \(\pi\).

Solution

For x′ ≠ x the kernel density is K(x → x′) = q(x′ | x) α(x, x′). Then π(x) q(x′ | x) α(x, x′) = min{π(x) q(x′ | x), π(x′) q(x | x′)}. This is symmetric in (x, x′), so it equals π(x′) K(x′ → x). The rejection mass sits at x′ = x, where balance is trivial. Integrating over x gives ∫ π(x) K(x → x′) dx = π(x′): π is stationary.

2. Self-normalized importance sampling. Show that the self-normalized importance estimator is consistent, and that \(\mathrm{ESS} = n\) when \(q = \pi\).

Solution

By the law of large numbers, (1/n)Σ w_s f(x_s) → E_q(wf) = c E_π f and (1/n)Σ w_s → E_q w = c, where c is π's unknown normalizing constant. The ratio therefore converges to E_π f (Slutsky). If q = π up to the constant, every w_s is equal, and (Σ w)²/Σ w² = n.

3. Gibbs on a correlated normal. Gibbs for \(N_2(0, [[1, \rho], [\rho, 1]])\): show \(x_1^{(t+1)}\) is AR(1) with coefficient \(\rho^2\); find its ESS.

Solution

x₁ | x₂ ~ N(ρx₂, 1 − ρ²) and x₂ | x₁ ~ N(ρx₁, 1 − ρ²). Over one sweep, x₁^{(t+1)} = ρ x₂^{(t)} + e and x₂^{(t)} = ρ x₁^{(t)} + e′, so x₁^{(t+1)} = ρ² x₁^{(t)} + (noise). That is an AR(1) with φ = ρ², whose ESS per draw is (1 − φ)/(1 + φ) = (1 − ρ²)/(1 + ρ²). For ρ = 0.95 this is 0.051, about 100 from 2,000, the stationary large-run reference. The displayed finite-run ESS estimate of 33 has substantial sampling uncertainty and is not a second theoretical value.

4. Leapfrog preserves volume and is reversible. Show that a leapfrog step preserves volume and is reversible (negate \(p\), step, negate again).

Solution

Each of the three substeps is a shear: (q, p) ↦ (q, p − (ε/2)∇U(q)) changes p by a function of q only, so its Jacobian is unit triangular with determinant 1; likewise q ↦ q + εM⁻¹p. A composition of shears preserves volume. Reversibility: apply a step from (q′, p′) with momentum negated. The first half-kick undoes the last, the drift undoes the drift, and the final half-kick undoes the first. You arrive at (q, −p).

5. The ELBO identity. Show that \(\log p(y) = \text{ELBO}(q) + \mathrm{KL}(q \,\|\, p(\theta \mid y))\).

Solution

log p(y) = E_q log p(y) = E_q log{p(y, θ)/p(θ | y)}. Write log p(y, θ)/p(θ | y) = log{p(y, θ)/q(θ)} + log{q(θ)/p(θ | y)}, and take expectations under q. The result is ELBO + KL(q ‖ p(θ | y)). Since KL ≥ 0, the ELBO is a lower bound, tight when q is the posterior.

6. The log transform's Jacobian. Show that if \(\tau = e^u\) and \(\tau \sim p\), then \(u\) has density \(p(e^u)\, e^u\).

Solution

For u = log τ, P(U ≤ u) = P(τ ≤ e^u), and differentiating gives p_U(u) = p_τ(e^u) e^u. So on the unconstrained scale the log density gains the term log|dτ/du| = u. That is exactly what Model adds for a "positive" parameter.

Notes and sources

Where it comes back

Idea Returns in
PSIS-LOO and WAIC 28
shrinkage priors by NUTS 32
Kalman filters and state-space models 38
Gaussian processes, INLA 39
multiple imputation by MCMC 41
Markov chains, mixing times 44
stochastic approximation 50
BvM and posterior contraction 53
the Coverage Board every part; 65

Glossary

  • Monte Carlo; ergodic theorem; MCSE: averages of draws; their convergence for Markov chains; the error of a Monte Carlo average.
  • Importance sampling; self-normalized; Kish's ESS; PSIS; k̂:
    • weighted draws from a proposal;
    • normalized by the weights' sum;
    • (Σw)²/Σw²;
    • Pareto smoothing of the largest weights;
    • the fitted tail shape, unreliable above 0.7.
  • Markov chain Monte Carlo; Metropolis–Hastings; detailed balance; acceptance rate; MALA:
    • chains whose limit is the posterior;
    • propose and accept by the Hastings ratio;
    • balanced flows;
    • limiting guidelines 0.234 (RWM) or 0.574 (MALA) for specific smooth product targets;
    • Langevin proposals.
  • Gibbs sampling; full conditional; data augmentation; blocking; collapsing:
    • coordinate-wise exact draws;
    • a parameter's distribution given all others;
    • latent variables that make conditionals easy;
    • updating together;
    • integrating out.
  • R̂; split, rank-normalized; bulk and tail ESS; rank plot; warmup; thinning: the multi-chain convergence diagnostic and its modern form, and the routine of a run.
  • Hamiltonian Monte Carlo; leapfrog; symplectic; mass matrix; divergence:
    • momentum-driven proposals;
    • the half-kick, drift, half-kick integrator;
    • volume- and structure-preserving;
    • the preconditioner;
    • an exploding energy error.
  • NUTS; U-turn; dual averaging; tree depth: self-tuning HMC and its parts.
  • Neal's funnel; centred and non-centred parametrizations: hierarchical geometry, and θ = μ + τz.
  • Probabilistic programming language; automatic differentiation; transform; Jacobian: models as code, gradients by reverse mode, and constrained parameters mapped to ℝ.
  • Particle filter; resampling; degeneracy; pseudo-marginal MCMC; tempered SMC: sequential importance sampling and its uses for likelihoods and evidences.
  • Variational inference; ELBO; KL(q ‖ p); mean field; CAVI; ADVI; normalizing flow; EP: optimization-based approximations and their families.
  • Laplace approximation; INLA: a normal at the mode; nested Laplace for latent Gaussian models.
  • ABC; summary statistic; tolerance; synthetic likelihood; neural posterior estimation: likelihood-free inference.
  • Coupling from the past; monotone coupling; unbiased MCMC: exact draws; order-preserving couplings; coupled chains for finite-sample unbiasedness.
  • Simulation-based calibration: rank checks that a computation reproduces the prior on average.

Sources

  • History.
    • N. Metropolis, A. Rosenbluth, M. Rosenbluth, A. Teller & E. Teller, J. Chem. Phys. 21 (1953).
    • W. Hastings, Biometrika 57 (1970).
    • S. Geman & D. Geman, IEEE PAMI 6 (1984); A. Gelfand & A. Smith, JASA 85 (1990).
    • S. Duane, A. Kennedy, B. Pendleton & D. Roweth, Physics Letters B 195 (1987).
  • Sampling.
    • G. Roberts, A. Gelman & W. Gilks, Ann. Appl. Prob. 7 (1997); G. Roberts & J. Rosenthal, JRSS B 60 (1998).
    • J. Albert & S. Chib, JASA 88 (1993); M. Tanner & W. Wong, JASA 82 (1987); J. Liu, JASA 89 (1994).
    • R. Neal, Ann. Stat. 31 (2003) and in the Handbook of MCMC (2011); M. Hoffman & A. Gelman, JMLR 15 (2014).
    • M. Girolami & B. Calderhead, JRSS B 73 (2011); O. Papaspiliopoulos, G. Roberts & M. Sköld, Stat. Sci. 22 (2007).
  • Diagnostics.
    • A. Gelman & D. Rubin, Stat. Sci. 7 (1992).
    • A. Vehtari, A. Gelman, D. Simpson, B. Carpenter & P.-C. Bürkner, Bayesian Analysis 16 (2021).
    • A. Vehtari, D. Simpson, A. Gelman, Y. Yao & J. Gabry, JMLR 25 (2024).
    • J. Zhang & M. Stephens, Technometrics 51 (2009); W. Link & M. Eaton, Methods Ecol. Evol. 3 (2012).
  • SMC.
    • N. Gordon, D. Salmond & A. Smith, IEE Proc. F 140 (1993); P. Del Moral, A. Doucet & A. Jasra, JRSS B 68 (2006).
    • C. Andrieu & G. Roberts, Ann. Stat. 37 (2009); C. Andrieu, A. Doucet & R. Holenstein, JRSS B 72 (2010).
    • T. Bengtsson, P. Bickel & B. Li (2008).
  • Approximations.
    • M. Jordan, Z. Ghahramani, T. Jaakkola & L. Saul, Machine Learning 37 (1999); D. Blei, A. Kucukelbir & J. McAuliffe, JASA 112 (2017).
    • A. Kucukelbir, D. Tran, R. Ranganath, A. Gelman & D. Blei, JMLR 18 (2017); Y. Yao, A. Vehtari, D. Simpson & A. Gelman, ICML (2018).
    • D. Rezende & S. Mohamed, ICML (2015); T. Minka, UAI (2001).
    • H. Rue, S. Martino & N. Chopin, JRSS B 71 (2009).
  • Likelihood-free.
    • J. Pritchard et al., Mol. Biol. Evol. 16 (1999); M. Beaumont, W. Zhang & D. Balding, Genetics 162 (2002).
    • P. Marjoram et al., PNAS 100 (2003); S. Sisson, Y. Fan & M. Tanaka, PNAS 104 (2007); S. Wood, Nature 466 (2010).
  • Exact sampling. J. Propp & D. Wilson, Random Structures & Algorithms 9 (1996); P. Jacob, J. O'Leary & Y. Atchadé, JRSS B 82 (2020).
  • Software. B. Carpenter et al., J. Stat. Software 76 (2017).
  • Books.
    • C. Robert & G. Casella, Monte Carlo Statistical Methods (2nd ed., 2004).
    • S. Brooks, A. Gelman, G. Jones & X.-L. Meng (eds.), Handbook of Markov Chain Monte Carlo (2011).
    • A. Doucet, N. de Freitas & N. Gordon (eds.), Sequential Monte Carlo Methods in Practice (2001).
    • C. Bishop, Pattern Recognition and Machine Learning (2006), chapter 10.
About this partfrom its README

Part 27 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the seventh part of Stage III, Master's. Part 26 integrated over one hyperparameter on a grid. This part computes posteriors no grid can reach:

  • importance sampling, Metropolis–Hastings, Gibbs, and Hamiltonian Monte Carlo with NUTS;
  • diagnostics that can detect failures but cannot prove convergence, and the reparametrization that fixes Neal's funnel;
  • particle methods, variational inference, Laplace and INLA, likelihood-free inference, and exact sampling.

Its centrepiece is statkit.ppl, a small probabilistic programming language built on AI, Built's automatic differentiation and checked against closed-form answers.

It opens with Metropolis, the Rosenbluths and the Tellers' hard disks (1953). Forty disks, uniform proposals, and overlapping moves rejected: 36% of moves accepted, and the lattice melts. Then a random walk on a curved posterior accepts 53% of its proposals.

From there the part covers:

  • Importance sampling.
    • The self-normalized estimator; Kish's ESS. Estimating E x² = 1 under N(0, 1) from 2,000 draws:

      Proposal Estimate ESS k̂
      N(0, 0.5²) 1.309 (1.194 after PSIS) 62 0.93
      N(0, 3²) 1.005 912 −1.59
      t₃ 1.003 1,831 −1.67
    • The optimal proposal: P(X > 3) = 0.00135, with SD 0.00088 naively and 0.000054 from N(3.15, 1), 16 times smaller.

    • Reweighting draws for a new prior or leave-one-out; PSIS and k̂ (Vehtari et al. 2024).

  • Metropolis–Hastings.
    • The Hastings ratio; detailed balance.
    • Traces at three step sizes in 20 dimensions: accepting 88%, 24% and 0.3%. ESS per iteration peaks near 23% acceptance, at about 0.0165 (Roberts, Gelman & Gilks 1997).
    • Scaling with dimension; MALA (0.574).
  • Gibbs.
    • Full conditionals. The zigzag at ρ = 0.95 gives ESS 33 from 2,000 sweeps.
    • Albert & Chib's probit by data augmentation on Bliss's 481 beetles: slope 19.80 (SD 1.51) against the MLE 19.73 (SE 1.48). ESS 226 from 2,500.
    • Blocking, collapsing and reparametrizing; BUGS.
  • Diagnostics.
    • ESS and MCSE; rank-normalized split R̂ (Vehtari et al. 2021).
    • A bimodal target: stuck chains give R̂ 1.53, ESS 7, mean −2.0. Mixing chains give R̂ 1.008, ESS 631.
    • Rank plots; warmup, thinning, MCSE.
  • Hamiltonian Monte Carlo.
    • Hamilton's equations; leapfrog. On a spring, Euler's energy grows from 0.5 to 88 in 60 steps, while leapfrog's error stays below 0.011.
    • The puck on the surface: 25-step trajectories on a correlation-0.9 normal, all accepted.
    • Neal's 100-dimensional normal: 6.3 effective draws per 1,000 gradients against the random walk's 0.045 per 1,000 evaluations, about 140 times better.
    • Tuning ε, L and the mass matrix; Riemannian HMC.
  • NUTS.
    • The U-turn criterion. Three trajectories on a correlation-0.95 normal take 7, 15 and 7 leapfrog steps.
    • Stan's warmup (dual averaging; windowed diagonal metric).
    • The eight schools, non-centred: mostly depth 3, 8.4 steps on average, ε 0.42, R̂(log τ) 1.002, ESS 1,830, no divergences.
    • Divergences; discrete parameters marginalized.
  • Neal's funnel and the eight schools.
    • The funnel. Centred NUTS never enters the neck: the 5% point of v is −2.12 against the true −4.93, with one divergence. Non-centred gives −4.98.

    • The eight schools, τ ~ half-Cauchy(5), μ ~ N(0, 5²), against an independently checked numerical grid (5% point 0.2464, median 2.7487):

      Form Divergences R̂ ESS 5% point of τ Gradients
      centred, δ = 0.8 47 1.049 60 0.90 154,706
      centred, δ = 0.99 4 1.056 75 0.55 496,566
      non-centred 0 1.003 1,909 0.25 78,473
    • QR and scale reparametrizations; centring vs non-centring by data strength (Papaspiliopoulos, Roberts & Sköld 2007).

  • A probabilistic programming language.
    • Models as log densities; autodiff; transforms and Jacobians.
    • The twelve-line eight schools model. Checks against closed forms: a normal mean, a proportion, a Poisson rate, and the eight schools' median τ and E θ_A, with explicit numerical-test tolerances; MCSE is shown for two posterior means.
    • Debugging; Stan, PyMC, NumPyro, Turing.
  • Sequential Monte Carlo.
    • The bootstrap particle filter tracks the Kalman filter on a 60-step local-level series.
    • Log-likelihood estimates: SD 1.20, 0.66 and 0.21 for 50, 200 and 1,000 particles (exact −110.41).
    • Degeneracy; particle MCMC.
    • Tempered SMC evidence for polynomial degrees 1–4 within 0.15 of the exact values, in 5–7 rungs.
  • Variational inference.
    • The ELBO; reverse KL.
    • Mean-field on a correlation-0.9 normal: SDs 0.41 and 0.37 against 1.
    • CAVI for a normal sample: SD(μ) 0.276 against the exact 0.289.
    • ADVI on the eight schools: τ's 90% interval [0.65, 6.66] against NUTS's [0.26, 10.3]; k̂ 0.62.
    • Full-rank, flows, EP.
  • Laplace and INLA.
    • A logistic slope with n = 20: the 95% point is 5.55 by NUTS and 4.77 by Laplace. At n = 400 they agree (2.18, 2.14).
    • Laplace for the evidence; INLA (Rue, Martino & Chopin 2009); a guide to every method.
  • Likelihood-free.
    • Rejection ABC for a Poisson rate (exact posterior mean 2.56, SD 0.40). With the sufficient mean, ε = 0.05 gives 2.58 (SD 0.41), keeping 1 simulation in 79. With the median, it gives 2.10 (SD 0.49): shifted, not just wider.
    • ABC-MCMC and ABC-SMC; regression ABC, synthetic likelihood, neural posterior estimation.
    • The Board.
  • Exact sampling.
    • Coupling from the past (Propp & Wilson 1996) for a 16 × 16 Ising model: coalescence from T = 32 at β = 0.3, and T = 128 at β = 0.42, near the critical point.
    • Unbiased MCMC with couplings (Jacob, O'Leary & Atchadé 2020).

Every number on screen is computed in compute.py:

  • the eight schools and Bliss's beetles are the Museum's;
  • the doctor-visit and polynomial data reuse Parts 24 and 26;
  • the rest are seeded simulations.

Built in this part:

  • statkit.ppl (explainer/stats/kit/ppl.py), checked in tests/test_stats_kit_ppl.py:
    • Models: Model (real/positive/unit supports with Jacobians), with log densities on autodiff Tensors.
    • Samplers:
      • leapfrog, HMC, and NUTS with simplified Stan-inspired warmup;
      • random-walk Metropolis;
      • Albert–Chib Gibbs.
    • Diagnostics: rank-normalized split R̂; bulk, tail and basic ESS; PSIS with k̂.
    • Approximations: mean-field ADVI with its PSIS check; tempered SMC; the bootstrap particle filter and the Kalman filter; rejection ABC.
    • Exact sampling: coupling from the past for the Ising model.
  • statkit.bayes: hier_normal now takes a normal prior on μ.
  • The puck on the surface (PuckSurface in explainer/stats/viz.py): an oblique wireframe of −log π, with trajectories drawn on it.

The Coverage Board gains four rows: simulation-based coverage of 90% intervals for the eight schools' effects. Truths are drawn from the prior (μ ~ N(0, 5²), τ ~ half-Cauchy(5)), 100 simulated data sets, 8 schools each.

Method Independent datasets / intervals Achieved Empirical MCSE Board verdict
numerical grid draws 100 / 800 90.375% 1.397 percentage points kept
NUTS, non-centred 100 / 800 87.875% 1.470 percentage points kept
NUTS, centred 100 / 800 90.750% 1.252 percentage points kept
mean-field ADVI 100 / 800 84.750% 2.007 percentage points kept (short, within the three-MCSE margin)

Each dataset contributes eight correlated interval indicators. MCSE is the standard error of the 100 dataset-level average coverages, not a binomial error treating 800 intervals as independent. All four methods produced valid finite ordered intervals on all 100 datasets. Invalid intervals would count as noncoverage and their dataset counts are stored separately. The simulation is resumable without changing the seeded stream.

These are noisy prior-averaged computational checks, not proof of calibration for every parameter value or dataset. The centred sampler's coverage is close to nominal in this run despite the separate observed-data tau distortion; this does not establish a general lack of effect. ADVI's shortfall is visible even though the Board's coarse three-MCSE rule retains its promise.

Chapter notes
# Chapter Numbers
0 Hard disks, 1953 36% of moves accepted; 53% on the banana
1 Importance sampling 1.309 with k̂ 0.93; tail SD 16× smaller
2 Metropolis–Hastings 88 / 24 / 0.3% acceptance; peak near 0.23
3 Gibbs sampling ESS 33 of 2,000; probit slope 19.80 vs 19.73
4 Diagnostics R̂ 1.53 (stuck) vs 1.008
5 Hamiltonian Monte Carlo Euler 0.5 → 88; leapfrog ±0.011; 140× in 100-D
6 NUTS 7 / 15 / 7 steps; ε 0.42; ESS 1,830
7 Neal's funnel and the eight schools v: −2.12 vs −4.93; τ 5%: 0.90 / 0.55 / 0.25 vs 0.25
8 A probabilistic programming language numerical comparisons with explicit test tolerances
9 Sequential Monte Carlo log-lik SD 1.20 / 0.66 / 0.21; evidence within 0.15
10 Variational inference SD 0.41 vs 1; τ [0.65, 6.66] vs [0.26, 10.3]; k̂ 0.62
11 Laplace and INLA 95% point 5.55 vs 4.77 (n = 20); 2.18 vs 2.14 (n = 400)
12 Likelihood-free inference mean summary 2.58; median summary 2.10 vs exact 2.56
13 Exact sampling T = 32 (β 0.3), 128 (β 0.42)
14 Outro —

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: Metropolis et al. (1953).
  2. Importance sampling. The optimal proposal; ESS; heavy-tailed weights; PSIS.
  3. Metropolis–Hastings. Detailed balance (Part 7); random-walk proposals; the 0.234 rule.
  4. Gibbs (Geman & Geman 1984; Gelfand & Smith 1990). Data augmentation; Albert–Chib probit.
  5. Diagnostics. ESS; R̂ (rank-normalized, Vehtari et al. 2021).
  6. HMC (Duane et al. 1987; Neal 2011). Leapfrog and symplecticity; the puck on the surface in 3D.
  7. NUTS (Hoffman & Gelman 2014). U-turns; adaptation; divergences.
  8. Neal's funnel and the eight schools. Centred vs non-centred.
  9. Built: a tiny probabilistic programming language. AI, Built's autodiff, NUTS, diagnostics, checked against closed-form posteriors.
  10. SMC. Particle filters; tempering; the evidence.
  11. Variational inference. The ELBO; CAVI; reverse KL underestimates variance (vs NUTS); ADVI; PSIS diagnostics.
  12. Laplace and INLA.
  13. Likelihood-free. ABC; neural posterior estimation; SBC (Talts et al. 2018) (Board).
  14. Exact sampling. Coupling from the past (Propp & Wilson 1996).
  15. Outro.

Built: statkit.ppl (the part's centrepiece).

Build the film

python -m videos.stats.stats27.compute        # the part's numbers, into .cache/stats27
python tools/build.py stats27                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats27 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/stats/stats27. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.stats.stats27.compute         # once (about an hour: the Board runs NUTS 200 times)
python tools/build.py stats27 -q l             # fast 480p preview
python tools/build.py stats27                  # 1080p30 -> renders/stats27.mp4
python tools/qa_scene.py stats27 Funnel
python tools/lecture_length.py stats27 --floor 50