Inference and computation / E125

A million rows on a laptop: minibatch ADVI, Pathfinder and Laplace against NUTS

Type
Advanced worked example - read, run, modify
Data
Simulated: one million flights with a known truth, generated in chunks, so that every method can be scored against the right answer. Real: the 547,271 US flights of January 2024 from the Reporting Carrier On-Time Performance table of the Bureau of Transportation Statistics, as the re-coded table this repository already holds for E87 (integer codes, no names; no licence or terms are stated for the source table)
Time
About 5 to 6 minutes on a laptop: six NUTS fits and a dozen approximate ones, the largest on a million rows
You will learn
What a row-level NUTS fit costs at a million rows, and what an honest subsample loses · minibatch ADVI with pm.Minibatch and total_size, mean-field and full-rank, and the three ways it goes wrong: a missing total_size, an optimiser stopped too early, a covariance it cannot learn · Laplace with fit_laplace and where its covariance comes from · Pathfinder with fit_pathfinder · a full-data yardstick built from a few Newton passes and NUTS on the hierarchy · the interval-width ratio, parameter by parameter, as the picture of what an approximation did to the spread · Pareto $\hat k$ as the check that needs no reference, and what it costs at this size · Pathfinder as a starting point for NUTS · the same comparison on a real month, scored on held-out flights

The question

An airline analyst has a million flight records and a hierarchical logistic regression: how much does the chance of a late departure depend on the carrier, on the airport, on the hour of the day, on how far the flight goes and on how late its aircraft came in? NUTS answers such questions exactly, and every earlier notebook of this series uses it. Its price is the gradient of the log density at every step, and that gradient is a sum over the rows. A fit of four chains takes about forty thousand gradients, and forty thousand passes over a million rows take many minutes.

There are two ways out, and they give up different things. The first keeps the sampler and gives up data: fit a random subsample that NUTS can afford. The posterior is then exact for the subsample and wider than it needs to be. The second keeps the data and gives up exactness: replace the posterior by a simple distribution, usually a Gaussian, that is fitted by optimisation.

  • ADVI (Kucukelbir, Tran, Ranganath, Gelman and Blei 2017) picks the Gaussian that maximises a lower bound on the evidence, by stochastic gradient ascent. Its gradient can be estimated from a small random batch of rows, the idea of stochastic variational inference (Hoffman, Blei, Wang and Paisley 2013), so a step costs the same at a thousand rows and at a billion.
  • The Laplace approximation finds the mode of the posterior and uses the curvature there as the Gaussian's covariance.
  • Pathfinder (Zhang, Carpenter, Gelman and Vehtari 2022) follows a quasi-Newton optimiser towards the mode and keeps, among the Gaussians the optimiser implies along its path, the one with the best lower bound.

The folklore about the second family fits in one sentence: variational inference gets the means right and the spread wrong, too narrow as a rule (Blei, Kucukelbir and McAuliffe 2017 review why), and worst for the standard deviations of a hierarchy. This notebook treats that sentence as a hypothesis and tests it at a million rows, where the truth is known because we simulate it. Each method gets a row on a scoreboard: wall time, memory, error against the truth and how often its 90% intervals hold it. The new picture is the interval-width ratio: for every parameter, the width of a method's interval divided by the width it should have. And since in real work there is no truth to compare with, we also compute the diagnostic that needs none, the Pareto $\hat k$ of Yao, Vehtari, Simpson and Gelman (2018), and see what it flags.

One remark on scope. E126, the sister notebook, shows that a model with only categorical covariates does not have a million terms at all: its rows collapse exactly into counts per cell, and NUTS on the counts takes seconds. The flights here carry two continuous covariates so that no two rows are alike and that road is closed. The last part goes back to a real table where it is open, and uses it to get an exact answer to compare with.

part question tool
1 What does NUTS cost at a million rows, and what does a subsample lose? a chunked simulator, one timed gradient, NUTS on 50,000 rows
2 What should a full-data answer look like? Newton's method on all rows, then NUTS on the hierarchy: a yardstick
3 Can a Gaussian be fitted from small batches? pm.Minibatch, total_size, mean-field and full-rank ADVI
4 And from whole passes? fit_laplace, fit_pathfinder
5 Did it work? the interval-width ratio, the scoreboard, Pareto $\hat k$
6 Does Pathfinder at least give NUTS a head start? warm-up from two starting points
7 Does any of it survive real data? a real month, an exact reference, held-out flights
8 Which one, when? a decision chart with the measured numbers
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 pymc_extras as pmx
import pytensor
import xarray as xr
from matplotlib.patches import FancyArrowPatch, FancyBboxPatch
from pymc.pytensorf import join_nonshared_inputs
from scipy import special, stats

from pymc_challenges import data
from pymc_challenges.scoreboard import Scoreboard

sys.modules.pop("jax", None)   # ArviZ's lazy JAX stub; nothing here uses JAX

RANDOM_SEED = 125
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")


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)

1 · A million flights, and what NUTS asks for

The simulated world is the one of E126 with finer categories: 12 carriers, 40 airports and the 16 departure hours from 6:00 to 21:00. Flights are spread unevenly over them, as in a real network: carriers and airports differ in size and each carrier has airports where it is strong. Every flight also has two continuous covariates on a standard scale. The first is the log distance, which is correlated with the airport. The second is the delay with which the aircraft arrived from its previous leg, which grows through the day. A flight leaves late with probability

$$\operatorname{logit} p_i = a + b^{\text{carrier}}_{c(i)} + b^{\text{airport}}_{o(i)} + b^{\text{hour}}_{h(i)} + \gamma_1\, \text{distance}_i + \gamma_2\, \text{inbound}_i ,$$

with effects that sum to zero within each family. The truth below is what every method is scored against: an intercept, two slopes and 68 effects, 71 numbers in all.

N_ROWS, CHUNK = 1_000_000, 250_000
SHAPE = (12, 40, 16)                                  # carriers, airports, departure hours
FAMILIES = ("carrier", "airport", "hour")
N_CELLS = int(np.prod(SHAPE))
COORDS = {"carrier": [f"carrier {i + 1}" for i in range(SHAPE[0])],
          "airport": [f"airport {i + 1}" for i in range(SHAPE[1])],
          "hour": [f"{h:02d}h" for h in range(6, 6 + SHAPE[2])],
          "covariate": ["distance", "inbound delay"]}
CARRIER, AIRPORT, HOUR = np.unravel_index(np.arange(N_CELLS), SHAPE)   # the three codes of each cell


def centred(x):
    return x - np.mean(x)


world = np.random.default_rng([RANDOM_SEED, 0])       # the truth, drawn once
TRUE = {"a": -1.7,
        "gamma": np.array([0.15, 0.45]),
        "b_carrier": centred(world.normal(0, 0.35, SHAPE[0])),
        "b_airport": centred(world.normal(0, 0.45, SHAPE[1])),
        "b_hour": centred(np.linspace(-0.6, 0.6, SHAPE[2]) + 0.12 * world.normal(size=SHAPE[2]))}
ETA_CELL = TRUE["a"] + TRUE["b_carrier"][CARRIER] + TRUE["b_airport"][AIRPORT] + TRUE["b_hour"][HOUR]

share_carrier = world.dirichlet(np.full(SHAPE[0], 2.0))
share_airport = world.dirichlet(np.full(SHAPE[1], 1.2))
hubs = np.exp(world.normal(0, 0.9, SHAPE[:2]))        # where each carrier is strong
share_hour = 1.0 + 0.5 * np.sin(np.linspace(0, 2 * np.pi, SHAPE[2]))
P_CELL = (share_carrier[:, None] * share_airport[None, :] * hubs)[:, :, None] * share_hour
P_CELL = (P_CELL / P_CELL.sum()).ravel()
AIRPORT_Z = centred(world.normal(0, 1, SHAPE[1]))     # airports differ in how far their flights go
AIRPORT_Z /= AIRPORT_Z.std()
HOUR_Z = centred(np.arange(SHAPE[2], dtype=float))    # inbound delays build up through the day
HOUR_Z /= HOUR_Z.std()


def flights(i):
    """Chunk ``i`` of the simulated flights: the cell code, the two covariates and the late flag."""
    r = np.random.default_rng([RANDOM_SEED, 1, i])    # a chunk is a pure function of its number
    cell = r.choice(N_CELLS, size=CHUNK, p=P_CELL)
    X = np.empty((CHUNK, 2), np.float32)
    X[:, 0] = 0.6 * AIRPORT_Z[AIRPORT[cell]] + 0.8 * r.standard_normal(CHUNK)
    X[:, 1] = 0.6 * HOUR_Z[HOUR[cell]] + 0.8 * r.standard_normal(CHUNK)
    late = r.random(CHUNK) < special.expit(ETA_CELL[cell] + X @ TRUE["gamma"])
    return cell.astype(np.int16), X, late.astype(np.int8)


