The question
Many models have a latent variable for every observation: the population a particle belongs to, the true level behind a noisy reading, the intensity behind a count. Written down as they are thought of, such models hand the sampler as many unknowns as there are rows, plus the handful of parameters we care about. NUTS can do that, and the earlier notebooks of this series let it. The price shows up in three places. Discrete latents cannot be moved by gradients at all, so PyMC falls back on a Gibbs step that visits them one at a time. Continuous latents can, but each of them is tied to the hyperparameters that set its scale, and that coupling is what makes hierarchical posteriors slow to explore (Papaspiliopoulos, Roberts and Sköld 2007). And every draw of every latent has to be stored.
The alternative is as old as the models: do the integral over the latent variables on paper or by a deterministic algorithm, sample only what is left, and compute the latent variables afterwards from their conditional distribution. Three cases cover most of what comes up in practice.
- A sum. A discrete label with a few values is removed by adding up the likelihood over its
values. This is what a mixture density is.
pymc_extras.marginalizedoes it to a model written with explicit labels, andrecoversamples the labels back. - An exact integral. If the latent states are Gaussian and everything is linear, the integral is Gaussian too, and the Kalman filter (Kalman 1960) computes it in one pass over the series. E13 introduced it on 192 months. Here the series has 20,160 steps, and the question becomes which implementation survives that length.
- An approximate integral. If the latent field is Gaussian but the observation is a count, the integral has no closed form. The Laplace approximation replaces the field's conditional distribution by a Gaussian at its mode and integrates that (Tierney and Kadane 1986). Doing so for every value of the hyperparameters, and then integrating over those few numerically, is the idea of INLA (Rue, Martino and Chopin 2009).
The promise that usually comes with these methods is hours to minutes with the same answer, with a footnote: the Laplace approximation can be wrong when the field's conditional distribution is far from Gaussian. We treat both halves as hypotheses. Every model below is simulated, so the truth is known. Every method gets a row on a scoreboard: wall time, memory, effective sample size per second for the hyperparameters, and error and interval coverage against the truth. The picture that goes with it, three times, puts run time and ESS per second as bars beside the overlaid posteriors, so that "faster" and "the same answer" can be read off one figure. Then we go looking for the footnote: we make the counts rarer until the Laplace answer breaks, measure by how much, and work out why.
The sister notebook E125 also uses a Laplace approximation, and the two should not be confused. There
the whole posterior was replaced by a Gaussian (pymc_extras.fit_laplace). Here only the latent
field is, inside the likelihood, one hyperparameter value at a time, and the hyperparameters keep
their exact shape.
| part | question | tool |
|---|---|---|
| 1 | Which population does each particle belong to? | NUTS with a Gibbs step, marginalize, pm.NormalMixture, recover |
| 2 | What is the level behind 20,160 noisy readings? | NUTS on the states, the Kalman filter three ways, a banded smoother |
| 3 | What is the intensity behind 2,000 counts? | NUTS on the field, nested Laplace with banded solvers, importance sampling |
| 4 | Where is the Laplace approximation wrong? | counts made rarer, a binary detector, an exact reference |
| 5 | Does it hold on a real series? | 112 years of coal-mining disasters |
| 6 | Which one, when? | the scoreboard and a decision chart |
import os
for name in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"):
os.environ.setdefault(name, "1") # before NumPy: one BLAS thread per chain
import logging
import sys
import time
import warnings
import arviz as az
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pymc as pm
import pytensor
import pytensor.tensor as pt
import xarray as xr
from matplotlib.patches import FancyArrowPatch, FancyBboxPatch
from pymc.blocking import DictToArrayBijection
from pymc.distributions.transforms import ordered
from pymc_extras.marginal import marginalize, recover
from pymc_extras.statespace import structural as st
from scipy import optimize, special, stats
from scipy.linalg import cho_solve_banded, cholesky_banded, solve_banded
from pymc_challenges import data
from pymc_challenges.scoreboard import Scoreboard, interval_stats
sys.modules.pop("jax", None) # ArviZ's lazy JAX stub; JAX itself is imported in part 2, after the last forked sampler
RANDOM_SEED = 129
rng = np.random.default_rng(RANDOM_SEED)
az.style.use("arviz-variat")
plt.rcParams.update({"axes.labelsize": 10, "xtick.labelsize": 9, "ytick.labelsize": 9, "axes.titlesize": 11})
logging.getLogger("pymc").setLevel(logging.WARNING)
logging.getLogger("pymc_extras").setLevel(logging.ERROR)
warnings.filterwarnings("ignore", category=RuntimeWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
pd.set_option("display.width", 170)
pd.set_option("display.max_columns", 30)
T_START = time.time()
INK, MUTED, LIGHT, GRID = "#222222", "#8a8a8a", "#d9d9d9", "#e1e0d9"
BLUE, ORANGE, AQUA, YELLOW, MAGENTA, VIOLET, RED = (
"#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#6250d6", "#e34948")
CI = 0.9 # every interval in this notebook is a central 90% interval
sb = Scoreboard(ci_prob=CI) # one table for the whole notebook; each row is scored against its own truth
def tidy(ax, grid="y"):
ax.spines[["top", "right"]].set_visible(False)
ax.grid(False)
if grid:
ax.grid(axis=grid, color=GRID, lw=0.6)
ax.set_axisbelow(True)
def flat_draws(idata, names):
"""Posterior draws as a flat dict of 1-D arrays: 'mu', or 'mu[0]', 'mu[1]', ... for a vector."""
out = {}
for name in names:
values = idata.posterior[name].values
values = values.reshape(values.shape[0] * values.shape[1], -1)
for k in range(values.shape[1]):
out[name if values.shape[1] == 1 else f"{name}[{k}]"] = values[:, k]
return out
def diagnostics(idata, names):
"""Smallest bulk ESS and largest r_hat over the named parameters, and the number of divergences."""
ds = idata.posterior.to_dataset()[names]
ess = min(float(v.min()) for v in az.ess(ds, method="bulk").data_vars.values())
rhat = max(float(v.max()) for v in az.rhat(ds).data_vars.values())
return ess, rhat, int(idata.sample_stats["diverging"].sum())
def time_gradient(model, repeats=10):
"""Seconds for one evaluation of a model's log density and its gradient, after compilation."""
logp_dlogp = model.logp_dlogp_function(ravel_inputs=True)
start = model.initial_point()
at = DictToArrayBijection.map({v.name: start[v.name] for v in model.value_vars}).data
logp_dlogp(at)
t0 = time.perf_counter()
for _ in range(repeats):
logp_dlogp(at)
return (time.perf_counter() - t0) / repeats
The figure this notebook adds to the series is drawn by one function. On the left it shows what the scoreboard measured, run time and ESS per second, both on a logarithmic axis. On the right it overlays, for the same methods and in the same colours, the posterior of a few parameters, with the true value as a dashed line. A method earns its bars only if its curve lies on the others.
PALETTE = [ORANGE, BLUE, AQUA, VIOLET, MAGENTA, YELLOW]
def density(ax, values, color, lo, hi, **style):
grid = np.linspace(lo, hi, 300)
values = np.asarray(values, dtype=float)
if np.ptp(values) > 0:
ax.plot(grid, stats.gaussian_kde(values)(grid), color=color, **style)
def bars_and_posteriors(rows, draws, panels, title, truth=None, labels=None):
"""Run time and ESS per second of scoreboard rows as bars, beside the overlaid posteriors of each method."""
table = sb.table().loc[list(rows)]
labels = labels or {}
colors = dict(zip(rows, PALETTE))
fig = plt.figure(figsize=(13.5, max(2.9, 0.5 * len(rows) + 1.8)))
grid = fig.add_gridspec(1, 2 + len(panels), width_ratios=[1.0, 1.0] + [1.3] * len(panels))
y = np.arange(len(rows))[::-1]
for j, (column, name) in enumerate((("seconds", "run time (s)"), ("ess_per_s", "ESS per second"))):
ax = fig.add_subplot(grid[0, j])
values = table[column].to_numpy()
ax.barh(y, values, color=[colors[r] for r in rows], height=0.62)
ax.set_xscale("log")
finite = values[np.isfinite(values)]
ax.set_xlim(finite.min() / 3, finite.max() * 12)
for yi, v in zip(y, values):
if np.isfinite(v):
ax.annotate(f"{v:,.0f}" if v >= 10 else f"{v:.2g}", (v, yi), xytext=(3, 0), textcoords="offset points",
va="center", fontsize=8.5)
else:
ax.text(0.04, yi, "not measured", transform=ax.get_yaxis_transform(), va="center", fontsize=8, color=MUTED)
ax.set_yticks(y, [labels.get(r, r.replace(" · ", "\n")) for r in rows] if j == 0 else [""] * len(rows), fontsize=9)
ax.set_title(name, loc="left", fontsize=10)
ax.minorticks_off()
tidy(ax, grid="x")
for j, (key, name) in enumerate(panels):
ax = fig.add_subplot(grid[0, 2 + j])
shown = [r for r in rows if r in draws]
pooled = np.concatenate([draws[r][key] for r in shown])
lo, hi = np.quantile(pooled, [0.002, 0.998])
lo, hi = lo - 0.08 * (hi - lo), hi + 0.08 * (hi - lo)
for r in shown:
density(ax, draws[r][key], colors[r], lo, hi, lw=1.8, alpha=0.9)
if truth is not None:
ax.axvline(truth[key], color=INK, ls="--", lw=1)
ax.set_yticks([])
ax.set_xlim(lo, hi)
ax.set_title(name, loc="left", fontsize=10)
tidy(ax, grid=None)
fig.suptitle(title, x=0.01, ha="left", fontsize=11)
return fig
1 · A sum: which population does each particle belong to?
An instrument sizes airborne particles one at a time. The sizes, on a standardised log scale, come from three populations that overlap: fine, medium and coarse. Nobody labels the particles. We want the three populations (their shares, centres and spreads) and, for each particle, the probability that it belongs to each of them. The simulated instrument sees 20,000 particles; the head-to-head comparison uses the first 1,000, because that is what the slow method can afford.
K = 3
MIX_TRUTH = {"w": np.array([0.5, 0.3, 0.2]), "mu": np.array([-2.0, 0.5, 3.0]), "sigma": np.array([1.0, 0.6, 1.2])}
N_BIG, N_SMALL = 20_000, 1_000
label_true = rng.choice(K, size=N_BIG, p=MIX_TRUTH["w"])
size = rng.normal(MIX_TRUTH["mu"][label_true], MIX_TRUTH["sigma"][label_true])
y_small, label_small = size[:N_SMALL], label_true[:N_SMALL]
POPULATIONS = ["fine", "medium", "coarse"]
grid = np.linspace(-6, 7.5, 400)
fig, axes = plt.subplots(1, 2, figsize=(13.5, 3.6), sharex=True)
for ax, (y, labels) in zip(axes, ((size, label_true), (y_small, label_small))):
ax.hist([y[labels == k] for k in range(K)], bins=np.linspace(-6, 7.5, 70), stacked=True,
color=[BLUE, AQUA, ORANGE], label=POPULATIONS, density=True)
ax.plot(grid, sum(MIX_TRUTH["w"][k] * stats.norm.pdf(grid, MIX_TRUTH["mu"][k], MIX_TRUTH["sigma"][k]) for k in range(K)),
color=INK, lw=1.2, label="true mixture density")
ax.set_xlabel("particle size (standardised log scale)")
ax.set_yticks([])
ax.set_title(f"{len(y):,} particles, coloured by the label the analyst does not have", loc="left")
tidy(ax, grid=None)
axes[0].legend(frameon=False, fontsize=9);

The model as we think of it
The generative story has a label for every particle:
$$z_i \sim \text{Categorical}(w), \qquad y_i \mid z_i \sim \text{N}(\mu_{z_i}, \sigma_{z_i}),$$
with a Dirichlet prior on the shares $w$, and the centres $\mu$ kept in increasing order so that
"fine" always means the leftmost population. Written this way the model has 9 continuous parameters
and one discrete label per particle. NUTS cannot move a discrete variable, so pm.sample splits the
work without being asked: NUTS for the nine, and a Gibbs step that proposes a new value for each
label in turn. The log below is PyMC's own account of what it chose. A discrete variable also makes
pm.sample leave nutpie for its multiprocess sampler, one process per chain, which is why we ask for
two chains on two cores here and for the default four chains everywhere else.
def labelled_model(y):
with pm.Model() as model:
w = pm.Dirichlet("w", np.ones(K))
mu = pm.Normal("mu", 0, 5, shape=K, transform=ordered)
sigma = pm.HalfNormal("sigma", 2, shape=K)
z = pm.Categorical("z", p=w, shape=len(y))
pm.Normal("y", mu[z], sigma[z], observed=y)
return model
def mix_start(y):
"""Ordered centres need a start that is ordered: three quantiles of the data."""
return {"mu": np.quantile(y, [0.15, 0.55, 0.92]), "sigma": np.full(K, 0.5 * y.std())}
MIX_NAMES = ["w", "mu", "sigma"]
GIBBS_1K = "labels 1k · NUTS + Gibbs on the labels"
logging.getLogger("pymc").setLevel(logging.INFO)
with labelled_model(y_small):
with sb.track(GIBBS_1K):
idata_gibbs = pm.sample(chains=2, cores=2, initvals=mix_start(y_small), random_seed=RANDOM_SEED, progressbar=False)
logging.getLogger("pymc").setLevel(logging.WARNING)
sb.score(GIBBS_1K, idata_gibbs, truth=MIX_TRUTH)
ess, rhat, divergent = diagnostics(idata_gibbs, MIX_NAMES)
print(f"\nsmallest bulk ESS {ess:.0f}, largest r_hat {rhat:.2f}, divergences {divergent}, "
f"wall time {sb.table().loc[GIBBS_1K, 'seconds']:.0f} s for {idata_gibbs.posterior.sizes['draw']} draws in each of "
f"{idata_gibbs.posterior.sizes['chain']} chains")
smallest bulk ESS 23, largest r_hat 1.07, divergences 0, wall time 38 s for 1000 draws in each of 2 chains
The run is healthy by its own lights: no divergences, and both chains in the same region of the parameters. It is slow twice over. It needs most of a minute for 1,000 particles, and the 2,000 draws it returns are worth about two dozen independent ones: the smallest bulk ESS is 23 and the largest r_hat 1.07, where 1.01 is the usual pass mark. The reason is the alternation. Given the labels, NUTS moves the populations only as far as those labels allow; given the populations, the Gibbs step relabels the particles near the boundaries; and the two take turns in small steps.
How does this grow with the data? One Gibbs sweep visits every label, and for each one it evaluates how the model's log density changes. We can time a sweep directly, on the 1,000 particles and on all 20,000, without running a chain.
def time_sweep(y, repeats=2):
"""Seconds for one pass of PyMC's Gibbs step over every label of the model."""
model = labelled_model(y)
with model:
step = pm.CategoricalGibbsMetropolis([model["z"]])
point = model.initial_point()
centres = mix_start(y)["mu"]
point["mu_ordered__"] = np.r_[centres[0], np.log(np.diff(centres))] # the ordered transform, by hand
point, _ = step.step(point)
t0 = time.perf_counter()
for _ in range(repeats):
point, _ = step.step(point)
return (time.perf_counter() - t0) / repeats
sweep_small, sweep_big = time_sweep(y_small), time_sweep(size)
iterations = idata_gibbs.posterior.sizes["draw"] + idata_gibbs.posterior.attrs["tuning_steps"]
gibbs_projected = iterations * sweep_big
GIBBS_BIG = "labels 20k · NUTS + Gibbs on the labels (projected)"
sb.add(GIBBS_BIG, seconds=gibbs_projected)
print(f"one sweep over {N_SMALL:,} labels: {1e3 * sweep_small:.0f} ms ({1e6 * sweep_small / N_SMALL:.0f} microseconds a label)")
print(f"one sweep over {N_BIG:,} labels: {sweep_big:.1f} s ({1e6 * sweep_big / N_BIG:.0f} microseconds a label)")
print(f"{iterations:,} sweeps of a chain at {N_BIG:,} particles: {gibbs_projected / 3600:.1f} hours, the NUTS half not counted")
one sweep over 1,000 labels: 18 ms (18 microseconds a label) one sweep over 20,000 labels: 2.1 s (107 microseconds a label) 2,000 sweeps of a chain at 20,000 particles: 1.2 hours, the NUTS half not counted
A sweep over 1,000 labels takes about 20 ms, one over 20,000 between two and three seconds. The cost per label is not constant, it grows five- to sixfold: PyMC's Gibbs step evaluates the log density of the whole model for every label it proposes, so a sweep is N evaluations of a sum of N terms. At 20,000 particles the 2,000 sweeps of one chain add up to an hour or more, with the NUTS half of every iteration still to come, and nothing suggests that those draws would be worth more than the ones above. This is the one place in the notebook where the slow baseline is counted in hours. We did not run it: its row on the scoreboard is this projection and is labelled as one.
The sum
The labels are only there to say which Normal each particle came from. Adding up over the three possibilities removes them:
$$p(y_i \mid w, \mu, \sigma) = \sum_{k=1}^{3} w_k\, \text{N}(y_i \mid \mu_k, \sigma_k).$$
Nothing is approximated. The nine parameters have the same posterior as before, and the model no
longer contains anything discrete. There are two ways to get there in PyMC. pm.NormalMixture
is the sum written as a distribution. pymc_extras.marginalize takes the model with its labels and
rewrites it: it finds every variable that depends on z, enumerates the values of z, and replaces
the pair by their sum. The second route keeps the generative code, and it leaves a model from which
the labels can be sampled back. (E04 did the same for a single changepoint and E24 for a whole chain
of hidden states, where the sum becomes the forward algorithm.)
def fit_marginalised(y, name):
model = marginalize(labelled_model(y), ["z"])
with model:
with sb.track(name):
idata = pm.sample(initvals=mix_start(y), random_seed=RANDOM_SEED, progressbar=False)
sb.score(name, idata, truth=MIX_TRUTH)
return model, idata
def fit_mixture(y, name):
with pm.Model() as model:
w = pm.Dirichlet("w", np.ones(K))
mu = pm.Normal("mu", 0, 5, shape=K, transform=ordered)
sigma = pm.HalfNormal("sigma", 2, shape=K)
pm.NormalMixture("y", w=w, mu=mu, sigma=sigma, observed=y)
with sb.track(name):
idata = pm.sample(initvals=mix_start(y), random_seed=RANDOM_SEED, progressbar=False)
sb.score(name, idata, truth=MIX_TRUTH)
return idata
MARG_1K, MIX_1K = "labels 1k · marginalize", "labels 1k · NormalMixture"
MARG_BIG, MIX_BIG = "labels 20k · marginalize", "labels 20k · NormalMixture"
marg_small, idata_marg_small = fit_marginalised(y_small, MARG_1K)
idata_mix_small = fit_mixture(y_small, MIX_1K)
marg_big, idata_marg_big = fit_marginalised(size, MARG_BIG)
idata_mix_big = fit_mixture(size, MIX_BIG)
print("free variables after marginalize:", [v.name for v in marg_big.free_RVs])
rows = {}
for name, idata in ((GIBBS_1K, idata_gibbs), (MARG_1K, idata_marg_small), (MIX_1K, idata_mix_small),
(MARG_BIG, idata_marg_big), (MIX_BIG, idata_mix_big)):
ess, rhat, divergent = diagnostics(idata, MIX_NAMES)
rows[name] = {"draws": idata.posterior.sizes["draw"] * idata.posterior.sizes["chain"], "smallest ESS": ess,
"largest r_hat": rhat, "divergences": divergent, "seconds": sb.table().loc[name, "seconds"]}
pd.DataFrame(rows).T.round(2)
free variables after marginalize: ['mu', 'sigma', 'w']
| draws | smallest ESS | largest r_hat | divergences | seconds | |
|---|---|---|---|---|---|
| labels 1k · NUTS + Gibbs on the labels | 2000.0 | 23.12 | 1.07 | 0.0 | 37.95 |
| labels 1k · marginalize | 4000.0 | 645.13 | 1.01 | 0.0 | 4.08 |
| labels 1k · NormalMixture | 4000.0 | 741.90 | 1.01 | 0.0 | 2.09 |
| labels 20k · marginalize | 4000.0 | 928.94 | 1.00 | 0.0 | 23.82 |
| labels 20k · NormalMixture | 4000.0 | 875.41 | 1.00 | 0.0 | 16.90 |
mix_draws = {name: flat_draws(idata, MIX_NAMES) for name, idata in
((GIBBS_1K, idata_gibbs), (MARG_1K, idata_marg_small), (MIX_1K, idata_mix_small))}
flat_truth = {f"{name}[{k}]": MIX_TRUTH[name][k] for name in MIX_NAMES for k in range(K)}
bars_and_posteriors([GIBBS_1K, MARG_1K, MIX_1K], mix_draws,
[("mu[2]", "centre, coarse"), ("sigma[1]", "spread, medium"), ("w[0]", "share, fine")],
f"The first {N_SMALL:,} particles, three ways: cost on the left, the posterior each method reports on the right",
truth=flat_truth);

The table and the figure tell the same story from two sides. On the first 1,000 particles the three curves in each panel lie on each other, as they must: these are three samplers for one posterior. The orange curve is ragged because it is drawn from two dozen effective draws. The bars say what that agreement cost: the two marginalised fits take a few seconds and return several hundred effective draws, a few hundred times as many per second as the sampler with labels.
At 20,000 particles both marginalised fits finish in well under a minute, with r_hat at 1.00. The
gradient is a sum over 20,000 rows of three Normal densities, nothing more. marginalize is the
slower of the two, by a third to a half in our runs: the rewritten model computes the same density through a more
general graph than the hand-written mixture. That is the price of keeping the labels in the model,
and what it buys is the next step.
One caution belongs here, because a mixture is the textbook example of a posterior with several
modes. Every fit here starts from three quantiles of the data as centres. While preparing this
notebook, a start that ignored the data (centres at -1, 0 and 1) left one chain of four in a
labelling where two components share one population, with r_hat 1.5. marginalize does not protect
against that any more than pm.NormalMixture does: it removes the labels, not the modes.
Getting the labels back
The labels were summed out, not thrown away. Given the nine parameters, each particle's label has a conditional distribution that we can write down,
$$\Pr(z_i = k \mid y_i, w, \mu, \sigma) = \frac{w_k\, \text{N}(y_i \mid \mu_k, \sigma_k)}{\sum_j w_j\, \text{N}(y_i \mid \mu_j, \sigma_j)},$$
and recover samples from it once for every posterior draw it is given. We give it every tenth draw:
400 draws of 20,000 labels are 8 million integers, and all 4,000 would be 640 MB. (In older releases
the function was called recover_marginals and returned log-probabilities as well. In
pymc_extras 0.15 that name is a deprecated alias, recover returns samples only, and with
extend_inferencedata=False it returns an xarray Dataset.) The share of draws in which a particle
gets label $k$ estimates its membership probability. Averaging the formula over the same draws gives
the same number without the sampling noise, and serves as the check.
def membership(y, idata):
"""Membership probabilities from the formula, averaged over the posterior draws."""
post = az.extract(idata, var_names=MIX_NAMES)
w, mu, sigma = (post[name].values.T for name in MIX_NAMES)
out = np.zeros((len(y), K))
for i in range(len(w)):
logp = np.log(w[i]) + stats.norm.logpdf(y[:, None], mu[i], sigma[i])
out += special.softmax(logp, axis=1)
return out / len(w)
def label_score(prob, truth):
"""How good membership probabilities are, against the true labels."""
return {"accuracy of the most probable label": (prob.argmax(axis=1) == truth).mean(),
"mean probability given to the true label": prob[np.arange(len(truth)), truth].mean()}
t0 = time.perf_counter()
thinned = idata_marg_big.isel(draw=slice(None, None, 10))
labels_back = recover(thinned, model=marg_big, random_seed=RANDOM_SEED, extend_inferencedata=False)["z"].values.reshape(-1, N_BIG)
recover_seconds = time.perf_counter() - t0
prob_recover = np.stack([(labels_back == k).mean(axis=0) for k in range(K)], axis=1)
prob_formula = membership(size, thinned)
labels_gibbs = idata_gibbs.posterior["z"].values.reshape(-1, N_SMALL)
prob_gibbs = np.stack([(labels_gibbs == k).mean(axis=0) for k in range(K)], axis=1)
prob_small = membership(y_small, idata_marg_small)
truth_prob = special.softmax(np.log(MIX_TRUTH["w"]) + stats.norm.logpdf(size[:, None], MIX_TRUTH["mu"], MIX_TRUTH["sigma"]), axis=1)
print(f"recover: {labels_back.shape[0]} draws of {N_BIG:,} labels in {recover_seconds:.1f} s; "
f"largest gap between its frequencies and the formula {np.abs(prob_recover - prob_formula).max():.3f}")
label_table = pd.DataFrame({
f"{N_SMALL:,} particles · NUTS + Gibbs": label_score(prob_gibbs, label_small),
f"{N_SMALL:,} particles · marginalize, labels from the formula": label_score(prob_small, label_small),
f"{N_BIG:,} particles · marginalize + recover": label_score(prob_recover, label_true),
f"{N_BIG:,} particles · the true parameters (the best possible)": label_score(truth_prob, label_true),
}).T
label_table.round(3)
recover: 400 draws of 20,000 labels in 0.9 s; largest gap between its frequencies and the formula 0.088
| accuracy of the most probable label | mean probability given to the true label | |
|---|---|---|
| 1,000 particles · NUTS + Gibbs | 0.907 | 0.843 |
| 1,000 particles · marginalize, labels from the formula | 0.908 | 0.840 |
| 20,000 particles · marginalize + recover | 0.917 | 0.873 |
| 20,000 particles · the true parameters (the best possible) | 0.918 | 0.875 |
confidence = prob_recover.max(axis=1)
correct = prob_recover.argmax(axis=1) == label_true
bins = [0.34, 0.6, 0.8, 0.95, 1.0001]
calibration = pd.DataFrame({
"particles": [np.sum((confidence >= lo) & (confidence < hi)) for lo, hi in zip(bins[:-1], bins[1:])],
"mean stated probability": [confidence[(confidence >= lo) & (confidence < hi)].mean() for lo, hi in zip(bins[:-1], bins[1:])],
"share correct": [correct[(confidence >= lo) & (confidence < hi)].mean() for lo, hi in zip(bins[:-1], bins[1:])],
}, index=[f"{lo:.2f} to {min(hi, 1):.2f}" for lo, hi in zip(bins[:-1], bins[1:])])
calibration.index.name = "probability of the most probable label"
order = np.argsort(size)[::40]
fig, ax = plt.subplots(figsize=(13.5, 3.4))
for k, color in enumerate((BLUE, AQUA, ORANGE)):
ax.scatter(size[order], prob_recover[order, k], s=7, color=color, alpha=0.55, lw=0,
label=f"{POPULATIONS[k]}: share of recovered labels" if k == 0 else POPULATIONS[k])
ax.plot(size[order], truth_prob[order, k], color=INK, lw=0.9, label="from the true parameters" if k == 0 else None)
ax.set_xlabel("particle size")
ax.set_ylabel("membership probability")
ax.set_xlim(-5, 6.5)
ax.legend(frameon=False, fontsize=9, ncols=4, loc="upper center", bbox_to_anchor=(0.5, 1.2))
tidy(ax)
calibration.round(3)
| particles | mean stated probability | share correct | |
|---|---|---|---|
| probability of the most probable label | |||
| 0.34 to 0.60 | 801 | 0.547 | 0.556 |
| 0.60 to 0.80 | 2296 | 0.710 | 0.727 |
| 0.80 to 0.95 | 5999 | 0.893 | 0.894 |
| 0.95 to 1.00 | 10904 | 0.996 | 0.997 |

The recovered labels are as good as labels can be on these data. Their most probable value is right
for 91.7% of the 20,000 particles, against 91.8% for an analyst who knew the true populations: the
remaining 8% are particles in the overlaps, which no method can assign. The probabilities are
honest as well as sharp. Among the particles whose most probable label was given a probability near
0.55, 56% have that label; near 0.71, 73%; near 0.89, 89%. The dots in the figure are recover's
frequencies and the lines the membership probabilities at the true parameters; the scatter around
the lines is the noise of 400 draws (the largest gap from the formula is under 0.1), and the formula
itself is free of it.
The sampler with labels, on its 1,000 particles, assigns them about as well as the marginalised fit of the same particles. The labels were never its problem. The nine parameters were.
The choice.
marginalizeon the model written with its labels, thenrecover. Rejected: NUTS with a Gibbs step on the labels, which gave the same posterior on 1,000 particles at a few hundred times the cost per effective draw and would need an hour or more for one chain at 20,000; and, narrowly,pm.NormalMixture, which is the same density and somewhat faster but has no labels to give back. What would change our mind: labels that depend on each other in a way no cheap sum untangles (neighbouring pixels, a matching between two files), where the sum has $K^N$ terms and a sampler over the labels is all there is; or a plain mixture whose labels nobody wants, wherepm.NormalMixtureis the shorter program.
2 · An exact integral: the level behind 20,160 noisy readings
A second instrument reports a concentration, on a standardised scale, once a minute. The quantity itself moves slowly around a mean level, and each reading adds noise of its own:
$$x_t - \mu = \rho\,(x_{t-1} - \mu) + \sigma\,\eta_t, \qquad y_t = x_t + s\,\varepsilon_t, \qquad \eta_t, \varepsilon_t \sim \text{N}(0, 1),$$
with $x_1$ drawn from the stationary distribution $\text{N}(\mu, \sigma^2 / (1 - \rho^2))$. Two weeks of minutes are 20,160 readings. There are four hyperparameters, the level $\mu$, the persistence $\rho$, the size $\sigma$ of the minute-to-minute changes and the noise $s$ of the instrument, and 20,160 latent states $x_t$, which are what the instrument's owner wants: the concentration without the noise. The noise is three times as large as a minute's change, so a single reading says little, and the model has to decide how many neighbouring readings to average. That decision is $\rho$, $\sigma$ and $s$.
STATE_TRUTH = {"mu": 2.0, "rho": 0.95, "sigma": 0.3, "s": 1.0}
STATE_NAMES = list(STATE_TRUTH)
T_BIG, T_SMALL = 20_160, 5_040
def simulate_ar1(n, mu, rho, sigma, rng):
x = np.empty(n)
x[0] = rng.normal(0, sigma / np.sqrt(1 - rho**2))
shocks = rng.normal(0, sigma, n)
for t in range(1, n):
x[t] = rho * x[t - 1] + shocks[t]
return mu + x
state_true = simulate_ar1(T_BIG, STATE_TRUTH["mu"], STATE_TRUTH["rho"], STATE_TRUTH["sigma"], rng)
reading = state_true + rng.normal(0, STATE_TRUTH["s"], T_BIG)
print(f"{T_BIG:,} readings; sd of the level {state_true.std():.2f}, sd of the instrument's noise {STATE_TRUTH['s']:.2f}")
20,160 readings; sd of the level 0.97, sd of the instrument's noise 1.00
The slow baseline: NUTS on every state
The model as written above is four lines of PyMC. pm.AR holds the states, and we write it around
its own mean (the constant is $\mu(1 - \rho)$) so that $\mu$ is the level of the path and not a
second intercept competing with it. NUTS then has 4 + T unknowns. We run it on the first quarter of
the series, 5,040 minutes. The whole series does run, and we come back to it below, but it does
not fit the memory budget of this notebook: nutpie stores every free variable, and var_names only
drops deterministics, so 4,000 draws of 20,160 states are 645 MB before anything is done with them.
def state_priors():
mu = pm.Normal("mu", 0, 5)
rho = pm.Beta("rho", 5, 1.5)
sigma = pm.HalfNormal("sigma", 1)
s = pm.HalfNormal("s", 2)
return mu, rho, sigma, s
def states_model(y):
with pm.Model() as model:
mu, rho, sigma, s = state_priors()
x = pm.AR("x", rho=pt.stack([mu * (1 - rho), rho]), sigma=sigma, constant=True,
init_dist=pm.Normal.dist(mu, sigma / pt.sqrt(1 - rho**2)), steps=len(y) - 1)
pm.Normal("y", x, s, observed=y)
return model
def thin_field(idata, name="x", keep=400):
"""Every k-th draw of a latent path, as float32: enough to score it, small enough to keep."""
values = idata.posterior[name].values
values = values.reshape(-1, values.shape[-1])
return values[:: max(1, len(values) // keep)].astype(np.float32)
NUTS_5K = "states 5k · NUTS on the states"
y_quarter, x_quarter = reading[:T_SMALL], state_true[:T_SMALL]
with states_model(y_quarter):
with sb.track(NUTS_5K):
idata_states = pm.sample(random_seed=RANDOM_SEED, progressbar=False)
ess_states, rhat_states, div_states = diagnostics(idata_states, STATE_NAMES)
ess_each = az.ess(idata_states.posterior.to_dataset()[STATE_NAMES], method="bulk")
rhat_each = az.rhat(idata_states.posterior.to_dataset()[STATE_NAMES])
gradients_states = int(idata_states.sample_stats["n_steps"].sum())
state_draws = {NUTS_5K: flat_draws(idata_states, STATE_NAMES)}
field_states = thin_field(idata_states)
sb.score(NUTS_5K, {"x": field_states}, truth={"x": x_quarter}, ess=ess_states)
del idata_states
seconds_states = sb.table().loc[NUTS_5K, "seconds"]
print(f"{T_SMALL:,} states + 4 hyperparameters: {seconds_states:.0f} s, {gradients_states:,} gradients after warm-up "
f"({gradients_states / 4000:.0f} a draw), divergences {div_states}")
print(f"hyperparameters: smallest bulk ESS {ess_states:.0f} of 4,000 draws, largest r_hat {rhat_states:.3f}")
pd.DataFrame({"bulk ESS": {k: float(ess_each[k]) for k in STATE_NAMES}, "r_hat": {k: float(rhat_each[k]) for k in STATE_NAMES}}).round(3)
5,040 states + 4 hyperparameters: 10 s, 437,856 gradients after warm-up (109 a draw), divergences 0 hyperparameters: smallest bulk ESS 60 of 4,000 draws, largest r_hat 1.058
| bulk ESS | r_hat | |
|---|---|---|
| mu | 4273.631 | 1.000 |
| rho | 182.489 | 1.024 |
| sigma | 60.376 | 1.058 |
| s | 678.432 | 1.006 |
Ten to twenty seconds for 5,044 unknowns is not slow, and that needs saying, because the folklore about this baseline says hours. One gradient of this model is a handful of vectorised operations, and nutpie evaluates more than 400,000 of them in that time. The trouble is in what the draws are worth. Each one costs about 110 gradients, and after 4,000 of them the smallest effective sample size among the four hyperparameters is about 60, with an r_hat of 1.06. By the usual standard this fit has not converged. The table says which parameters are responsible: the level $\mu$ and the instrument's noise $s$ are sampled well, and the two that describe the path, $\rho$ and $\sigma$, are not. They set the scale and smoothness of 5,040 states, and can only move as fast as all the states move with them.
The integral, and three ways to compute it
Given the hyperparameters, the states and the readings are jointly Gaussian, so the density of the readings alone, with the states integrated out, is Gaussian too. The Kalman filter computes it without ever forming a 20,160 by 20,160 covariance matrix. It walks through the series once and keeps two numbers, the mean $a_t$ and variance $p_t$ of the state given the readings so far:
$$f_t = p_t + s^2, \quad v_t = y_t - \mu - a_t, \quad k_t = p_t / f_t, \qquad a_{t+1} = \rho\,(a_t + k_t v_t), \quad p_{t+1} = \rho^2 p_t (1 - k_t) + \sigma^2 .$$
Each reading is predicted from the past with error $v_t$ and variance $f_t$, and the log-likelihood
is the sum of those one-step predictions, $\sum_t \log \text{N}(v_t \mid 0, f_t)$. E13 derives the
recursion and checks it against pymc_extras.statespace on 192 months. What changes at 20,160
steps is the cost of the gradient, because NUTS differentiates through every step of the loop.
Before writing anything we check what exists. Three implementations of the same recursion are on
offer in this environment:
pymc_extras.statespace, the general package: any linear-Gaussian model, matrices and all;- the scalar recursion above in
pytensor.scan; - the same recursion in
jax.lax.scan, brought into the model withpytensor.wrap_jax.
We build all three on the full series and time one gradient of each.
import jax # from here on no sampler forks, so JAX can be loaded (see AUTHORING, "Fork after JAX")
import jax.numpy as jnp
jax.config.update("jax_enable_x64", True)
def kalman_model(y):
"""The four hyperparameters, with the states integrated out by a Kalman filter written in JAX."""
y_jax = jnp.asarray(y)
def loglik(mu, rho, sigma, s):
def step(carry, y_t):
a, p = carry # mean and variance of x_t - mu given the readings before t
f = p + s**2 # variance of the prediction of y_t
v = y_t - mu - a # its error
k = p / f # the Kalman gain: how far to move towards the reading
return (rho * (a + k * v), rho**2 * p * (1 - k) + sigma**2), -0.5 * (jnp.log(2 * jnp.pi * f) + v**2 / f)
_, terms = jax.lax.scan(step, (jnp.zeros(()), sigma**2 / (1 - rho**2)), y_jax)
return terms.sum()
with pm.Model() as model:
mu, rho, sigma, s = state_priors()
pm.Potential("loglik", pytensor.wrap_jax(loglik)(mu, rho, sigma, s))
return model, loglik
def scan_model(y):
"""The same filter in pytensor.scan."""
def step(y_t, a, p, total, mu, rho, sigma, s):
f = p + s**2
v = y_t - mu - a
k = p / f
return rho * (a + k * v), rho**2 * p * (1 - k) + sigma**2, total - 0.5 * (pt.log(2 * np.pi * f) + v**2 / f)
with pm.Model() as model:
mu, rho, sigma, s = state_priors()
_, _, total = pytensor.scan(step, sequences=[pt.as_tensor(y)], non_sequences=[mu, rho, sigma, s],
outputs_info=[pt.zeros(()), sigma**2 / (1 - rho**2), pt.zeros(())], return_updates=False)
pm.Potential("loglik", total[-1])
return model
def statespace_model(y):
"""The package: an AR(1) component plus measurement error, on the readings minus their mean."""
series = pd.Series(y - y.mean(), index=pd.date_range("2025-03-03", periods=len(y), freq="min"), name="reading")
module = (st.AutoregressiveComponent(order=1, name="ar") + st.MeasurementError(name="obs")).build(name="ar1", verbose=False)
with pm.Model(coords=module.coords) as model:
rho = pm.Beta("params_ar", 5, 1.5, dims=module.param_dims["params_ar"])
sigma = pm.HalfNormal("sigma_ar", 1)
pm.HalfNormal("sigma_obs", 2)
pm.Deterministic("P0", sigma**2 / (1 - rho[0] ** 2) * pt.eye(1), dims=module.param_dims["P0"])
module.build_statespace_graph(series)
return model
def ar1_precision(n, rho, sigma):
"""Precision matrix of a stationary AR(1) path, as the two bands SciPy's banded solvers take."""
band = np.empty((2, n))
band[1] = (1 + rho**2) / sigma**2 # the diagonal ...
band[1, [0, -1]] = 1 / sigma**2 # ... lighter at the two ends
band[0] = -rho / sigma**2 # the first off-diagonal (its entry 0 is not used)
return band
def gaussian_loglik(y, mu, rho, sigma, s):
"""log p(y | hyperparameters) for the linear-Gaussian model, from two banded Cholesky factors and no filter."""
n, r = len(y), y - mu
posterior = ar1_precision(n, rho, sigma)
posterior[1] += 1 / s**2 # precision of the states given the readings
chol = cholesky_banded(posterior)
mean = cho_solve_banded((chol, False), r / s**2)
log_det_prior = np.log(1 - rho**2) - 2 * n * np.log(sigma)
return (-0.5 * n * np.log(2 * np.pi) - n * np.log(s) + 0.5 * log_det_prior - np.log(chol[1]).sum()
- 0.5 * (r @ r / s**2 - r @ mean / s**2))
kalman_big, loglik_big = kalman_model(reading)
check = (float(loglik_big(*STATE_TRUTH.values())), gaussian_loglik(reading, *STATE_TRUTH.values()))
print(f"log-likelihood of the {T_BIG:,} readings at the true hyperparameters: Kalman filter {check[0]:.6f}, "
f"banded closed form {check[1]:.6f}")
gradient_ms = {}
for name, model in (("pymc_extras.statespace", statespace_model(reading)), ("pytensor.scan", scan_model(reading)),
("jax.lax.scan through wrap_jax", kalman_big)):
gradient_ms[name] = 1e3 * time_gradient(model)
gradient_ms["NUTS on the states (one gradient of 20,164 unknowns)"] = 1e3 * time_gradient(states_model(reading), repeats=50)
pd.DataFrame({f"one gradient at {T_BIG:,} steps (ms)": gradient_ms}).round(2)
log-likelihood of the 20,160 readings at the true hyperparameters: Kalman filter -31252.088599, banded closed form -31252.088599
| one gradient at 20,160 steps (ms) | |
|---|---|
| pymc_extras.statespace | 34.43 |
| pytensor.scan | 9.31 |
| jax.lax.scan through wrap_jax | 0.73 |
| NUTS on the states (one gradient of 20,164 unknowns) | 0.09 |
All three compute the same number, and the line above the table checks the recursion against a
closed form that uses no filter at all: they agree to six decimals at 20,160 steps. Their gradients
differ by a factor of forty or more. The package needs 30 to 40 ms, the pytensor.scan loop about
10 ms, the JAX loop under 1 ms. The package pays for its generality: it carries matrices where this
model has scalars, with the safeguards a general filter needs and a scalar recursion does not. For the
structural models of E13, with fifteen states over 192 months, that is the right trade. scan pays
an overhead at each of its 20,160 steps, forwards and backwards. JAX compiles the loop and its
reverse pass into one program.
The last row is the surprise. A gradient of the slow model, states and all, costs a tenth to a fifth of a millisecond, several times less than the best filter's. The baseline is not slow because its gradient is expensive. Its problem is how many gradients a draw takes and how little each draw is worth.
The fit, at both lengths
def fit_kalman(model, y, name):
with model:
with sb.track(name):
idata = pm.sample(random_seed=RANDOM_SEED, progressbar=False,
compile_kwargs={"backend": "jax", "gradient_backend": "jax"})
return idata
def smoother_draws(y, hyper, rng, keep=400):
"""One joint draw of all the states for each of `keep` posterior draws of the hyperparameters."""
pick = np.linspace(0, len(hyper["mu"]) - 1, keep).astype(int)
out = np.empty((keep, len(y)), dtype=np.float32)
for i, j in enumerate(pick):
mu, rho, sigma, s = (hyper[name][j] for name in STATE_NAMES)
band = ar1_precision(len(y), rho, sigma)
band[1] += 1 / s**2 # precision of the states given the readings
chol = cholesky_banded(band) # upper factor: precision = U'U
mean = mu + cho_solve_banded((chol, False), (y - mu) / s**2)
out[i] = mean + solve_banded((0, 1), chol, rng.standard_normal(len(y))) # U^-1 z has the right covariance
return out
KALMAN_5K, KALMAN_BIG = "states 5k · Kalman filter", "states 20k · Kalman filter"
kalman_small, _ = kalman_model(y_quarter)
fields, kalman_stats = {NUTS_5K: field_states}, {}
for name, model, y, truth in ((KALMAN_5K, kalman_small, y_quarter, x_quarter), (KALMAN_BIG, kalman_big, reading, state_true)):
idata = fit_kalman(model, y, name)
fit_seconds = sb.table().loc[name, "seconds"]
ess, rhat, divergent = diagnostics(idata, STATE_NAMES)
state_draws[name] = flat_draws(idata, STATE_NAMES)
t0 = time.perf_counter()
fields[name] = smoother_draws(y, state_draws[name], rng)
smoother_seconds = time.perf_counter() - t0
sb.add(name, seconds=fit_seconds + smoother_seconds)
sb.score(name, {"x": fields[name]}, truth={"x": truth}, ess=ess)
kalman_stats[name] = {"fit (s)": fit_seconds, "smoother, 400 draws (s)": smoother_seconds, "smallest ESS": ess,
"largest r_hat": rhat, "divergences": divergent,
"gradients after warm-up": int(idata.sample_stats["n_steps"].sum())}
del idata
needed = kalman_stats[KALMAN_BIG]["gradients after warm-up"]
print(f"the {needed:,} gradients of the fit at {T_BIG:,} steps, one after the other: "
+ ", ".join(f"{name} {needed * ms / 60e3:.1f} min" for name, ms in list(gradient_ms.items())[:3]))
pd.DataFrame(kalman_stats).T.round(3)
the 17,948 gradients of the fit at 20,160 steps, one after the other: pymc_extras.statespace 10.3 min, pytensor.scan 2.8 min, jax.lax.scan through wrap_jax 0.2 min
| fit (s) | smoother, 400 draws (s) | smallest ESS | largest r_hat | divergences | gradients after warm-up | |
|---|---|---|---|---|---|---|
| states 5k · Kalman filter | 2.028 | 0.089 | 2188.010 | 1.001 | 0.0 | 17830.0 |
| states 20k · Kalman filter | 4.887 | 0.321 | 1890.543 | 1.001 | 0.0 | 17948.0 |
With the states gone, NUTS has a four-dimensional posterior that is close to Gaussian. It takes
four or five gradients a draw where the baseline took 110, every chain agrees with every other
(r_hat 1.00), and the smallest ESS is about 2,000 of 4,000 draws at both lengths. The full series
takes a few seconds more than the quarter, part of both being compilation. The same 18,000
gradients would have taken about three minutes with the scan filter and about ten with the
package, single-threaded, which is the whole case for timing the candidates before choosing one.
The states, afterwards
The filter never held the states, and they are the point of the exercise. Given the
hyperparameters, the states have a Gaussian distribution given all the readings, with precision
matrix $Q(\rho, \sigma) + I / s^2$: the prior precision of an AR(1) path, which is tridiagonal, plus
what the readings add on the diagonal. A banded Cholesky factor gives its mean in one solve and a
joint draw in another (Rue 2001), at a cost proportional to T. smoother_draws above does that for
400 posterior draws of the hyperparameters, one path each, which is the simulation smoother of the
state-space literature (Durbin and Koopman 2002) in the form used for Gaussian Markov random fields.
The same factor is what gaussian_loglik used to check the filter: the Kalman filter and the banded
factorisation are two orders of doing the same elimination.
def field_table(fields, truths):
rows = {}
for name, draws in fields.items():
covered, width, error = interval_stats(draws, truths[name], CI)
rows[name] = {"RMSE of the posterior mean": np.sqrt(np.mean(error**2)), "coverage of 90% intervals": covered.mean(),
"mean interval width": width.mean()}
return pd.DataFrame(rows).T
window = slice(1000, 1360)
minutes = np.arange(T_BIG)[window]
fig, ax = plt.subplots(figsize=(13.5, 3.8))
ax.scatter(minutes, reading[window], s=6, color=MUTED, alpha=0.6, lw=0, label="readings")
for name, color in ((NUTS_5K, ORANGE), (KALMAN_5K, BLUE)):
lo, hi = np.quantile(fields[name][:, window], [0.05, 0.95], axis=0)
ax.fill_between(minutes, lo, hi, color=color, alpha=0.25, lw=0)
ax.plot(minutes, fields[name][:, window].mean(axis=0), color=color, lw=1.6, label=name.split(" · ")[1] + ": mean and 90% band")
ax.plot(minutes, state_true[window], color=INK, lw=1.0, label="true level")
ax.set_xlabel("minute")
ax.set_ylabel("concentration")
ax.legend(frameon=False, fontsize=9, ncols=4, loc="upper center", bbox_to_anchor=(0.5, 1.17))
tidy(ax)
raw_error = np.sqrt(np.mean((reading - state_true) ** 2))
print(f"RMSE of the raw readings against the true level: {raw_error:.3f}")
field_table(fields, {NUTS_5K: x_quarter, KALMAN_5K: x_quarter, KALMAN_BIG: state_true}).round(3)
RMSE of the raw readings against the true level: 0.999
| RMSE of the posterior mean | coverage of 90% intervals | mean interval width | |
|---|---|---|---|
| states 5k · NUTS on the states | 0.400 | 0.894 | 1.299 |
| states 5k · Kalman filter | 0.399 | 0.894 | 1.294 |
| states 20k · Kalman filter | 0.388 | 0.902 | 1.294 |

NUTS_BIG = "states 20k · NUTS on the states (run outside)"
# the baseline on all 20,160 readings: the same model and data, run once outside the notebook under the 3 GB guard
OUTSIDE_STATES = {"seconds": 55.5, "peak_gb": 2.28, "ess": 65.6, "rhat": 1.063,
"posterior": {"mu": (2.0455, 0.0430), "rho": (0.9467, 0.0033), "sigma": (0.3150, 0.0081), "s": (0.9942, 0.0062)}}
sb.add(NUTS_BIG, seconds=OUTSIDE_STATES["seconds"], peak_gb=OUTSIDE_STATES["peak_gb"], ess=OUTSIDE_STATES["ess"])
print(f"baseline on {T_BIG:,} readings, scaled from the quarter by the number of steps alone: at least "
f"{seconds_states * T_BIG / T_SMALL:.0f} s; measured once outside this notebook: {OUTSIDE_STATES['seconds']:.0f} s, "
f"{OUTSIDE_STATES['peak_gb']:.1f} GB, smallest ESS {OUTSIDE_STATES['ess']:.0f}, r_hat {OUTSIDE_STATES['rhat']:.2f}\n")
both = pd.DataFrame({name: {"Kalman filter, mean": state_draws[KALMAN_BIG][name].mean(), "Kalman filter, sd": state_draws[KALMAN_BIG][name].std(),
"NUTS on the states (outside), mean": OUTSIDE_STATES["posterior"][name][0],
"NUTS on the states (outside), sd": OUTSIDE_STATES["posterior"][name][1]} for name in STATE_NAMES}).T
both["difference (Kalman sds)"] = (both.iloc[:, 2] - both.iloc[:, 0]) / both.iloc[:, 1]
print(both.assign(truth=pd.Series(STATE_TRUTH)).round(4).to_string())
bars_and_posteriors([NUTS_5K, KALMAN_5K, KALMAN_BIG, NUTS_BIG], {k: state_draws[k] for k in (NUTS_5K, KALMAN_5K)},
[("rho", "persistence ρ"), ("sigma", "change σ"), ("s", "instrument noise s")],
f"Bars: both lengths. Curves: the two fits of the first {T_SMALL:,} readings, which should coincide",
truth=STATE_TRUTH);
baseline on 20,160 readings, scaled from the quarter by the number of steps alone: at least 40 s; measured once outside this notebook: 56 s, 2.3 GB, smallest ESS 66, r_hat 1.06
Kalman filter, mean Kalman filter, sd NUTS on the states (outside), mean NUTS on the states (outside), sd difference (Kalman sds) truth
mu 2.0456 0.0426 2.0455 0.0430 -0.0030 2.00
rho 0.9465 0.0032 0.9467 0.0033 0.0508 0.95
sigma 0.3156 0.0078 0.3150 0.0081 -0.0824 0.30
s 0.9938 0.0062 0.9942 0.0062 0.0606 1.00
On the first 5,040 readings the two fits give the same answer for everything we can compare. The bands in the upper figure cover each other so closely that one colour hides the other. The table puts numbers on it: the posterior mean of the states is 0.40 from the truth by either route, against 1.00 for the raw readings, and the 90% intervals hold the true level 89% of the time, both with the same width. The posteriors of $\rho$, $\sigma$ and $s$ in the lower figure coincide up to the wobble of the baseline's 60 effective draws.
The bars are where the routes part. On the quarter series the filter is several times faster in wall time and a hundred times or more faster per effective draw. On the full series the comparison needs the run we could not hold in this notebook's memory. Run once outside it, with the same model and the same 20,160 readings, NUTS on the states took 56 seconds, held 2.3 GB at its peak, and came back with an ESS of 66 and an r_hat of 1.06. The filter needs a few seconds, smoother included, for an ESS near 1,900. The two posteriors, side by side in the small table, agree within a tenth of a standard deviation on all four hyperparameters. An ESS of 66 does not make the baseline's answer wrong. It makes its Monte Carlo error five times the filter's, and its r_hat a reason not to report it.
So the first half of the hypothesis holds in substance and fails in its units. The answer is the same. The gain is not hours to minutes: it is a minute to a few seconds in wall time, a factor in the hundreds in effective draws per second, and 2.3 GB to almost nothing in memory. Getting 400 effective draws out of the baseline would take about six minutes at this rate, if it scaled, where the filter delivers 1,900 in those few seconds.
The choice. The Kalman filter as a
jax.lax.scaninside the model for the likelihood, and a banded factorisation for the states afterwards. Rejected:pymc_extras.statespaceat this length (the same number at forty times the cost per gradient or more; it remains the tool for a structural model with trend, seasons and regressors over a few hundred steps, where its bookkeeping is worth far more than its speed); thepytensor.scanfilter (a dozen times the cost); NUTS on the states (correct, and useful as the check on 5,040 steps, but not converged with default settings and too large to store at 20,160). What would change our mind: an observation that is not Gaussian, or a state equation that is not linear. Then there is no filter of two numbers, and the next part begins.
3 · An approximate integral: the intensity behind 2,000 counts
The third instrument counts particles: an integer every minute, and the quantity behind it is again a slowly moving level, now on the log scale,
$$x_t - \mu = \rho\,(x_{t-1} - \mu) + \sigma\,\eta_t, \qquad y_t \mid x_t \sim \text{Poisson}(e^{x_t}).$$
This is the model of part 2 with the Gaussian reading replaced by a count. The latent field $x$ is still Gaussian given the hyperparameters $\theta = (\mu, \rho, \sigma)$. The integral over it is no longer available: the product of a Gaussian prior and 2,000 Poisson terms is not a Gaussian in $x$, and no filter of two numbers per step describes it.
COUNT_TRUTH = {"mu": 1.5, "rho": 0.95, "sigma": 0.25}
COUNT_NAMES = list(COUNT_TRUTH)
COUNT_PRIOR = {"mu": (0.0, 3.0), "rho": (5.0, 1.5), "sigma": 1.0} # Normal(mean, sd), Beta(a, b), HalfNormal(sd)
N_COUNT = 2_000
def simulate_counts(n, mu, rho, sigma, kind, seed):
"""A latent AR(1) path and what the instrument reports: a count, or only whether it saw anything."""
local = np.random.default_rng(seed)
x = simulate_ar1(n, mu, rho, sigma, local)
y = local.poisson(np.exp(x)) if kind == "poisson" else local.binomial(1, special.expit(x))
return x, y.astype(float)
field_true, counts = simulate_counts(N_COUNT, **COUNT_TRUTH, kind="poisson", seed=RANDOM_SEED)
print(f"{N_COUNT:,} minutes: mean count {counts.mean():.1f}, largest {counts.max():.0f}, minutes with no particle {np.mean(counts == 0):.0%}")
2,000 minutes: mean count 6.8, largest 39, minutes with no particle 4%
The baseline again: NUTS on the field
The model in PyMC is the one of part 2 with one line changed.
def likelihood(kind, x, y):
if kind == "poisson":
pm.Poisson("y", pt.exp(x), observed=y)
else:
pm.Bernoulli("y", logit_p=x, observed=y)
def count_priors():
mu = pm.Normal("mu", *COUNT_PRIOR["mu"])
rho = pm.Beta("rho", *COUNT_PRIOR["rho"])
sigma = pm.HalfNormal("sigma", COUNT_PRIOR["sigma"])
return mu, rho, sigma
def field_model(y, kind="poisson"):
"""Every x_t is a parameter (the 'centred' form: the field itself is sampled)."""
with pm.Model() as model:
mu, rho, sigma = count_priors()
x = pm.AR("x", rho=pt.stack([mu * (1 - rho), rho]), sigma=sigma, constant=True,
init_dist=pm.Normal.dist(mu, sigma / pt.sqrt(1 - rho**2)), steps=len(y) - 1)
likelihood(kind, x, y)
return model
def fit_field(model, name=None, **sample_kwargs):
"""NUTS on a model that holds the field; returns what we keep: hyperparameter draws, a thinned field, diagnostics."""
t0 = time.perf_counter()
with model:
if name is None:
idata = pm.sample(random_seed=RANDOM_SEED, progressbar=False, **sample_kwargs)
else:
with sb.track(name):
idata = pm.sample(random_seed=RANDOM_SEED, progressbar=False, **sample_kwargs)
ess, rhat, divergent = diagnostics(idata, COUNT_NAMES)
return {"hyper": flat_draws(idata, COUNT_NAMES), "x": thin_field(idata), "ess": ess, "rhat": rhat,
"divergences": divergent, "seconds": time.perf_counter() - t0}
NUTS_COUNTS = "counts · NUTS on the field"
nuts_counts = fit_field(field_model(counts), NUTS_COUNTS)
sb.score(NUTS_COUNTS, {"x": nuts_counts["x"]}, truth={"x": field_true}, ess=nuts_counts["ess"])
print(f"{N_COUNT:,} field values + 3 hyperparameters: {nuts_counts['seconds']:.0f} s, smallest bulk ESS {nuts_counts['ess']:.0f}, "
f"largest r_hat {nuts_counts['rhat']:.3f}, divergences {nuts_counts['divergences']}")
2,000 field values + 3 hyperparameters: 3 s, smallest bulk ESS 318, largest r_hat 1.005, divergences 0
NUTS handles this one better than the readings of part 2: a few seconds, an ESS of about 300 and an r_hat of 1.005. A count of seven particles pins its $x_t$ down far better than a reading with noise as large as the signal did, and a field that the data determine is a field whose scale NUTS can learn without a struggle. Keep that in mind for part 4, where the data stop determining it.
The Laplace approximation, inside the model
Fix the hyperparameters $\theta$ and look at the field alone. Its conditional density is
$$\log p(x \mid y, \theta) = \sum_t \big(y_t x_t - e^{x_t}\big) - \tfrac12 (x - \mu)^\top Q_\theta\, (x - \mu) + \text{const},$$
where $Q_\theta$ is the tridiagonal precision matrix of an AR(1) path. This function is concave in $x$, so it has one maximum $x^*(\theta)$, and Newton's method finds it: each step solves a linear system with the matrix $Q_\theta + D$, where $D$ is diagonal with entries $e^{x_t}$, the curvature of the Poisson terms. That matrix is tridiagonal as well, so a step costs a banded Cholesky factor, linear in the length of the series. Replacing the conditional density by the Gaussian with mean $x^*$ and precision $Q_\theta + D$ gives the Laplace approximation of the integral we could not do:
$$\log \tilde p(y \mid \theta) = \log p(y \mid x^*) + \log p(x^* \mid \theta) + \tfrac{n}{2} \log 2\pi - \tfrac12 \log \det\big(Q_\theta + D\big).$$
It is the identity $p(y \mid \theta) = p(y \mid x)\, p(x \mid \theta) / p(x \mid y, \theta)$, evaluated at $x^*$ with the Gaussian in the denominator. When the observation is Gaussian the conditional density is that Gaussian and the formula is exact, which gives us a test: fed the readings of part 2, the code below must return the Kalman filter's number.
What remains is a function of three numbers. That is what "nested" means, and it is why the method scales: the 2,000-dimensional part is handled by optimisation and linear algebra, and only $\theta$ has to be explored. The Laplace approximation of E125 was a different object, one Gaussian for the whole posterior with the hyperparameters inside it; here the hyperparameters are left alone.
class Poisson:
"""log p(y | x) for a count with mean exp(x): the value, its first derivative and minus its second."""
logp = staticmethod(lambda y, x: y * x - np.exp(x) - special.gammaln(y + 1))
slope = staticmethod(lambda y, x: y - np.exp(x))
curvature = staticmethod(lambda y, x: np.exp(x))
start = staticmethod(lambda y: np.log(y + 0.5))
level = staticmethod(lambda y: np.log(max(y.mean(), 1e-3)))
class Bernoulli:
"""The same three functions for a binary observation with logit x."""
logp = staticmethod(lambda y, x: y * x - np.logaddexp(0, x))
slope = staticmethod(lambda y, x: y - special.expit(x))
curvature = staticmethod(lambda y, x: special.expit(x) * special.expit(-x))
start = staticmethod(lambda y: np.where(y > 0, 1.0, -1.0))
level = staticmethod(lambda y: special.logit(np.clip(y.mean(), 0.01, 0.99)))
def gaussian_observation(s):
"""A Normal reading with sd s, for which the Laplace approximation is exact."""
class Gaussian:
logp = staticmethod(lambda y, x: stats.norm.logpdf(y, x, s))
slope = staticmethod(lambda y, x: (y - x) / s**2)
curvature = staticmethod(lambda y, x: np.full_like(x, 1 / s**2))
start = staticmethod(lambda y: y.copy())
return Gaussian
def q_times(band, v):
"""A tridiagonal matrix, stored as two bands, times a vector."""
out = band[1] * v
out[:-1] += band[0, 1:] * v[1:]
out[1:] += band[0, 1:] * v[:-1]
return out
def field_mode(y, mu, rho, sigma, obs, x0=None, tol=1e-8, max_steps=60):
"""Newton's method for the mode of p(x | y, theta). Returns the mode, the Cholesky factor of Q + D, and the steps taken."""
band = ar1_precision(len(y), rho, sigma)
def objective(x):
return obs.logp(y, x).sum() - 0.5 * (x - mu) @ q_times(band, x - mu)
x = obs.start(y) if x0 is None else x0
value = objective(x)
for steps in range(1, max_steps + 1):
hessian = band.copy()
hessian[1] += obs.curvature(y, x)
move = cho_solve_banded((cholesky_banded(hessian), False), obs.slope(y, x) - q_times(band, x - mu))
scale = 1.0
while True: # the objective is concave: halve the step until it goes up
proposal = x + scale * move
new_value = objective(proposal)
if new_value >= value - 1e-12 or scale < 1e-4:
break
scale /= 2
converged = np.max(np.abs(proposal - x)) < tol
x, value = proposal, new_value
if converged:
break
hessian = band.copy()
hessian[1] += obs.curvature(y, x)
return x, cholesky_banded(hessian), band, steps
def laplace_loglik(y, mu, rho, sigma, obs, x0=None):
"""The Laplace approximation of log p(y | theta), with the mode and the factor it was computed from."""
x, chol, band, steps = field_mode(y, mu, rho, sigma, obs, x0)
log_det_prior = np.log(1 - rho**2) - 2 * len(y) * np.log(sigma)
value = (obs.logp(y, x).sum() + 0.5 * log_det_prior - 0.5 * (x - mu) @ q_times(band, x - mu) - np.log(chol[1]).sum())
return value, x, chol, steps
exact = gaussian_loglik(reading, *STATE_TRUTH.values())
approx, _, _, _ = laplace_loglik(reading, STATE_TRUTH["mu"], STATE_TRUTH["rho"], STATE_TRUTH["sigma"],
gaussian_observation(STATE_TRUTH["s"]))
print(f"Gaussian readings of part 2, {T_BIG:,} steps: Laplace {approx:.6f}, exact {exact:.6f}")
t0 = time.perf_counter()
value, _, _, steps = laplace_loglik(counts, **COUNT_TRUTH, obs=Poisson)
print(f"the {N_COUNT:,} counts at the true hyperparameters: log p(y | theta) is about {value:.2f}; Newton took {steps} steps "
f"from a cold start, {1e3 * (time.perf_counter() - t0):.1f} ms in all")
Gaussian readings of part 2, 20,160 steps: Laplace -31252.088599, exact -31252.088599 the 2,000 counts at the true hyperparameters: log p(y | theta) is about -5013.52; Newton took 6 steps from a cold start, 0.9 ms in all
Fed the Gaussian readings, the approximation returns the exact log-likelihood of part 2 to six decimals at 20,160 steps, so the algebra and the banded solver are right. On the counts Newton's method needs six steps from a crude start (the logarithm of each count), and one evaluation of $\log \tilde p(y \mid \theta)$ for 2,000 counts takes about a millisecond.
Exploring three numbers
INLA proper lays a grid over $\theta$. With three hyperparameters we can afford something that returns draws and reports on its own quality: importance sampling. We find the mode of $\log \tilde p(y \mid \theta) + \log p(\theta)$ on the unconstrained scale $(\mu, \text{logit}\,\rho, \log \sigma)$ with a derivative-free optimiser, take the curvature there by finite differences, and draw 2,000 proposals from a Student-t with 5 degrees of freedom around it. Each proposal costs one Laplace approximation, started from the field's mode at the centre, and gets the weight target over proposal. Two numbers say whether the proposals covered the target: the effective sample size of the weights (Kish's $(\sum w)^2 / \sum w^2$) and the Pareto $\hat k$ of their tail (below 0.7 is the usual pass mark; E125 used the same diagnostic). For the field, we take 400 of the resampled hyperparameter draws and draw one path for each from its Gaussian approximation $\text{N}(x^*(\theta), (Q_\theta + D)^{-1})$, with the banded factor that is already there.
def log_prior(u, prior):
"""Log prior density of u = (mu, logit rho, log sigma), with the Jacobians of the two transforms."""
mu, rho, sigma = u[0], special.expit(u[1]), np.exp(u[2])
return (stats.norm.logpdf(mu, *prior["mu"]) + stats.beta.logpdf(rho, *prior["rho"]) + np.log(rho) + np.log1p(-rho)
+ stats.halfnorm.logpdf(sigma, scale=prior["sigma"]) + u[2])
def nested_laplace(y, obs, prior=COUNT_PRIOR, n_draws=2000, n_field=400, df=5, seed=RANDOM_SEED):
"""Hyperparameters by importance sampling on the Laplace-approximated marginal likelihood, then the field."""
local = np.random.default_rng(seed)
warm = {"x": None}
def log_post(u):
if abs(u[1]) > 12 or abs(u[2]) > 8:
return -1e12
value, x, _, _ = laplace_loglik(y, u[0], special.expit(u[1]), np.exp(u[2]), obs, warm["x"])
warm["x"] = x # the next evaluation starts Newton from this mode
return value + log_prior(u, prior)
found = optimize.minimize(lambda u: -log_post(u), [obs.level(y), 2.0, np.log(0.3)], method="Nelder-Mead",
options={"xatol": 1e-5, "fatol": 1e-8, "maxiter": 4000})
centre, x_centre = found.x, warm["x"].copy()
h, hessian = 0.01, np.empty((3, 3))
for i in range(3):
for j in range(i, 3):
e_i, e_j = np.eye(3)[i] * h, np.eye(3)[j] * h
hessian[i, j] = hessian[j, i] = -(log_post(centre + e_i + e_j) - log_post(centre + e_i - e_j)
- log_post(centre - e_i + e_j) + log_post(centre - e_i - e_j)) / (4 * h * h)
cov = np.linalg.inv(hessian)
proposals = centre + (local.standard_normal((n_draws, 3)) / np.sqrt(local.chisquare(df, n_draws) / df)[:, None]) @ np.linalg.cholesky(cov).T
log_target = np.empty(n_draws)
for i in range(n_draws):
warm["x"] = x_centre
log_target[i] = log_post(proposals[i])
log_w = log_target - stats.multivariate_t.logpdf(proposals, loc=centre, shape=cov, df=df)
w = np.exp(log_w - log_w.max())
w /= w.sum()
khat = float((-xr.DataArray(log_w, dims=["sample"])).azstats.psislw(dim="sample")[1])
kept = proposals[local.choice(n_draws, size=n_draws, p=w)]
hyper = {"mu": kept[:, 0], "rho": special.expit(kept[:, 1]), "sigma": np.exp(kept[:, 2])}
field = np.empty((n_field, len(y)), dtype=np.float32)
for i in range(n_field):
_, x, chol, _ = laplace_loglik(y, hyper["mu"][i], hyper["rho"][i], hyper["sigma"][i], obs, x_centre)
field[i] = x + solve_banded((0, 1), chol, local.standard_normal(len(y)))
return {"hyper": hyper, "x": field, "ess": 1 / np.sum(w**2), "khat": khat, "evaluations": found.nfev + 24 + n_draws + n_field,
"centre": {"mu": centre[0], "rho": special.expit(centre[1]), "sigma": np.exp(centre[2])}, "log_post": log_post}
LAPLACE_COUNTS = "counts · nested Laplace"
with sb.track(LAPLACE_COUNTS):
laplace_counts = nested_laplace(counts, Poisson)
sb.score(LAPLACE_COUNTS, {"x": laplace_counts["x"]}, truth={"x": field_true}, ess=laplace_counts["ess"])
print(f"nested Laplace: {sb.table().loc[LAPLACE_COUNTS, 'seconds']:.1f} s for {laplace_counts['evaluations']:,} Laplace approximations; "
f"importance-sampling ESS {laplace_counts['ess']:.0f} of 2,000, Pareto k {laplace_counts['khat']:.2f}")
def versus(a, b, names=COUNT_NAMES):
"""Method a against reference b: shift of the posterior mean in units of b's sd, and ratio of the sds."""
return pd.DataFrame({name: {"reference mean": b[name].mean(), "reference sd": b[name].std(), "mean": a[name].mean(),
"sd": a[name].std(), "shift (reference sds)": (a[name].mean() - b[name].mean()) / b[name].std(),
"sd ratio": a[name].std() / b[name].std()} for name in names}).T
count_fields = {NUTS_COUNTS: nuts_counts["x"], LAPLACE_COUNTS: laplace_counts["x"]}
print(field_table(count_fields, dict.fromkeys(count_fields, field_true)).round(3).to_string(), "\n")
versus(laplace_counts["hyper"], nuts_counts["hyper"]).assign(truth=pd.Series(COUNT_TRUTH)).round(3)
nested Laplace: 1.5 s for 2,560 Laplace approximations; importance-sampling ESS 1696 of 2,000, Pareto k -0.30
RMSE of the posterior mean coverage of 90% intervals mean interval width
counts · NUTS on the field 0.222 0.896 0.732
counts · nested Laplace 0.226 0.904 0.730 | reference mean | reference sd | mean | sd | shift (reference sds) | sd ratio | truth | |
|---|---|---|---|---|---|---|---|
| mu | 1.702 | 0.089 | 1.701 | 0.084 | -0.006 | 0.944 | 1.50 |
| rho | 0.936 | 0.009 | 0.936 | 0.009 | -0.016 | 1.000 | 0.95 |
| sigma | 0.237 | 0.010 | 0.237 | 0.010 | -0.036 | 1.006 | 0.25 |
window = slice(600, 900)
minutes = np.arange(N_COUNT)[window]
fig, ax = plt.subplots(figsize=(13.5, 3.8))
ax.scatter(minutes, counts[window], s=7, color=MUTED, alpha=0.7, lw=0, label="counts")
for name, color in ((NUTS_COUNTS, ORANGE), (LAPLACE_COUNTS, BLUE)):
rate = np.exp(count_fields[name][:, window])
lo, hi = np.quantile(rate, [0.05, 0.95], axis=0)
ax.fill_between(minutes, lo, hi, color=color, alpha=0.25, lw=0)
ax.plot(minutes, rate.mean(axis=0), color=color, lw=1.6, label=name.split(" · ")[1] + ": mean and 90% band")
ax.plot(minutes, np.exp(field_true[window]), color=INK, lw=1.0, label="true intensity")
ax.set_xlabel("minute")
ax.set_ylabel("particles per minute")
ax.legend(frameon=False, fontsize=9, ncols=4, loc="upper center", bbox_to_anchor=(0.5, 1.17))
tidy(ax)
bars_and_posteriors([NUTS_COUNTS, LAPLACE_COUNTS], {NUTS_COUNTS: nuts_counts["hyper"], LAPLACE_COUNTS: laplace_counts["hyper"]},
[("mu", "level μ"), ("rho", "persistence ρ"), ("sigma", "change σ")],
f"{N_COUNT:,} counts: NUTS on the field and the nested Laplace approximation", truth=COUNT_TRUTH);


The nested Laplace approximation took about a second and a half for some 2,600 evaluations: a few hundred to find the mode, 2,000 proposals, and 400 for the field. The importance sampler reports on itself as hoped: the weights are worth about 1,700 draws of the 2,000, and a Pareto $\hat k$ of -0.3 says their tail is short, so a Student-t around the mode is a good proposal for this posterior.
And the answer is the one NUTS gives. The three posterior means differ by less than a twentieth of a posterior standard deviation, the standard deviations by less than 6%, and the two curves in each panel lie on each other. The field is recovered as well by one route as by the other: an error of 0.22 against the truth and 90% intervals that hold it 90% of the time, with the same width. Both posteriors of $\mu$ sit two standard deviations above the true level. That is the path, which wandered high over these 2,000 minutes, and both methods report it faithfully.
Two remarks on the bars. The wall times are a few seconds against one and a half, so nobody waited for either. And the effective sample sizes are not of the same kind. NUTS's 300 is the worth of a Markov chain that targets the exact posterior. The 1,700 is the worth of independent weighted draws that target the approximate posterior. It is a fair count of draws and says nothing about bias, which only the comparison with NUTS, or the truth, can measure. On these counts there is none to see.
What pymc_extras ships
pymc_extras 0.15 has this idea built in, marked experimental: marginalize(model, laplace_approx={x: Q})
returns a model in which the field x has been replaced by its Laplace-approximated marginal
likelihood, and fit_INLA is that call followed by pm.sample. The field must be given with its
precision matrix Q, and the hyperparameters are then sampled by NUTS, with gradients through the
inner optimisation. We try it on the first 100 counts and compare its log-likelihood with ours.
def dense_precision(n, rho, sigma):
diagonal = pt.concatenate([pt.ones(1), pt.full((n - 2,), 1 + rho**2), pt.ones(1)]) / sigma**2
off = pt.full((n - 1,), -rho / sigma**2)
return pt.diag(diagonal) + pt.diag(off, 1) + pt.diag(off, -1)
def packaged_laplace(y):
with pm.Model() as model:
mu, rho, sigma = count_priors()
Q = dense_precision(len(y), rho, sigma)
x = pm.MvNormal("x", mu=mu * pt.ones(len(y)), tau=Q)
pm.Poisson("y", pt.exp(x), observed=y)
return marginalize(model, laplace_approx={"x": Q})
short = counts[:100]
packaged = packaged_laplace(short)
start = packaged.initial_point()
theirs = float(packaged.compile_logp(vars=packaged.observed_RVs)(start))
ours = laplace_loglik(short, float(start["mu"]), special.expit(float(start["rho_logodds__"])),
np.exp(float(start["sigma_log__"])), Poisson)[0]
packaged_ms = 1e3 * time_gradient(packaged, repeats=5)
print(f"free variables: {[v.name for v in packaged.free_RVs]}")
print(f"log p(y | theta) for 100 counts at the starting point: pymc_extras {theirs:.4f}, banded code above {ours:.4f}")
print(f"one gradient at 100 steps: {packaged_ms:.1f} ms")
free variables: ['sigma', 'rho', 'mu'] log p(y | theta) for 100 counts at the starting point: pymc_extras -286.9354, banded code above -286.9356 one gradient at 100 steps: 5.0 ms
The packaged version computes the same quantity: its log-likelihood agrees with ours to three
decimals, the difference being the tolerance of its inner optimiser (L-BFGS-B, where we take Newton
steps). It samples the hyperparameters with NUTS, which importance sampling cannot offer once there
are more than a handful of them. Its limits at this release are two. It cannot return the field:
fit_INLA(return_latent_posteriors=True) raises NotImplementedError. And it works with dense
matrices: the Hessian of the field is built by automatic differentiation as an n by n array and
factorised as one, with no use of its three bands. A gradient takes several milliseconds at 100
steps. Outside the notebook we measured 57 ms at 200 steps, and at 800 steps the job passed 3 GB
and was stopped before its first gradient. The 2,000 counts of this part are out of its reach. A
series of a hundred steps is not, and part 5 has one.
The choice. The nested Laplace approximation written with banded solvers, and importance sampling over the three hyperparameters. Rejected:
marginalize(..., laplace_approx=...)for a series of this length (dense algebra, and no field at the end); NUTS on the field as the routine method (it stays as the check, and on these counts it is a cheap one). What would change our mind: more than five or six hyperparameters, where a Student-t proposal stops covering the target and the hyperparameters have to be sampled by NUTS with gradients through the inner optimisation (Margossian, Vehtari, Simpson and Agrawal 2020); or counts that are rare, which is next.
4 · Where the Laplace approximation is wrong
The Laplace approximation is exact when the field's conditional distribution is Gaussian, and the counts of part 3 were large enough to make it nearly so: a Poisson count of 7 is close to a Normal observation of the log-intensity. The textbook warning is about the other end. A count of zero says only that the intensity is not large, a one-sided statement that no Gaussian mimics, and a binary observation says even less. We now turn the level $\mu$ down, with the field's dynamics unchanged, so that the same instrument sees fewer and fewer particles, and compare the nested Laplace approximation with NUTS at each level. The last row replaces the counter by a detector that reports only whether it saw anything.
A reference that can be trusted
The comparison is worth nothing unless NUTS itself is right, and with rare counts the model of part 3 is not a safe baseline. When the data say little about each $x_t$, the field follows its prior, and the prior's scale is $\sigma$: the funnel of every hierarchical model. The standard cure is to sample the standardised shocks $\eta_t$ and build the path from them (the non-centred form), which for an AR(1) needs a recursion. We write the recursion in JAX. The first check below fits the rarest Poisson series both ways.
def ar1_path(shocks, mu, rho, sigma):
"""The AR(1) path built from standard Normal shocks (JAX)."""
first = sigma / jnp.sqrt(1 - rho**2) * shocks[0]
def step(previous, shock):
new = rho * previous + sigma * shock
return new, new
_, rest = jax.lax.scan(step, first, shocks[1:])
return mu + jnp.concatenate([first[None], rest])
def shock_model(y, kind="poisson"):
"""The same model with the standardised shocks as parameters (the 'non-centred' form)."""
with pm.Model() as model:
mu, rho, sigma = count_priors()
shocks = pm.Normal("shocks", 0, 1, shape=len(y))
x = pm.Deterministic("x", pt.specify_shape(pytensor.wrap_jax(ar1_path)(shocks, mu, rho, sigma), (len(y),)))
likelihood(kind, x, y)
return model
JAX_BACKEND = {"compile_kwargs": {"backend": "jax", "gradient_backend": "jax"}}
LEVELS = [("counts, level -1", {"mu": -1.0, "rho": 0.95, "sigma": 0.25}, "poisson"),
("counts, level -2", {"mu": -2.0, "rho": 0.95, "sigma": 0.25}, "poisson"),
("counts, level -3", {"mu": -3.0, "rho": 0.95, "sigma": 0.25}, "poisson"),
("binary detector", {"mu": 0.0, "rho": 0.8, "sigma": 1.0}, "bernoulli")]
series = {name: simulate_counts(N_COUNT, **theta, kind=kind, seed=RANDOM_SEED) for name, theta, kind in LEVELS}
rare_x, rare_y = series["counts, level -3"]
centred = fit_field(field_model(rare_y), target_accept=0.9)
reference = {"counts, level -3": fit_field(shock_model(rare_y), target_accept=0.9, **JAX_BACKEND)}
pd.DataFrame({form: {"seconds": fit["seconds"], "smallest ESS": fit["ess"], "largest r_hat": fit["rhat"],
"divergences": fit["divergences"], "sigma, posterior mean": fit["hyper"]["sigma"].mean(),
"sigma, posterior sd": fit["hyper"]["sigma"].std()}
for form, fit in (("field as parameters (part 3)", centred), ("shocks as parameters", reference["counts, level -3"]))}).T.round(3)
| seconds | smallest ESS | largest r_hat | divergences | sigma, posterior mean | sigma, posterior sd | |
|---|---|---|---|---|---|---|
| field as parameters (part 3) | 9.678 | 5.345 | 2.068 | 0.0 | 0.337 | 0.160 |
| shocks as parameters | 7.409 | 452.462 | 1.005 | 0.0 | 0.417 | 0.181 |
The same model, the same data, the same sampler, and two different answers, of which one announces itself as wrong. With the field as parameters the four chains disagree outright (r_hat 2.1, an ESS of 5), and its posterior mean of $\sigma$ is not to be believed. With the shocks as parameters r_hat is 1.00 and the ESS in the hundreds. So the slow baseline has a failure of its own. In part 3 the counts were informative enough for the field to be sampled directly. Here they are not, and the model has to be rewritten for the data it meets. The integrated likelihoods of parts 1 to 3 have no such choice to get wrong. For the sweep we use the shocks.
The sweep
laplace_fits = {"counts, level 1.5 (part 3)": laplace_counts}
reference["counts, level 1.5 (part 3)"] = nuts_counts
series["counts, level 1.5 (part 3)"] = (field_true, counts)
truths = {"counts, level 1.5 (part 3)": COUNT_TRUTH} | {name: theta for name, theta, _ in LEVELS}
for name, theta, kind in LEVELS:
x, y = series[name]
t0 = time.perf_counter()
laplace_fits[name] = nested_laplace(y, Poisson if kind == "poisson" else Bernoulli)
laplace_fits[name]["seconds"] = time.perf_counter() - t0
if name not in reference:
reference[name] = fit_field(shock_model(y, kind), target_accept=0.9, **JAX_BACKEND)
ORDER = ["counts, level 1.5 (part 3)"] + [name for name, _, _ in LEVELS]
rows = {}
for name in ORDER:
x, y = series[name]
lap, ref = laplace_fits[name], reference[name]
compare = versus(lap["hyper"], ref["hyper"])
scores = field_table({"Laplace": lap["x"], "NUTS": ref["x"]}, {"Laplace": x, "NUTS": x})
rows[name] = {"mean of y": y.mean(), "share of zeros": np.mean(y == 0),
"NUTS ESS": ref["ess"], "NUTS r_hat": ref["rhat"], "IS Pareto k": lap["khat"],
**{f"{p}: shift (sd)": compare.loc[p, "shift (reference sds)"] for p in COUNT_NAMES},
**{f"{p}: sd ratio": compare.loc[p, "sd ratio"] for p in COUNT_NAMES},
"field RMSE, Laplace": scores.loc["Laplace", "RMSE of the posterior mean"],
"field RMSE, NUTS": scores.loc["NUTS", "RMSE of the posterior mean"],
"field coverage, Laplace": scores.loc["Laplace", "coverage of 90% intervals"],
"field coverage, NUTS": scores.loc["NUTS", "coverage of 90% intervals"]}
sweep = pd.DataFrame(rows).T
sweep.iloc[:, :11].round(2)
| mean of y | share of zeros | NUTS ESS | NUTS r_hat | IS Pareto k | mu: shift (sd) | rho: shift (sd) | sigma: shift (sd) | mu: sd ratio | rho: sd ratio | sigma: sd ratio | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| counts, level 1.5 (part 3) | 6.79 | 0.04 | 318.08 | 1.00 | -0.30 | -0.01 | -0.02 | -0.04 | 0.94 | 1.00 | 1.01 |
| counts, level -1 | 0.56 | 0.60 | 603.06 | 1.01 | -0.08 | -0.03 | -0.20 | 0.12 | 0.94 | 1.04 | 0.98 |
| counts, level -2 | 0.22 | 0.81 | 706.74 | 1.00 | 0.65 | -0.43 | -1.67 | 1.49 | 1.06 | 2.44 | 1.92 |
| counts, level -3 | 0.08 | 0.93 | 452.46 | 1.00 | 0.56 | -10.36 | -4.50 | 10.31 | 2.84 | 0.46 | 2.36 |
| binary detector | 0.54 | 0.46 | 329.04 | 1.02 | -0.12 | -0.28 | 1.80 | -2.31 | 0.87 | 0.66 | 0.44 |
sweep.iloc[:, 11:].round(3)
| field RMSE, Laplace | field RMSE, NUTS | field coverage, Laplace | field coverage, NUTS | |
|---|---|---|---|---|
| counts, level 1.5 (part 3) | 0.226 | 0.222 | 0.904 | 0.896 |
| counts, level -1 | 0.430 | 0.421 | 0.888 | 0.886 |
| counts, level -2 | 0.529 | 0.513 | 0.928 | 0.906 |
| counts, level -3 | 1.662 | 0.615 | 0.986 | 0.916 |
| binary detector | 1.150 | 1.118 | 0.788 | 0.911 |
def hyper_table(name):
table = versus(laplace_fits[name]["hyper"], reference[name]["hyper"]).rename(
columns={"reference mean": "NUTS mean", "reference sd": "NUTS sd", "mean": "Laplace mean", "sd": "Laplace sd"})
return table.assign(truth=pd.Series(truths[name])).iloc[:, [6, 0, 1, 2, 3, 4, 5]]
print("counts, level -3:")
print(hyper_table("counts, level -3").round(3).to_string())
print("\nbinary detector:")
print(hyper_table("binary detector").round(3).to_string())
poisson_levels = ORDER[:4]
mean_counts = sweep.loc[poisson_levels, "mean of y"].to_numpy(dtype=float)
fig, axes = plt.subplots(1, 4, figsize=(13.5, 3.7), gridspec_kw={"width_ratios": [1.25, 1.0, 1.0, 1.0]})
ax = axes[0]
ax.axhspan(-0.5, 0.5, color=LIGHT, alpha=0.6, lw=0)
for p, color, label in (("mu", BLUE, "level μ"), ("rho", ORANGE, "persistence ρ"), ("sigma", AQUA, "change σ")):
ax.plot(mean_counts, sweep.loc[poisson_levels, f"{p}: shift (sd)"].to_numpy(dtype=float), "o-", color=color, label=label)
ax.set_xscale("log")
ax.set_yscale("symlog", linthresh=1)
ax.set_yticks([-10, -3, -1, 0, 1, 3, 10], ["-10", "-3", "-1", "0", "1", "3", "10"])
ax.set_ylim(-25, 25)
ax.set_xticks(mean_counts, [f"{m:.2g}" for m in mean_counts])
ax.minorticks_off()
ax.invert_xaxis()
ax.set_xlabel("mean count per minute (rarer to the right)")
ax.set_ylabel("Laplace minus NUTS, in NUTS sds")
ax.set_title("Hyperparameters: shift of the mean", loc="left")
ax.legend(frameon=False, fontsize=8.5)
tidy(ax)
ax = axes[1]
for method, color in (("NUTS", ORANGE), ("Laplace", BLUE)):
ax.plot(mean_counts, sweep.loc[poisson_levels, f"field RMSE, {method}"].to_numpy(dtype=float), "o-", color=color, label=method)
ax.set_xscale("log")
ax.set_xticks(mean_counts, [f"{m:.2g}" for m in mean_counts])
ax.minorticks_off()
ax.invert_xaxis()
ax.set_xlabel("mean count per minute")
ax.set_title("Field: RMSE against the truth", loc="left")
ax.legend(frameon=False, fontsize=8.5)
tidy(ax)
for ax, name, p, label in ((axes[2], "counts, level -3", "sigma", "σ, rarest counts"), (axes[3], "binary detector", "sigma", "σ, binary detector")):
pooled = np.concatenate([laplace_fits[name]["hyper"][p], reference[name]["hyper"][p]])
lo, hi = 0.0, np.quantile(pooled, 0.999) * 1.05
density(ax, reference[name]["hyper"][p], ORANGE, lo, hi, lw=1.8, label="NUTS")
density(ax, laplace_fits[name]["hyper"][p], BLUE, lo, hi, lw=1.8, label="nested Laplace")
ax.axvline(truths[name][p], color=INK, ls="--", lw=1)
ax.set_yticks([])
ax.set_xlim(lo, hi)
ax.set_title(f"Posterior of {label}", loc="left")
ax.legend(frameon=False, fontsize=8.5)
tidy(ax, grid=None)
counts, level -3:
truth NUTS mean NUTS sd Laplace mean Laplace sd shift (reference sds) sd ratio
mu -3.00 -2.763 0.150 -4.318 0.427 -10.360 2.843
rho 0.95 0.758 0.133 0.160 0.061 -4.500 0.459
sigma 0.25 0.417 0.181 2.279 0.426 10.312 2.357
binary detector:
truth NUTS mean NUTS sd Laplace mean Laplace sd shift (reference sds) sd ratio
mu 0.0 0.232 0.114 0.200 0.099 -0.284 0.866
rho 0.8 0.735 0.043 0.812 0.029 1.797 0.663
sigma 1.0 1.155 0.192 0.710 0.084 -2.314 0.437
Read the first figure panel from left to right. At seven particles a minute the three shifts are zero. At 0.6 a minute, with six minutes in ten empty, they are still inside the grey band of half a standard deviation. At 0.2 a minute the approximation has started to drift: $\rho$ sits 1.7 standard deviations low and $\sigma$ 1.5 high, and both intervals are about twice as wide as they should be. At 0.08 a minute, with 93% of the minutes empty, it has left: $\mu$ and $\sigma$ are ten NUTS standard deviations from where NUTS puts them, and $\rho$ is 0.16 where NUTS says 0.76 and the truth is 0.95. The nested Laplace approximation has explained the same counts with a different story: a rough field with nine times the true innovation and almost no memory, around a much lower level. The field it returns follows that story, and its error against the true field is 1.7 where NUTS's is 0.6.
The binary detector fails in the other direction. There the approximation makes the field too calm: $\sigma$ is 0.71 with an interval less than half as wide as it should be, where NUTS has 1.16 and the truth is 1. The field's intervals inherit the overconfidence and hold the truth 79% of the time in place of 90%. This is the case the INLA literature warns about: Fong, Rue and Wakefield (2010) found the approximation less accurate for binary data, and Ferkingstad and Rue (2015) built a correction for it, which R-INLA applies and this notebook does not.
Nothing in the fit itself gave a warning. The Newton iterations converged, the importance sampler's $\hat k$ stayed below 0.7 at every level, and the posterior at the rarest counts is narrow and smooth. $\hat k$ answers the question it was asked, whether the proposals cover the approximate posterior, and has no opinion on whether that posterior is the right one.
Why: an error per minute that the data cannot outvote
Is this the optimiser's fault, or the importance sampler's? Neither: we can evaluate the Laplace log posterior at the place NUTS puts the hyperparameters and at the place the Laplace fit puts them, and it prefers its own by a wide margin. The approximation itself ranks the two wrongly.
To see why, we need a case where the exact answer is available, and there is one: a field without memory. With $\rho = 0$ the $x_t$ are independent, the integral falls apart into 2,000 one-dimensional integrals, and Gauss-Hermite quadrature does each of them to machine precision. So for an independent field we can compare the Laplace log-likelihood with the exact one, on the very same series, as a function of the field's standard deviation $\tau$. For each $\tau$ the level is set so that the model's mean count matches the data ($\mu = \log \bar y - \tau^2 / 2$; for the detector, $\mu = 0$).
print("Laplace log posterior on the rarest counts, at two places:")
for label, theta in (("NUTS posterior mean", {p: reference["counts, level -3"]["hyper"][p].mean() for p in COUNT_NAMES}),
("Laplace posterior mean", {p: laplace_fits["counts, level -3"]["hyper"][p].mean() for p in COUNT_NAMES})):
u = np.array([theta["mu"], special.logit(theta["rho"]), np.log(theta["sigma"])])
print(f" {label:22s} mu {theta['mu']:6.2f} rho {theta['rho']:.2f} sigma {theta['sigma']:.2f}: "
f"{laplace_fits['counts, level -3']['log_post'](u):9.2f}")
nodes, weights = np.polynomial.hermite_e.hermegauss(150)
def exact_loglik_independent(y, mu, tau, obs):
"""log p(y | mu, tau) when the x_t are independent N(mu, tau): one Gauss-Hermite integral per observation."""
x = mu + tau * nodes[None, :]
return (special.logsumexp(obs.logp(y[:, None], x) + np.log(weights), axis=1) - 0.5 * np.log(2 * np.pi)).sum()
taus = np.linspace(0.3, 2.5, 23)
panels = [("counts, level 1.5 (part 3)", Poisson), ("counts, level -3", Poisson), ("binary detector", Bernoulli)]
fig, axes = plt.subplots(1, 3, figsize=(13.5, 3.6))
gap = {}
for ax, (name, obs) in zip(axes, panels):
y = series[name][1]
level = (lambda tau: 0.0) if obs is Bernoulli else (lambda tau, y=y: np.log(y.mean()) - tau**2 / 2)
exact = np.array([exact_loglik_independent(y, level(tau), tau, obs) for tau in taus])
approx = np.array([laplace_loglik(y, level(tau), 0.0, tau, obs)[0] for tau in taus])
gap[name] = approx - exact
ax.plot(taus, exact - exact[0], color=INK, lw=1.6, label="exact (quadrature)")
ax.plot(taus, approx - exact[0], color=BLUE, lw=1.6, label="Laplace")
ax.set_xlabel("standard deviation τ of an independent field")
ax.set_title(f"{name}: mean of y {y.mean():.2f}", loc="left")
tidy(ax)
axes[0].set_ylabel("log-likelihood, relative to exact at τ = 0.3")
axes[0].legend(frameon=False, fontsize=9)
pd.DataFrame({name: {f"tau = {taus[i]:.1f}": gap[name][i] for i in (0, 5, 10, 17, 22)} for name, _ in panels}).T.round(1)
Laplace log posterior on the rarest counts, at two places: NUTS posterior mean mu -2.76 rho 0.76 sigma 0.42: -568.80 Laplace posterior mean mu -4.32 rho 0.16 sigma 2.28: -550.51
| tau = 0.3 | tau = 0.8 | tau = 1.3 | tau = 2.0 | tau = 2.5 | |
|---|---|---|---|---|---|
| counts, level 1.5 (part 3) | 1.9 | -5.9 | -15.6 | -25.1 | -23.0 |
| counts, level -3 | 0.2 | 5.6 | 22.4 | 43.7 | 44.7 |
| binary detector | -0.2 | -7.8 | -28.7 | -60.9 | -79.2 |

The two printed lines settle the first question. The approximate log posterior at its own answer is 18 units above its value at the answer NUTS gives. The optimiser and the sampler did their job; the function they were handed is wrong.
The figure shows how. With seven particles a minute (left) the exact and the approximate curves fall by two thousand units as the field is made rougher than the data support, and the gap between them, 25 at most, is invisible at that scale. The data have a firm opinion and an error of that size cannot overturn it. With 0.08 particles a minute (centre) the exact log-likelihood is nearly flat up to a standard deviation of 1 and then falls: rare counts say little about how rough the field is. The Laplace curve rises, by 24 units, to a maximum near 1.7. The approximation is off by a few hundredths of a unit per minute, always in the same direction and more so for a rougher field, and 2,000 minutes of that outweigh the little the data say. For the detector (right) the exact curve is flat, since at $\mu = 0$ a binary observation of an independent field carries no information about its spread at all, and the Laplace curve falls by 80: the same kind of error with the opposite sign, which is why $\sigma$ came out too small.
That is the mechanism, and it corrects the textbook warning in one respect. The warning says the approximation fails when the field's conditional distribution is far from Gaussian. Per minute the error is never large: each one-dimensional integral is off by a few hundredths of a unit at most. What fails is the sum. The errors add up over the whole series and depend on the hyperparameters, while the evidence in the data shrinks as the counts get rarer, and at some point the first is larger than the second. A smooth field postpones that point, because neighbouring minutes pool their counts, which is why the approximation survived down to one particle in two minutes. It also means that a longer series is no cure. The error and the evidence both grow in proportion to the number of observations, so by this arithmetic more data leave the bias where it is and only narrow the interval around the wrong value. We have not run that experiment; the third exercise does.
The choice. For rare counts and for binary observations, NUTS on the standardised shocks, and the Laplace answer only where it has been checked against it on a stretch of the series. Rejected: the nested Laplace approximation as the routine method below about half a particle a minute on a field this smooth (wrong by 1.5 to 10 standard deviations, with clean diagnostics); NUTS on the field itself (r_hat 2.1). What would change our mind: a corrected approximation, such as the ones R-INLA ships, tested the same way; or several observations for each latent value, which is what makes each conditional close to Gaussian again.
5 · A real series: 112 years of coal-mining disasters
The simulated counter came with a truth. A real series does not, so here the test is agreement between the routes, on data whose counts are small without being rare. The series is the classic one of E04: explosions in British coal mines that killed ten or more miners, counted per year from 1851 to 1962. E04 asked when the rate changed and fitted a step. The model of this notebook lets the log-rate drift as an AR(1) path, which is the smooth alternative to a step and needs a latent value for each of the 112 years.
data.describe("coal")
coal = data.load("coal")
years = np.arange(1851, 1963)
disasters = (pd.Series(np.floor(coal["date"]).astype(int)).value_counts().reindex(years, fill_value=0)
.to_numpy().astype(float))
print(f"\n{len(years)} years, {disasters.sum():.0f} disasters; mean {disasters.mean():.2f} a year, years with none {np.mean(disasters == 0):.0%}; "
f"before 1890: {disasters[years < 1890].mean():.2f} a year, after: {disasters[years >= 1890].mean():.2f}")
coal: Dates (decimal years) of 191 explosions that killed 10 or more miners. source: Jarrett (1979), UK coal-mining disasters 1851-1962, via R package `boot`. url: https://vincentarelbundock.github.io/Rdatasets/csv/boot/coal.csv 112 years, 191 disasters; mean 1.71 a year, years with none 29%; before 1890: 3.15 a year, after: 0.93
NUTS_COAL, LAPLACE_COAL = "coal · NUTS on the field", "coal · nested Laplace"
nuts_coal = fit_field(shock_model(disasters), NUTS_COAL, target_accept=0.99, **JAX_BACKEND)
sb.add(NUTS_COAL, ess=nuts_coal["ess"])
with sb.track(LAPLACE_COAL):
laplace_coal = nested_laplace(disasters, Poisson, n_draws=4000)
sb.add(LAPLACE_COAL, ess=laplace_coal["ess"])
PACKAGED_COAL = "coal · pymc_extras Laplace + NUTS (run outside)"
# marginalize(..., laplace_approx=...) and pm.sample, default settings, on these 112 counts: run once outside the notebook
OUTSIDE_COAL = {"seconds": 218.1, "ess": 940.0, "gradient_ms": 9.0, "divergences": 178,
"mu": (0.271, 0.639), "rho": (0.956, 0.034), "sigma": (0.211, 0.068)}
sb.add(PACKAGED_COAL, seconds=OUTSIDE_COAL["seconds"], ess=OUTSIDE_COAL["ess"])
print(f"NUTS on the shocks: {nuts_coal['seconds']:.0f} s, smallest ESS {nuts_coal['ess']:.0f}, largest r_hat {nuts_coal['rhat']:.3f}, "
f"divergences {nuts_coal['divergences']}")
print(f"nested Laplace: {sb.table().loc[LAPLACE_COAL, 'seconds']:.1f} s, importance-sampling ESS {laplace_coal['ess']:.0f} of 4,000, "
f"Pareto k {laplace_coal['khat']:.2f}")
coal_table = versus(laplace_coal["hyper"], nuts_coal["hyper"]).rename(
columns={"reference mean": "NUTS mean", "reference sd": "NUTS sd", "mean": "Laplace mean", "sd": "Laplace sd"})
coal_table.assign(**{"pymc_extras mean": pd.Series({p: OUTSIDE_COAL[p][0] for p in COUNT_NAMES}),
"pymc_extras sd": pd.Series({p: OUTSIDE_COAL[p][1] for p in COUNT_NAMES})}).round(3)
NUTS on the shocks: 19 s, smallest ESS 423, largest r_hat 1.013, divergences 0 nested Laplace: 1.0 s, importance-sampling ESS 1056 of 4,000, Pareto k 0.57
| NUTS mean | NUTS sd | Laplace mean | Laplace sd | shift (reference sds) | sd ratio | pymc_extras mean | pymc_extras sd | |
|---|---|---|---|---|---|---|---|---|
| mu | 0.305 | 0.584 | 0.233 | 0.542 | -0.122 | 0.928 | 0.271 | 0.639 |
| rho | 0.956 | 0.033 | 0.956 | 0.033 | -0.008 | 0.987 | 0.956 | 0.034 |
| sigma | 0.211 | 0.068 | 0.212 | 0.069 | 0.027 | 1.024 | 0.211 | 0.068 |
fig, axes = plt.subplots(1, 2, figsize=(13.5, 3.9), gridspec_kw={"width_ratios": [2.2, 1]})
ax = axes[0]
ax.bar(years, disasters, color=LIGHT, width=0.9, label="disasters per year")
for fit, color, label in ((nuts_coal, ORANGE, "NUTS on the field"), (laplace_coal, BLUE, "nested Laplace")):
rate = np.exp(fit["x"])
lo, hi = np.quantile(rate, [0.05, 0.95], axis=0)
ax.fill_between(years, lo, hi, color=color, alpha=0.25, lw=0)
ax.plot(years, rate.mean(axis=0), color=color, lw=1.8, label=f"{label}: mean rate and 90% band")
ax.set_xlabel("year")
ax.set_ylabel("disasters per year")
ax.set_xlim(1850, 1963)
ax.legend(frameon=False, fontsize=9)
tidy(ax)
ax = axes[1]
lo, hi = 0.0, np.quantile(nuts_coal["hyper"]["sigma"], 0.998) * 1.1
density(ax, nuts_coal["hyper"]["sigma"], ORANGE, lo, hi, lw=1.8, label="NUTS on the field")
density(ax, laplace_coal["hyper"]["sigma"], BLUE, lo, hi, lw=1.8, label="nested Laplace")
ax.set_yticks([])
ax.set_xlim(lo, hi)
ax.set_xlabel("year-to-year change σ of the log-rate")
ax.legend(frameon=False, fontsize=9)
tidy(ax, grid=None)
rate_nuts, rate_laplace = np.exp(nuts_coal["x"]).mean(axis=0), np.exp(laplace_coal["x"]).mean(axis=0)
print(f"mean rate, NUTS against Laplace: 1860 {rate_nuts[9]:.2f} / {rate_laplace[9]:.2f}, 1900 {rate_nuts[49]:.2f} / {rate_laplace[49]:.2f}, "
f"1950 {rate_nuts[99]:.2f} / {rate_laplace[99]:.2f}; largest gap over the 112 years {np.abs(rate_nuts - rate_laplace).max():.2f}")
mean rate, NUTS against Laplace: 1860 3.18 / 3.24, 1900 0.94 / 1.01, 1950 0.67 / 0.73; largest gap over the 112 years 0.17

The series has 1.7 disasters a year on average and no disaster in 29% of the years, more than three
a year before 1890 and fewer than one after. On the sweep of part 4 that puts it at the comfortable
end, and the three routes agree. NUTS on the shocks is run with target_accept=0.99 (at 0.9 we saw
72 divergences), because the posterior of $\rho$ leans against 1, where the stationary variance of
the path grows without bound. The nested Laplace approximation takes about a second. Its importance
sampler works harder here than on the simulated counts: the weights are worth about a quarter of
the 4,000 proposals and $\hat k$ is 0.57, under the pass mark of 0.7 but not by much, because a
posterior that leans against a boundary is not well covered by a symmetric proposal. The
hyperparameters agree to about a tenth of a standard deviation, and the two bands for the rate
nearly coincide, from more than three disasters a year in the 1860s to about 0.7 in the 1950s. The
Laplace rate runs a little above the other throughout, by 0.17 disasters a year at most. E04's
step in the 1890s appears here as a decline spread over two decades, with a second, smaller rise
around 1930-1940 that a single step cannot show.
This is also the size at which the packaged laplace_approx is usable, so we ran it: NUTS over the
three hyperparameters with the field marginalised, 112 steps, default settings. Its posterior is in
the last two columns and agrees with the other two. It took three and a half minutes outside the
notebook, at 9 ms a gradient, and reported 178 divergent transitions at the default
target_accept, the same boundary at work. The banded code needs a second and NUTS on the shocks
ten to twenty.
The choice. On this series any of the three; we would report the banded nested Laplace fit and keep NUTS on the shocks as its check. Rejected: nothing on grounds of accuracy; the packaged version on grounds of time. What would change our mind: a rarer series, such as disasters counted per month in place of per year (a mean of 0.14, well inside the region where part 4 saw the approximation drift), where only the NUTS fit should be reported.
6 · Which one, when?
The scoreboard
Every fit of the notebook, in the order it was run. Three rows were not measured here and say so in their names: the Gibbs sampler on 20,000 labels is a projection from timed sweeps, and two fits were run once outside the notebook because they do not fit its budget of time or memory. The last three columns are scored against the truth each row has: the nine mixture parameters for the labels, the latent states or field for the others. The coal rows have no truth.
scoreboard = sb.table()
scoreboard.round({"seconds": 1, "peak_gb": 2, "added_gb": 2, "ess": 0, "ess_per_s": 2, "rmse": 3, "coverage": 3, "width": 3})
| seconds | peak_gb | added_gb | ess | ess_per_s | rmse | coverage | width | |
|---|---|---|---|---|---|---|---|---|
| method | ||||||||
| labels 1k · NUTS + Gibbs on the labels | 38.0 | 0.57 | 0.27 | 23.0 | 0.61 | 0.156 | 1.000 | 0.369 |
| labels 20k · NUTS + Gibbs on the labels (projected) | 4261.0 | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
| labels 1k · marginalize | 4.1 | 0.56 | 0.09 | 645.0 | 158.14 | 0.171 | 1.000 | 0.372 |
| labels 1k · NormalMixture | 2.1 | 0.56 | 0.02 | 742.0 | 354.20 | 0.183 | 1.000 | 0.396 |
| labels 20k · marginalize | 23.8 | 0.63 | 0.07 | 929.0 | 39.00 | 0.016 | 0.889 | 0.061 |
| labels 20k · NormalMixture | 16.9 | 0.64 | 0.01 | 875.0 | 51.80 | 0.016 | 0.889 | 0.063 |
| states 5k · NUTS on the states | 9.9 | 1.18 | 0.47 | 60.0 | 6.09 | 0.400 | 0.894 | 1.299 |
| states 5k · Kalman filter | 2.1 | 1.24 | 0.01 | 2188.0 | 1033.43 | 0.399 | 0.894 | 1.294 |
| states 20k · Kalman filter | 5.2 | 1.26 | 0.01 | 1891.0 | 362.98 | 0.388 | 0.902 | 1.294 |
| states 20k · NUTS on the states (run outside) | 55.5 | 2.28 | NaN | 66.0 | 1.18 | NaN | NaN | NaN |
| counts · NUTS on the field | 3.2 | 1.46 | 0.13 | 318.0 | 100.27 | 0.222 | 0.896 | 0.732 |
| counts · nested Laplace | 1.5 | 1.31 | 0.00 | 1696.0 | 1141.21 | 0.226 | 0.904 | 0.730 |
| coal · NUTS on the field | 19.1 | 1.02 | 0.02 | 423.0 | 22.18 | NaN | NaN | NaN |
| coal · nested Laplace | 1.0 | 0.98 | 0.00 | 1056.0 | 1103.64 | NaN | NaN | NaN |
| coal · pymc_extras Laplace + NUTS (run outside) | 218.1 | NaN | NaN | 940.0 | 4.31 | NaN | NaN | NaN |
INTEGRATED = [MARG_1K, MIX_1K, MARG_BIG, MIX_BIG, KALMAN_5K, KALMAN_BIG, LAPLACE_COUNTS, LAPLACE_COAL, PACKAGED_COAL]
sb.plot(highlight=INTEGRATED);

The scoreboard supports three statements. Wherever a latent variable was integrated out and the result could be checked, the error and the coverage of the recovered latent variables are the same as for NUTS on all of them: the pairs of rows for the 5,040 states and for the counts differ in the third decimal. The integrated fits are faster in wall time by a factor of two to about twenty where the baseline runs at all, and by a much larger factor in effective draws per second. And memory, which the hypothesis did not mention, separates them as clearly as time: the only fit above 2 GB is NUTS on 20,160 states.
Three caveats sit in the table. The ESS of the two nested Laplace rows counts weighted independent draws for the approximate posterior. The labels at 1,000 particles are scored on nine numbers, so their coverage moves in steps of 0.11. And the scoreboard shows no row for the place where the Laplace approximation fails, because that comparison is against NUTS and not against time: it is the sweep of part 4, and the chart below carries its numbers.
The decision chart
t = scoreboard
BOXES = [
("Is the latent variable a discrete label with\na few values, one per row or along a chain?",
"Sum it out: pymc_extras.marginalize or\npm.Mixture, then recover the labels",
f"{N_BIG:,} labels: {t.loc[MARG_BIG, 'seconds']:.0f} s, ESS {t.loc[MARG_BIG, 'ess']:,.0f}\n"
f"NUTS + Gibbs: about {gibbs_projected / 3600:.1f} hours a chain (projected)"),
("Are the latent states Gaussian, and is every\nrelation between them and the data linear?",
"Kalman filter for the likelihood (a JAX scan\nat this length), banded smoother afterwards",
f"{T_BIG:,} steps: {t.loc[KALMAN_BIG, 'seconds']:.0f} s, ESS {t.loc[KALMAN_BIG, 'ess']:,.0f}\n"
f"NUTS on the states: {OUTSIDE_STATES['seconds']:.0f} s, ESS {OUTSIDE_STATES['ess']:.0f}, {OUTSIDE_STATES['peak_gb']:.1f} GB"),
("Gaussian field, counts on top, a handful of\nhyperparameters, and counts that are not rare?",
"Nested Laplace with banded solvers,\nimportance sampling over the hyperparameters",
f"{N_COUNT:,} counts, mean {counts.mean():.0f}: {t.loc[LAPLACE_COUNTS, 'seconds']:.1f} s against {t.loc[NUTS_COUNTS, 'seconds']:.0f} s\n"
f"largest shift of a hyperparameter {np.abs(sweep.iloc[0, 5:8].to_numpy(dtype=float)).max():.2f} sd"),
("Rare counts (most of them zero),\nor binary observations?",
"NUTS on the standardised shocks;\nno Laplace without a check",
f"mean count {sweep.loc['counts, level -3', 'mean of y']:.2f}: Laplace off by {np.abs(sweep.loc['counts, level -3'].iloc[5:8].to_numpy(dtype=float)).max():.0f} sd\n"
f"binary: σ off by {abs(sweep.loc['binary detector', 'sigma: shift (sd)']):.1f} sd, intervals x{sweep.loc['binary detector', 'sigma: sd ratio']:.2f}"),
]
fig, ax = plt.subplots(figsize=(13.5, 7.4))
for row, (question, action, numbers) in enumerate(BOXES):
y = 6.1 - 1.5 * row
ax.add_patch(FancyBboxPatch((0.1, y - 0.5), 3.9, 1.0, boxstyle="round,pad=0.02,rounding_size=0.08", fc="#f4f3ee", ec=MUTED, lw=1.1))
ax.text(2.05, y, question, ha="center", va="center", fontsize=9.6, color=INK, linespacing=1.3)
ax.add_patch(FancyArrowPatch((4.05, y), (4.95, y), arrowstyle="-|>", mutation_scale=13, color=BLUE, lw=1.6))
ax.text(4.5, y + 0.13, "yes", ha="center", fontsize=9, color=BLUE)
ax.add_patch(FancyBboxPatch((5.0, y - 0.5), 3.7, 1.0, boxstyle="round,pad=0.02,rounding_size=0.08", fc="#cde2fb", ec=BLUE, lw=1.4))
ax.text(6.85, y, action, ha="center", va="center", fontsize=9.6, color=INK, linespacing=1.3, fontweight="bold")
ax.text(8.9, y, numbers, ha="left", va="center", fontsize=9.2, color=INK, linespacing=1.35)
ax.add_patch(FancyArrowPatch((2.05, y - 0.53), (2.05, y - 0.97), arrowstyle="-|>", mutation_scale=13, color=MUTED, lw=1.4))
ax.text(2.17, y - 0.76, "no", fontsize=9, color=MUTED, va="center")
y = 6.1 - 1.5 * len(BOXES)
ax.add_patch(FancyBboxPatch((0.1, y - 0.5), 8.6, 1.0, boxstyle="round,pad=0.02,rounding_size=0.08", fc="#fbe9e1", ec=ORANGE, lw=1.4))
ax.text(4.4, y, "Always available, and the reference for everything above: NUTS on all the latent variables.\n"
"Choose the parameterisation for the data (field when they are informative, shocks when they are not) and read r_hat.",
ha="center", va="center", fontsize=9.6, color=INK, linespacing=1.35)
ax.text(8.9, y, f"rarest counts, field as parameters: r_hat {centred['rhat']:.2f}\nshocks as parameters: r_hat {reference['counts, level -3']['rhat']:.2f}",
ha="left", va="center", fontsize=9.2, color=INK, linespacing=1.35)
ax.set_xlim(0, 13.4)
ax.set_ylim(y - 0.7, 7.0)
ax.axis("off")
ax.set_title("When to reach for which: ask in this order", loc="left");

The chart is the notebook in the order in which the questions should be asked. The first two answers are exact, so the only thing to check is the code, and both parts showed a closed form to check it against. The third is an approximation with a region where it is excellent and a region where it is confidently wrong, and the boundary between them is not marked by any diagnostic of the approximation itself. The fourth is that region. The box at the bottom is the method the others were measured against, and it has a condition of its own.
Summary
- Summing out the labels gave the same posterior for a few hundred times less work per effective
draw, and at 20,000 particles it is half a minute against an hour or more. NUTS with
a Gibbs step needed most of a minute for 1,000 particles and returned an ESS of 23. Its cost per label grows
with the number of particles, and 20,000 of them would take an hour or more per chain.
marginalizeandpm.NormalMixturefitted all 20,000 in well under a minute.recoverthen returned labels that were right for 91.7% of the particles, against 91.8% with the true parameters, and calibrated. Limit: the sum removes the labels, not the modes of a mixture. - For the Gaussian states the answer was the same and the gain was not "hours to minutes". NUTS on 20,160 states took about a minute, since one of its gradients costs a fraction of a millisecond. What it did not do was converge: an ESS of 66, an r_hat of 1.06 and 2.3 GB. The Kalman filter took a few seconds for an ESS near 1,900, and a banded smoother returned states with the same error (0.40 against 1.00 for the raw readings) and the same 89 to 90% coverage as NUTS.
- Which Kalman filter mattered more than whether to use one. At 20,160 steps a gradient cost
30 to 40 ms in
pymc_extras.statespace, 10 ms inpytensor.scanand under 1 ms as a JAX scan. All three return the same log-likelihood, which a closed form with banded matrices confirmed to six decimals. - The nested Laplace approximation matched NUTS where counts were not rare. On 2,000 counts with a mean of 7, and down to a mean of 0.6, the hyperparameters agreed within a fifth of a standard deviation and the field had the same error and coverage, in about a second and a half. On 112 years of coal-mining disasters (mean 1.7) three routes agreed. Limit: three hyperparameters, explored by importance sampling; more of them need NUTS with gradients through the inner optimisation.
- It failed somewhere below half a count per step, and for binary data, without any warning from its own diagnostics. At a mean of 0.2 two hyperparameters were 1.5 to 1.7 standard deviations off; at 0.08 the approximation reported a rough field with almost no memory, ten standard deviations from NUTS, and its error on the field was almost three times NUTS's. For a binary detector it made the field too calm and its intervals too narrow (79% coverage in place of 90%). The Pareto $\hat k$ of the importance sampler passed every time.
- The failure is a sum of small errors against weak evidence, not a large error anywhere. For an independent field the exact log-likelihood is available by quadrature. The Laplace value was off by a few hundredths of a unit per observation, in a direction that depends on the hyperparameters: 44 units over 2,000 rare counts, enough to turn a falling likelihood into a rising one. Limit: the thresholds are those of one field ($\rho = 0.95$, $\sigma = 0.25$) and one length. We expect a rougher field to fail at larger counts, and did not measure it.
pymc_extras0.15 ships the same idea asmarginalize(..., laplace_approx=...). It agreed with the banded code to three decimals and with NUTS on the coal series. It is dense: 9 ms a gradient at 112 steps, three and a half minutes for that fit, more than 3 GB at 800 steps, and it cannot return the field.- The slow baseline has to be written for the data. With the field as parameters NUTS was fine on informative counts and gave r_hat 2.1 on rare ones; with the shocks as parameters it was the reference for the rare ones. The integrated likelihoods have no such choice to get wrong.
Try it yourself
- An hour without readings. Set the readings of minutes 2,000 to 2,059 to missing. In the Kalman
step a missing reading means no update: the gain is zero and the term adds nothing to the
log-likelihood (
jnp.whereon a mask does both). In the smoother it means no $1/s^2$ on the diagonal for those minutes. How wide is the 90% band in the middle of the gap, compared with the stationary standard deviation of the level, and how many minutes into the gap does it take to get there? - A grid in place of importance sampling. INLA proper evaluates the hyperparameters on a grid.
In
nested_laplace, replace the Student-t proposals by a 7 x 7 x 7 grid along the columns of the Cholesky factor ofcov, from -3 to 3 standard deviations, with weights proportional to the target. Compare the posterior means and standard deviations with the importance sampler's on the 2,000 counts and on the coal series. How many evaluations does each need for the same accuracy, and what would a fourth and a fifth hyperparameter do to each count? - Find the edge, and what it depends on. Rerun the sweep of part 4 with levels from -1 to -3 in steps of 0.25, then again with $\rho = 0.5$ (a field that pools fewer neighbours), and with 500 and with 8,000 minutes in place of 2,000. Where does the shift of $\sigma$ pass one standard deviation in each case, and does a longer series move that point? Is the mean count per minute the right axis, or does the mean count per correlation time, $\bar y\,(1 + \rho) / (1 - \rho)$, line the curves up better?
print(f"total run time: {time.time() - T_START:.0f} s")
total run time: 210 s