Inference and computation / E126

Ten million rows, one thousand cells: make the likelihood smaller before making the sampler faster

Type
Advanced worked example - read, run, modify
Data
Simulated: ten million flights generated in chunks, with a known truth, 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)
You will learn
Collapsing a Bernoulli regression with categorical covariates into binomial counts per cell, exactly · reducing a Gaussian regression to its sufficient statistics $(n, X^\top X, X^\top y, y^\top y)$, accumulated chunk by chunk · proving that each compression is exact by fitting rows and summaries on the same data · timing fits against the number of rows · what compression cannot do: check its own model, or survive one continuous covariate · the approximate case, banding a continuous covariate, with its bias measured against the full-data answer · why a weighted subsample claims a precision it does not have · the first compression again on a real month of flights, scored on held-out flights

The question

An airline analyst has ten million flight records and one question: how much does the chance of a late departure depend on the carrier, on the airport and on the time of day? The model is a hierarchical logistic regression, the kind every earlier notebook of this series fits in a few seconds. On ten million rows it does not. NUTS needs the gradient of the log density at every step, the gradient is a sum over the rows, and a fit of four chains takes about forty thousand gradients. Forty thousand passes over ten million rows take an hour or more on a laptop.

The usual reactions are to take a subsample, or to reach for a faster and rougher algorithm: variational inference, a Laplace approximation, a sampler on a GPU. This notebook is about a question that comes before any of them: does the likelihood really have ten million terms?

Fisher (1922) called a statistic sufficient when it carries everything the sample has to say about the parameters. Where a sufficient statistic of fixed size exists, the likelihood can be written from it alone, and the posterior is the same posterior, not an approximation of it, whether it is computed from the rows or from the summary. Two families cover a large share of applied work:

  • a model for a binary or count outcome whose covariates are all categorical depends on the data only through the counts in each combination of categories, a cell;
  • a Gaussian regression depends on the data only through $n$, $X^\top X$, $X^\top y$ and $y^\top y$.

Outside these families nothing is exact, and the literature offers approximations: replacing the data set by a much smaller one that stands for it, called data squashing (DuMouchel, Volinsky, Johnson, Cortes and Pregibon 1999), or by a weighted subset with guarantees on the error, a coreset (Huggins, Campbell and Broderick 2016; Campbell and Broderick 2019). We try the two simplest members of that family and measure what they cost.

Parts 1 to 4 are simulated, so the truth is known and each method gets a row on a scoreboard: wall time, memory, effective sample size per second, error against the truth, and how often its 90% intervals hold the truth. Part 5 repeats the first compression on a real month of flights, where there is no truth to score against and the test is a held-out one.

part question tool
1 What do ten million rows look like, and what would it take to fit them as they are? a chunked simulator, integer codes, one count
2 Can a logistic regression be fitted without its rows? Bernoulli rows against binomial cells, on the same data
3 Can a Gaussian regression? four accumulated sums and a pm.Potential
4 What if one covariate is continuous? banding, a full-data yardstick, a weighted subsample
5 Does it survive real data? one real month of flights, cells against a sample of rows, held-out scores
6 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 pytensor.tensor as pt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.patches import FancyArrowPatch, FancyBboxPatch, Patch
from matplotlib.ticker import MaxNLocator
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 = 126
rng = np.random.default_rng(RANDOM_SEED)
az.style.use("arviz-variat")
plt.rcParams.update({"axes.labelsize": 10, "xtick.labelsize": 9, "ytick.labelsize": 9})
logging.getLogger("pymc").setLevel(logging.WARNING)
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")
SEQ = LinearSegmentedColormap.from_list("blues", ["#fcfcfb", "#cde2fb", "#6da7ec", "#256abf", "#0d366b"])


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 · Ten million rows

The simulated world has 10 carriers, 20 airports and 5 departure blocks through the day, which makes $10 \times 20 \times 5 = 1{,}000$ cells. Flights are spread unevenly over them: carriers and airports differ in size, and each carrier has airports where it is strong, as hubs are in the real network. A flight leaves late with a probability that depends on its three categories,

$$\operatorname{logit} p_i = a + b^{\text{carrier}}_{c(i)} + b^{\text{airport}}_{o(i)} + b^{\text{block}}_{h(i)},$$

with effects that sum to zero within each family and delays that build up through the day. Each flight also has a continuous covariate, its log distance $z_i$ on a standard scale, which is correlated with the airport; a second outcome, a late arrival, which depends on $z$ as well (part 4); and a duration with five further covariates (part 3). The truth below is what every method will be scored against.

N_ROWS, CHUNK = 10_000_000, 1_000_000
SHAPE = (10, 20, 5)                                   # carriers, airports, departure blocks
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])],
          "block": ["06-09", "09-12", "12-15", "15-18", "18-22"]}
CARRIER, AIRPORT, BLOCK = 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.5,                                    # late departures
        "b_carrier": centred(world.normal(0, 0.35, SHAPE[0])),
        "b_airport": centred(world.normal(0, 0.45, SHAPE[1])),
        "b_block": centred(np.array([-0.55, -0.25, 0.0, 0.30, 0.50]))}
TRUE_ARR = {**TRUE, "a": -1.4, "gamma": 0.5}          # late arrivals: the same effects and a slope on distance
ETA_CELL = TRUE["a"] + TRUE["b_carrier"][CARRIER] + TRUE["b_airport"][AIRPORT] + TRUE["b_block"][BLOCK]

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_block = np.array([0.16, 0.24, 0.22, 0.22, 0.16])
P_CELL = (share_carrier[:, None] * share_airport[None, :] * hubs)[:, :, None] * share_block
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()

X_NAMES = ["intercept", "log distance", "headwind", "congestion", "seats", "temperature", "load factor"]
BETA_TRUE = np.array([4.9, 0.45, 0.03, 0.05, 0.01, -0.005, 0.0])       # log minutes, gate to gate
SIGMA_TRUE = 0.10
MIX = np.eye(5) + 0.35 * world.normal(size=(5, 5))    # the five other covariates are correlated
MIX /= np.sqrt((MIX**2).sum(axis=1, keepdims=True))
ON_DISTANCE = np.array([0.3, -0.2, 0.4, 0.0, 0.1])    # and lean on distance


def flights(i):
    """Chunk ``i`` of the simulated flights: codes, distance, two late flags, the regression's rows."""
    r, n = np.random.default_rng([RANDOM_SEED, 1, i]), CHUNK    # a chunk is a pure function of its number
    cell = r.choice(N_CELLS, size=n, p=P_CELL)
    z = (0.6 * AIRPORT_Z[AIRPORT[cell]] + 0.8 * r.standard_normal(n)).astype(np.float32)
    late_dep = r.random(n) < special.expit(ETA_CELL[cell])
    late_arr = r.random(n) < special.expit(ETA_CELL[cell] + TRUE_ARR["a"] - TRUE["a"] + TRUE_ARR["gamma"] * z)
    X = np.empty((n, len(BETA_TRUE)))
    X[:, 0], X[:, 1] = 1.0, z
    X[:, 2:] = r.standard_normal((n, 5)) @ MIX.T + np.outer(z, ON_DISTANCE)
    log_minutes = X @ BETA_TRUE + SIGMA_TRUE * r.standard_normal(n)
    return cell.astype(np.int16), z, late_dep, late_arr, X, log_minutes

The flights are generated a million at a time, and what we keep of each row is what a careful analyst would store: the cell as a 16-bit integer, the two late flags as bytes and the distance as a 32-bit float. The regression rows of part 3 are not kept at all.