cell = np.empty(N_ROWS, np.int16)
X = np.empty((N_ROWS, 2), np.float32)
late = np.empty(N_ROWS, np.int8)
for i in range(N_ROWS // CHUNK):
    rows = slice(i * CHUNK, (i + 1) * CHUNK)
    cell[rows], X[rows], late[rows] = flights(i)

per_airport = np.bincount(AIRPORT[cell], minlength=SHAPE[1])
print(f"{N_ROWS:,} flights, {late.mean():.1%} late; stored as codes and two 32-bit covariates: "
      f"{(cell.nbytes + X.nbytes + late.nbytes) / 1e6:.0f} MB")
print(f"flights per airport: smallest {per_airport.min():,}, median {int(np.median(per_airport)):,}, "
      f"largest {per_airport.max():,}")
print(f"distinct rows (cell and both covariates): {len(np.unique(np.c_[cell, X], axis=0)):,}")
1,000,000 flights, 17.2% late; stored as codes and two 32-bit covariates: 11 MB
flights per airport: smallest 458, median 17,340, largest 130,993
distinct rows (cell and both covariates): 1,000,000
fig, axes = plt.subplots(1, 3, figsize=(13.5, 3.6))
ax = axes[0]
ax.plot(range(SHAPE[2]), np.bincount(HOUR[cell], weights=late) / np.bincount(HOUR[cell]), "o-", color=BLUE, lw=1.8, ms=4)
ax.set_xticks(range(0, SHAPE[2], 3), COORDS["hour"][::3])
ax.set_xlabel("departure hour")
ax.set_ylabel("share of departures late")
ax.set_title("Delays build up through the day", loc="left")
tidy(ax)

ax = axes[1]
for j, (name, color) in enumerate(zip(COORDS["covariate"], (AQUA, ORANGE))):
    edges = np.quantile(X[:, j], np.linspace(0, 1, 11))
    tenth = np.clip(np.searchsorted(edges, X[:, j]) - 1, 0, 9)
    ax.plot(np.bincount(tenth, weights=X[:, j]) / np.bincount(tenth), np.bincount(tenth, weights=late) / np.bincount(tenth),
            "o-", color=color, lw=1.8, ms=4, label=name)
ax.set_xlabel("covariate (tenths of the flights)")
ax.set_ylabel("share of departures late")
ax.legend(frameon=False, fontsize=9)
ax.set_title("Two continuous covariates", loc="left")
tidy(ax)

ax = axes[2]
ax.plot(np.arange(1, SHAPE[1] + 1), np.sort(per_airport)[::-1], color=BLUE, lw=1.8)
ax.set_yscale("log")
ax.set_xlabel("airports, largest first")
ax.set_ylabel("flights at the airport")
ax.set_title("Airports of very different sizes", loc="left")
tidy(ax);
Figure

A million flights stored as codes take 11 MB, so memory is not the difficulty here. The count of distinct rows is the reason this notebook exists: it is a million. With two continuous covariates no two flights are alike, and the exact compression of E126 has nothing to count. The right panel matters later. The largest airport has a few hundred times the flights of the smallest, so some effects are pinned down by a hundred thousand rows and others by a few hundred.

The model is the one a careful analyst would write: an intercept, zero-sum effects for each family with a standard deviation that the data choose, and a slope for each covariate. The same function builds it on rows, on binomial counts (part 7), and on random minibatches of rows (part 3).

def delay_model(codes, late, coords, X=None, trials=None, batch_size=None, total_size=None):
    """Hierarchical logistic model of a late flight on rows, on counts (``trials``), or on minibatches of rows.

    ``codes`` maps each family of effects to the integer codes of the rows.
    """
    families = list(codes)
    arrays = [np.asarray(codes[f], np.int32) for f in families]
    arrays += ([np.asarray(X)] if X is not None else []) + [np.asarray(late, np.int32)]
    with pm.Model(coords=coords) as model:
        if batch_size is not None:                     # the same random rows of every array, redrawn at each step
            arrays = pm.Minibatch(*arrays, batch_size=batch_size)
        eta = pm.Normal("a", -1.0, 1.5)
        for family, code in zip(families, arrays):
            sd = pm.HalfNormal(f"sd_{family}", 1.0)
            eta = eta + pm.ZeroSumNormal(f"b_{family}", sigma=sd, dims=family)[code]
        if X is not None:
            eta = eta + pm.math.dot(arrays[len(families)], pm.Normal("gamma", 0.0, 1.0, dims="covariate"))
        if trials is not None:
            pm.Binomial("late", n=trials, logit_p=eta, observed=arrays[-1])
        else:
            pm.Bernoulli("late", logit_p=eta, observed=arrays[-1], total_size=total_size)
    return model


def codes_of(cells, shape=SHAPE, families=FAMILIES):
    return dict(zip(families, np.unravel_index(np.asarray(cells, np.int64), shape)))


EFFECTS = ["a", "gamma", "b_carrier", "b_airport", "b_hour"]          # scored against the truth
SDS = ["sd_carrier", "sd_airport", "sd_hour"]
DIAGNOSTICS = {}


def as_draws(post):
    """Posterior draws as a dict of arrays with the draws on the first axis."""
    return {v: post[v].values.reshape(-1, *post[v].shape[2:]) for v in post.data_vars}


def nuts(sb, name, model, **kwargs):
    """Sample ``model`` on the scoreboard's clock; keep its diagnostics."""
    with sb.track(name):
        with model:
            idata = pm.sample(random_seed=RANDOM_SEED, progressbar=False, **kwargs)
    sb.score(name, idata)
    post = idata.posterior.to_dataset()
    DIAGNOSTICS[name] = {"divergences": int(idata.sample_stats["diverging"].sum()),
                         "max r_hat": max(float(v.max()) for v in az.rhat(post).data_vars.values()),
                         "steps per draw": float(idata.sample_stats["n_steps"].mean())}
    return idata

One gradient, timed

Before fitting anything we time the one operation NUTS repeats: the log density and its gradient, on 50,000 rows and on all of them.

def gradient_ms(model, repeats=10):
    """Milliseconds per evaluation of the log density and its gradient."""
    f = model.logp_dlogp_function(ravel_inputs=True)
    x0 = pm.blocking.DictToArrayBijection.map(model.initial_point()).data
    f(x0)
    t0 = time.perf_counter()
    for _ in range(repeats):
        f(x0)
    return (time.perf_counter() - t0) / repeats * 1e3


N_SUB = 50_000
subsample = np.sort(rng.choice(N_ROWS, N_SUB, replace=False))        # drawn at random, never the first rows
model_sub = delay_model(codes_of(cell[subsample]), late[subsample], COORDS, X=X[subsample])
model_full = delay_model(codes_of(cell), late, COORDS, X=X)
ms_sub, ms_full = gradient_ms(model_sub), gradient_ms(model_full)
print(f"one gradient: {ms_sub:.1f} ms on {N_SUB:,} rows, {ms_full:.1f} ms on {N_ROWS:,} rows")
one gradient: 1.3 ms on 50,000 rows, 31.3 ms on 1,000,000 rows

The honest baseline: NUTS on a random subsample

The first way out needs no new method. We draw 50,000 flights at random and fit them with NUTS, four chains with the default settings. We keep the warm-up draws, which part 6 will need.

sb = Scoreboard(truth=TRUE)
idata_sub = nuts(sb, "NUTS · 50k subsample", model_sub, discard_tuned_samples=False)
nuts_sub = as_draws(idata_sub.posterior)
gradients = int(idata_sub.sample_stats["n_steps"].sum() + idata_sub["warmup_sample_stats"]["n_steps"].sum())
seconds_sub = sb.table().loc["NUTS · 50k subsample", "seconds"]
print(f"NUTS on {N_SUB:,} rows: {seconds_sub:.0f} s, {gradients:,} gradients over 4 chains, warm-up included")
print(f"the same fit on all {N_ROWS:,} rows, projected: {seconds_sub * N_ROWS / N_SUB / 60:.0f} minutes by proportion, "
      f"{gradients * ms_full / 1e3 / 4 / 60:.0f} minutes from the timed gradient if four chains ran at full speed side by side")
pd.DataFrame(DIAGNOSTICS).T.round(3)
NUTS on 50,000 rows: 24 s, 45,806 gradients over 4 chains, warm-up included
the same fit on all 1,000,000 rows, projected: 8 minutes by proportion, 6 minutes from the timed gradient if four chains ran at full speed side by side
divergences max r_hat steps per draw
NUTS · 50k subsample 0.0 1.004 7.402

The subsample fits in twenty to thirty seconds with clean diagnostics: no divergences, $\hat R$ at 1.00 and about seven gradients per draw. This is a correct posterior, for a twentieth of the data. The two figures for all the rows are projections, not measurements. The first scales the wall time by twenty. The second multiplies the number of gradients by the time of one, and assumes that four chains run side by side at full speed, which chains that share one memory bus do not. We ran the row-level fit once, outside this notebook, and it took close to ten minutes. That is the cost of exactness at a million rows on a laptop: affordable once, far too slow for a model that is still being changed, and ten times worse at ten million.

What the subsample loses is precision. A posterior standard deviation shrinks with the square root of the number of rows, so intervals from 50,000 rows are $\sqrt{20} \approx 4.5$ times as wide as the full data would give. Part 2 measures that factor, and finds three parameters for which it is not 4.5 but 1.

The choice. A random subsample of 50,000 rows as the baseline: exact for the data it sees, and cheap enough to rerun. Rejected: the row-level fit of all rows as a working tool (about ten minutes a fit), and the first 50,000 rows as the subsample (harmless in a simulation, wrong on a real file, as part 7 shows). What would change our mind: covariates that are all categorical. Then the rows collapse into counts and NUTS on all of them takes seconds (E126).

2 · A yardstick: all the rows a few times, then NUTS on what is left

To say that an approximation has the spread wrong we need the right spread, for the full data. The truth alone cannot give it: it tells us whether intervals cover, on 71 numbers, and not how wide each interval ought to be. The row-level NUTS fit could, at ten minutes a run. There is a cheaper route to nearly the same thing, and it rests on asking which part of this posterior is hard.

The likelihood is not. With a million rows it is very close to a Gaussian function of the intercept, the slopes and the effects: its logarithm is well described by its maximum $\hat\theta$ and its curvature $H$ there,

$$\log p(y \mid \theta) \approx \text{const} - \tfrac12 (\theta - \hat\theta)^\top H\, (\theta - \hat\theta).$$

Newton's method finds $\hat\theta$ and $H$ in a handful of passes over the rows, as E126 showed. The part of the posterior that is not Gaussian is the hierarchy: three standard deviations, each learned from 12, 40 or 16 effects, however many flights there are. So we keep the hierarchical prior as it is, replace the million-term likelihood by the quadratic above, and let NUTS sample the result. The quadratic is a 71 by 71 matrix, so the fit no longer depends on the number of rows.

This is not the Laplace approximation of part 4, which makes the whole posterior Gaussian, standard deviations included. Here only the likelihood is approximated, and NUTS does the rest.

N_COEF = 1 + sum(SHAPE)
DESIGN = np.zeros((N_CELLS, N_COEF))                  # the cells' one-hot rows: intercept, carrier, airport, hour
DESIGN[:, 0] = 1.0
for offset, code in zip(np.cumsum([1, *SHAPE[:2]]), (CARRIER, AIRPORT, HOUR)):
    DESIGN[np.arange(N_CELLS), offset + code] = 1.0


def newton(cells, X, late, iterations=25):
    """Maximum likelihood by Newton's method in chunked passes.

    Returns the estimate (intercept, the three families of effects, the slopes), the curvature of the
    negative log-likelihood there, and the number of passes over the rows.
    """
    p = X.shape[1]
    theta = np.zeros(N_COEF + p)
    for passes in range(1, iterations + 1):
        eta_cell = DESIGN @ theta[:N_COEF]
        resid_cell, w_cell, wx_cell = np.zeros(N_CELLS), np.zeros(N_CELLS), np.zeros((p, N_CELLS))
        resid_x, wxx = np.zeros(p), np.zeros((p, p))
        for start in range(0, len(cells), CHUNK):
            rows = slice(start, start + CHUNK)
            c, x = cells[rows], X[rows].astype(float)
            prob = special.expit(eta_cell[c] + x @ theta[N_COEF:])
            resid, w = late[rows] - prob, prob * (1 - prob)
            resid_cell += np.bincount(c, weights=resid, minlength=N_CELLS)
            w_cell += np.bincount(c, weights=w, minlength=N_CELLS)
            for j in range(p):
                wx_cell[j] += np.bincount(c, weights=w * x[:, j], minlength=N_CELLS)
            resid_x += resid @ x
            wxx += (x * w[:, None]).T @ x
        gradient = np.r_[DESIGN.T @ resid_cell, resid_x]
        H = np.empty((N_COEF + p, N_COEF + p))
        H[:N_COEF, :N_COEF] = DESIGN.T @ (w_cell[:, None] * DESIGN)
        H[:N_COEF, N_COEF:] = DESIGN.T @ wx_cell.T
        H[N_COEF:, :N_COEF] = H[:N_COEF, N_COEF:].T
        H[N_COEF:, N_COEF:] = wxx
        step = np.linalg.lstsq(H, gradient, rcond=1e-10)[0]
        theta += step
        if np.abs(step).max() < 1e-9:
            break
    return theta, H, passes


def summary_model(theta_hat, H):
    """The hierarchical model with the likelihood replaced by its quadratic expansion at the maximum."""
    with pm.Model(coords=COORDS) as model:
        parts = [pm.Normal("a", -1.0, 1.5)[None]]
        for family in FAMILIES:
            sd = pm.HalfNormal(f"sd_{family}", 1.0)
            parts.append(pm.ZeroSumNormal(f"b_{family}", sigma=sd, dims=family))
        parts.append(pm.Normal("gamma", 0.0, 1.0, dims="covariate"))
        d = pm.math.concatenate(parts) - theta_hat
        pm.Potential("likelihood", -0.5 * pm.math.dot(d, pm.math.dot(H, d)))
    return model


def stack(draws, names):
    """Named draws side by side: one column per scalar parameter."""
    return np.concatenate([np.asarray(draws[v]).reshape(len(draws[names[0]]), -1) for v in names], axis=1)


def width(columns, prob=0.9):
    lo, hi = np.quantile(columns, [(1 - prob) / 2, (1 + prob) / 2], axis=0)
    return hi - lo


def versus(draws, reference, names):
    """Per scalar: the gap between the means in reference standard deviations, and the ratio of interval widths."""
    f, r = stack(draws, names), stack(reference, names)
    return (f.mean(axis=0) - r.mean(axis=0)) / r.std(axis=0), width(f) / width(r)

A yardstick has to be checked before it is used. On the 50,000 rows of the subsample we have the exact answer from NUTS, and it is the harder test, since the likelihood of fewer rows is less Gaussian. So we build the yardstick there first and compare.

sb_check = Scoreboard(truth=TRUE)
with sb_check.track("Newton"):
    theta_sub, H_sub, passes_sub = newton(cell[subsample], X[subsample], late[subsample])
yard_sub = as_draws(nuts(sb_check, "summary NUTS", summary_model(theta_sub, H_sub)).posterior)
for label, names in (("intercept, slopes and effects", EFFECTS), ("hierarchical standard deviations", SDS)):
    gap, ratio = versus(yard_sub, nuts_sub, names)
    print(f"yardstick against NUTS on the same {N_SUB:,} rows, {label}: means differ by at most {np.abs(gap).max():.2f} sd; "
          f"interval-width ratio {ratio.min():.2f} to {ratio.max():.2f}")
print(f"Newton: {passes_sub} passes; yardstick in {sb_check.table()['seconds'].sum():.1f} s against {seconds_sub:.0f} s for NUTS on the rows")
yardstick against NUTS on the same 50,000 rows, intercept, slopes and effects: means differ by at most 0.30 sd; interval-width ratio 0.93 to 1.09
yardstick against NUTS on the same 50,000 rows, hierarchical standard deviations: means differ by at most 0.06 sd; interval-width ratio 0.98 to 1.03
Newton: 7 passes; yardstick in 1.5 s against 24 s for NUTS on the rows
with sb.track("Newton + NUTS on the hierarchy"):
    theta_hat, H_full, passes = newton(cell, X, late)
    with summary_model(theta_hat, H_full):
        idata_yard = pm.sample(random_seed=RANDOM_SEED, progressbar=False)
sb.score("Newton + NUTS on the hierarchy", idata_yard)
yard = as_draws(idata_yard.posterior)
print(f"all {N_ROWS:,} rows: {passes} Newton passes, then NUTS on the summary; "
      f"{sb.table().loc['Newton + NUTS on the hierarchy', 'seconds']:.1f} s in all, "
      f"{int(idata_yard.sample_stats['diverging'].sum())} divergences")
sub_ratio, sub_ratio_sd = versus(nuts_sub, yard, EFFECTS)[1], versus(nuts_sub, yard, SDS)[1]
print(f"intervals of the {N_SUB:,}-row subsample against the yardstick: {np.median(sub_ratio):.1f} times as wide for the "
      f"intercept, slopes and effects (median, from {sub_ratio.min():.1f} to {sub_ratio.max():.1f}), "
      f"{np.median(sub_ratio_sd):.2f} times for the standard deviations")
all 1,000,000 rows: 7 Newton passes, then NUTS on the summary; 1.6 s in all, 0 divergences
intervals of the 50,000-row subsample against the yardstick: 4.3 times as wide for the intercept, slopes and effects (median, from 2.3 to 4.7), 1.02 times for the standard deviations

On the subsample the yardstick reproduces NUTS: the means agree to within a third of a posterior standard deviation, and the interval widths to within the Monte Carlo noise of two sets of 4,000 draws, the three standard deviations included. It does so in a small fraction of the time. On all the rows it takes seven Newton passes and a second or two of NUTS. We also compared it with the one row-level NUTS fit of all the rows that we ran outside the notebook: there the means agreed to within 0.14 standard deviations and the widths to within 7%.

The last line is the first result. Against the yardstick the subsample's intervals are more than four times as wide for the intercept, the slopes and most effects, close to the square root of 20. The smallest airports lose less, because part of what is known about them comes from the hierarchy and not from their own flights. For the three hierarchical standard deviations the factor is 1. A standard deviation between carriers is learned from twelve carriers, and a million flights do not make them thirteen. Whatever a method does with the full data, it cannot improve on the subsample there.

The choice. Newton's method on all rows followed by NUTS on the hierarchy, as the reference for every full-data fit below, and as a method in its own right on the scoreboard. Rejected: the truth alone (it scores coverage, not the width each interval should have), and the row-level NUTS fit as the reference (ten minutes, for the same widths). What would change our mind: a likelihood that is not close to quadratic. That happens with few rows per parameter, and part 7 meets a table where the maximum does not even exist.

3 · Minibatch ADVI: a Gaussian fitted from five thousand rows at a time

The idea

Variational inference turns sampling into optimisation. Choose a family of distributions $q_\phi$, here Gaussians on the unconstrained parameters (the standard deviations enter as logarithms), and find the member closest to the posterior in Kullback-Leibler divergence. That is the same as maximising the evidence lower bound,

$$\text{ELBO}(\phi) = \mathbb{E}_{q_\phi}\Big[\log p(\theta) + \sum_{i=1}^{N} \log p(y_i \mid \theta)\Big] + \text{entropy}(q_\phi).$$

Mean-field ADVI uses independent Gaussians, a mean and a standard deviation per parameter. Full-rank ADVI uses one Gaussian with a full covariance matrix. Both are fitted by stochastic gradient ascent, with one draw from $q_\phi$ per step.

The sum over rows is where the minibatch comes in. Replace it by a sum over a random batch of $B$ rows, scaled up to the full data:

$$\sum_{i=1}^{N} \log p(y_i \mid \theta) \;\approx\; \frac{N}{B} \sum_{i \in \text{batch}} \log p(y_i \mid \theta).$$

The right-hand side is an unbiased estimate of the left, so its gradient is an unbiased estimate of the full gradient, and stochastic gradient ascent tolerates noise in its gradients by design. A step then costs $B$ rows, whatever $N$ is.

In PyMC the two halves are separate. pm.Minibatch(...) wraps the data arrays and draws the same $B$ random rows of each at every step. The factor $N/B$ is the argument total_size=N of the likelihood. Nothing forces them to appear together.

Failure 1: forgetting total_size

Without total_size the model runs without an error or a warning. The likelihood then counts each batch as if it were the whole data set.

def advi(model, kind="advi", n=30_000, rates=(0.02, 0.0002), watch=None, every=100):
    """ADVI by stochastic gradient ascent. Returns the Gaussian (mean and covariance on the unconstrained scale).

    With ``rates`` Adam's learning rate falls geometrically from the first value to the second; with
    ``rates=None`` the optimiser is PyMC's default. ``watch`` records the mean and the standard deviation
    of one unconstrained coordinate along the way (mean-field only).
    """
    with model:
        inference = pm.ADVI(random_seed=RANDOM_SEED) if kind == "advi" else pm.FullRankADVI(random_seed=RANDOM_SEED)
        params = {p.name: p for p in inference.approx.params}
        path, callbacks, options = [], [], {}
        if rates is not None:
            rate = pytensor.shared(rates[0])
            callbacks.append(lambda approx, losses, i: rate.set_value(rates[0] * (rates[1] / rates[0]) ** (i / n)))
            options["obj_optimizer"] = pm.adam(learning_rate=rate)
        if watch is not None:
            def record(approx, losses, i):
                if i % every == 0:                     # softplus(rho) is the mean-field standard deviation
                    path.append((i, params["mu"].get_value()[watch], np.log1p(np.exp(params["rho"].get_value()[watch]))))
            callbacks.append(record)
        approx = inference.fit(n, callbacks=callbacks, progressbar=False, **options)
        return {"mean": approx.mean.eval(), "cov": approx.cov.eval(), "loss": np.asarray(approx.hist), "path": np.array(path)}


def flat_functions(model):
    """log p(theta, y) with the Jacobian, and the named parameters, as functions of one flat unconstrained vector."""
    point = model.initial_point()
    [logp], flat = join_nonshared_inputs(point=point, outputs=[model.logp(jacobian=True)], inputs=model.value_vars)
    logp_fn = pytensor.function([flat], logp)
    outputs, flat = join_nonshared_inputs(point=point, outputs=model.unobserved_value_vars, inputs=model.value_vars)
    constrain_fn = pytensor.function([flat], outputs)
    names = [v.name for v in model.unobserved_value_vars]

    def constrain(xs):
        columns = [constrain_fn(row) for row in xs]
        return {name: np.stack([c[j] for c in columns]) for j, name in enumerate(names)}

    return (lambda xs: np.array([logp_fn(row) for row in xs])), constrain


def gaussian_draws(gaussian, constrain, n=2000):
    """Draws from a Gaussian on the unconstrained scale: the flat draws and the named parameters."""
    xs = np.random.default_rng(RANDOM_SEED).multivariate_normal(gaussian["mean"], gaussian["cov"], n, method="eigh")
    return xs, constrain(xs)


def quality(draws, reference, effects=EFFECTS, sds=SDS):
    """What a method did to the means and to the interval widths, against a reference."""
    gap, ratio = versus(draws, reference, effects)
    gap_sd, ratio_sd = versus(draws, reference, sds)
    return {"mean error, rms (sd)": np.sqrt(np.mean(gap**2)), "mean error, worst (sd)": np.abs(gap).max(),
            "width ratio, median": np.median(ratio), "width ratio, lowest": ratio.min(), "width ratio, highest": ratio.max(),
            "sds: mean error, worst (sd)": np.abs(gap_sd).max(), "sds: width ratio, lowest": ratio_sd.min(),
            "sds: width ratio, highest": ratio_sd.max()}


BATCH = 5_000
logp_full, constrain = flat_functions(model_full)
GAUSSIANS, DRAWS, FLAT = {}, {"NUTS · 50k subsample": nuts_sub}, {}


def fit_advi(name, kind="advi", total_size=N_ROWS, **kwargs):
    """Minibatch ADVI on all the rows, on the scoreboard's clock."""
    with sb.track(name):
        GAUSSIANS[name] = advi(delay_model(codes_of(cell), late, COORDS, X=X, batch_size=BATCH, total_size=total_size),
                               kind, **kwargs)
        FLAT[name], DRAWS[name] = gaussian_draws(GAUSSIANS[name], constrain)
    sb.score(name, DRAWS[name])
    return pd.Series(quality(DRAWS[name], yard), name=name)


rows = [fit_advi("ADVI mean-field · no total_size", total_size=None, n=10_000)]
pd.DataFrame(rows).T.round(2)
ADVI mean-field · no total_size
mean error, rms (sd) 8.32
mean error, worst (sd) 15.92
width ratio, median 10.66
width ratio, lowest 2.53
width ratio, highest 14.47
sds: mean error, worst (sd) 1.76
sds: width ratio, lowest 0.72
sds: width ratio, highest 0.79

The fit is not unstable. It is a well-behaved answer to a different question: the posterior of a data set of 5,000 flights, averaged over batches. Its intervals are about ten times as wide as they should be for a million rows, up to the factor $\sqrt{200} \approx 14$ that the missing scale implies, and its means sit eight full-data standard deviations from where they belong, as estimates from 5,000 rows do. The reverse mistake, a total_size larger than the data, would produce intervals that are too narrow by the same square-root rule. The check costs nothing: the number passed as total_size must be the number of rows the minibatches are drawn from.

Failure 2: stopping when the bound looks flat

With total_size in place we fit the mean-field approximation twice. The first run uses PyMC's defaults: 10,000 steps of its default optimiser. The second uses 30,000 steps of Adam with a learning rate that falls from 0.02 to 0.0002. Along both we record the lower bound and the standard deviation that the approximation assigns to one parameter, the slope on the inbound delay.

WATCH = -1                                                              # the last flat coordinate: the slope on inbound delay
assert [v.name for v in model_full.value_vars][-1] == "gamma"
rows.append(fit_advi("ADVI mean-field · defaults", n=10_000, rates=None, watch=WATCH))
rows.append(fit_advi("ADVI mean-field", watch=WATCH))
slope_sd = yard["gamma"][:, 1].std()                                    # the posterior sd of the slope on inbound delay
slope_conditional = 1 / np.sqrt(H_full[-1, -1])                         # its sd if every other parameter were known
pd.DataFrame(rows).T.round(2)
ADVI mean-field · no total_size ADVI mean-field · defaults ADVI mean-field
mean error, rms (sd) 8.32 3.95 0.32
mean error, worst (sd) 15.92 15.94 0.86
width ratio, median 10.66 12.05 0.96
width ratio, lowest 2.53 4.61 0.45
width ratio, highest 14.47 36.41 1.18
sds: mean error, worst (sd) 1.76 3.98 0.07
sds: width ratio, lowest 0.72 3.54 0.92
sds: width ratio, highest 0.79 4.22 0.99
fig, axes = plt.subplots(1, 3, figsize=(13.5, 3.8))
runs = (("ADVI mean-field · defaults", MUTED, "defaults: 10,000 steps"), ("ADVI mean-field", BLUE, "Adam with a falling rate: 30,000 steps"))
for name, color, label in runs:
    g = GAUSSIANS[name]
    smooth = pd.Series(g["loss"]).rolling(200, min_periods=50).mean()
    axes[0].plot(np.arange(len(smooth)), smooth, color=color, lw=1.5, label=label)
    steps, mean, sd = g["path"].T
    axes[1].plot(steps, sd, color=color, lw=1.8)
    axes[2].plot(steps, np.abs(mean - yard["gamma"][:, 1].mean()) / slope_sd, color=color, lw=1.2)
axes[0].set_ylim(np.nanmin(pd.Series(GAUSSIANS["ADVI mean-field"]["loss"]).rolling(200).mean()) - 3, None)
axes[0].set_yscale("log")
axes[0].set_xlabel("step")
axes[0].set_ylabel("negative ELBO per batch (running mean of 200)")
axes[0].legend(frameon=False, fontsize=9)
axes[0].set_title("The bound flattens early", loc="left")
axes[1].axhline(slope_sd, color=INK, lw=1, ls="--")
axes[1].axhline(slope_conditional, color=ORANGE, lw=1, ls=":")
axes[1].text(30_000, slope_sd * 1.12, "posterior sd (yardstick)", ha="right", fontsize=8.5, color=INK)
axes[1].text(30_000, slope_conditional / 1.3, "sd with all other parameters known", ha="right", fontsize=8.5, color=ORANGE)
axes[1].set_yscale("log")
axes[1].set_xlabel("step")
axes[1].set_ylabel("sd given to the slope on inbound delay")
axes[1].set_title("The spread is still shrinking", loc="left")
axes[2].axhline(1, color=INK, lw=1, ls="--")
axes[2].set_yscale("log")
axes[2].set_xlabel("step")
axes[2].set_ylabel("error of the slope's mean, in posterior sd")
axes[2].set_title("The mean wanders with the rate", loc="left")
for ax in axes:
    tidy(ax, grid="both")
Figure

Start with the grey run, the defaults. Each variational standard deviation starts near 0.7, and the posterior standard deviation of this slope is 0.0035: the optimiser has a factor of two hundred to travel, in steps that the default optimiser keeps near 0.001. After 10,000 steps it has covered less than a third of the way on the logarithmic scale of the middle panel. The table says the same of all the parameters: the default run reports intervals about twelve times too wide, far wider than those of the 50,000-row subsample, from twenty times the data. PyMC returns this without a warning. Here the bound in the left panel is at least still falling, for whoever plots it.

The blue run is the trap. Its bound is flat after a thousand steps, to the eye and to any stopping rule based on it. The middle panel shows the standard deviation still shrinking by a factor of thirty after that point, and reaching its floor only around step 17,000. The bound hardly notices, because a Gaussian that is too wide around the right place gives up very little of it. The right panel shows why the learning rate has to fall. A stochastic optimiser with a fixed rate never settles: its means keep moving by about one step, and a step of 0.01 is three posterior standard deviations of this slope. Only when the rate has dropped a hundredfold does the mean stay within one.

Two honest remarks about that run. First, the schedule was tuned against the yardstick, which is cheating: without a reference one would have to watch the parameters themselves, as in the middle panel, not the bound. Second, 30,000 steps of 5,000 rows are 150 million row visits, the cost of 150 passes over the data. Minibatching makes each step cheap. It does not make the fit cheap, because a posterior this concentrated needs many small steps, and it gets more concentrated with every row. Newton's method took seven passes.

What mean-field is expected to get wrong

The middle panel also holds the answer to where the tuned run settles: below the posterior standard deviation, near the dotted line. This is the textbook defect of the mean-field family, and for a Gaussian posterior it has a closed form. If the posterior has covariance $\Sigma$, the best independent Gaussian in the Kullback-Leibler sense has the right means and the variances $1 / (\Sigma^{-1})_{jj}$: the variance of each parameter given all the others, not its marginal variance. The two agree for a parameter that is uncorrelated with the rest and differ by the factor $1 - R_j^2$ otherwise, where $R_j^2$ is how well the other parameters predict parameter $j$. The slope on the inbound delay is correlated with the hour effects, because inbound delays grow through the day, and the intercept is correlated with nearly everything. Part 5 puts this prediction next to what the optimiser delivered.

Full-rank ADVI

The full-rank family contains the Gaussian with the right covariance, so in principle it removes the defect. It has 71 means and 2,556 covariance entries to learn from the same noisy gradients, and we give it the same 30,000 steps.

rows.append(fit_advi("ADVI full-rank", kind="fullrank_advi"))
pd.DataFrame(rows).T.round(2)
ADVI mean-field · no total_size ADVI mean-field · defaults ADVI mean-field ADVI full-rank
mean error, rms (sd) 8.32 3.95 0.32 0.32
mean error, worst (sd) 15.92 15.94 0.86 0.85
width ratio, median 10.66 12.05 0.96 1.94
width ratio, lowest 2.53 4.61 0.45 1.08
width ratio, highest 14.47 36.41 1.18 5.18
sds: mean error, worst (sd) 1.76 3.98 0.07 0.02
sds: width ratio, lowest 0.72 3.54 0.92 0.93
sds: width ratio, highest 0.79 4.22 0.99 1.01

The means are as good as the mean-field ones, a third of a standard deviation from the yardstick. The spread is not: after 30,000 steps the full-rank intervals are still too wide, by a factor of two at the median and five for the slopes. The covariance has not converged. In prototypes for this notebook we doubled the number of steps and tried lower final learning rates, and the widths stayed between 1.7 and 3 times too large. The reason is the parameterisation. The optimiser adjusts the entries of a triangular factor of the covariance directly, 2,556 numbers that have to end up between 0.0001 and 0.1, with steps that never go below the final learning rate. Noise of that size in seventy entries of one row adds up to a visible excess of variance.

The choice. Mean-field ADVI on batches of 5,000 rows with total_size, 30,000 steps of Adam and a learning rate falling from 0.02 to 0.0002. Rejected: the defaults (intervals twelve times too wide after 10,000 steps), a constant learning rate (the means never settle), and full-rank ADVI at this budget (its covariance does not converge). What would change our mind: data that do not fit in memory or arrive as a stream. Then batches are the only way to see the rows at all, and everything in the next part is unavailable.

4 · Laplace and Pathfinder: whole passes, and few of them

The other two approximations use the full gradient. A million rows fit in memory, one gradient takes a few hundredths of a second, and an optimiser that needs a few hundred of them is done in seconds.

Laplace

The Laplace approximation is the oldest of the three: find the mode of the posterior, take the matrix of second derivatives of the log density there, and use its inverse as the covariance of a Gaussian centred on the mode. pymc_extras.fit_laplace does this, and two of its conventions decide what one gets. They are easiest to see on the subsample, where a fit takes a second or two and NUTS gives the exact answer. We run it with two optimisers, its default and a popular alternative.

def laplace_gaussian(result, model):
    """The mean and covariance of ``fit_laplace``, reordered to the model's flat unconstrained vector."""
    labels = np.array([str(label).split("[")[0] for label in result["fit"]["rows"].values])
    order = np.concatenate([np.flatnonzero(labels == v.name) for v in model.value_vars])
    return {"mean": result["fit"]["mean_vector"].values[order],
            "cov": result["fit"]["covariance_matrix"].values[np.ix_(order, order)]}


_, constrain_sub = flat_functions(model_sub)
variants = {"BFGS (the default)": {"optimize_method": "BFGS"}, "L-BFGS-B": {"optimize_method": "L-BFGS-B"}}
laplace_rows = {}
for label, options in variants.items():
    t0 = time.perf_counter()
    with model_sub:
        result = pmx.fit_laplace(random_seed=RANDOM_SEED, progressbar=False, draws=10, **options)
    seconds = time.perf_counter() - t0
    draws = gaussian_draws(laplace_gaussian(result, model_sub), constrain_sub)[1]
    laplace_rows[label] = {"seconds": seconds, **quality(draws, nuts_sub)}
pd.DataFrame(laplace_rows).round(2)
BFGS (the default) L-BFGS-B
seconds 0.78 0.85
mean error, rms (sd) 0.09 0.41
mean error, worst (sd) 0.38 1.65
width ratio, median 1.00 16.86
width ratio, lowest 0.94 3.28
width ratio, highest 1.06 36.20
sds: mean error, worst (sd) 0.75 196.08
sds: width ratio, lowest 0.75 12.25
sds: width ratio, highest 0.84 174.89

Where the covariance comes from. With these two optimisers fit_laplace does not compute the matrix of second derivatives at all. It returns the optimiser's own running estimate of the inverse curvature, which quasi-Newton methods build from the gradients they happened to see. BFGS keeps a full matrix, and by the time it has converged in 71 dimensions its estimate is good: the widths of the effects are within a few percent of NUTS. L-BFGS-B keeps only the last ten gradient pairs, and its "covariance" has little to do with the posterior: the intervals are seventeen times too wide at the median and the standard deviations are off the map. Nothing warns. With an optimiser that uses exact second derivatives, such as trust-exact with use_hess=True, fit_laplace inverts the exact matrix, and that is what we use on the million rows.

Which mode. The standard deviations are sampled as logarithms, and a density changes when its variable is transformed. fit_laplace takes the mode of the density of the standard deviations themselves and then places a Gaussian around it on the log scale. The mode of a right-skewed posterior sits below its mean, so the three standard deviations come out low, here by three quarters of a posterior standard deviation, with intervals a fifth to a quarter too narrow.

with sb.track("Laplace"):
    with model_full:
        laplace = pmx.fit_laplace(optimize_method="trust-exact", use_hess=True, random_seed=RANDOM_SEED,
                                  progressbar=False, draws=10)
    GAUSSIANS["Laplace"] = laplace_gaussian(laplace, model_full)
    FLAT["Laplace"], DRAWS["Laplace"] = gaussian_draws(GAUSSIANS["Laplace"], constrain)
sb.score("Laplace", DRAWS["Laplace"])
outcome = laplace["optimizer_result"]
print(f"optimiser: {int(outcome['nit'])} iterations, each with a full matrix of second derivatives; largest gradient entry "
      f"at the end {float(np.abs(outcome['jac']).max()):.1e}; success flag {bool(outcome['success'])} ({str(outcome['message'].values)[:60]})")
pd.DataFrame([pd.Series(quality(DRAWS["Laplace"], yard), name="Laplace")]).T.round(2)
optimiser: 10 iterations, each with a full matrix of second derivatives; largest gradient entry at the end 3.0e-07; success flag False (A bad approximation caused failure to predict improvement.)
Laplace
mean error, rms (sd) 0.02
mean error, worst (sd) 0.06
width ratio, median 1.00
width ratio, lowest 0.93
width ratio, highest 1.06
sds: mean error, worst (sd) 0.41
sds: width ratio, lowest 0.82
sds: width ratio, highest 0.91

On all the rows the Laplace approximation is the best of the Gaussians for the 71 scored numbers: the means agree with the yardstick to a few hundredths of a standard deviation and the widths to within Monte Carlo noise. That is what part 2 led us to expect, since the likelihood is nearly quadratic. The three standard deviations keep the defect seen on the subsample, less of it: 0.4 standard deviations low and a tenth to a fifth too narrow. More data will not cure the rest, because their posterior does not change with the number of rows. The optimiser's success flag is False, with a message about a failed prediction of improvement, although the largest entry of the gradient at the end is below one millionth, for a log density of several hundred thousand. The flag reports how the trust region stopped, not whether a mode was found, and we go by the gradient.

The fit is also not fast. Ten exact matrices of second derivatives, each computed by automatic differentiation over a million rows, take several times longer than the Newton passes of part 2, which exploit the structure of this particular likelihood.

Pathfinder

Pathfinder runs L-BFGS from several random starting points towards the mode. At each iterate it forms a Gaussian from the optimiser's low-rank estimate of the curvature, estimates that Gaussian's lower bound from a few draws, and keeps the best one along each path. The draws of all paths are then pooled and reweighted by importance sampling. Each estimate of the bound and each importance weight is an evaluation of the log density on all the rows, so at this size the method is far from free. We run two paths where the default is four, and 250 draws a path where the default is 1,000. Two settings matter for memory: vectorize_logp=False, because the default evaluates all the draws at once and would build an array of draws by rows, and parallel=False, because the default starts one process per path, each with its own copy of the model.

def pathfinder(model, paths, draws_per_path=250):
    with model:
        result = pmx.fit_pathfinder(num_paths=paths, num_draws=paths * draws_per_path, num_draws_per_path=draws_per_path,
                                    parallel=False, vectorize_logp=False, random_seed=RANDOM_SEED, progressbar=False)
    return result, float(result["pathfinder"]["pareto_k"])


with sb.track("Pathfinder"):
    pf_full, khat_pathfinder = pathfinder(model_full, paths=2)
    DRAWS["Pathfinder"] = as_draws(pf_full.posterior)
sb.score("Pathfinder", DRAWS["Pathfinder"])

t0 = time.perf_counter()
pf_sub, khat_pathfinder_sub = pathfinder(model_sub, paths=4)
seconds_pf_sub = time.perf_counter() - t0
pd.DataFrame({f"all {N_ROWS:,} rows, against the yardstick": {"seconds": sb.table().loc["Pathfinder", "seconds"],
                                                              "Pareto k": khat_pathfinder, **quality(DRAWS["Pathfinder"], yard)},
              f"the {N_SUB:,}-row subsample, against NUTS": {"seconds": seconds_pf_sub, "Pareto k": khat_pathfinder_sub,
                                                            **quality(as_draws(pf_sub.posterior), nuts_sub)}}).round(2)
all 1,000,000 rows, against the yardstick the 50,000-row subsample, against NUTS
seconds 29.68 3.98
Pareto k 1.77 1.03
mean error, rms (sd) 1.69 0.09
mean error, worst (sd) 9.59 0.29
width ratio, median 1.11 0.93
width ratio, lowest 0.28 0.47
width ratio, highest 3.84 1.27
sds: mean error, worst (sd) 72.46 0.55
sds: width ratio, lowest 0.13 0.30
sds: width ratio, highest 5.68 0.94

Pathfinder does not survive the million rows. On the subsample (second column, scored against NUTS) it is a rough approximation with good means: within a tenth of a standard deviation on average and three tenths at worst, with widths wrong by up to a factor of two and one standard deviation given a third of its spread. On the full data (first column, against the yardstick) the means of the effects are off by up to ten standard deviations and the hierarchical standard deviations are nowhere near. It is also the slowest of the fast methods.

A plausible reading is that the two results are the same weakness at two sizes. L-BFGS describes the curvature with a dozen gradient pairs. The curvature along the effects grows with the number of rows, while the curvature along the three log standard deviations does not: at a million rows the two differ by about four orders of magnitude, and a low-rank estimate that resolves the steep directions has nothing left for the flat ones. More data make this model harder for Pathfinder, not easier. Its own diagnostic says so, which is the subject of the next part.

The choice. fit_laplace with trust-exact and exact second derivatives, and Pathfinder with two paths as the method under test. Rejected: fit_laplace with L-BFGS-B or BFGS (the covariance is the optimiser's estimate, absurd for the first), and Pathfinder's defaults for memory (vectorize_logp=True on a million rows). What would change our mind about Laplace: a posterior that is not close to Gaussian in the parameters we report. Here the three standard deviations are that case, and part 7 has a sharper one.

5 · Did it work?

The interval-width ratio

Every method now has draws for the same 74 parameters, and the yardstick says how wide each interval should be. The figure below is the comparison this notebook was built for. For each method and each parameter it shows the width of the method's 90% interval divided by the yardstick's. A dot on the line at 1 is an interval of the right width, a dot at 0.5 one that is half as wide as it should be, and a dot at 4.5 the price of using a twentieth of the data. The grey band marks ten percent either way, about what two sets of a few thousand draws differ by. The hollow circles in the mean-field panel are the closed-form prediction of part 3, computed from the Laplace covariance.

def mean_field_optimum(gaussian):
    """The best independent Gaussian for a Gaussian target: the same mean, the conditional variances."""
    return {"mean": gaussian["mean"], "cov": np.diag(1 / np.diag(np.linalg.inv(gaussian["cov"])))}


def ratio_figure(methods, reference, groups, title, predicted=None, limits=(0.2, 12.0)):
    """One panel per method: the interval-width ratio of every parameter, family by family."""
    fig, axes = plt.subplots(1, len(methods), figsize=(13.5, 4.3), sharey=True)
    for ax, (name, draws) in zip(axes, methods.items()):
        ax.axhspan(0.9, 1.1, color=LIGHT, alpha=0.7, lw=0)
        ax.axhline(1, color=INK, lw=0.9)
        for k, (label, names, color) in enumerate(groups):
            layers = [(versus(draws, reference, names)[1], {"color": color, "alpha": 0.85, "lw": 0, "zorder": 3})]
            if predicted is not None and name in predicted:
                layers.append((versus(predicted[name], reference, names)[1],
                               {"facecolors": "none", "edgecolors": INK, "lw": 0.7, "zorder": 4}))
            for ratio, style in layers:
                x = k + (np.linspace(-0.3, 0.3, len(ratio)) if len(ratio) > 1 else np.zeros(1))
                low, high = ratio < limits[0], ratio > limits[1]
                ax.scatter(x[~low & ~high], ratio[~low & ~high], s=16, **style)
                ax.scatter(x[high], np.full(high.sum(), limits[1]), s=30, marker="^", **style)   # off the scale
                ax.scatter(x[low], np.full(low.sum(), limits[0]), s=30, marker="v", **style)
        ax.set_yscale("log")
        ax.set_ylim(limits[0] / 1.15, limits[1] * 1.15)
        ax.set_yticks([0.25, 0.5, 1, 2, 4, 8], ["0.25", "0.5", "1", "2", "4", "8"])
        ax.minorticks_off()
        ax.set_xticks(range(len(groups)), [g[0] for g in groups], rotation=55, ha="right")
        ax.set_xlim(-0.6, len(groups) - 0.4)
        ax.set_title(name.replace(" · ", "\n"), fontsize=9.5, loc="left")
        tidy(ax)
    axes[0].set_ylabel("interval width / reference width")
    fig.suptitle(title, x=0.01, ha="left", fontsize=11)
    return fig


GROUPS = [("intercept", ["a"], BLUE), ("slopes", ["gamma"], BLUE), ("carriers", ["b_carrier"], BLUE),
          ("airports", ["b_airport"], BLUE), ("hours", ["b_hour"], BLUE), ("the three sds", SDS, ORANGE)]
SHOWN = ["NUTS · 50k subsample", "ADVI mean-field · defaults", "ADVI mean-field", "ADVI full-rank", "Laplace", "Pathfinder"]
predicted = {"ADVI mean-field": gaussian_draws(mean_field_optimum(GAUSSIANS["Laplace"]), constrain)[1]}
ratio_figure({name: DRAWS[name] for name in SHOWN}, yard, GROUPS,
             "Interval width against the full-data yardstick, one dot per parameter (triangles: off the scale)",
             predicted=predicted);
Figure
verdict = pd.DataFrame({name: quality(DRAWS[name], yard) for name in SHOWN}).T
predicted_gap, predicted_ratio = versus(predicted["ADVI mean-field"], yard, EFFECTS)
_, got_ratio = versus(DRAWS["ADVI mean-field"], yard, EFFECTS)
print(f"mean-field, predicted from the Laplace covariance: intercept {predicted_ratio[0]:.2f}, slopes {predicted_ratio[1]:.2f} and "
      f"{predicted_ratio[2]:.2f}, median of all {np.median(predicted_ratio):.2f}")
print(f"mean-field, delivered by the optimiser:            intercept {got_ratio[0]:.2f}, slopes {got_ratio[1]:.2f} and "
      f"{got_ratio[2]:.2f}, median of all {np.median(got_ratio):.2f}; correlation of the two over the "
      f"{len(got_ratio)} parameters {np.corrcoef(np.log(predicted_ratio), np.log(got_ratio))[0, 1]:.2f}")
verdict.round(2)
mean-field, predicted from the Laplace covariance: intercept 0.42, slopes 0.70 and 0.81, median of all 0.97
mean-field, delivered by the optimiser:            intercept 0.45, slopes 0.71 and 0.85, median of all 0.96; correlation of the two over the 71 parameters 0.92
mean error, rms (sd) mean error, worst (sd) width ratio, median width ratio, lowest width ratio, highest sds: mean error, worst (sd) sds: width ratio, lowest sds: width ratio, highest
NUTS · 50k subsample 4.03 8.74 4.32 2.35 4.70 0.30 1.01 1.02
ADVI mean-field · defaults 3.95 15.94 12.05 4.61 36.41 3.98 3.54 4.22
ADVI mean-field 0.32 0.86 0.96 0.45 1.18 0.07 0.92 0.99
ADVI full-rank 0.32 0.85 1.94 1.08 5.18 0.02 0.93 1.01
Laplace 0.02 0.06 1.00 0.93 1.06 0.41 0.82 0.91
Pathfinder 1.69 9.59 1.11 0.28 3.84 72.46 0.13 5.68

Read the panels from left to right.

The subsample is the cleanest picture in the figure: nearly every effect a little above 4, the smallest airports somewhat lower, and the three standard deviations at 1. It is wrong about nothing, and it wastes nineteen flights in twenty.

Mean-field ADVI with the defaults sits above the subsample: a million rows went in and intervals wider than those of 50,000 rows came out. Its error is in the direction opposite to the folklore.

Mean-field ADVI, tuned, is close to the line for most effects and visibly below it for a few parameters, and the hollow circles say which and by how much. The intercept's interval is less than half as wide as it should be, the two slopes lose a sixth to a third, and a handful of airports lose as much: these are the parameters that the others predict well. The dots sit on the circles, so what remains is the family's defect and not the optimiser's. The three standard deviations are on the line. That is the part of the folklore that fails here: the hierarchical standard deviations are not where mean-field goes wrong on these data. With a million rows the effects are known so precisely that each standard deviation is almost independent of everything else, and an independent Gaussian on the log scale describes it about as well as any Gaussian can.

Full-rank ADVI has every effect above the line. It is the family that could be right and the optimiser that is not.

Laplace is on the line for the effects and a little below it for the standard deviations.

Pathfinder has dots everywhere, some of them off the scale.

The scoreboard

The same fits against the truth, with the clock and the memory.

table = sb.table()
table.round(4)
seconds peak_gb added_gb ess ess_per_s rmse coverage width
method
NUTS · 50k subsample 23.8383 0.7834 0.0601 1074.1752 45.0609 0.1031 0.8873 0.2711
Newton + NUTS on the hierarchy 1.6108 0.8264 0.0170 1041.8597 646.7899 0.0178 0.9296 0.0686
ADVI mean-field · no total_size 7.6247 0.9230 0.0906 NaN NaN 0.1722 0.9718 0.5676
ADVI mean-field · defaults 7.8554 0.9704 0.1322 NaN NaN 0.1467 1.0000 0.6504
ADVI mean-field 17.4343 0.9933 0.0229 NaN NaN 0.0182 0.8873 0.0631
ADVI full-rank 19.8588 1.0594 0.0644 NaN NaN 0.0190 1.0000 0.1241
Laplace 17.0044 1.5290 0.4691 NaN NaN 0.0182 0.9296 0.0685
Pathfinder 29.6781 1.5215 0.3132 NaN NaN 0.1408 0.8028 0.1018
sb.plot(highlight=["Newton + NUTS on the hierarchy"]);
Figure
PICKS = [("a", None, "Intercept"), ("gamma", 1, "Slope, inbound delay"),
         ("b_airport", int(np.argmin(per_airport)), "Smallest airport"), ("sd_airport", None, "sd between airports")]
ORDER = ["NUTS · 50k subsample", "ADVI mean-field · defaults", "ADVI mean-field", "ADVI full-rank", "Laplace", "Pathfinder"]
colors = dict(zip(ORDER, (MUTED, YELLOW, BLUE, VIOLET, AQUA, MAGENTA)))
fig, axes = plt.subplots(1, 4, figsize=(13.5, 3.5), sharey=True)
for ax, (var, index, title) in zip(axes, PICKS):
    pick = lambda d: np.asarray(d[var]) if index is None else np.asarray(d[var])[:, index]
    listed = [("Newton + NUTS on the hierarchy", pick(yard), INK)] + [(name, pick(DRAWS[name]), colors[name]) for name in ORDER[::-1]]
    centre, half = np.median(pick(yard)), 4.5 * width(pick(yard)[:, None])[0]
    left, right = (max(centre - half, 0.0) if var in SDS else centre - half), centre + half
    for y, (name, draws, color) in enumerate(listed):
        lo, mid, hi = np.quantile(draws, [0.05, 0.5, 0.95])
        ax.plot([lo, hi], [y, y], color=color, lw=3, solid_capstyle="butt")
        if left < mid < right:
            ax.plot(mid, y, "o", color=color, ms=5)
        else:                                          # the whole interval is outside the panel
            ax.plot(left + 0.03 * half if mid < left else right - 0.03 * half, y, "<" if mid < left else ">", color=color, ms=7)
    if var in TRUE:
        ax.axvline(TRUE[var] if index is None else TRUE[var][index], color=INK, lw=1, ls="--")
    ax.set_xlim(left, right)
    ax.set_yticks(range(len(listed)), [row[0] for row in listed])
    ax.set_title(title, loc="left")
    tidy(ax, grid="x")
fig.supxlabel("posterior median and 90% interval (dashed: truth); long intervals are cut, arrowheads mark intervals off the panel",
              fontsize=9.5);
Figure

Coverage is counted over the intercept, the two slopes and the 68 effects, at a nominal 90%. With 71 numbers one of them is 1.4 percentage points, and the effects of one fit are not independent, so a coverage between about 83% and 96% is what a calibrated method produces.

The yardstick and Laplace are calibrated and have the smallest error: they use all the data and get the spread right. The subsample is calibrated with an error almost six times larger, which is the honest version of the same thing. The two wide approximations, default mean-field and full-rank, cover every one of the 71 numbers. That is a failure too: an interval that always holds the truth is not a 90% interval, and the width column shows what it costs. Tuned mean-field ADVI has the yardstick's error to within a few percent and the subsample's coverage. On this count the truth does not catch it: the intervals that are much too narrow are a handful among 71, and for the rest the missing few percent of width hide inside the sampling noise of a coverage figure. The interval-width ratio saw what coverage could not. Pathfinder is the one method that is both less calibrated than the subsample and further from the truth.

The four panels above show the same story on four parameters. For the intercept, mean-field ADVI is centred well and too sure. For the smallest airport Laplace and the two tuned ADVI fits agree with the yardstick, and the subsample's interval is several times as long. For the standard deviation between airports nobody gains anything on the subsample.

The time column needs one remark. The yardstick is the fastest fit on the board and the most accurate. It is also the least general: it needs a likelihood whose maximum and curvature can be had in a few passes, and enough rows per parameter for the quadratic to be a good description.

A check that needs no reference: Pareto $\hat k$

Everything above used the truth or the yardstick. On real data there is neither. Yao, Vehtari, Simpson and Gelman (2018) proposed a check that needs only the approximation itself. Draw from the approximation $q$, compute for each draw the ratio $p(\theta, y) / q(\theta)$ of the unnormalised posterior to the approximation, and look at the largest ratios. If $q$ covers the posterior they are bounded. If $q$ is too narrow or misplaced, a few draws in its tails carry enormous ratios, and the shape parameter $\hat k$ of a generalised Pareto distribution fitted to that tail is large. The usual reading is that below 0.5 is good, up to 0.7 is usable, and above 0.7 the approximation should not be trusted (E12 goes through the method on a small model). In ArviZ 1 the fit is .azstats.psislw, which expects the negative log ratios.

At this size the check has a price that small models hide: each ratio is one evaluation of the log density on all the rows. We use 500 draws per method. fit_pathfinder reports its own $\hat k$, computed from the draws it had already evaluated.

def psis(log_ratios):
    """Pareto k-hat of the importance ratios p / q, and the smoothed, normalised weights."""
    log_w, k = xr.DataArray(-log_ratios, dims=["sample"]).azstats.psislw(dim="sample")   # wants -log ratios
    w = np.exp(log_w.values - log_w.values.max())
    return float(k), w / w.sum()


def gaussian_psis(name, logp, n=500):
    xs = FLAT[name][:n]
    log_q = stats.multivariate_normal(GAUSSIANS[name]["mean"], GAUSSIANS[name]["cov"], allow_singular=True).logpdf(xs)
    return psis(logp(xs) - log_q)


khat, khat_seconds, weights = {"Pathfinder": khat_pathfinder}, {}, {}
for name in ("ADVI mean-field", "ADVI full-rank", "Laplace"):
    t0 = time.perf_counter()
    khat[name], weights[name] = gaussian_psis(name, logp_full)
    khat_seconds[name] = time.perf_counter() - t0
check = verdict.loc[list(khat), ["mean error, rms (sd)", "width ratio, median", "width ratio, lowest", "width ratio, highest",
                                 "sds: mean error, worst (sd)", "sds: width ratio, lowest"]]
check.insert(0, "Pareto k", pd.Series(khat))
check.insert(1, "seconds for k", pd.Series(khat_seconds))
check["coverage"] = table["coverage"]
check.sort_values("Pareto k").T.round(2)
Laplace ADVI mean-field Pathfinder ADVI full-rank
Pareto k 0.40 1.26 1.77 12.26
seconds for k 10.65 10.70 NaN 10.30
mean error, rms (sd) 0.02 0.32 1.69 0.32
width ratio, median 1.00 0.96 1.11 1.94
width ratio, lowest 0.93 0.45 0.28 1.08
width ratio, highest 1.06 1.18 3.84 5.18
sds: mean error, worst (sd) 0.41 0.07 72.46 0.02
sds: width ratio, lowest 0.82 0.92 0.13 0.93
coverage 0.93 0.89 0.80 1.00
def weighted(values, w):
    mean = w @ values
    return mean, np.sqrt(w @ (values - mean) ** 2)


corrected = {}
for name in SDS:
    target, values = yard[name], DRAWS["Laplace"][name][:500]
    plain, reweighted = weighted(values, np.full(500, 1 / 500)), weighted(values, weights["Laplace"])
    corrected[name] = {"Laplace: mean error (sd)": (plain[0] - target.mean()) / target.std(), "Laplace: sd ratio": plain[1] / target.std(),
                       "reweighted: mean error (sd)": (reweighted[0] - target.mean()) / target.std(),
                       "reweighted: sd ratio": reweighted[1] / target.std()}
print(f"effective number of the 500 Laplace draws after reweighting: {1 / np.sum(weights['Laplace'] ** 2):.0f}")
pd.DataFrame(corrected).T.round(2)
effective number of the 500 Laplace draws after reweighting: 272
Laplace: mean error (sd) Laplace: sd ratio reweighted: mean error (sd) reweighted: sd ratio
sd_carrier -0.36 0.79 0.01 0.95
sd_airport -0.22 0.90 0.05 0.97
sd_hour -0.34 0.87 0.05 1.03

The first table is sorted by $\hat k$, and here the order is the order of merit. Laplace is the only approximation below 0.5, and it is the only one whose intervals for the effects are right. Mean-field ADVI, at 1.3, has good means and a few intervals that are much too narrow, the fault the check was designed for. Pathfinder, at 1.8, is flagged by its own output. Full-rank ADVI gets the worst value by far, although its means are as good as the mean-field ones and its intervals are merely too wide. $\hat k$ judges the joint density in 71 dimensions, and a covariance that is off in every entry is very far from the posterior by that measure. So a large $\hat k$ says that the approximation as a whole cannot be vouched for. It does not say in which direction it errs, or which parameters to distrust. For that we needed the yardstick.

A small $\hat k$ says more than "pass". It says that the importance weights can be used, and the second table uses them on the one fault Laplace had. Unweighted, its three standard deviations are a quarter to a third of a posterior standard deviation low, with a spread 10% to 20% too small. Weighted, they are within 0.05 standard deviations of the yardstick and their spread is within 5%. The 500 draws are then worth about 270, which is the price of the correction. This is the one route in the notebook that ends with every parameter right and needs neither a known truth nor a second, trusted fit.

The check is not free at this size. Five hundred evaluations of the log density on a million rows take about ten seconds per method, half the cost of the fits they judge.

The choice. For the effects, a full-data fit whose spread we could check: the yardstick, or Laplace with exact second derivatives, passed by $\hat k$ and corrected by its weights. For the hierarchical standard deviations, NUTS, on the subsample or through the yardstick, or the reweighted Laplace draws. Rejected: reading the spread off an ADVI fit without a reference (defaults far too wide, full-rank too wide, mean-field too narrow for the intercept and the slopes), and Pathfinder's draws at this size. What would change our mind: a $\hat k$ above 0.7 for Laplace. Part 7 meets one.

6 · Pathfinder as a starting point for NUTS

An approximation that cannot be trusted for its draws may still be useful for its location. A common suggestion is to start NUTS from a Pathfinder fit and save warm-up. We test it where NUTS is affordable, on the subsample: the fit of part 1 started from PyMC's default initial point with nutpie's jitter, and a second fit starts every chain from the mean of the Pathfinder draws of part 4.

sb_start = Scoreboard(truth=TRUE)
start = {rv.name: pf_sub.posterior[rv.name].mean(("chain", "draw")).values for rv in model_sub.free_RVs}
idata_pf = nuts(sb_start, "NUTS from Pathfinder", model_sub, initvals=start, compile_kwargs={"jitter_rvs": set()},
                discard_tuned_samples=False)
typical = np.quantile(idata_sub.sample_stats["logp"].values, [0.03, 0.97])
starts = {}
for label, idata in (("default start", idata_sub), ("Pathfinder start", idata_pf)):
    logp = idata["warmup_sample_stats"]["logp"].values
    arrival = [int(np.argmax((chain > typical[0]) & (chain < typical[1]))) for chain in logp]
    ess = az.ess(idata.posterior.to_dataset(), method="bulk")
    starts[label] = {"warm-up iterations until log p is in its usual range (slowest chain)": max(arrival),
                     "warm-up gradients": int(idata["warmup_sample_stats"]["n_steps"].sum()),
                     "sampling gradients": int(idata.sample_stats["n_steps"].sum()),
                     "smallest bulk ESS": round(min(float(v.min()) for v in ess.data_vars.values())),
                     "divergences": int(idata.sample_stats["diverging"].sum())}
print(f"Pathfinder on the subsample took {seconds_pf_sub:.1f} s; warm-up length {idata_sub.posterior.attrs['tuning_steps']} iterations per chain")
pd.DataFrame(starts)
Pathfinder on the subsample took 4.0 s; warm-up length 400 iterations per chain
default start Pathfinder start
warm-up iterations until log p is in its usual range (slowest chain) 15 4
warm-up gradients 16198 17053
sampling gradients 29608 28832
smallest bulk ESS 1074 1141
divergences 0 0
fig, ax = plt.subplots(figsize=(8.5, 3.3))
ax.axhspan(*typical, color=LIGHT, alpha=0.8, lw=0, label="94% range of log p while sampling")
for label, idata, color in (("default start", idata_sub, MUTED), ("Pathfinder start", idata_pf, ORANGE)):
    logp = idata["warmup_sample_stats"]["logp"].values[:, :40]
    ax.plot(logp.T, color=color, lw=1.2, label=[label, None, None, None])
ax.set_ylim(typical[0] - 300, typical[1] + 60)
ax.set_xlabel("warm-up iteration")
ax.set_ylabel("log p")
ax.legend(frameon=False, fontsize=9, loc="lower right")
ax.set_title("The first 40 of 400 warm-up iterations", loc="left")
tidy(ax);
Figure

Pathfinder does what was asked of it. Its chains start at the top of the density, above the range they will live in, and are inside that range within four iterations, where the default start takes fifteen. Those eleven iterations are all there was to save. The warm-up is 400 iterations long because the sampler spends it learning a step size and a mass matrix, and a starting point teaches it neither. Counted in gradients, which is the work done, the warm-up from the Pathfinder start was not shorter: it used a few percent more of them, a difference of the size that two seeds produce, like the difference in effective sample size. And the Pathfinder fit itself has to be paid for first. We do not compare wall times here: the two fits ran minutes apart on a machine that was doing other work, and identical fits differ by more than this effect.

E12 found the same on a small stochastic-volatility model. The suggestion pays when finding the region of high probability is the hard part of warm-up: badly scaled models where it takes hundreds of iterations, or models with several modes, where a bad start is a wrong answer. A logistic regression is neither.

The choice. The default start. Rejected: a Pathfinder run before every NUTS fit (it saved eleven of 400 warm-up iterations, no gradients, and cost several seconds). What would change our mind: a model whose chains take a large share of warm-up to reach their stationary range, which the same picture would show.

7 · A real month

The simulated flights followed the model they were fitted with. Real ones do not, so we repeat the comparison on a real table: the domestic flights that the reporting carriers filed for January 2024, from the on-time performance data of the Bureau of Transportation Statistics, as stored in this repository for E87 and used in E126. Each row has a flag (the flight arrived more than 30 minutes late, or was cancelled), the day of the month, and codes for the carrier and the origin airport. The codes are shuffled integers without names, and nothing below needs to know which is which.

This table has no departure hour and no continuous covariate, so the model becomes an intercept and zero-sum effects for the carrier, the origin airport and the day of the month. That changes the comparison in a useful way. With categorical covariates only, the rows collapse exactly into counts per cell, as in E126, and NUTS on the counts of all the training flights is affordable. On this table variational inference is therefore not needed, and we use the table for the opposite purpose: it is real, and it comes with an exact answer to measure the fast methods against. There is no known truth, so the second test is a held-out one: a random fifth of the flights is set aside, and each fit is scored on flights it has not seen.

data.describe("e87_month_rows")
archive = np.load(data.path("e87_month_rows"))
print("\nnotice:", str(archive["notice"]))
late_real = archive["y"].astype(np.int8)
day = archive["day"].astype(int) - 1
carrier_real = archive["carrier"].astype(int)
origin_real = np.unique(archive["origin"], return_inverse=True)[1]      # codes with gaps, renumbered from 0
REAL_COORDS = {"carrier": np.arange(carrier_real.max() + 1), "origin": np.arange(origin_real.max() + 1),
               "day": np.arange(1, 32)}
REAL_SHAPE = tuple(len(v) for v in REAL_COORDS.values())
REAL_FAMILIES = tuple(REAL_COORDS)
cell_real = np.ravel_multi_index((carrier_real, origin_real, day), REAL_SHAPE)

split = np.random.default_rng([RANDOM_SEED, 3])
held_out = split.random(len(late_real)) < 0.2
train = np.flatnonzero(~held_out)
sample = np.sort(split.choice(train, N_SUB, replace=False))


def real_counts(rows):
    """The codes, late flights and flights of each non-empty cell among the given rows."""
    trials = np.bincount(cell_real[rows], minlength=int(np.prod(REAL_SHAPE)))
    k = np.bincount(cell_real[rows], weights=late_real[rows], minlength=len(trials)).astype(int)
    keep = np.flatnonzero(trials > 0)
    return codes_of(keep, REAL_SHAPE, REAL_FAMILIES), k[keep], trials[keep]


late_by_origin = np.bincount(origin_real[train], weights=late_real[train], minlength=REAL_SHAPE[1])
print(f"\n{len(late_real):,} flights, {REAL_SHAPE[0]} carriers, {REAL_SHAPE[1]} origin airports, {REAL_SHAPE[2]} days; "
      f"late or cancelled: {late_real.mean():.1%}")
print(f"training flights {len(train):,} in {len(real_counts(train)[1]):,} cells; held out {held_out.sum():,}")
print(f"carriers among the first {BATCH:,} rows of the file: {len(np.unique(carrier_real[:BATCH]))}; "
      f"among {BATCH:,} rows drawn at random: {len(np.unique(carrier_real[split.choice(train, BATCH)]))}")
print(f"airports with fewer than 100 training flights: {np.sum(np.bincount(origin_real[train], minlength=REAL_SHAPE[1]) < 100)}; "
      f"airports with no late flight at all in training: {np.sum(late_by_origin == 0)}")
e87_month_rows: NumPy archive, not a table: open data.path() with np.load. 547,271 rows in the file's own order, so anyone with the public file can match the codes back: y (late or cancelled), day, carrier, origin, dest, flight, tail, as integers with no names. Flight and tail codes run by first appearance in the file. Tail 0 and any other tail code are not aircraft registrations; rows with no tail share one code. `notice` holds the source notice.
  source: As `e87_flights`: one month, 2024-01. DERIVED by tools/build_e87_data.py --tables - keep the cached file. No endorsement by BTS or DOT is implied.
  url:    https://transtats.bts.gov/DatabaseInfo.asp?QO_VQ=EFD

notice: Derived from US DOT Bureau of Transportation Statistics, Reporting Carrier On-Time Performance (1987-present). Modified: aggregated and re-coded, see tools/build_e87_data.py. No endorsement by BTS or DOT is implied.

547,271 flights, 15 carriers, 334 origin airports, 31 days; late or cancelled: 18.7%
training flights 437,549 in 41,037 cells; held out 109,722
carriers among the first 5,000 rows of the file: 1; among 5,000 rows drawn at random: 15
airports with fewer than 100 training flights: 126; airports with no late flight at all in training: 2

The table carries the notice above and no names. Two lines of the printout are about methods of this notebook.

The file is in the order it was published in, and its first 5,000 rows belong to a single carrier. A minibatch must be a random draw from all the rows. pm.Minibatch draws random row numbers at every step, so it is safe. A hand-written loop over consecutive blocks of this file would feed the optimiser one carrier at a time, and the scaling by total_size would then announce that the whole month looks like that carrier.

And the yardstick of part 2 cannot be built here. It expands the likelihood around its maximum, and for the two airports that had no late flight in the training month the maximum is at minus infinity. For the 126 airports with fewer than a hundred training flights the likelihood has a maximum, but a few dozen flights do not make it quadratic. The method that won on the simulated flights needs many rows per parameter, and a real network has a long tail of small airports.

The model has 384 parameters: an intercept, 380 effects of which 334 are airports, and three standard deviations. The reference is NUTS on the counts of all the training flights. Next to it we fit NUTS on a random subsample of 50,000 flights, mean-field and full-rank ADVI on minibatches of the training rows with 20,000 steps each, and Laplace and Pathfinder on the counts, which carry the same likelihood as the rows.

REAL_EFFECTS = ["a", "b_carrier", "b_origin", "b_day"]
REAL_SDS = ["sd_carrier", "sd_origin", "sd_day"]
sb_real = Scoreboard()                                # no known truth here: time, memory and ESS only
model_cells = delay_model(*real_counts(train)[:2], REAL_COORDS, trials=real_counts(train)[2])
reference = as_draws(nuts(sb_real, "NUTS · all training flights", model_cells).posterior)
REAL = {"NUTS · 50k subsample": as_draws(nuts(sb_real, "NUTS · 50k subsample",
                                                delay_model(*real_counts(sample)[:2], REAL_COORDS,
                                                            trials=real_counts(sample)[2])).posterior)}
pd.DataFrame({k: v for k, v in DIAGNOSTICS.items() if k in sb_real.table().index}).T.round(3)
divergences max r_hat steps per draw
NUTS · 50k subsample 0.0 1.008 15.0
NUTS · all training flights 0.0 1.007 15.0
logp_real, constrain_real = flat_functions(model_cells)
train_codes = {"carrier": carrier_real[train], "origin": origin_real[train], "day": day[train]}
for name, kind in (("ADVI mean-field", "advi"), ("ADVI full-rank", "fullrank_advi")):
    with sb_real.track(name):
        GAUSSIANS[f"real {name}"] = advi(delay_model(train_codes, late_real[train], REAL_COORDS, batch_size=BATCH,
                                                     total_size=len(train)), kind, n=20_000)
        FLAT[f"real {name}"], REAL[name] = gaussian_draws(GAUSSIANS[f"real {name}"], constrain_real)

with sb_real.track("Laplace"):
    with model_cells:
        laplace_real = pmx.fit_laplace(optimize_method="trust-exact", use_hess=True, random_seed=RANDOM_SEED,
                                       progressbar=False, draws=10)
    GAUSSIANS["real Laplace"] = laplace_gaussian(laplace_real, model_cells)
    FLAT["real Laplace"], REAL["Laplace"] = gaussian_draws(GAUSSIANS["real Laplace"], constrain_real)

with sb_real.track("Pathfinder"):
    pf_real, khat_pathfinder_real = pathfinder(model_cells, paths=4)
    REAL["Pathfinder"] = as_draws(pf_real.posterior)
R_CARRIER, R_ORIGIN, R_DAY = (real_counts(np.flatnonzero(held_out))[0][f] for f in REAL_FAMILIES)
_, test_late, test_n = real_counts(np.flatnonzero(held_out))


def held_out_score(draws, thin=4):
    """Log predictive density per held-out flight, from the posterior mean late rate of each cell."""
    d = {v: np.asarray(draws[v])[::thin] for v in REAL_EFFECTS}
    p = special.expit(d["a"][:, None] + d["b_carrier"][:, R_CARRIER] + d["b_origin"][:, R_ORIGIN]
                      + d["b_day"][:, R_DAY]).mean(axis=0)
    return (test_late * np.log(p) + (test_n - test_late) * np.log1p(-p)).sum() / test_n.sum()


base_rate = late_real[train].mean()
constant = (test_late.sum() * np.log(base_rate) + (test_n - test_late).sum() * np.log1p(-base_rate)) / test_n.sum()
khat_real = {"Pathfinder": khat_pathfinder_real,
             **{name: gaussian_psis(f"real {name}", logp_real)[0] for name in ("ADVI mean-field", "ADVI full-rank", "Laplace")}}
real_table = sb_real.table()[["seconds", "peak_gb", "ess"]]
real_table["held-out log score"] = pd.Series({"NUTS · all training flights": held_out_score(reference),
                                               **{name: held_out_score(draws) for name, draws in REAL.items()}})
real_table["gain over a constant rate"] = real_table["held-out log score"] - constant
real_table["Pareto k"] = pd.Series(khat_real)
real_quality = pd.DataFrame({name: quality(draws, reference, REAL_EFFECTS, REAL_SDS) for name, draws in REAL.items()}).T
print(f"held-out log score per flight of a constant late rate: {constant:.4f}; Laplace success flag "
      f"{bool(laplace_real['optimizer_result']['success'])}, largest gradient entry {float(np.abs(laplace_real['optimizer_result']['jac']).max()):.1e}")
real_table.join(real_quality).T.map(lambda v: "" if pd.isna(v) else f"{v:.3f}" if abs(v) < 1e4 else f"{v:.0e}")
held-out log score per flight of a constant late rate: -0.4802; Laplace success flag False, largest gradient entry 1.5e-06
method NUTS · all training flights NUTS · 50k subsample ADVI mean-field ADVI full-rank Laplace Pathfinder
seconds 42.661 18.478 11.028 16.212 3.721 5.496
peak_gb 1.056 1.043 1.128 1.204 1.222 1.258
ess 634.660 773.539
held-out log score -0.427 -0.428 -0.427 -0.469 -0.427 -0.427
gain over a constant rate 0.053 0.052 0.053 0.011 0.053 0.053
Pareto k 2.021 inf 2.291 8.191
mean error, rms (sd) 1.968 0.145 75.913 0.270 0.171
mean error, worst (sd) 7.202 0.827 765.055 0.822 1.191
width ratio, median 1.994 0.980 15.889 0.946 0.486
width ratio, lowest 0.954 0.388 4.678 0.731 0.172
width ratio, highest 3.146 1.245 1097.417 1.081 2.291
sds: mean error, worst (sd) 1.721 0.122 4e+21 4.616 1.724
sds: width ratio, lowest 0.924 0.704 4.581 0.794 0.215
sds: width ratio, highest 1.405 0.967 8e+11 0.887 1.135
hierarchy = {"reference: posterior mean": {v: reference[v].mean() for v in REAL_SDS},
             "reference: posterior sd": {v: reference[v].std() for v in REAL_SDS}}
for name, draws in REAL.items():
    if name != "ADVI full-rank":
        gap, ratio = versus(draws, reference, REAL_SDS)
        hierarchy[f"{name}: mean error (sd)"] = dict(zip(REAL_SDS, gap))
        hierarchy[f"{name}: width ratio"] = dict(zip(REAL_SDS, ratio))
pd.DataFrame(hierarchy).T.round(2)
sd_carrier sd_origin sd_day
reference: posterior mean 0.39 0.43 0.82
reference: posterior sd 0.08 0.02 0.11
NUTS · 50k subsample: mean error (sd) -0.20 -1.72 0.02
NUTS · 50k subsample: width ratio 1.00 1.40 0.92
ADVI mean-field: mean error (sd) -0.03 -0.12 0.01
ADVI mean-field: width ratio 0.94 0.70 0.97
Laplace: mean error (sd) -0.43 -4.62 -0.28
Laplace: width ratio 0.85 0.79 0.89
Pathfinder: mean error (sd) -0.27 -1.72 -0.05
Pathfinder: width ratio 0.22 1.13 0.53
REAL_GROUPS = [("intercept", ["a"], BLUE), ("carriers", ["b_carrier"], BLUE), ("origins", ["b_origin"], BLUE),
               ("days", ["b_day"], BLUE), ("the three sds", REAL_SDS, ORANGE)]
ratio_figure(REAL, reference, REAL_GROUPS,
             "A real month: interval width against NUTS on all the training flights (triangles: off the scale)",
             predicted={"ADVI mean-field": gaussian_draws(mean_field_optimum(GAUSSIANS["real Laplace"]), constrain_real)[1]});
Figure
sb_real.plot(highlight=["NUTS · all training flights"]);
Figure
codes_train, late_train, n_train = real_counts(train)
d = {v: reference[v][::10] for v in REAL_EFFECTS}
p_train = special.expit(d["a"][:, None] + d["b_carrier"][:, codes_train["carrier"]] + d["b_origin"][:, codes_train["origin"]]
                        + d["b_day"][:, codes_train["day"]])
lo, hi = np.quantile(rng.binomial(n_train, p_train), [0.05, 0.95], axis=0)
big = n_train >= 50
inside = (late_train >= lo) & (late_train <= hi)
print(f"training cells with 50 flights or more whose late count lies inside the model's 90% predictive interval: "
      f"{inside[big].mean():.0%} of {big.sum():,}")
training cells with 50 flights or more whose late count lies inside the model's 90% predictive interval: 52% of 1,948

The reference is clean: no divergences, $\hat R$ at 1.01, fifteen gradients per draw, and under a minute for all 437,549 training flights. The table reads best row by row.

Prediction does not separate the methods. The held-out log score is -0.427 per flight for NUTS on all the flights, for mean-field ADVI, for Laplace and for Pathfinder, and -0.428 for the subsample, against -0.480 for a constant late rate. A prediction depends on the posterior means of the late rates, all of these fits get the means nearly right, and a held-out score does not see the spread at all. A team that only predicts could use any of them.

Full-rank ADVI collapses. With 384 parameters the full covariance has 72,771 free entries. After 20,000 steps the means are tens of standard deviations from the reference, one standard deviation of the hierarchy has left the scale altogether, and the held-out score keeps a fifth of the model's gain over a constant rate. On the simulated flights full-rank ADVI was too wide. Here it is wrong, and $\hat k$ is infinite.

Mean-field ADVI does here what the folklore says. Its means are within 0.15 standard deviations of the reference on average and 0.8 at worst. Its spread is wrong where the closed form (the hollow circles again) says it will be. The intercept's interval has two fifths of its proper width, and the formula says it would fall to a third with more steps. The carriers lose about a sixth, two of them a third or more. And, unlike in the simulation, a hierarchical standard deviation is too narrow as well: the one between origins, at 0.70 (second table). The difference is the long tail of small airports. In the simulation every airport had hundreds of flights and its effect was fixed by its own data. Here 126 airports have fewer than a hundred, their effects lean on the standard deviation between airports, it leans on them, and that mutual dependence is what an independent Gaussian cannot hold. So the expectation that mean-field is wrong about hierarchical standard deviations is true for a hierarchy of small groups and false for one of large groups.

Laplace is right about the effects and wrong about one number. The means of the effects are within 0.3 standard deviations, the widths about right. The standard deviation between origins sits 4.6 posterior standard deviations below NUTS, which puts it at 0.43 with a standard deviation of 0.02. The mode of the joint density, at which many small effects and their standard deviation shrink together, is not where the probability is. $\hat k$ is 2.3, where it was 0.4 on the simulated flights: the check that passed Laplace there fails it here, and with a $\hat k$ like this the weights cannot repair it.

Pathfinder has good means and a spread between a sixth and twice the right one, with a $\hat k$ of 8.

The subsample behaves as in the simulation, with one difference. Its intervals are twice to three times as wide for the well-observed parameters, and on this table the hierarchy suffers too: the standard deviation between origins is 1.7 standard deviations low and its interval 1.4 times as wide, because a subsample of a network with a long tail has fewer usable airports to learn it from.

The last line of the printout is about the model, and it applies to every row of the table. Among the cells with 50 flights or more, about half of the late counts fall inside the model's 90% predictive interval. Flights of one carrier at one airport on one day are late together, and a binomial count cannot say so. E126 found the same with weekdays in place of days. Every interval in this part, the reference's included, is therefore too narrow for the real world, and the width ratios above compare each method with the exact posterior of this model. A fast method can reproduce a posterior. It cannot make it the right one.

The choice. On this table, NUTS on the counts of all the training flights: exact, and under a minute. Rejected: full-rank ADVI (collapsed), Laplace for the hierarchy (one standard deviation 4.6 standard deviations low, flagged by $\hat k$), and the widths of mean-field ADVI (the intercept at two fifths). What would change our mind: one continuous covariate. The counts would then be gone, and the working pair would be mean-field ADVI for the means and the predictions, and NUTS on a random subsample for the spread.

8 · Which one, when?

t_sim, t_real = sb.table(), sb_real.table()
BOXES = [
    ("Are all covariates categorical,\nor the likelihood Gaussian?",
     "Compress exactly (E126),\nthen NUTS on the counts",
     f"real month: {len(train):,} rows in {len(late_train):,} cells\nNUTS on all of them: {t_real.loc['NUTS · all training flights', 'seconds']:.0f} s"),
    ("Is the likelihood smooth, with many rows\nper parameter and a cheap curvature?",
     "Newton on all rows, then NUTS on\nthe hierarchy with the quadratic",
     f"{N_ROWS:,} rows: {t_sim.loc['Newton + NUTS on the hierarchy', 'seconds']:.1f} s, coverage "
     f"{t_sim.loc['Newton + NUTS on the hierarchy', 'coverage']:.0%}\nfails with small groups: no maximum on the real month"),
    ("Do the rows fit in memory, and are the\nreported parameters close to Gaussian?",
     "Laplace with exact second\nderivatives, kept if Pareto k < 0.7",
     f"{N_ROWS:,} rows: {t_sim.loc['Laplace', 'seconds']:.0f} s, effect widths x{verdict.loc['Laplace', 'width ratio, median']:.2f}, "
     f"Pareto k {khat['Laplace']:.1f}\nreal month: an sd {real_quality.loc['Laplace', 'sds: mean error, worst (sd)']:.1f} sd off, "
     f"Pareto k {khat_real['Laplace']:.1f}"),
    ("Is the data a stream, or too large\nfor whole passes?",
     "Minibatch mean-field ADVI with\ntotal_size and a falling rate",
     f"{N_ROWS:,} rows: {t_sim.loc['ADVI mean-field', 'seconds']:.0f} s, means within "
     f"{verdict.loc['ADVI mean-field', 'mean error, rms (sd)']:.1f} sd\nintercept interval x{got_ratio[0]:.2f}: distrust the spread"),
]
fig, ax = plt.subplots(figsize=(13.5, 7.6))
for row, (question, action, numbers) in enumerate(BOXES):
    y = 6.1 - 1.5 * row
    ax.add_patch(FancyBboxPatch((0.1, y - 0.5), 3.7, 1.0, boxstyle="round,pad=0.02,rounding_size=0.08", fc="#f4f3ee", ec=MUTED, lw=1.1))
    ax.text(1.95, y, question, ha="center", va="center", fontsize=9.6, color=INK, linespacing=1.3)
    ax.add_patch(FancyArrowPatch((3.85, y), (4.75, y), arrowstyle="-|>", mutation_scale=13, color=BLUE, lw=1.6))
    ax.text(4.3, y + 0.13, "yes", ha="center", fontsize=9, color=BLUE)
    ax.add_patch(FancyBboxPatch((4.8, y - 0.5), 3.5, 1.0, boxstyle="round,pad=0.02,rounding_size=0.08", fc="#cde2fb", ec=BLUE, lw=1.4))
    ax.text(6.55, y, action, ha="center", va="center", fontsize=9.6, color=INK, linespacing=1.3, fontweight="bold")
    ax.text(8.5, y, numbers, ha="left", va="center", fontsize=9.2, color=INK, linespacing=1.35)
    ax.add_patch(FancyArrowPatch((1.95, y - 0.53), (1.95, y - 0.97), arrowstyle="-|>", mutation_scale=13, color=MUTED, lw=1.4))
    ax.text(2.07, 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.2, 1.0, boxstyle="round,pad=0.02,rounding_size=0.08", fc="#fbe9e1", ec=ORANGE, lw=1.4))
ax.text(4.2, y, "Always available, and the reference for everything above: NUTS on a random subsample.\n"
        "Exact for the rows it sees; intervals wider by the square root of N / n, except for the hierarchical sds.",
        ha="center", va="center", fontsize=9.6, color=INK, linespacing=1.35)
ax.text(8.5, y, f"{N_SUB:,} of {N_ROWS:,} rows: {t_sim.loc['NUTS · 50k subsample', 'seconds']:.0f} s\n"
        f"effect widths x{np.median(sub_ratio):.1f}, sd widths x{np.median(sub_ratio_sd):.2f}", ha="left", va="center",
        fontsize=9.2, color=INK, linespacing=1.35)
y -= 1.25
ax.text(0.1, y, "Not on the chart, on the evidence of this notebook: full-rank ADVI beyond a few dozen parameters "
        f"(real month, {sum(REAL_SHAPE) + 4} parameters: held-out score {real_table.loc['ADVI full-rank', 'held-out log score']:.3f} "
        f"against {real_table.loc['ADVI mean-field', 'held-out log score']:.3f}),\nPathfinder's draws at large N "
        f"(Pareto k {khat_pathfinder:.1f} on the million rows), and a Laplace covariance taken from L-BFGS-B.",
        ha="left", va="center", fontsize=9.2, color=INK, linespacing=1.4)
ax.set_xlim(0, 13.4)
ax.set_ylim(y - 0.5, 7.0)
ax.axis("off")
ax.set_title("When to reach for which: ask in this order", loc="left");
Figure

The chart is the notebook in the order in which the questions should be asked. The first answer is exact. The second approximates only the likelihood and keeps NUTS for the rest. The third makes the whole posterior Gaussian and comes with a check that can pass it or fail it. The fourth is what remains when the rows cannot be visited in whole passes, and it is the one whose spread has to be taken from somewhere else. The box at the bottom is where that somewhere else usually is.

Summary

  • An honest subsample loses a known factor, and nothing where there is nothing to lose. NUTS on 50,000 of a million rows took twenty to thirty seconds and covered the truth as often as it should. Its intervals were 4.3 times as wide as the full data allow for the intercept, the slopes and the effects, and exactly as wide for the three hierarchical standard deviations, which are learned from the number of groups and not of rows. The row-level fit of all the rows took about ten minutes, run once outside the notebook.
  • The best full-data answer came from asking which part of the posterior is hard. Seven Newton passes over all the rows, then NUTS on the hierarchy with the likelihood replaced by its quadratic expansion: a few seconds, the same answer as NUTS where we could check (means within 0.3 standard deviations, widths within noise), and an error against the truth almost six times smaller than the subsample's. Limit: it needs many rows per parameter. It could not be built on the real month, where two airports had no late flight and 126 had fewer than a hundred flights.
  • Minibatch ADVI failed silently in three ways before it worked. Without total_size it fitted the posterior of one batch: intervals ten times too wide. With PyMC's defaults it had not converged after 10,000 steps: intervals twelve times too wide, wider than the subsample's. With a tuned schedule its bound was flat after 1,000 steps while its standard deviations kept shrinking until step 17,000. The tuned fit put the means within 0.3 standard deviations of the yardstick, after the equivalent of 150 passes over the data.
  • Mean-field ADVI got the spread wrong exactly where a formula says it will. It reports each parameter's spread given all the others: the intercept's interval at 0.45 of its proper width, the slopes at 0.7 and 0.85, most effects within a few percent, as predicted from the covariance. The hierarchical standard deviations, the folklore's worst case, were right on the simulated flights (large groups), and one of them was 30% too narrow on the real month (many small airports). Coverage against the truth, counted over 71 numbers, did not notice any of it. The interval-width ratio did.
  • Full-rank ADVI did not deliver the covariance it promises. With 71 parameters its intervals were twice too wide after 30,000 steps. With 384, on the real month, it collapsed and kept a fifth of the model's gain in held-out score.
  • Laplace was the best Gaussian where the posterior is Gaussian. With exact second derivatives it matched the yardstick for the effects, and its faults in the three standard deviations were removed by importance weights that $\hat k = 0.4$ said could be trusted. On the real month it put the standard deviation between origins 4.6 posterior standard deviations low, and $\hat k = 2.3$ said so. Limit: fit_laplace takes its covariance from the optimiser's own estimate unless the optimiser uses exact second derivatives; with L-BFGS-B the intervals were seventeen times too wide.
  • Pathfinder was usable on 50,000 rows and failed on a million. Its means on the full data were up to ten standard deviations off, it was the slowest of the fast fits, and its own $\hat k$ of 1.8 flagged it. As a starting point for NUTS it saved eleven of 400 warm-up iterations and no gradients.
  • $\hat k$ ranked the approximations correctly and explained nothing. It passed the one fit that deserved it and failed the others, at ten seconds a method on a million rows. It did not say that full-rank ADVI was too wide and mean-field too narrow.
  • On real data the fast methods agreed on the predictions, and the model was the weak point. The held-out score was the same to three decimals for every full-data fit but the collapsed one. Half of the larger cells fell outside the model's 90% intervals, so no method's spread, exact or approximate, should be believed there. Limit: one month, a random hold-out, and a table without departure times or distances.

Try it yourself

  1. Ten million rows. Set N_ROWS = 10_000_000 and rerun parts 1 to 3 (the generator works in chunks and the codes take 110 MB, but each model holds several arrays of that length, so watch the memory). Which costs grow tenfold and which do not? The posterior standard deviations shrink by $\sqrt{10}$: at which step does the watched standard deviation of the mean-field fit now reach its floor, and does the schedule that worked for a million rows still leave the means within a third of a standard deviation?
  2. A better start for ADVI. pm.ADVI accepts start_sigma, a dictionary of starting standard deviations per variable. Start every one at 0.02 in place of the default, and redraw the middle panel of the convergence figure. How many steps does the tuned fit save, and does the default optimiser now arrive within its 10,000 steps?
  3. Break the yardstick on purpose. Set N_SUB = 5_000 and rebuild the yardstick of part 2 against NUTS on the same rows. The smallest airports now have a handful of flights. Which parameters does the quadratic get wrong first, by how much, and what happens to Newton's method when an airport has no late flight at all?
print(f"total run time: {time.time() - T_START:.0f} s")
total run time: 297 s