cell = np.empty(N_ROWS, np.int16)
z = np.empty(N_ROWS, np.float32)
late_dep = np.empty(N_ROWS, np.int8)
late_arr = np.empty(N_ROWS, np.int8)
t0 = time.perf_counter()
for i in range(N_ROWS // CHUNK):
    rows = slice(i * CHUNK, (i + 1) * CHUNK)
    cell[rows], z[rows], late_dep[rows], late_arr[rows], _, _ = flights(i)
t_generate = time.perf_counter() - t0

stored_mb = (cell.nbytes + z.nbytes + late_dep.nbytes + late_arr.nbytes) / 1e6
n_coef = 1 + sum(SHAPE)
print(f"{N_ROWS:,} flights generated in {t_generate:.0f} s; late departures {late_dep.mean():.1%}, "
      f"late arrivals {late_arr.mean():.1%}")
print(f"stored as codes: {stored_mb:.0f} MB.  As a dense design matrix of {n_coef} columns in float64: "
      f"{N_ROWS * n_coef * 8 / 1e9:.1f} GB, which is never built here")

t0 = time.perf_counter()
trials_all = np.bincount(cell, minlength=N_CELLS)
late_all = np.bincount(cell, weights=late_dep, minlength=N_CELLS).astype(int)
t_count = time.perf_counter() - t0
print(f"\ncounting the {N_CELLS:,} cells takes {t_count * 1e3:.0f} ms; flights per cell: smallest {trials_all.min():,}, "
      f"median {int(np.median(trials_all)):,}, largest {trials_all.max():,}")
first = np.bincount(cell[:100_000], minlength=N_CELLS)
print(f"in the first 100,000 flights: median {int(np.median(first))} per cell, {np.sum(first == 0)} cells empty")
print(f"the largest carrier-airport pair holds {trials_all.reshape(SHAPE).sum(axis=2).max() / N_ROWS:.1%} of the flights")
10,000,000 flights generated in 2 s; late departures 16.6%, late arrivals 21.5%
stored as codes: 80 MB.  As a dense design matrix of 36 columns in float64: 2.9 GB, which is never built here

counting the 1,000 cells takes 65 ms; flights per cell: smallest 63, median 2,971, largest 216,813
in the first 100,000 flights: median 30 per cell, 15 cells empty
the largest carrier-airport pair holds 9.0% of the flights
fig, axes = plt.subplots(1, 3, figsize=(13.5, 3.9), gridspec_kw={"width_ratios": [1.5, 1, 1]})
ax = axes[0]
per_pair = trials_all.reshape(SHAPE).sum(axis=2)
im = ax.imshow(per_pair / 1e3, aspect="auto", cmap=SEQ, vmin=0)
ax.set_xticks(range(0, SHAPE[1], 2), range(1, SHAPE[1] + 1, 2))
ax.set_yticks(range(SHAPE[0]), range(1, SHAPE[0] + 1))
ax.set_xlabel("airport")
ax.set_ylabel("carrier")
ax.grid(False)
ax.set_title("Flights per carrier and airport", loc="left")
fig.colorbar(im, ax=ax, pad=0.02, label="thousand flights")

ax = axes[1]
for n, color in ((100_000, ORANGE), (N_ROWS, BLUE)):
    sizes = np.sort(np.bincount(cell[:n], minlength=N_CELLS))[::-1]
    ax.plot(np.arange(1, N_CELLS + 1), np.maximum(sizes, 0.5), color=color, lw=1.8, label=f"{n:,} rows")
ax.set_yscale("log")
ax.set_xlabel("cells, largest first")
ax.set_ylabel("flights in the cell")
ax.legend(frameon=False, fontsize=9)
ax.set_title("How many rows a cell holds", loc="left")
tidy(ax)

ax = axes[2]
rate = (late_all.reshape(SHAPE).sum(axis=1) / trials_all.reshape(SHAPE).sum(axis=1))   # carrier x block
for c in range(SHAPE[0]):
    ax.plot(range(SHAPE[2]), rate[c], color=BLUE, lw=1, alpha=0.55)
ax.plot(range(SHAPE[2]), late_all.reshape(SHAPE).sum(axis=(0, 1)) / trials_all.reshape(SHAPE).sum(axis=(0, 1)),
        color=INK, lw=2.2, label="all carriers")
ax.set_xticks(range(SHAPE[2]), COORDS["block"])
ax.set_xlabel("departure block")
ax.set_ylabel("share of departures late")
ax.legend(frameon=False, fontsize=9)
ax.set_title("Delays build up through the day", loc="left")
tidy(ax);
Figure

Stored as codes, the ten million flights take 80 MB. The same flights as the design matrix a regression routine would ask for, 36 columns of zeros and ones in double precision, would take 2.9 GB, which is about all the memory this notebook allows itself. The count that part 2 rests on takes a fraction of a second.

The left panel shows how unevenly the flights are spread: one carrier at its main airport holds 9% of them, and much of the grid is nearly empty. The middle panel says the same of the 1,000 cells. With all ten million rows the smallest cell still has 63 flights and the median about 3,000. In the first 100,000 rows the median cell has 30 flights, and 15 cells have none. The right panel is the signal the model is after: the share of late departures rises from 10% in the first block of the day to 24% in the last, and one carrier is late far more often than the rest.

One note on the data. Part 5 repeats the exercise on a real month, the flights of January 2024 from the on-time performance table of the Bureau of Transportation Statistics, in the re-coded form this repository already holds for E87. The larger extract this notebook was planned around, about a million flights with departure hours and distances, was not built: we found no licence statement for that table on the pages of the bureau or of the Department of Transportation.

2 · A logistic regression without its rows

The idea

Write $y_i \in \{0, 1\}$ for "flight $i$ left late". Under the model every flight in the same cell has the same probability $p_c$, so the likelihood groups by cell:

$$\prod_{i=1}^{N} p_{c(i)}^{\,y_i}\,(1 - p_{c(i)})^{1 - y_i} \;=\; \prod_{c=1}^{1000} p_c^{\,k_c}\,(1 - p_c)^{\,n_c - k_c},$$

where $n_c$ is the number of flights in cell $c$ and $k_c$ the number of them that left late. The right-hand side is a binomial likelihood for $k_c$ out of $n_c$, up to the factor $\binom{n_c}{k_c}$, which does not involve the parameters and so drops out of the posterior. Nothing was approximated. The two thousand numbers $(n_c, k_c)$ are a sufficient statistic, and a model that sees them instead of the rows has the same posterior, not a similar one.

In PyMC the change is one line: pm.Bernoulli(..., observed=y) on rows becomes pm.Binomial(n=n, ..., observed=k) on cells. The function below builds either, and also the two variants part 4 needs, a slope on a continuous covariate and a weight on the log-likelihood.

def delay_model(cells, late, trials=None, z=None, weight=None, coords=COORDS):
    """Hierarchical logistic model of a late flight, on rows (``trials=None``) or on cell counts."""
    shape = tuple(len(levels) for levels in coords.values())
    with pm.Model(coords=coords) as model:
        eta = pm.Normal("a", -1.0, 1.5)
        for name, codes in zip(coords, np.unravel_index(np.asarray(cells, dtype=np.int64), shape)):
            sd = pm.HalfNormal(f"sd_{name}", 1.0)
            eta = eta + pm.ZeroSumNormal(f"b_{name}", sigma=sd, dims=name)[codes]
        if z is not None:
            eta = eta + pm.Normal("gamma", 0.0, 1.0) * np.asarray(z, dtype=float)
        if trials is not None:
            pm.Binomial("late", n=trials, logit_p=eta, observed=late)
        elif weight is None:
            pm.Bernoulli("late", logit_p=eta, observed=late)
        else:                                          # every row counted `weight` times
            pm.Potential("late", weight * pm.logp(pm.Bernoulli.dist(logit_p=eta), late).sum())
    return model


def cell_counts(n, late=late_dep):
    """Flights and late flights per non-empty cell among the first ``n`` rows."""
    trials = np.bincount(cell[:n], minlength=N_CELLS)
    k = np.bincount(cell[:n], weights=late[:n], minlength=N_CELLS).astype(int)
    keep = trials > 0
    return np.flatnonzero(keep), k[keep], trials[keep]


DIAGNOSTICS = {}


def fit(sb, name, model):
    """Sample ``model`` on the scoreboard's clock; keep its posterior and its diagnostics."""
    with sb.track(name):
        with model:
            idata = pm.sample(random_seed=RANDOM_SEED, progressbar=False)
    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 post


def label(n):
    return f"{n // 1_000_000}M" if n >= 1_000_000 else f"{n // 1000}k"

The priors are the ones we would use on real flights: an intercept near a delay rate of a quarter, and effects in each family that sum to zero with a standard deviation the data choose. Before fitting, we look at what they imply for the quantity we can picture, the delay rate of a cell.

with delay_model(*cell_counts(N_ROWS)) as cells_10m:
    prior = pm.sample_prior_predictive(draws=500, random_seed=RANDOM_SEED)
prior_rate = (prior.prior_predictive["late"].values[0] / cell_counts(N_ROWS)[2]).ravel()
print("prior predictive delay rate of a cell, quantiles 5%, 25%, 50%, 75%, 95%:",
      np.round(np.quantile(prior_rate, [0.05, 0.25, 0.5, 0.75, 0.95]), 3))
del prior
prior predictive delay rate of a cell, quantiles 5%, 25%, 50%, 75%, 95%: [0.009 0.083 0.276 0.626 0.936]

The priors are loose: they let the delay rate of a cell be anything from 1% to more than 90%, with a median near a quarter. With thousands of flights in a typical cell they will hardly matter, and in the sparse cells the hierarchy shares information across carriers and airports.

The same data, twice

The claim is that rows and cells give the same posterior. We check it where the row-level fit is still affordable: the first 10,000, 30,000 and 100,000 flights, fitted as Bernoulli rows, and the same flights fitted as binomial cells. Then the cells alone carry on to a million and to all ten million. Every fit uses the default sampler settings (nutpie, four chains, 1,000 draws each), and the clock includes compiling the model.

sb_a = Scoreboard(truth=TRUE)
post_a = {}
for n in (10_000, 30_000, 100_000):
    post_a[f"rows · {label(n)}"] = fit(sb_a, f"rows · {label(n)}", delay_model(cell[:n], late_dep[:n]))
for n in (10_000, 100_000, 1_000_000, N_ROWS):
    post_a[f"cells · {label(n)}"] = fit(sb_a, f"cells · {label(n)}", delay_model(*cell_counts(n)))
pd.DataFrame(DIAGNOSTICS).T.round(3)
divergences max r_hat steps per draw
rows · 10k 0.0 1.005 7.032
rows · 30k 0.0 1.003 7.052
rows · 100k 0.0 1.007 7.046
cells · 10k 0.0 1.004 7.044
cells · 100k 0.0 1.005 7.062
cells · 1M 0.0 1.005 7.054
cells · 10M 0.0 1.004 7.076
sb_a.table().round(4)
seconds peak_gb added_gb ess ess_per_s rmse coverage width
method
rows · 10k 9.7920 0.8237 0.0201 1115.4992 113.9192 0.1058 0.9722 0.4195
rows · 30k 18.8562 0.4950 0.0639 857.7357 45.4884 0.0911 0.8333 0.2501
rows · 100k 56.3094 0.5461 0.0507 806.9540 14.3307 0.0530 0.9444 0.1401
cells · 10k 1.7111 0.4631 0.2496 1399.0870 817.6770 0.1057 0.9722 0.4184
cells · 100k 1.8368 0.4755 0.0119 961.3343 523.3806 0.0526 0.9444 0.1390
cells · 1M 1.8503 0.5068 0.0122 968.5409 523.4565 0.0145 0.9444 0.0444
cells · 10M 1.8077 0.7043 0.0105 920.7490 509.3450 0.0040 0.9722 0.0142
sb_a.plot(highlight=[m for m in post_a if m.startswith("cells")]);
Figure

All seven fits are clean: no divergences, $\hat R$ below 1.01, and about seven gradient evaluations per draw whatever the data.

Read the scoreboard in pairs. On the same 10,000 flights rows and cells have the same error against the truth (0.106) and the same coverage; on the same 100,000 they agree again (0.053). What differs is the clock. The row-level fit takes longer as the rows grow, more than half a minute for 100,000, and the cell-level fit takes a few seconds every time, most of them spent compiling the model. Then the cells go where the rows cannot follow. On all ten million flights the fit takes no longer, and the error falls to 0.004, thirteen times smaller than on the 100,000-row subsample that took more than ten times as long. Coverage of the 90% intervals stays between 0.83 and 0.97; with 36 parameters one parameter is 3 points, so none of these is far from nominal.

The subsample is the method that loses here, and it is worth saying how. Its posterior is honest: the intervals are wide and they hold the truth. But it is the posterior of 1% of the data, when the other 99% could have been used at no cost.

The table says the two fits agree on the truth. The next cell compares them with each other.

def same_posterior(p, q, names):
    """Largest gap between two posteriors' means, in posterior sds, and the range of their sd ratio."""
    gap, ratio = [], []
    for v in names:
        sd = p[v].std(("chain", "draw")).values
        gap.append(np.ravel(np.abs(p[v].mean(("chain", "draw")).values - q[v].mean(("chain", "draw")).values) / sd))
        ratio.append(np.ravel(q[v].std(("chain", "draw")).values / sd))
    return np.concatenate(gap), np.concatenate(ratio)


def flat(post, names):
    """Draws of the named parameters as one (draws, parameters) array."""
    return np.column_stack([post[v].values.reshape(post[v].shape[0] * post[v].shape[1], -1) for v in names])


EFFECTS = ["a", "b_carrier", "b_airport", "b_block"]
gap, ratio = same_posterior(post_a["rows · 100k"], post_a["cells · 100k"], EFFECTS + ["sd_carrier", "sd_airport", "sd_block"])
print(f"rows against cells on the same 100,000 flights, {len(gap)} parameters:")
print(f"  largest gap between posterior means: {gap.max():.3f} posterior sd;  ratio of posterior sds: "
      f"{ratio.min():.2f} to {ratio.max():.2f}")
print(f"  Monte Carlo error expected for a mean with this ESS: about {1 / np.sqrt(sb_a.table().loc['rows · 100k', 'ess']):.3f} sd")
rows against cells on the same 100,000 flights, 39 parameters:
  largest gap between posterior means: 0.050 posterior sd;  ratio of posterior sds: 0.93 to 1.07
  Monte Carlo error expected for a mean with this ESS: about 0.035 sd
truth_vec = np.concatenate([np.ravel(TRUE[v]) for v in EFFECTS])
order = np.argsort(truth_vec)
fig, axes = plt.subplots(1, 2, figsize=(13.5, 4.4), gridspec_kw={"width_ratios": [1.7, 1]})
ax = axes[0]
for name, color, shift in (("rows · 100k", ORANGE, -0.22), ("cells · 100k", BLUE, 0.0), ("cells · 10M", INK, 0.22)):
    draws = flat(post_a[name], EFFECTS)[:, order]
    lo, hi = np.quantile(draws, [0.05, 0.95], axis=0)
    x = np.arange(len(order)) + shift
    ax.vlines(x, lo - truth_vec[order], hi - truth_vec[order], color=color, lw=1.6, label=name)
    ax.plot(x, draws.mean(axis=0) - truth_vec[order], "o", color=color, ms=2.6)
ax.axhline(0, color=MUTED, lw=0.9)
ax.set_xlabel("the 36 parameters, ordered by their true value")
ax.set_ylabel("posterior minus truth (logit)")
ax.set_xticks([])
ax.legend(frameon=False, fontsize=9, ncol=3, loc="upper left")
ax.set_title("90% intervals, with the truth subtracted", loc="left")
tidy(ax)

ax = axes[1]
lo_r, hi_r = np.quantile(flat(post_a["rows · 100k"], EFFECTS), [0.05, 0.95], axis=0)
lo_c, hi_c = np.quantile(flat(post_a["cells · 100k"], EFFECTS), [0.05, 0.95], axis=0)
ax.plot([lo_r.min(), hi_r.max()], [lo_r.min(), hi_r.max()], color=MUTED, lw=0.9)
ax.plot(lo_r, lo_c, "o", color=BLUE, ms=4, label="5% bound")
ax.plot(hi_r, hi_c, "s", color=ORANGE, ms=4, label="95% bound")
ax.set_xlabel("from 100,000 Bernoulli rows")
ax.set_ylabel("from the binomial cells of the same rows")
ax.legend(frameon=False, fontsize=9)
ax.set_title("Interval bounds: rows against cells", loc="left")
tidy(ax, grid="both");
Figure

The largest gap between the two sets of posterior means is 0.05 posterior standard deviations, the size of the Monte Carlo error of either fit, and the posterior standard deviations agree to within 7%, which is what two runs of about a thousand effective draws give. In the left panel the orange and blue intervals are the same intervals, and the right panel plots their ends against each other: they lie on the diagonal. The black intervals are the fit on ten million rows, a tenth as wide and still around the truth.

Fit time against the number of rows

To see where the row-level fit goes beyond 100,000 flights without waiting for it, we time the thing it is made of: one evaluation of the log density and its gradient, on up to all ten million rows.

def gradient_ms(model, repeats=5):
    """Milliseconds for one evaluation of a model's log density and its gradient: the best of a few."""
    f = model.logp_dlogp_function(ravel_inputs=True)
    x = np.concatenate([np.ravel(v) for v in model.initial_point().values()])
    f(x)                                              # compile, and warm up
    best = np.inf
    for _ in range(repeats):
        t0 = time.perf_counter()
        f(x)
        best = min(best, time.perf_counter() - t0)    # the minimum ignores whatever else the machine is doing
    return 1e3 * best


SIZES = (10_000, 100_000, 1_000_000, N_ROWS)
grad_cells = {n: gradient_ms(delay_model(*cell_counts(n))) for n in SIZES}
grad_rows = {n: gradient_ms(delay_model(cell[:n], late_dep[:n])) for n in SIZES[:-1]}
probe = Scoreboard()                                  # borrowed for its memory watcher
with probe.track("rows · 10M"):
    grad_rows[N_ROWS] = gradient_ms(delay_model(cell, late_dep))
steps = (400 + 1000) * DIAGNOSTICS["rows · 100k"]["steps per draw"]            # gradients per chain: warm-up and draws
print(pd.DataFrame({"rows (ms)": grad_rows, "cells (ms)": grad_cells}).round(3).to_string())
print(f"\na chain takes about {steps:,.0f} gradient evaluations; on ten million rows that is "
      f"{steps * grad_rows[N_ROWS] / 1e3 / 60:.0f} minutes of gradients for each chain")
print(f"memory added while the gradient runs on ten million rows, for one chain: {probe.table().loc['rows · 10M', 'added_gb']:.1f} GB")
          rows (ms)  cells (ms)
10000         0.249       0.033
100000        2.426       0.038
1000000      24.328       0.034
10000000    314.184       0.033

a chain takes about 9,864 gradient evaluations; on ten million rows that is 52 minutes of gradients for each chain
memory added while the gradient runs on ten million rows, for one chain: 0.5 GB
def time_figure(ax, sb, kind, grad, title, compress_s):
    """Fit time against rows: measured fits, and the row-level fit projected from its gradient cost."""
    table = sb.table()
    rows = {n: table.loc[f"rows · {label(n)}", "seconds"] for n in (10_000, 30_000, 100_000)}
    small = {n: table.loc[f"{kind} · {label(n)}", "seconds"] for n in SIZES}
    projected = {n: rows[100_000] * grad[n] / grad[100_000] for n in (100_000, 1_000_000, N_ROWS)}
    ax.plot(list(rows), list(rows.values()), "o-", color=ORANGE, lw=2, label="rows: fits we ran")
    ax.plot(list(projected), list(projected.values()), "o--", color=ORANGE, lw=1.6, mfc="white",
            label="rows: projected from the measured gradient")
    ax.plot(list(small), list(small.values()), "s-", color=BLUE, lw=2, label=f"{kind}: fits we ran")
    ax.plot(list(compress_s), list(compress_s.values()), ":", color=BLUE, lw=1.6, label="the one pass that compresses")
    ax.annotate(f"{projected[N_ROWS] / 60:.0f} min", (N_ROWS, projected[N_ROWS]), xytext=(-8, 6),
                textcoords="offset points", ha="right", fontsize=9, color=ORANGE)
    ax.annotate(f"{small[N_ROWS]:.1f} s", (N_ROWS, small[N_ROWS]), xytext=(-8, 6), textcoords="offset points",
                ha="right", fontsize=9, color=BLUE)
    ax.set_xscale("log")
    ax.set_yscale("log")
    ax.set_ylim(top=30 * projected[N_ROWS])
    ax.set_xlabel("rows")
    ax.set_ylabel("seconds")
    ax.set_title(title, loc="left")
    tidy(ax, grid="both")
    return projected


count_s = {}
for n in SIZES:
    t0 = time.perf_counter()
    cell_counts(n)
    count_s[n] = time.perf_counter() - t0
fig, ax = plt.subplots(figsize=(7.6, 4.6))
projected_a = time_figure(ax, sb_a, "cells", grad_rows, "Logistic regression: fit time against rows", count_s)
ax.legend(frameon=False, fontsize=9, loc="upper left");
Figure

The table shows two regimes. One gradient of the row-level model costs a fraction of a millisecond on 10,000 rows and a few tenths of a second on ten million: it is proportional to the rows, as a sum over rows must be. One gradient of the cell-level model costs less than a tenth of a millisecond at every size, thousands of times less at ten million rows. A chain needs about 10,000 gradients, so the row-level fit of all the flights would spend of the order of an hour per chain on gradients alone, the time printed under the table. The last line is the memory that one such gradient function adds while it runs, and each chain needs its own.

The figure is the one this notebook is named for. The solid orange points are row-level fits we ran. The hollow ones scale the 100,000-row fit by the measured cost of a gradient, which puts the fit of ten million rows at an hour or more; the label on the figure is this run's value, and it moves with whatever else the machine is doing. The blue line is flat: once the rows are counted, the model does not know how many there were. The dotted line is the price of the counting itself, a single pass that takes a fraction of a second for ten million rows, less than one row-level gradient.

A check that needs the cells

Compression also gives something back. A row of zeros and ones cannot show overdispersion; a cell can. If flights in the same cell were late together more often than the model allows (a storm, a strike), the cell counts would scatter more widely than binomial, and their predictive intervals would miss too often.

def cell_logit(post, n_draws=400):
    """Draws of the linear predictor of each of the 1,000 cells."""
    pick = rng.choice(post.sizes["chain"] * post.sizes["draw"], n_draws, replace=False)
    d = {v: post[v].values.reshape(-1, *post[v].shape[2:])[pick] for v in EFFECTS}
    return d["a"][:, None] + d["b_carrier"][:, CARRIER] + d["b_airport"][:, AIRPORT] + d["b_block"][:, BLOCK]


replicated = rng.binomial(trials_all, special.expit(cell_logit(post_a["cells · 10M"])))
lo, hi = np.quantile(replicated, [0.05, 0.95], axis=0)
print(f"cells whose late count lies inside its 90% predictive interval: {np.mean((late_all >= lo) & (late_all <= hi)):.1%} "
      f"of {N_CELLS:,}")
cells whose late count lies inside its 90% predictive interval: 91.3% of 1,000

About 91% of the cells sit inside their 90% interval, as binomial counts should: the simulated flights share no shocks. Real flights do, and part 5 finds this number well below 90% on a real month. The remedy is a term in the model, the simplest being a beta-binomial likelihood on the same cells.

Where the cells run out

The compression is exact, and it is tied to the model. The cells are the combinations of the covariates the model uses, so each covariate we add multiplies them, and the count below shows how fast ten million rows stop being many. It is the expected number of non-empty cells when further categorical covariates are spread evenly over their levels.

rows = []
for added, levels in (("carrier x airport x block", 1), ("+ day of week", 7), ("+ month", 7 * 12),
                      ("+ destination airport", 7 * 12 * 20), ("+ aircraft type (30)", 7 * 12 * 20 * 30)):
    occupied = levels * np.sum(-np.expm1(-N_ROWS * P_CELL / levels))        # expected non-empty cells
    rows.append({"covariates": added, "possible cells": N_CELLS * levels, "non-empty cells": round(occupied),
                 "rows per cell": N_ROWS / occupied})
pd.DataFrame(rows).set_index("covariates").round(1)
possible cells non-empty cells rows per cell
covariates
carrier x airport x block 1000 1000 10000.0
+ day of week 7000 7000 1428.6
+ month 84000 83267 120.1
+ destination airport 1680000 1206554 8.3
+ aircraft type (30) 50400000 6905174 1.4

With the three covariates of our model a cell averages 10,000 flights. Day of week and month still leave over a hundred flights per cell, though 83,000 cells cost about what as many rows would. The destination airport brings the average to 8 flights, and one more covariate with 30 levels to 1.4: by then most cells hold a single flight and counting has compressed nothing. The method is for models with a handful of categorical covariates, or for data whose rows are many compared with the product of the levels.

The choice. Count the rows into cells and fit a binomial model. Rejected: fitting the rows (the same posterior, more than ten times slower on 100,000 rows and an hour or more on ten million), and fitting a subsample of rows (an honest posterior, of a hundredth of the data). What would change our mind: a covariate that takes a different value on nearly every row, which is part 4, or a model with something to estimate for each row.

3 · A Gaussian regression in four sums

The idea

The second outcome is the logarithm of the gate-to-gate time of a flight, regressed on log distance and five other continuous covariates: headwind, congestion at the origin, seats, temperature and load factor. No two flights share a row of $X$, so there are no cells to count. But the Gaussian log-likelihood touches the data only through a sum of squares,

$$\sum_{i=1}^{N} (y_i - x_i^\top \beta)^2 \;=\; y^\top y - 2\,\beta^\top X^\top y + \beta^\top X^\top X \beta \;=\; \mathrm{RSS} + (\beta - \hat\beta)^\top X^\top X\, (\beta - \hat\beta),$$

where $\hat\beta = (X^\top X)^{-1} X^\top y$ is the least-squares estimate and $\mathrm{RSS} = y^\top y - \hat\beta^\top X^\top y$ its residual sum of squares. The whole likelihood is therefore

$$\log p(y \mid \beta, \sigma) = -\tfrac{n}{2}\log(2\pi\sigma^2) - \frac{\mathrm{RSS} + (\beta - \hat\beta)^\top X^\top X\,(\beta - \hat\beta)}{2\sigma^2},$$

a function of $n$, the $7 \times 7$ matrix $X^\top X$, the vector $X^\top y$ and the number $y^\top y$: 58 numbers for any number of rows. Each of them is a sum over rows, so they can be accumulated a chunk at a time, on data that never fit in memory together. The second form, centred on $\hat\beta$, is the one to code: the first subtracts large numbers that nearly cancel.

P = len(BETA_TRUE)


def new_statistics(dtype=np.float64):
    return {"n": 0, "XtX": np.zeros((P, P), dtype), "Xty": np.zeros(P, dtype), "yty": dtype(0), "seconds": 0.0}


def add_rows(s, X, y):
    """Add a chunk of rows to the running n, X'X, X'y and y'y, in the precision the statistics were opened with."""
    X, y = X.astype(s["XtX"].dtype), y.astype(s["XtX"].dtype)
    t0 = time.perf_counter()
    s["n"] += len(y)
    s["XtX"] += X.T @ X
    s["Xty"] += X.T @ y
    s["yty"] += y @ y
    s["seconds"] += time.perf_counter() - t0
    return s


def least_squares(s):
    """beta_hat and RSS from the accumulated statistics."""
    XtX, Xty = s["XtX"].astype(float), s["Xty"].astype(float)
    beta_hat = np.linalg.solve(XtX, Xty)
    return beta_hat, float(s["yty"]) - beta_hat @ Xty


def gaussian_loglik(beta, sigma, s):
    """The Gaussian log-likelihood of all the rows behind the statistics ``s`` (NumPy or PyTensor arguments)."""
    beta_hat, rss = least_squares(s)
    d = beta - beta_hat
    symbolic = isinstance(sigma, pt.TensorVariable)
    quad = pt.dot(d, pt.dot(s["XtX"].astype(float), d)) if symbolic else d @ s["XtX"] @ d
    return -0.5 * s["n"] * (pt.log if symbolic else np.log)(2 * np.pi * sigma**2) - (rss + quad) / (2 * sigma**2)


def regression_model(X=None, y=None, s=None):
    """Gaussian regression on rows (``X``, ``y``) or on the accumulated statistics ``s``."""
    with pm.Model(coords={"covariate": X_NAMES}) as model:
        beta = pm.Normal("beta", np.r_[5.0, np.zeros(P - 1)], np.r_[2.0, np.ones(P - 1)], dims="covariate")
        sigma = pm.HalfNormal("sigma", 1.0)
        if s is None:
            pm.Normal("y", pt.dot(X, beta), sigma, observed=y)
        else:
            pm.Potential("y", gaussian_loglik(beta, sigma, s))
    return model


def heavy_tails(X, i):
    """A second outcome for the same rows: the same mean and noise variance, Student-t noise on 3 degrees of freedom."""
    noise = np.random.default_rng([RANDOM_SEED, 2, i]).standard_t(3, len(X)) / np.sqrt(3)
    return X @ BETA_TRUE + SIGMA_TRUE * noise


# One pass over the ten million rows. It also keeps two things for the end of this part: the same sums
# in single precision, and the sums of a second outcome whose noise is not Gaussian.
stats_all, stats_32, stats_t = new_statistics(), new_statistics(np.float32), new_statistics()
for i in range(N_ROWS // CHUNK):
    *_, X, y = flights(i)
    add_rows(stats_all, X, y)
    add_rows(stats_32, X, y)
    add_rows(stats_t, X, heavy_tails(X, i))
    if i == 0:
        X_head, y_head = X, y                          # the first million rows, kept for the row-level fits
beta_hat, rss = least_squares(stats_all)
print(f"one pass over {stats_all['n']:,} rows: {stats_all['seconds']:.1f} s of accumulation, in chunks of "
      f"{CHUNK * P * 8 / 1e6:.0f} MB; all {N_ROWS:,} rows of X at once would be {N_ROWS * P * 8 / 1e6:.0f} MB")
print(f"what is kept: n, a {P} x {P} matrix, a vector of {P} and one number, {P * P + P + 2} numbers in all")

# The helper against the definition: the log-likelihood from the statistics, and the sum over rows.
stats_n = {n: add_rows(new_statistics(), X_head[:n], y_head[:n]) for n in (10_000, 100_000, 1_000_000)} | {N_ROWS: stats_all}
worst = 0.0
for _ in range(5):
    b, sg = BETA_TRUE + 0.02 * rng.standard_normal(P), SIGMA_TRUE * np.exp(0.2 * rng.standard_normal())
    direct = stats.norm(X_head[:100_000] @ b, sg).logpdf(y_head[:100_000]).sum()
    worst = max(worst, abs(gaussian_loglik(b, sg, stats_n[100_000]) - direct) / abs(direct))
print(f"log-likelihood from the statistics against the sum over rows, at 5 random parameter values: "
      f"largest relative difference {worst:.0e}")
one pass over 10,000,000 rows: 0.3 s of accumulation, in chunks of 56 MB; all 10,000,000 rows of X at once would be 560 MB
what is kept: n, a 7 x 7 matrix, a vector of 7 and one number, 58 numbers in all
log-likelihood from the statistics against the sum over rows, at 5 random parameter values: largest relative difference 1e-12

The pass adds a fraction of a second of arithmetic to the cost of reading the rows, in pieces of 56 MB where the whole of $X$ would be 560 MB. The helper agrees with the definition to twelve digits on 100,000 rows, at parameter values drawn around the truth.

The same data, twice, again

Rows first, then the statistics of the same rows, then the statistics of more rows than a row-level fit can hold.

TRUE_REG = {"beta": BETA_TRUE, "sigma": SIGMA_TRUE}
sb_b = Scoreboard(truth=TRUE_REG)
post_b = {}
for n in (10_000, 30_000, 100_000):
    post_b[f"rows · {label(n)}"] = fit(sb_b, f"rows · {label(n)}", regression_model(X_head[:n], y_head[:n]))
for n in SIZES:
    post_b[f"statistics · {label(n)}"] = fit(sb_b, f"statistics · {label(n)}", regression_model(s=stats_n[n]))

# The closed form the sampler should agree with: a flat prior gives a multivariate t around beta_hat.
with sb_b.track("closed form · 10M"):
    b_closed, rss_closed = least_squares(stats_all)
    dof = stats_all["n"] - P
    scale = np.sqrt(rss_closed / dof * np.diag(np.linalg.inv(stats_all["XtX"])))
    closed = {"beta": b_closed + scale * stats.t(dof).rvs((4000, P), random_state=rng),
              "sigma": np.sqrt(rss_closed / stats.chi2(dof).rvs(4000, random_state=rng))}
sb_b.score("closed form · 10M", closed)
pd.DataFrame({k: v for k, v in DIAGNOSTICS.items() if k in post_b}).T.round(3)
divergences max r_hat steps per draw
rows · 10k 0.0 1.002 6.373
rows · 30k 0.0 1.002 6.180
rows · 100k 0.0 1.002 6.370
statistics · 10k 0.0 1.001 6.444
statistics · 100k 0.0 1.002 6.198
statistics · 1M 0.0 1.004 6.396
statistics · 10M 0.0 1.001 6.262
sb_b.table().round(5)
seconds peak_gb added_gb ess ess_per_s rmse coverage width
method
rows · 10k 2.13479 1.47199 0.03734 2326.99741 1090.03711 0.00167 0.875 0.00410
rows · 30k 5.18527 1.39282 0.03270 2273.65740 438.48384 0.00113 0.750 0.00234
rows · 100k 14.45440 1.00503 0.03835 2030.28650 140.46148 0.00054 0.875 0.00128
statistics · 10k 0.58253 1.00991 0.00488 2407.31952 4132.51212 0.00169 0.875 0.00407
statistics · 100k 0.79356 1.01532 0.00541 1974.64527 2488.35195 0.00054 0.875 0.00129
statistics · 1M 0.56575 1.01791 0.00259 2333.77326 4125.12582 0.00009 1.000 0.00041
statistics · 10M 0.57339 1.02159 0.00365 2134.21828 3722.11127 0.00001 1.000 0.00013
closed form · 10M 0.00144 1.02159 0.00000 NaN NaN 0.00001 1.000 0.00013
fig = sb_b.plot(highlight=[m for m in sb_b.table().index if not m.startswith("rows")])
fig.axes[3].xaxis.set_major_locator(MaxNLocator(3));
Figure
gap, ratio = same_posterior(post_b["rows · 100k"], post_b["statistics · 100k"], ["beta", "sigma"])
print(f"rows against statistics on the same 100,000 flights: largest gap between posterior means {gap.max():.3f} sd; "
      f"ratio of posterior sds {ratio.min():.2f} to {ratio.max():.2f}")
nuts = flat(post_b["statistics · 10M"], ["beta"])
print(f"NUTS on the statistics of 10M rows against the closed form: means differ by at most "
      f"{np.abs((nuts.mean(axis=0) - b_closed) / scale).max():.3f} sd; sd ratio "
      f"{(nuts.std(axis=0) / scale).min():.2f} to {(nuts.std(axis=0) / scale).max():.2f}")

grad_rows_b = {n: gradient_ms(regression_model(X_head[:n], y_head[:n])) for n in SIZES[:-1]}
grad_rows_b[N_ROWS] = 10 * grad_rows_b[1_000_000]     # 560 MB of rows are not built: ten times the cost of a million
print("one gradient of the row-level regression (ms):", {label(n): round(v, 2) for n, v in grad_rows_b.items()})
fig, ax = plt.subplots(figsize=(7.6, 4.6))
projected_b = time_figure(ax, sb_b, "statistics", grad_rows_b, "Gaussian regression: fit time against rows",
                          {n: s["seconds"] for n, s in stats_n.items()})
ax.legend(frameon=False, fontsize=9, loc="upper left");
rows against statistics on the same 100,000 flights: largest gap between posterior means 0.048 sd; ratio of posterior sds 0.98 to 1.02
NUTS on the statistics of 10M rows against the closed form: means differ by at most 0.018 sd; sd ratio 1.01 to 1.03
one gradient of the row-level regression (ms): {'10k': 0.13, '100k': 0.94, '1M': 9.72, '10M': 97.24}
Figure

The pattern of part 2 repeats. On the same 10,000 and the same 100,000 flights the two fits have the same error against the truth, and their posteriors agree to 0.05 standard deviations. The row-level fit takes of the order of ten seconds for 100,000 rows, the fit on the statistics about a second or less, and on ten million rows its error is 0.00001. With eight parameters coverage is a coarse number: one parameter is 12 points, the fits cover between six and eight of them, and rows and statistics cover the same number on the same data.

The last row of the scoreboard is the closed form, which needs no sampler: under a flat prior the coefficients have a multivariate t posterior around $\hat\beta$. NUTS on the statistics reproduces it, with means within 0.02 standard deviations and standard deviations within 3%. By the same projection as before, the row-level regression would take more than a quarter of an hour on ten million rows, on a design matrix of 560 MB.

What four sums cannot tell

Two cautions come with this compression, and we measure both.

The first is arithmetic. The statistics are sums of ten million products, and $\mathrm{RSS}$ is a small difference between large ones: here $y^\top y$ is about 2,600 times the residual sum of squares. Accumulating in single precision, which is what data stored as 32-bit floats or a GPU would do by default, puts that difference at risk.

The second is statistical. The four sums are sufficient for the Gaussian model. A data set whose noise has heavy tails has almost the same sums as one whose noise is Gaussian with the same variance, so it gets the same posterior, and nothing in the statistics says that the model is wrong. Checking takes a second pass over the rows, with the fitted line in hand.

b32, rss32 = least_squares(stats_32)
sd_sigma = np.sqrt(rss / N_ROWS) / np.sqrt(2 * N_ROWS)
print(f"y'y / RSS = {stats_all['yty'] / rss:,.0f}")
print(f"single-precision accumulators: beta_hat moves by at most {np.abs((b32 - beta_hat) / scale).max():.2f} posterior sd, "
      f"sigma_hat by {(np.sqrt(rss32 / N_ROWS) - np.sqrt(rss / N_ROWS)) / sd_sigma:+.2f} posterior sd")

b_t, rss_t = least_squares(stats_t)
print(f"\nGaussian noise:     sigma_hat {np.sqrt(rss / N_ROWS):.4f}, largest |beta_hat - truth| {np.abs(beta_hat - BETA_TRUE).max():.5f}")
print(f"heavy-tailed noise: sigma_hat {np.sqrt(rss_t / N_ROWS):.4f}, largest |beta_hat - truth| {np.abs(b_t - BETA_TRUE).max():.5f}")

beyond = {"Gaussian noise": 0, "heavy-tailed noise": 0}                   # the second pass: residuals beyond 4 sd
for i in range(N_ROWS // CHUNK):
    *_, X, y = flights(i)
    beyond["Gaussian noise"] += np.sum(np.abs(y - X @ beta_hat) > 4 * np.sqrt(rss / N_ROWS))
    beyond["heavy-tailed noise"] += np.sum(np.abs(heavy_tails(X, i) - X @ b_t) > 4 * np.sqrt(rss_t / N_ROWS))
print(f"\nresiduals beyond 4 sd, expected under the Gaussian model: {2 * stats.norm.sf(4) * N_ROWS:,.0f} of {N_ROWS:,}")
for name, count in beyond.items():
    print(f"  {name}: {count:,}")
y'y / RSS = 2,643
single-precision accumulators: beta_hat moves by at most 0.02 posterior sd, sigma_hat by +0.57 posterior sd

Gaussian noise:     sigma_hat 0.1000, largest |beta_hat - truth| 0.00002
heavy-tailed noise: sigma_hat 0.0995, largest |beta_hat - truth| 0.00007
residuals beyond 4 sd, expected under the Gaussian model: 633 of 10,000,000
  Gaussian noise: 606
  heavy-tailed noise: 62,171

The arithmetic first. Forming a difference 2,600 times smaller than its terms costs between three and four of the digits the sums carry. Double precision has sixteen to spend. Single precision has seven, and the result shows: the coefficients do not move, but $\hat\sigma$ shifts by more than half a posterior standard deviation, from rounding alone. That is not a failure at this size. It is close enough to one to settle the choice: accumulate in double precision, whatever precision the data are stored in.

The statistical caution is the larger one. The heavy-tailed outcome gives nearly the same $\hat\sigma$ and coefficients that are still right to four decimal places, so a posterior built from its statistics looks as healthy as the other. The second pass shows what the statistics could not. The Gaussian model expects about 630 residuals in ten million beyond four standard deviations; the Gaussian data have about 600 and the heavy-tailed data about 62,000. For the coefficients this misspecification is mild. For anything that depends on the shape of the noise, such as a prediction interval for one flight or a rule that flags unusual flights, the Gaussian model is wrong a hundred times over in the tails, and only the rows can say so.

The choice. Accumulate $n$, $X^\top X$, $X^\top y$ and $y^\top y$ in double precision in one pass, and write the likelihood from them, centred on $\hat\beta$. Rejected: fitting rows (the same posterior, more than ten times slower on 100,000 rows), and for this plain model the sampler itself, since the closed form gives the same intervals at once. The potential earns its place when the prior is not conjugate: a hierarchy over groups, a horseshoe on many coefficients. What would change our mind: residuals that are not Gaussian, as in the second pass above. A Student-t likelihood has no sufficient statistic of fixed size, and the choice is then between the rows and the robust methods of E131 to E133.

4 · One continuous covariate

No two rows alike

The third outcome is a late arrival. It follows the same model as a late departure with one more term, a slope $\gamma$ on the log distance $z_i$ of the flight:

$$\operatorname{logit} p_i = a + b^{\text{carrier}}_{c(i)} + b^{\text{airport}}_{o(i)} + b^{\text{block}}_{h(i)} + \gamma z_i .$$

Distance takes a different value on nearly every flight, so a cell of flights with equal covariates holds one flight, and counting compresses nothing. The Gaussian trick is no help either: the logistic log-likelihood contains the term $\sum_i \log(1 + e^{\eta_i})$, a different function of the parameters for every distinct row, and no summary of fixed size reproduces it. This is the usual situation, and it is where approximation starts.

A yardstick: all ten million rows, a few times over

To measure an approximation we need the answer it approximates. The truth is known, but a single data set's estimate sits about one standard error away from it, which would blur any bias smaller than that. A sharper yardstick is the estimate from all the rows. NUTS cannot give it in reasonable time, but the maximum of the likelihood can be found by Newton's method, which needs the gradient and the curvature a handful of times, not forty thousand. Each of the two is a sum over rows that one chunked pass computes. With ten million rows the prior hardly matters and the posterior is close to Gaussian, so the maximum and the curvature there describe it well: this is the Laplace approximation that E125 examines, used here as a reference.

DESIGN = np.zeros((N_CELLS, n_coef))                  # the cells' one-hot rows: intercept, carrier, airport, block
DESIGN[:, 0] = 1.0
for offset, codes in zip(np.cumsum([1, *SHAPE[:2]]), (CARRIER, AIRPORT, BLOCK)):
    DESIGN[np.arange(N_CELLS), offset + codes] = 1.0
TO_ZERO_SUM = np.zeros((n_coef + 1, n_coef + 1))      # from one-hot coefficients to (a, zero-sum effects, gamma)
TO_ZERO_SUM[0, 0] = TO_ZERO_SUM[-1, -1] = 1.0
for offset, size in zip(np.cumsum([1, *SHAPE[:2]]), SHAPE):
    TO_ZERO_SUM[0, offset:offset + size] = 1 / size
    TO_ZERO_SUM[offset:offset + size, offset:offset + size] = np.eye(size) - 1 / size


def newton_logit(cells, z, late, trials=None, iterations=12):
    """Maximum likelihood for logit p = cell effects + gamma z, on rows or on cells, by chunked Newton steps.

    Returns the estimate and its covariance in the model's parameterisation (a, the zero-sum effects, gamma),
    and the number of passes over the data.
    """
    theta = np.zeros(n_coef + 1)
    for passes in range(1, iterations + 1):
        eta_cell = DESIGN @ theta[:-1]
        sums = np.zeros((4, N_CELLS))                  # per cell: residual, weight, weight * z, weight * z^2
        resid_z = 0.0
        for start in range(0, len(cells), CHUNK):
            rows = slice(start, start + CHUNK)
            c, zz = cells[rows], z[rows].astype(float)
            n = 1.0 if trials is None else trials[rows]
            p = special.expit(eta_cell[c] + theta[-1] * zz)
            resid, w = late[rows] - n * p, n * p * (1 - p)
            for k, values in enumerate((resid, w, w * zz, w * zz * zz)):
                sums[k] += np.bincount(c, weights=values, minlength=N_CELLS)
            resid_z += resid @ zz
        gradient = np.r_[DESIGN.T @ sums[0], resid_z]
        hessian = np.empty((n_coef + 1, n_coef + 1))
        hessian[:-1, :-1] = DESIGN.T @ (sums[1][:, None] * DESIGN)
        hessian[:-1, -1] = hessian[-1, :-1] = DESIGN.T @ sums[2]
        hessian[-1, -1] = sums[3].sum()
        step = np.linalg.lstsq(hessian, gradient, rcond=1e-10)[0]
        theta += step
        if np.abs(step).max() < 1e-10:
            break
    return TO_ZERO_SUM @ theta, TO_ZERO_SUM @ np.linalg.pinv(hessian, rcond=1e-10) @ TO_ZERO_SUM.T, passes


def unpack(vector):
    """Split (..., 37) estimates into the model's named parameters."""
    a, c, o, h, g = np.split(vector, np.cumsum([1, *SHAPE]), axis=-1)
    return {"a": a[..., 0], "b_carrier": c, "b_airport": o, "b_block": h, "gamma": g[..., 0]}


sb_c = Scoreboard(truth=TRUE_ARR)
with sb_c.track("Newton · all 10M rows"):
    full, full_cov, passes = newton_logit(cell, z, late_arr)
    full_draws = unpack(rng.multivariate_normal(full, full_cov, 4000, method="svd"))
sb_c.score("Newton · all 10M rows", full_draws)
full_sd = np.sqrt(np.diag(full_cov))
truth_arr = np.concatenate([np.ravel(TRUE_ARR[v]) for v in (*EFFECTS, "gamma")])
print(f"Newton on all rows: {passes} passes, {sb_c.table().loc['Newton · all 10M rows', 'seconds']:.1f} s; "
      f"gamma = {full[-1]:.4f} with sd {full_sd[-1]:.4f} (truth {TRUE_ARR['gamma']})")
print(f"largest |estimate - truth| over the {len(full)} parameters: {np.abs((full - truth_arr) / full_sd).max():.1f} sd")

cells_a, late_a, trials_a = cell_counts(N_ROWS)
check, _, _ = newton_logit(cells_a, np.zeros(len(cells_a)), late_a, trials_a)
nuts_a = flat(post_a["cells · 10M"], EFFECTS)
print(f"the same routine on the cells of part 2, against NUTS: means differ by at most "
      f"{np.abs((check[:-1] - nuts_a.mean(axis=0)) / nuts_a.std(axis=0)).max():.2f} posterior sd")
Newton on all rows: 6 passes, 1.0 s; gamma = 0.5006 with sd 0.0010 (truth 0.5)
largest |estimate - truth| over the 37 parameters: 2.3 sd
the same routine on the cells of part 2, against NUTS: means differ by at most 0.10 posterior sd

Six passes of Newton's method reach the maximum in about a second, on all ten million rows and with distance at full resolution. Each pass is cheap for the reason part 2 gave, since the sums it needs are accumulated per cell and combined in a 37 by 37 system. Its estimates sit within 2.3 standard errors of the truth across the 37 parameters, as estimates from one data set should. The same routine applied to the cells of part 2 lands within a tenth of a posterior standard deviation of NUTS, the difference that a hierarchical prior and Monte Carlo error make at this size.

It goes on the scoreboard as a method in its own right, and we come back to it at the end of this part. For now it is the yardstick: the slope is 0.5006 with a standard deviation of 0.0010, so an approximation that moves the slope by 0.001 has moved it by one posterior standard deviation.

Banding the distance

The obvious way back to cells is to cut the continuous covariate into bands, as published tables often do with distance or age, and to treat every flight in a band as if it had one representative distance. The cells are then carrier × airport × block × band, and the binomial model of part 2 applies with $\gamma$ multiplying the representative value. This is no longer exact, and there are two choices to make: how many bands, and which value stands for a band. We try three rules for the value:

  • the midpoint of the band, which is all one has when the data arrive already banded;
  • the mean distance of the band, over all flights;
  • the mean distance of each cell and band, which costs one more accumulated sum per cell.

Why should the rule matter? Inside a band write $z_i = \bar z + u_i$. Expanding the log-likelihood of the band's flights around $\bar z$, the term of first order in $u_i$ sums to zero exactly when $\bar z$ is the mean of the flights being summarised, and what remains is, on average, of second order: proportional to $\gamma^2$ times the variance of distance inside the band. This is the situation Berkson (1950) described, a recorded value around which the true one scatters. With any other representative value a first-order error stays, and since distance is correlated with the airport, that error differs from airport to airport: it looks like an airport effect.

We count the flights once into 256 narrow bands and merge those into coarser ones, then refit each banded table by the same Newton routine and compare with the yardstick.

FINE, LIMIT = 256, 3.2                                # 256 bands of equal width on [-3.2, 3.2]; the tails join the end bands
band = np.clip(((z + LIMIT) / (2 * LIMIT) * FINE).astype(np.int32), 0, FINE - 1)
key = cell.astype(np.int32) * FINE + band
fine = {"n": np.bincount(key, minlength=N_CELLS * FINE).reshape(N_CELLS, FINE),
        "late": np.bincount(key, weights=late_arr, minlength=N_CELLS * FINE).reshape(N_CELLS, FINE),
        "z": np.bincount(key, weights=z, minlength=N_CELLS * FINE).reshape(N_CELLS, FINE)}
del band, key
print(f"flights beyond the outer bands' edges: {np.mean(np.abs(z) > LIMIT):.2%}")


def banded(bands, rule):
    """The table of non-empty carrier x airport x block x band cells, with a representative distance."""
    n, late, zsum = (fine[k].reshape(N_CELLS, bands, FINE // bands).sum(axis=2) for k in ("n", "late", "z"))
    if rule == "midpoint":
        edges = np.linspace(-LIMIT, LIMIT, bands + 1)
        value = np.broadcast_to((edges[:-1] + edges[1:]) / 2, n.shape)
    elif rule == "band mean":
        value = np.broadcast_to(zsum.sum(axis=0) / n.sum(axis=0), n.shape)
    else:                                              # "cell mean"
        value = zsum / np.maximum(n, 1)
    keep = n > 0
    return np.nonzero(keep)[0], value[keep], late[keep].astype(int), n[keep]


RULES = {"midpoint": RED, "band mean": YELLOW, "cell mean": BLUE}
sweep = []
for bands in (2, 4, 8, 16, 32, 64, 128, 256):
    for rule in RULES:
        cells_b, z_b, late_b, n_b = banded(bands, rule)
        est, cov, _ = newton_logit(cells_b, z_b, late_b, n_b)
        dev = (est - full) / full_sd
        sweep.append({"bands": bands, "rule": rule, "cells": len(cells_b), "gamma": est[-1],
                      "gamma, sd from full": dev[-1], "worst effect, sd from full": np.abs(dev[:-1]).max(),
                      "sd ratio": np.sqrt(cov[-1, -1]) / full_sd[-1]})
sweep = pd.DataFrame(sweep)
print("non-empty cells:", {int(b): int(c) for b, c in sweep.groupby("bands")["cells"].first().items()})
sweep.pivot(index="bands", columns="rule", values=["gamma", "gamma, sd from full", "worst effect, sd from full"]).round(3)
flights beyond the outer bands' edges: 0.46%
non-empty cells: {2: 2000, 4: 3917, 8: 7358, 16: 14040, 32: 26842, 64: 50896, 128: 95534, 256: 176418}
gamma gamma, sd from full worst effect, sd from full
rule band mean cell mean midpoint band mean cell mean midpoint band mean cell mean midpoint
bands
2 0.389 0.500 0.211 -108.012 -0.372 -280.854 170.618 12.969 170.618
4 0.443 0.498 0.376 -56.144 -2.469 -120.551 73.474 7.239 74.758
8 0.483 0.500 0.465 -17.533 -0.991 -34.636 22.859 2.254 23.851
16 0.496 0.500 0.493 -4.759 -0.355 -6.997 6.194 0.614 6.771
32 0.500 0.501 0.501 -1.037 0.126 0.352 1.552 0.136 1.962
64 0.500 0.501 0.503 -0.198 0.120 1.965 0.405 0.030 0.736
128 0.501 0.501 0.503 -0.055 0.047 2.229 0.149 0.013 0.584
256 0.501 0.501 0.503 0.024 0.066 2.290 0.057 0.017 0.598
fig, axes = plt.subplots(1, 2, figsize=(13.5, 4.5), sharey=True)
for ax, column, title in ((axes[0], "gamma, sd from full", "The slope on distance"),
                          (axes[1], "worst effect, sd from full", "The worst of the 36 other parameters")):
    ax.axhspan(1e-3, 1, color=AQUA, alpha=0.12, lw=0)
    for rule, color in RULES.items():
        part = sweep[sweep["rule"] == rule]
        ax.plot(part["bands"], part[column].abs(), "o-", color=color, lw=2, label=rule)
    ax.set_xscale("log", base=2)
    ax.set_yscale("log")
    ax.set_ylim(5e-3, 500)
    ax.set_xticks(sweep["bands"].unique(), sweep["bands"].unique())
    ax.set_xlabel("bands of distance")
    ax.set_title(title, loc="left")
    tidy(ax, grid="both")
axes[0].set_ylabel("distance from the full-data estimate (posterior sd)")
axes[0].legend(frameon=False, fontsize=9, title="value that stands for a band", title_fontsize=9, loc="lower left")
axes[1].legend(handles=[Patch(color=AQUA, alpha=0.25, label="within one posterior sd of the full-data answer")],
               frameon=False, fontsize=9, loc="upper right");
Figure

Read the table from the top. With two bands and midpoints the slope comes out at 0.21 where the full data say 0.50; with four, 0.38; with sixteen, 0.493, which looks close and is seven posterior standard deviations low. Past 32 bands the midpoint rule stops improving and settles 2.3 standard deviations high: the outermost bands also hold the 0.46% of flights beyond their edges, and a midpoint cannot stand for a tail. The dip at 32 bands is where the two errors, of opposite sign, cross. It is not a setting to trust.

The band mean repairs the tails and little else. Its slope is better, but the worst of the other parameters is as far off as with midpoints, 6 standard deviations at 16 bands. That parameter is an airport effect. Airports differ in how far their flights go, so within a band the flights of a long-haul airport sit above the band's mean and those of a short-haul airport below it, and the model books the difference to the airport. Coarsening one covariate has biased the coefficients of another, which is how a coarsely measured confounder behaves in any regression.

The cell mean removes that error at its source. With 16 bands every parameter is within 0.6 standard deviations of the full-data answer, and with 32 within 0.15, on about 14,000 and 27,000 cells where the rows number ten million. From 8 bands on, each halving of the band width divides the worst error by about four, the second-order behaviour the argument predicts. Even two bands leave the slope within half a standard deviation, though the other parameters are then up to 13 away, so the slope alone is a poor witness. The value that stands for a band mattered more than the number of bands: on the slope, 16 bands with cell means are closer than 256 with midpoints.

All of this is measured in units of a very small number. Seven standard deviations on the slope is 0.007, or 1.4% of its value, an error nobody would notice with 100,000 rows, where the posterior standard deviation is ten times larger. It matters at ten million because the posterior claims a precision of 0.2%, and an approximation has to be better than the claim it supports.

The scoreboard, and a subsample that pretends

Four more fits go on the scoreboard, all by NUTS and all scored against the truth: 16 bands with midpoints and 16 bands with cell means, which differ only in the representative value; and the two things one can do with a subsample of 50,000 rows. The first is to fit it as it is, an honest posterior of a two-hundredth of the data. The second is to count each sampled row 200 times, so that the subsample "represents" the ten million. A uniform subsample with equal weights is the simplest weighted subset of the data, the object that Huggins, Campbell and Broderick (2016) call a coreset, and weighting a sample up to the population is common practice in its own right.

post_c = {}
for rule in ("midpoint", "cell mean"):
    cells_b, z_b, late_b, n_b = banded(16, rule)
    post_c[f"16 bands, {rule}"] = fit(sb_c, f"16 bands, {rule} · 10M", delay_model(cells_b, late_b, n_b, z=z_b))
M = 50_000
post_c["subsample"] = fit(sb_c, "subsample · 50k rows", delay_model(cell[:M], late_arr[:M], z=z[:M]))
post_c["weighted"] = fit(sb_c, "subsample weighted x200", delay_model(cell[:M], late_arr[:M], z=z[:M], weight=N_ROWS / M))
pd.DataFrame({k: v for k, v in DIAGNOSTICS.items() if k in sb_c.table().index}).T.round(3)
divergences max r_hat steps per draw
16 bands, midpoint · 10M 0.0 1.004 7.334
16 bands, cell mean · 10M 0.0 1.005 7.360
subsample · 50k rows 0.0 1.005 7.254
subsample weighted x200 0.0 1.004 7.286
sb_c.table().round(4)
seconds peak_gb added_gb ess ess_per_s rmse coverage width
method
Newton · all 10M rows 1.0493 1.2812 0.0706 NaN NaN 0.0059 0.8649 0.0136
16 bands, midpoint · 10M 13.2693 1.4435 0.0213 852.2244 64.2254 0.0069 0.7568 0.0135
16 bands, cell mean · 10M 13.3149 1.0708 0.0161 945.5361 71.0131 0.0058 0.8649 0.0136
subsample · 50k rows 33.5917 1.0802 0.0149 932.8596 27.7705 0.0615 0.9730 0.1891
subsample weighted x200 36.2905 0.6112 0.0754 943.4018 25.9959 0.0654 0.0270 0.0136
sb_c.plot(highlight=["16 bands, cell mean · 10M"]);
Figure
shown = [("subsample · 50k rows", post_c["subsample"], MUTED), ("subsample weighted x200", post_c["weighted"], RED),
         ("16 bands, midpoint", post_c["16 bands, midpoint"], ORANGE), ("16 bands, cell mean", post_c["16 bands, cell mean"], BLUE)]
worst_airport = int(np.argmax(np.abs(post_c["16 bands, midpoint"]["b_airport"].mean(("chain", "draw")).values
                                     - full_draws["b_airport"].mean(axis=0))))
fig, axes = plt.subplots(1, 2, figsize=(13.5, 3.6))
for ax, pick, true_value, title in (
        (axes[0], lambda d: np.ravel(d["gamma"]), TRUE_ARR["gamma"], "Slope on distance"),
        (axes[1], lambda d: np.asarray(d["b_airport"]).reshape(-1, SHAPE[1])[:, worst_airport],
         TRUE_ARR["b_airport"][worst_airport], f"Effect of {COORDS['airport'][worst_airport]}")):
    rows = [(name, pick({v: post[v].values for v in post.data_vars}), color) for name, post, color in shown]
    rows.append(("Newton · all 10M rows", pick(full_draws), INK))
    for y, (name, draws, color) in enumerate(rows[::-1]):
        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")
        ax.plot(mid, y, "o", color=color, ms=5)
    ax.axvline(true_value, color=INK, lw=1, ls="--")
    ax.set_yticks(range(len(rows)), [r[0] for r in rows[::-1]])
    ax.set_xlabel("posterior median and 90% interval (dashed: truth)")
    ax.set_title(title, loc="left")
    tidy(ax, grid="x")
axes[1].set_yticklabels([]);
Figure

The four fits are clean by the usual diagnostics, and that is worth noticing: nothing in $\hat R$ or the divergences separates the good approximations from the bad.

Sixteen bands with cell means reproduce the full-data answer. They have the same error against the truth as the Newton fit on all the rows (0.006) and the same coverage (32 of 37 intervals), from about 14,000 cells. The same bands with midpoints cost as much and cover 28 of 37; their error against the truth is only a fifth larger, which is the smallness in absolute terms again.

The two subsample rows are the ones to remember. The plain subsample has ten times the error, intervals fourteen times as wide and coverage of 0.97: an honest answer from less data. The weighted subsample has the same error, as it must, since it is centred where the same 50,000 rows put it. Its intervals are as narrow as the full data's, because multiplying the log-likelihood by 200 multiplies its curvature by 200. They hold the truth for 1 parameter in 37. The last figure shows it for the slope and for one airport: a tight interval in the wrong place. Weights can make a subsample stand for a population when the aim is an unbiased average. They cannot make it carry the information of rows that were never read. Constructions that earn the name coreset choose the points and the weights so that the weighted log-likelihood follows the full one (Campbell and Broderick 2019); a uniform subsample with equal weights is where they start, and we did not go further here.

Last, the Newton row. It is the fastest of the table by a factor of ten or so and as accurate as the best: a second of computing, all the rows, no banding. On this problem, with 37 well-identified parameters and ten million rows, the Gaussian approximation at the maximum is as good as anything a sampler returns. The reason to band is to keep NUTS: for the hierarchical standard deviations, which the maximum-likelihood fit does not estimate, for posteriors that are not Gaussian, and for models whose answer is not at a maximum. When the Gaussian approximation breaks, and how to tell, is the subject of E125.

The choice. Sixteen bands of distance, each cell keeping its own mean distance, fitted as binomial cells. Rejected: band midpoints (the slope seven standard deviations low and an airport effect as far off, from the same number of cells), the weighted subsample (1 interval in 37 holds the truth), and the plain subsample when the full data are there to be counted. What would change our mind: a steeper or strongly curved effect, since the error grows with the square of the band width and, by the argument above, of the slope; several continuous covariates at once, since bands multiply like any other cells; or a posterior that is Gaussian enough for the Newton fit above, which was faster than everything else on this page.

5 · A real month

The simulated flights were built to compress well. Real ones were not, so we repeat part 2 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 it is already stored in this repository for E87. 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. Anyone with the public file could match them back; we do not, and nothing below needs to know which carrier or airport is which.

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)
carrier_real = archive["carrier"].astype(int)
origin_real = np.unique(archive["origin"], return_inverse=True)[1]      # codes with gaps, renumbered from 0
weekday = (day - 1) % 7                                                 # 1 January 2024 was a Monday
REAL_COORDS = {"carrier": np.arange(carrier_real.max() + 1), "origin": np.arange(origin_real.max() + 1),
               "weekday": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]}
REAL_SHAPE = tuple(len(v) for v in REAL_COORDS.values())
cell_real = np.ravel_multi_index((carrier_real, origin_real, weekday), REAL_SHAPE)
pair = carrier_real * REAL_SHAPE[1] + origin_real
print(f"\n{len(late_real):,} flights, {REAL_SHAPE[0]} carriers, {REAL_SHAPE[1]} origin airports; "
      f"late or cancelled: {late_real.mean():.1%}")
print(f"airports with fewer than 100 flights in the month: {np.sum(np.bincount(origin_real) < 100)}")

rows = []
for name, key, possible in (("carrier x origin", pair, REAL_SHAPE[0] * REAL_SHAPE[1]),
                            ("carrier x origin x weekday", cell_real, int(np.prod(REAL_SHAPE))),
                            ("carrier x origin x day of the month", pair * 31 + day - 1, REAL_SHAPE[0] * REAL_SHAPE[1] * 31)):
    sizes = np.bincount(key, minlength=possible)
    sizes = sizes[sizes > 0]
    rows.append({"cells": name, "possible": possible, "non-empty": len(sizes), "rows per cell": len(late_real) / len(sizes),
                 "median cell": int(np.median(sizes)), "largest cell": sizes.max(), "cells under 10 flights": np.mean(sizes < 10)})
pd.DataFrame(rows).set_index("cells").round(2)
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; late or cancelled: 18.7%
airports with fewer than 100 flights in the month: 117
possible non-empty rows per cell median cell largest cell cells under 10 flights
cells
carrier x origin 5010 1564 349.92 93 16511 0.06
carrier x origin x weekday 35070 10494 52.15 14 2669 0.36
carrier x origin x day of the month 155310 42915 12.75 4 590 0.76

The table carries the notice above and no names. Compare it with part 2. The carrier and the origin airport alone give 1,564 non-empty cells of 5,010 possible, since most carriers do not fly from most airports. Adding the weekday, which we derive from the day of the month, gives 10,494 cells for 547,271 flights: 52 flights per cell on average, where the simulation had 10,000. The median cell holds 14 flights and a third of the cells hold fewer than ten. Going to the day of the month would leave 13 flights per cell. On a real month the compression is by a factor of fifty, not ten thousand.

The model is the one of part 2 with the weekday in place of the departure block, which this table does not have: an intercept and zero-sum effects for 15 carriers, 334 airports and 7 weekdays. There is no known truth here, so the test is a held-out one. We set aside a random fifth of the flights, fit on the rest, and score each fit by the log predictive density of the flights it has not seen. There are three fits: a sample of 30,000 training flights as Bernoulli rows, the same 30,000 as binomial cells, and the cells of all 438,000 training flights.

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, 30_000, replace=False))
print(f"training flights {len(train):,}, held out {held_out.sum():,}")
print(f"cells among the first 30,000 rows of the file: {len(np.unique(cell_real[:30_000])):,}, with "
      f"{len(np.unique(carrier_real[:30_000]))} of the {REAL_SHAPE[0]} carriers;  among 30,000 rows drawn at random: "
      f"{len(np.unique(cell_real[sample])):,}, with {len(np.unique(carrier_real[sample]))} carriers")


def real_counts(rows):
    """Flights and late flights per non-empty real 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 = trials > 0
    return np.flatnonzero(keep), k[keep], trials[keep]


sb_d = Scoreboard()                                   # no known truth here: time, memory and ESS only
post_d = {"rows": fit(sb_d, "real rows · 30k", delay_model(cell_real[sample], late_real[sample], coords=REAL_COORDS)),
          "cells": fit(sb_d, "real cells · same 30k", delay_model(*real_counts(sample), coords=REAL_COORDS)),
          "all": fit(sb_d, "real cells · all 438k", delay_model(*real_counts(train), coords=REAL_COORDS))}
seconds = sb_d.table()["seconds"]
print(f"row-level fit of all {len(train):,} training flights, projected by proportion from the sample: "
      f"{seconds['real rows · 30k'] * len(train) / 30_000 / 60:.0f} minutes")
pd.DataFrame({k: v for k, v in DIAGNOSTICS.items() if k in sb_d.table().index}).T.round(3)
training flights 438,119, held out 109,152
cells among the first 30,000 rows of the file: 1,369, with 2 of the 15 carriers;  among 30,000 rows drawn at random: 6,035, with 15 carriers
row-level fit of all 438,119 training flights, projected by proportion from the sample: 9 minutes
divergences max r_hat steps per draw
real rows · 30k 0.0 1.008 14.968
real cells · same 30k 0.0 1.008 14.968
real cells · all 438k 0.0 1.008 15.000
REAL_EFFECTS = ["a", "b_carrier", "b_origin", "b_weekday"]
R_CARRIER, R_ORIGIN, R_WEEKDAY = np.unravel_index(np.arange(int(np.prod(REAL_SHAPE))), REAL_SHAPE)


def late_rate(post, cells, thin=4):
    """Posterior draws of the late rate of the given real cells."""
    d = {v: post[v].values.reshape(-1, *post[v].shape[2:])[::thin] for v in REAL_EFFECTS}
    return special.expit(d["a"][:, None] + d["b_carrier"][:, R_CARRIER[cells]] + d["b_origin"][:, R_ORIGIN[cells]]
                         + d["b_weekday"][:, R_WEEKDAY[cells]])


def log_score(p, late, trials):
    """Log predictive density of the held-out flights, per cell: late flights and the others."""
    return late * np.log(p) + (trials - late) * np.log1p(-p)


test_cells, test_late, test_n = real_counts(np.flatnonzero(held_out))
predicted = {k: late_rate(post, test_cells).mean(axis=0) for k, post in post_d.items()}
constant = log_score(late_real[train].mean(), test_late, test_n).sum() / test_n.sum()
held = {name: log_score(predicted[k], test_late, test_n).sum() / test_n.sum()
        for name, k in zip(sb_d.table().index, post_d)}
real_table = sb_d.table()[["seconds", "peak_gb", "added_gb", "ess", "ess_per_s"]].assign(
    held_out_log_score=pd.Series(held), gain_over_constant_rate=pd.Series(held) - constant)
gap, ratio = same_posterior(post_d["rows"], post_d["cells"], REAL_EFFECTS + ["sd_carrier", "sd_origin", "sd_weekday"])
print(f"rows against cells on the same 30,000 flights, {len(gap)} parameters: largest gap between posterior means "
      f"{gap.max():.3f} sd; ratio of posterior sds {ratio.min():.2f} to {ratio.max():.2f}")

# the gain of the full month over the sample, flight by flight (late flights and the others in each cell)
d_late = np.log(predicted["all"] / predicted["rows"])
d_other = np.log1p(-predicted["all"]) - np.log1p(-predicted["rows"])
mean_gain = (test_late * d_late + (test_n - test_late) * d_other).sum() / test_n.sum()
se_gain = np.sqrt(((test_late * d_late**2 + (test_n - test_late) * d_other**2).sum() / test_n.sum() - mean_gain**2) / test_n.sum())
print(f"held-out log score per flight: constant rate {constant:.4f};  full month minus sample {mean_gain:+.4f} "
      f"(standard error {se_gain:.4f}, taking flights as independent)")
real_table.round(4)
rows against cells on the same 30,000 flights, 360 parameters: largest gap between posterior means 0.000 sd; ratio of posterior sds 1.00 to 1.00
held-out log score per flight: constant rate -0.4842;  full month minus sample +0.0023 (standard error 0.0002, taking flights as independent)
seconds peak_gb added_gb ess ess_per_s held_out_log_score gain_over_constant_rate
method
real rows · 30k 35.9113 0.6493 0.0113 503.1665 14.0114 -0.4705 0.0137
real cells · same 30k 8.1465 0.7149 0.1664 503.1614 61.7641 -0.4705 0.0137
real cells · all 438k 13.3180 0.7441 0.0232 661.3146 49.6556 -0.4682 0.0160
sb_d.plot(highlight=["real cells · all 438k"]);
Figure
train_cells, train_late, train_n = real_counts(train)
rate_draws = late_rate(post_d["all"], train_cells, thin=10)
replicated = rng.binomial(train_n, rate_draws)
lo, hi = np.quantile(replicated, [0.05, 0.95], axis=0)
inside = (train_late >= lo) & (train_late <= hi)
big = train_n >= 50
print(f"cells whose late count lies inside its 90% predictive interval: {inside.mean():.1%} of all {len(inside):,} cells, "
      f"{inside[big].mean():.1%} of the {big.sum():,} cells with 50 flights or more")
p_mean = rate_draws.mean(axis=0)
zscore = (train_late - train_n * p_mean) / np.sqrt(train_n * p_mean * (1 - p_mean))
by_day = np.bincount(day, weights=late_real)[1:] / np.bincount(day)[1:]
print(f"standard deviation of the standardised residuals of those cells: {zscore[big].std():.2f} (binomial counts: 1)")
print(f"share of flights late or cancelled, by day of the month: from {by_day.min():.0%} to {by_day.max():.0%}")

fig, axes = plt.subplots(1, 3, figsize=(13.5, 4.1))
ax = axes[0]
for sizes, color, name in ((np.bincount(cell[:len(late_real)], minlength=N_CELLS), MUTED, f"simulated, first {len(late_real):,} rows"),
                           (np.bincount(cell_real), BLUE, f"real month, {len(late_real):,} rows")):
    sizes = np.sort(sizes[sizes > 0])[::-1]
    ax.plot(np.arange(1, len(sizes) + 1), sizes, color=color, lw=1.8, label=name)
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlabel("non-empty cells, largest first")
ax.set_ylabel("flights in the cell")
ax.legend(frameon=False, fontsize=9, loc="lower left")
ax.set_title("Real cells are many and thin", loc="left")
tidy(ax, grid="both")

ax = axes[1]
for k, color, name in (("rows", ORANGE, "30,000 rows"), ("all", BLUE, "cells of the full month")):
    order = np.argsort(predicted[k])
    groups = np.searchsorted(np.cumsum(test_n[order]), np.linspace(0, test_n.sum(), 11)[1:-1])
    pred = [np.average(predicted[k][idx], weights=test_n[idx]) for idx in np.split(order, groups)]
    seen = [test_late[idx].sum() / test_n[idx].sum() for idx in np.split(order, groups)]
    ax.plot(pred, seen, "o-", color=color, lw=1.6, ms=4, label=name)
ax.plot([0.05, 0.4], [0.05, 0.4], color=MUTED, lw=0.9)
ax.set_xlabel("predicted late rate (tenths of the held-out flights)")
ax.set_ylabel("observed late rate, held out")
ax.legend(frameon=False, fontsize=9, title="fitted on", title_fontsize=9)
ax.set_title("Held-out calibration", loc="left")
tidy(ax, grid="both")

ax = axes[2]
grid = np.linspace(-6, 6, 200)
ax.hist(np.clip(zscore[big], -6, 6), bins=np.linspace(-6, 6, 49), density=True, color=BLUE, alpha=0.6,
        label="cells with 50 flights or more")
ax.plot(grid, stats.norm.pdf(grid), color=INK, lw=1.4, label="what binomial counts would give")
ax.set_xlabel("standardised residual of the cell's late count")
ax.set_ylim(0, 0.52)
ax.legend(frameon=False, fontsize=9, loc="upper right")
ax.set_title("Flights are late together", loc="left")
tidy(ax);
cells whose late count lies inside its 90% predictive interval: 89.2% of all 10,390 cells, 64.9% of the 1,728 cells with 50 flights or more
standard deviation of the standardised residuals of those cells: 2.10 (binomial counts: 1)
share of flights late or cancelled, by day of the month: from 5% to 49%
Figure

Start with the line about the file. Its first 30,000 rows hold two of the fifteen carriers: the file is in the order it was published in, and a subsample made of its first rows is not a sample. In the simulation the first rows were as good as any, and we used them. Here the 30,000 rows are drawn at random.

The exactness holds, as it must. On the same 30,000 flights the rows and the cells agree to the third decimal of a posterior standard deviation, closer than in part 2: with the same seed, the sampler meets two log densities that differ by a constant and takes the same path. The clock differs by less than before, a factor of three or four, because 30,000 real flights fall into 6,000 cells: at this size the compression is five to one. On the full training month it is forty to one, and the cells of 438,000 flights fit in about half the time of the row-level fit of the sample. The row-level fit of the whole month, projected by proportion in the line above, would take several minutes. Every fit is also dearer per draw than in the simulation, about fifteen gradients where the simulated model took seven: this model has 357 effects, and a third of its airports have fewer than a hundred flights in the month.

Does the rest of the data buy anything? On the held-out flights the model fitted to the sample scores -0.4705 per flight and the model fitted to the full month -0.4682, against -0.4842 for a constant late rate. The gain of the full month over the sample, 0.0023, is small beside the 0.0137 that the model had already gained from 30,000 rows, and it is ten times its standard error, computed as if flights were independent, which the last panel says they are not. The calibration panel agrees: both fits put their tenths of the held-out flights on the diagonal, and the full month reaches a little further at both ends. Thirty thousand flights were enough to learn the carriers and the larger airports, and the rest of the month sharpens the small ones. That is a more modest result than in the simulation, where the full data cut the error thirteen-fold. The fit of the full month is better and cheaper, and on this question the difference in prediction is in the third decimal place.

The last panel is the difference that matters most. Part 2 said that a cell can show overdispersion and that real flights would. They do. Among the 1,728 cells with 50 flights or more, 65% of the late counts fall inside their 90% predictive interval, where the simulation had 91%, and the standardised residuals spread about twice as wide as binomial counts would. The reason is in the calendar. The share of flights late or cancelled ranges from 5% on the best day of the month to 49% on the worst, so the flights of one carrier at one airport on a Tuesday are four or five particular Tuesdays, some of them very bad days. The weekday effects this model reports are those days, not weekdays in general, and its intervals are too narrow for the same reason. The binomial model on these cells is exact as a compression and wrong as a model, and it is the cells that let us see it.

The choice. Cells of carrier, origin and weekday for the whole month: the same posterior as the rows where we could check, a better held-out score than the sample, in about half the time. Rejected: the row-level fit of a sample (the same model on less data, and slower), and the first rows of the file as a sample (two carriers of fifteen). What would change our mind: nothing about the compression. It is the model that has to change before its intervals are believed: a term for the day of the month, which still leaves 13 flights per cell, or a beta-binomial likelihood on the same cells.

6 · Which one, when?

t_a, t_b, t_c = sb_a.table(), sb_b.table(), sb_c.table()
worst_16 = sweep[(sweep["bands"] == 16) & (sweep["rule"] == "cell mean")]["worst effect, sd from full"].iloc[0]
BOXES = [
    (0, "Do rows share their covariate values?\nall categorical, or few distinct rows",
     "Count the cells: Binomial, Poisson\nwith exposure, Normal group means",
     f"exact · {N_ROWS:,} rows → {N_CELLS:,} cells\nfit {t_a.loc['cells · 10M', 'seconds']:.1f} s against {projected_a[N_ROWS] / 60:.0f} min on rows\n"
     f"real month: {len(train):,} rows → {len(train_cells):,} cells, overdispersed"),
    (1, "Is the likelihood Gaussian,\nwith a mean linear in the parameters?",
     "Accumulate n, X'X, X'y, y'y\nin double precision, chunk by chunk",
     f"exact · {P * P + P + 2} numbers whatever N\nfit {t_b.loc['statistics · 10M', 'seconds']:.1f} s · check residuals in a 2nd pass"),
    (2, "Is what is left one or two\nsmooth continuous covariates?",
     "Band them, and keep each\ncell's own mean of the covariate",
     f"approximate · 16 bands: worst parameter\n{worst_16:.1f} sd from the full-data answer"),
]
fig, ax = plt.subplots(figsize=(13.5, 6.4))
for row, question, action, numbers in BOXES:
    y = 4.6 - 1.5 * row
    ax.add_patch(FancyBboxPatch((0.1, y - 0.5), 3.5, 1.0, boxstyle="round,pad=0.02,rounding_size=0.08", fc="#f4f3ee", ec=MUTED, lw=1.1))
    ax.text(1.85, y, question, ha="center", va="center", fontsize=9.6, color=INK, linespacing=1.3)
    ax.add_patch(FancyArrowPatch((3.65, y), (4.55, y), arrowstyle="-|>", mutation_scale=13, color=BLUE, lw=1.6))
    ax.text(4.1, y + 0.13, "yes", ha="center", fontsize=9, color=BLUE)
    ax.add_patch(FancyBboxPatch((4.6, y - 0.5), 3.4, 1.0, boxstyle="round,pad=0.02,rounding_size=0.08", fc="#cde2fb", ec=BLUE, lw=1.4))
    ax.text(6.3, y, action, ha="center", va="center", fontsize=9.6, color=INK, linespacing=1.3, fontweight="bold")
    ax.text(8.2, y, numbers, ha="left", va="center", fontsize=9.2, color=INK, linespacing=1.35)
    ax.add_patch(FancyArrowPatch((1.85, y - 0.53), (1.85, y - 0.97), arrowstyle="-|>", mutation_scale=13, color=MUTED, lw=1.4))
    ax.text(1.97, y - 0.76, "no", fontsize=9, color=MUTED, va="center")
y = 4.6 - 1.5 * 3
ax.add_patch(FancyBboxPatch((0.1, y - 0.5), 7.9, 1.0, boxstyle="round,pad=0.02,rounding_size=0.08", fc="#fbe9e1", ec=ORANGE, lw=1.4))
ax.text(4.05, y, "Nothing compresses: keep the rows and change the algorithm.  A few Newton passes if the posterior is\n"
        "close to Gaussian, variational inference (E125), shards (E127), or an honest subsample.", ha="center",
        va="center", fontsize=9.6, color=INK, linespacing=1.35)
ax.text(8.2, y, f"Newton on {N_ROWS:,} rows: {t_c.loc['Newton · all 10M rows', 'seconds']:.1f} s\n"
        f"never weight a subsample up to N:\ncoverage {t_c.loc['subsample weighted x200', 'coverage']:.0%} at a nominal 90%",
        ha="left", va="center", fontsize=9.2, color=INK, linespacing=1.35)
ax.set_xlim(0, 13.2)
ax.set_ylim(-0.6, 5.5)
ax.axis("off")
ax.set_title("When to reach for which: ask in this order, before choosing a sampler", loc="left");
Figure

The chart is the notebook in the order in which the questions should be asked. The first two answers are exact and cost one pass over the data. The third is an approximation whose error can be measured, as part 4 measured it, against a reference computed on all the rows. Only when all three fail is the size of the data a problem for the sampler and not for the bookkeeping.

Summary

  • A Bernoulli regression on categorical covariates is a binomial regression on cells, exactly. Ten million flights with a carrier, an airport and a departure block are 1,000 pairs of counts. On the same 100,000 flights rows and cells gave the same posterior (means within 0.05 standard deviations); the rows took more than half a minute, the cells a few seconds at any number of rows. Limit: the cells are the model's covariates, and five more covariates leave 1.4 flights per cell.
  • Use all the data before speeding up the sampler. The 100,000-row subsample that a row-level fit can afford gave an honest posterior with thirteen times the error of the cell-level fit of all ten million rows, which ran more than ten times faster. The row-level fit of all rows is projected at an hour or more.
  • A Gaussian regression is 58 numbers. $n$, $X^\top X$, $X^\top y$ and $y^\top y$ accumulate chunk by chunk; the potential written from them matched the row-level posterior (0.05 standard deviations) and the closed form, in about a second or less at any size. Limit: accumulate in double precision (single precision moved $\hat\sigma$ by half a posterior standard deviation), and check the model in a second pass: heavy-tailed noise with a hundred times too many residuals beyond four standard deviations left the statistics looking healthy.
  • One continuous covariate ends exactness, and banding recovers it if each cell keeps its own mean. With 16 bands of distance and cell means, every parameter was within 0.6 posterior standard deviations of the full-data answer. Band midpoints put the slope 7 standard deviations low, and a mean shared by the band left an airport effect 6 off, because distance is correlated with the airport. Limit: measured at one slope (0.5); the error should grow with the square of the slope and of the band width.
  • A weighted subsample has the error of the subsample and the confidence of the full data. 50,000 rows counted 200 times each: 1 of 37 intervals held the truth. The same rows unweighted: 36 of 37, with intervals fourteen times as wide.
  • On a real month the compression was fifty to one, and the model was the weak point. The 547,271 flights of January 2024 made 10,494 cells of carrier, origin and weekday. Rows and cells gave the same posterior on 30,000 flights; the cells of the whole training month fitted in about half the time of that row-level sample and scored 0.0023 better per held-out flight, where the model's gain over a constant rate was 0.0137. Only 65% of the larger cells fell inside their 90% predictive intervals: real flights are late together, and the cells showed it. Limit: one month, a random hold-out, and a table with no departure time or distance.
  • The usual diagnostics saw none of this. Every fit here had no divergences and $\hat R$ below 1.01. The good and the bad approximations were told apart by a known truth and by a reference computed on all the rows.
  • When the posterior is Gaussian, a few passes are enough. Newton's method on all ten million rows took about a second and matched the best compressed fit. Limit: it gives no posterior for the hierarchical standard deviations, and E125 shows where the approximation fails.

Try it yourself

  1. A covariate too many. Add the day of the week to the simulator and to the model of part 2 (a seventh of the flights in each, with an effect of your choice), and count the cells again. Then add the month. At what number of non-empty cells does the binomial fit take as long as 100,000 rows, and how does that compare with the table at the end of part 2?
  2. Group means instead of a matrix. Give the regression of part 3 an intercept for each of the 1,000 cells with a hierarchical prior. The sufficient statistics are now per cell. Accumulate them in one pass and write the potential; with 1,000 intercepts and a learned spread there is no closed form to fall back on, which is the case the potential is for.
  3. Break the bands. Set the slope on distance to 1.5 in TRUE_ARR, and rerun part 4. The argument in the text says the error of the cell-mean rule grows with the square of the slope: how many bands does it now take to stay within one posterior standard deviation of the full-data answer? Then replace the equal-width bands by bands holding equal numbers of flights, and see whether the tails or the middle needed the resolution.
print(f"total run time: {time.time() - T_START:.0f} s")
total run time: 314 s