The question
An airline analyst wants a logistic regression of late departures on a table that no longer fits. NUTS needs the gradient of the log density at every step, the gradient is a sum over the rows, and the table has to sit in memory with a working array as long as itself for every chain. Past some number of rows the fit takes hours, and past another it does not start. E126 asked whether the likelihood really has that many terms, and E125 traded the sampler for an approximation. This notebook takes the third road, the one that keeps both the rows and the sampler: cut the table into $K$ pieces, sample each piece where it fits, and put the $K$ answers together.
The road exists because of one line of algebra. If the rows of different pieces are independent given the parameters, the posterior factorises over the pieces:
$$p(\theta \mid y) \;\propto\; p(\theta)\prod_{k=1}^{K} p(y_k \mid \theta) \;=\; \prod_{k=1}^{K} \Big[\, p(\theta)^{1/K}\, p(y_k \mid \theta) \Big].$$
Each bracket is a posterior in its own right, a sub-posterior: the data of one shard under a prior raised to the power $1/K$. A machine that holds only shard $k$ can sample it, and the product of the $K$ densities is the posterior we wanted. The catch is in the word densities. A sampler returns draws, and there is no exact way to multiply $K$ sets of draws. Every method in this family is a rule for doing it approximately.
Consensus Monte Carlo (Scott, Blocker, Bonassi, Chipman, George and McCulloch 2016) averages the draws of the shards, weighting each by the inverse of its covariance matrix. The parametric rule of Neiswanger, Wang and Xing (2014) fits a Gaussian to each sub-posterior and multiplies the Gaussians. Both are exact when every sub-posterior is Gaussian. A second family changes what each machine samples: it keeps the whole prior and raises the likelihood of the shard to the power $K$, as if every row had been seen $K$ times, so that each machine holds a noisy copy of the full posterior with about the right width. The copies are then averaged as distributions. The Wasserstein posterior, WASP (Srivastava, Cevher, Dinh and Dunson 2015; Srivastava, Li and Dunson 2018), takes their barycentre in Wasserstein distance, the mean of a set of distributions (Agueh and Carlier 2011). The median posterior (Minsker, Srivastava, Lin and Dunson 2014, 2017) takes their geometric median instead. The two are often mentioned in one breath, and they are different things: a mean and a median, built for different purposes, and we keep them apart.
The guarantees are asymptotic for all of them. Consensus is exact for Gaussian sub-posteriors; Li, Srivastava and Dunson (2017) prove the accuracy of averaged quantiles from the Bernstein-von Mises theorem, that is, for shards large enough to have a Gaussian limit; and Srivastava et al. report that the barycentre copes with non-Gaussian sub-posteriors better than the product rules do. That suggests a hypothesis, and this notebook is organised around testing it: the rules agree on Gaussian-shaped posteriors and part ways on skewed or multimodal ones, and for each posterior there is a $K$ at which the stitching breaks.
To test it we need the answer the stitching is supposed to give, the posterior of all the rows. So every problem below is built so that this posterior can be computed: small enough to fit, or compressible to counts and sums by the devices of E126. That has a consequence which we state once. Wherever E126's compression applies, nobody should split the data: the cells are exact and the shards are not. Splitting is for the case with continuous covariates and a likelihood that is not Gaussian, which is where part 1 starts. The compressible problems of the later parts serve as test benches, because they make a shard's fit cost a twentieth of a second and so let us run fifteen hundred of them.
| part | question | tool |
|---|---|---|
| 1 | What do the pieces have to reproduce, and what does the whole cost as its rows grow? | a logistic regression with continuous covariates, a full-data fit, a short run on two million rows |
| 2 | What does each machine sample? | one compiled model refilled with each shard, a tempered prior, the failure without it |
| 3 | How are $K$ sets of draws made into one? | consensus, Gaussian product, barycentre, median; clouds of draws; the scoreboard |
| 4 | How many shards can the coefficients take? | a sweep of $K$ from 2 to 64, and a rare event in closed form |
| 5 | Does it matter who gets which rows? | the same rows dealt at random and in the order of the file |
| 6 | What about a group-level standard deviation? | 64 stations, shards by station and by row |
| 7 | And a posterior with two modes? | a two-component mixture, with and without an ordering |
| 8 | Does it survive a real month? | the flights of January 2024 as 31 daily files |
| 9 | Which rule, 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 nutpie
import pandas as pd
import pymc as pm
import pytensor.tensor as pt
import xarray as xr
from matplotlib.patches import FancyArrowPatch, FancyBboxPatch
from scipy import special, stats
from scipy.optimize import linear_sum_assignment
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 = 127
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")
RULE_STYLE = {"consensus": dict(color=BLUE, marker="o", ls="-"),
"consensus, scalar weights": dict(color=AQUA, marker="v", ls="--"),
"Gaussian product": dict(color=ORANGE, marker="s", ls=":"),
"barycentre": dict(color=VIOLET, marker="D", ls="-"),
"median": dict(color=MAGENTA, marker="^", ls="-.")}
def tidy(ax, grid="y"):
ax.spines[["top", "right"]].set_visible(False)
ax.grid(False)
if grid:
ax.grid(axis=grid, color=GRID, lw=0.6)
ax.set_axisbelow(True)
1 · A regression that outgrows its machine
The model is the one an analyst would write first. A flight leaves late with a probability that depends on how far it flies, how full it is, whether it leaves in a peak hour, and on one rare circumstance: about one flight in seventy holds a priority slot, which makes a late departure much less likely. Distance and load factor are continuous, so no two rows are alike and nothing can be counted into cells. The priors are $\mathcal{N}(0, 1)$ on every coefficient, on standardised covariates: loose for the common effects, and not negligible for the priority slot, whose coefficient rests on a few hundred flights.
NAMES = ["intercept", "distance", "load", "peak", "priority"]
BETA = np.array([-2.0, 0.5, 0.4, 0.6, -1.0])
PRIOR_SD = 1.0
N_ROW = 40_000
def simulate_rows(n, seed, share_priority=0.015):
"""Flights with two continuous covariates: nothing here can be counted into cells."""
g = np.random.default_rng([RANDOM_SEED, seed])
X = np.column_stack([np.ones(n), g.normal(size=n), g.normal(size=n), g.random(n) < 0.3,
g.random(n) < share_priority]).astype(float)
return X, (g.random(n) < special.expit(X @ BETA)).astype(float)
X_row, late_row = simulate_rows(N_ROW, 1)
prio = X_row[:, 4] == 1
print(f"{N_ROW:,} flights, {late_row.mean():.1%} late; {prio.sum()} hold a priority slot, of which {int(late_row[prio].sum())} left late")
def logistic_model():
"""One logistic regression for rows and for cells, with two dials that the shards will turn."""
with pm.Model(coords={"coef": NAMES}) as model:
X = pm.Data("X", np.zeros((2, len(NAMES))))
late = pm.Data("late", np.zeros(2)) # late flights in the row (0 or 1) or in the cell
flights = pm.Data("flights", np.ones(2)) # flights in the row (1) or in the cell
prior_scale = pm.Data("prior_scale", 1.0) # sqrt(K) raises a Normal prior to the power 1/K
power = pm.Data("power", 1.0) # K raises the likelihood to the power K
beta = pm.Normal("beta", 0.0, PRIOR_SD * prior_scale, dims="coef")
eta = pt.dot(X, beta)
pm.Potential("loglik", power * (late * eta - flights * pt.softplus(eta)).sum())
return model
def rhat(chains):
"""Largest potential scale reduction over the parameters (between and within chains, no rank transform).
``chains`` has shape (chains, draws, parameters). The plain version is enough to see a shard whose
chains disagree, and it is cheap enough to compute for two thousand fits.
"""
n = chains.shape[1]
within = chains.var(axis=1, ddof=1).mean(axis=0)
between = n * chains.mean(axis=1).var(axis=0, ddof=1)
return float(np.sqrt(((n - 1) / n * within + between / n) / within).max())
def fit_one(compiled, piece, names, scale=1.0, power=1.0, chains=4, draws=500, tune=300, seed=0, **sampler):
"""One NUTS fit of a compiled model on new data. Draws come back as (chains, draws, parameters)."""
t0 = time.perf_counter()
filled = compiled.with_data(**piece, prior_scale=np.array(float(scale)), power=np.array(float(power)))
trace = nutpie.sample(filled, draws=draws, tune=tune, chains=chains, cores=4, seed=seed, progress_bar=False, **sampler)
out = np.concatenate([trace.posterior[v].values.reshape(chains, draws, -1) for v in names], axis=2)
steps = trace.sample_stats["n_steps"]
return out, {"seconds": time.perf_counter() - t0, "divergences": int(trace.sample_stats["diverging"].sum()),
"rhat": rhat(out), "steps": float(steps.mean()),
"gradients": int(steps.sum() + trace.warmup_sample_stats["n_steps"].sum())} # warm-up included
def as_posterior(chains, name="beta"):
"""Draws of shape (chains, draws, parameters) as a posterior the scoreboard can read."""
return xr.Dataset({name: (("chain", "draw", "coef"), chains)})
t0 = time.perf_counter()
LOGIT = nutpie.compile_pymc_model(logistic_model())
print(f"compiled once, in {time.perf_counter() - t0:.1f} s")
40,000 flights, 15.4% late; 567 hold a priority slot, of which 44 left late
compiled once, in 2.4 s
The likelihood is written as a potential, $\sum_i \big[y_i\eta_i - n_i\log(1+e^{\eta_i})\big]$, which
is the Bernoulli log-likelihood when a row is one flight ($n_i = 1$) and the binomial one when a row
is a cell of $n_i$ flights. Two numbers are left as data: a multiplier on the prior's standard
deviation and a power on the likelihood. They do nothing yet. nutpie compiles the model once, and
with_data refills it with other rows, of any number, without compiling again. Everything in the
first five parts is this one compiled function.
The answer the pieces must reproduce
At 40,000 rows the regression fits in a few seconds, which is why this part stays there: we can compute the posterior of all the rows and hold the stitched one against it. Each fit that is compared gets a row on a scoreboard: wall time, memory, effective sample size per second, error against the simulated truth, and how many of the five 90% intervals hold it.
sb = Scoreboard(truth={"beta": BETA})
all_rows = dict(X=X_row, late=late_row, flights=np.ones(N_ROW))
with sb.track("all rows · NUTS"):
full_row, info_row = fit_one(LOGIT, all_rows, ["beta"], draws=1000, tune=400, seed=RANDOM_SEED)
sb.score("all rows · NUTS", as_posterior(full_row))
full_row = full_row.reshape(-1, len(NAMES))
print(f"all {N_ROW:,} rows: {info_row['seconds']:.1f} s, {info_row['divergences']} divergences, r_hat {info_row['rhat']:.3f}, "
f"{info_row['steps']:.1f} gradients per draw")
pd.DataFrame({"truth": BETA, "posterior mean": full_row.mean(axis=0), "sd": full_row.std(axis=0),
"skewness": stats.skew(full_row, axis=0)}, index=NAMES).round(3)
all 40,000 rows: 5.0 s, 0 divergences, r_hat 1.001, 4.6 gradients per draw
| truth | posterior mean | sd | skewness | |
|---|---|---|---|---|
| intercept | -2.0 | -2.029 | 0.019 | 0.055 |
| distance | 0.5 | 0.491 | 0.015 | -0.021 |
| load | 0.4 | 0.407 | 0.014 | -0.049 |
| peak | 0.6 | 0.585 | 0.029 | -0.048 |
| priority | -1.0 | -0.859 | 0.158 | -0.082 |
The four common coefficients are known to between one and three hundredths. The priority slot is known ten times less well, to 0.16, because it rests on 44 late departures among the flights that hold one. With all the rows its posterior is still close to symmetric. This is the parameter to watch.
What it would cost at fifty times the size
The same fit on two million rows is out of this notebook's budget, so we measure what it is made of. We generate two million rows, run the sampler on all of them for thirty iterations, long enough to time a gradient and to see the memory it takes, and do the same on an eighth of them, the shard that one of eight machines would hold. The time of a complete fit is then projected from the 40,000-row fit we ran, in proportion to the cost of a gradient.
N_BIG, K_BIG = 2_000_000, 8
X_big, late_big = simulate_rows(N_BIG, 2)
cost = {}
for n in (N_ROW, N_BIG // K_BIG, N_BIG):
probe = Scoreboard() # borrowed for its memory watcher
with probe.track("short run"):
_, info = fit_one(LOGIT, dict(X=X_big[:n], late=late_big[:n], flights=np.ones(n)), ["beta"], draws=10, tune=20,
seed=RANDOM_SEED, maxdepth=4)
cost[n] = {"table in memory (GB)": n * (len(NAMES) + 2) * 8 / 1e9, "added by the sampler (GB)": probe.table().loc["short run", "added_gb"],
"one gradient (ms)": 1e3 * info["seconds"] * 4 / info["gradients"]}
del X_big, late_big
COST = pd.DataFrame(cost).T.rename_axis("rows")
COST["a full fit, projected (min)"] = info_row["seconds"] * COST["one gradient (ms)"] / COST.loc[N_ROW, "one gradient (ms)"] / 60
print(COST.round(3).to_string())
table in memory (GB) added by the sampler (GB) one gradient (ms) a full fit, projected (min) rows 40000 0.002 0.000 1.189 0.083 250000 0.014 0.013 5.555 0.390 2000000 0.112 0.061 56.354 3.952
A gradient costs in proportion to the rows, as a sum over rows must, and so does everything built from gradients. On two million rows a fit of four chains is projected at a few minutes (the figure moves with whatever else the machine is doing), and the shard that one of eight machines would hold at an eighth of that. The memory has two parts. The table itself takes 56 bytes a row here, seven numbers in double precision. On top of it the sampler added a few tens of megabytes for two million rows, about one working array of that length for each chain. Neither is a problem at this size. Both are proportional to the rows: at forty million rows the same arithmetic gives more than three gigabytes, which is past the budget of the laptop this notebook is written for, and a fit of an hour or more. An eighth of that table fits with room to spare. That is the case for splitting: memory first, and time only if the pieces run on different machines.
The choice. A problem small enough to fit whole, so that the full-data posterior exists and every stitched answer can be held against it. Rejected: demonstrating on two million rows, where the shards could be fitted and nobody could say whether their combination was right. What would change our mind: nothing in the algebra depends on the number of rows, but the cost does, and the table above is the part of the argument that is measured at full size.
2 · Split and sample
We deal the rows at random into $K = 8$ shards of 5,000. Each machine is to sample its sub-posterior, the shard's likelihood under the prior to the power $1/8$. For a Normal prior that power has a name: $\mathcal{N}(0, s^2)^{1/K} \propto \mathcal{N}(0, K s^2)$, the same prior with its standard deviation multiplied by $\sqrt{K}$. That is the first of the two dials in the model. The shards are fitted one after another here, in one process; on $K$ machines they would run side by side, and the wall time would be that of the slowest shard. We record both numbers, and the second is a projection from the first.
VARIANTS = {"tempered": lambda K: dict(scale=np.sqrt(K), power=1.0), # prior^(1/K) x shard likelihood
"powered": lambda K: dict(scale=1.0, power=float(K)), # prior x shard likelihood^K
"full prior": lambda K: dict(scale=1.0, power=1.0)} # the mistake of part 2
class Shards:
"""The fits of K shards: draws of shape (K, chains, draws, parameters), and each fit's time and health."""
def __init__(self, fits):
self.chains = np.stack([f[0] for f in fits])
self.flat = self.chains.reshape(len(fits), -1, self.chains.shape[-1])
self.seconds = np.array([f[1]["seconds"] for f in fits])
self.divergences = sum(f[1]["divergences"] for f in fits)
self.rhat = max(f[1]["rhat"] for f in fits)
def fit_shards(compiled, pieces, names, variant, seed=0, **kwargs):
"""Fit every shard in turn, as K machines would side by side."""
dials = VARIANTS[variant](len(pieces))
return Shards([fit_one(compiled, piece, names, **dials, seed=RANDOM_SEED + 1000 * seed + k, **kwargs)
for k, piece in enumerate(pieces)])
K_ROW = 8
deal = np.random.default_rng([RANDOM_SEED, 3]).permutation(N_ROW)
row_pieces = [dict(X=X_row[i], late=late_row[i], flights=np.ones(len(i))) for i in np.array_split(deal, K_ROW)]
late_prio = [int(p["late"][p["X"][:, 4] == 1].sum()) for p in row_pieces]
print(f"late departures among the priority flights of each shard: {late_prio}")
with sb.track("one shard alone"):
alone, _ = fit_one(LOGIT, row_pieces[0], ["beta"], draws=1000, tune=400, seed=RANDOM_SEED + 1)
sb.score("one shard alone", as_posterior(alone))
with sb.track(f"{K_ROW} shards · consensus"):
tempered = fit_shards(LOGIT, row_pieces, ["beta"], "tempered", seed=1)
print(f"tempered prior: {tempered.seconds.sum():.1f} s summed over the shards, {tempered.seconds.max():.2f} s for the slowest; "
f"{tempered.divergences} divergences, largest r_hat {tempered.rhat:.3f}")
sub_sd = tempered.flat.std(axis=1).mean(axis=0)
pd.DataFrame({"sd, all rows": full_row.std(axis=0), "sd, a sub-posterior (mean of 8)": sub_sd,
"ratio": sub_sd / full_row.std(axis=0)}, index=NAMES).round(3)
late departures among the priority flights of each shard: [6, 4, 7, 6, 6, 4, 3, 8]
tempered prior: 3.3 s summed over the shards, 0.47 s for the slowest; 0 divergences, largest r_hat 1.007
| sd, all rows | sd, a sub-posterior (mean of 8) | ratio | |
|---|---|---|---|
| intercept | 0.019 | 0.054 | 2.801 |
| distance | 0.015 | 0.042 | 2.816 |
| load | 0.014 | 0.041 | 2.880 |
| peak | 0.029 | 0.082 | 2.856 |
| priority | 0.158 | 0.477 | 3.012 |
A sub-posterior is about $\sqrt{8} \approx 2.8$ times as wide as the posterior of all the rows, as it should be: it holds an eighth of the data and an eighth of the prior. Summed over the shards, the sampling took somewhat less time than the fit of all the rows, and only because we gave each shard 800 iterations where the full fit had 1,400. Per iteration the work is the same: eight gradients on five thousand rows cost what one costs on forty thousand. On one machine, then, splitting buys memory and no time. The time is bought by the other seven machines.
Failure 1: the whole prior in every shard
The easiest mistake is to run the model unchanged on each shard. Each machine then multiplies its likelihood by the whole prior, the product of the eight sub-posteriors contains the prior eight times, and the combination is the posterior under $\mathcal{N}(0, 1/8)$ instead of $\mathcal{N}(0, 1)$. We run it, and combine both sets of shards with the first rule of part 3, the weighted average of consensus Monte Carlo.
def consensus(draws, weights="matrix"):
"""Consensus Monte Carlo: draw by draw, the weighted average of the K shards.
``draws`` has shape (K, S, d) and comes from sub-posteriors with a tempered prior. The weights are
the inverses of the shards' covariance matrices, or of their variances (``weights="scalar"``).
"""
if weights == "scalar":
w = 1.0 / draws.var(axis=1, ddof=1)
return (w[:, None, :] * draws).sum(axis=0) / w.sum(axis=0)
W = np.stack([np.linalg.inv(np.atleast_2d(np.cov(d, rowvar=False))) for d in draws])
V = np.linalg.inv(W.sum(axis=0))
return np.einsum("ij,ksj->si", V, np.einsum("kij,ksj->ksi", W, draws))
sb.add(f"{K_ROW} shards · Gaussian product", **sb.table().loc[f"{K_ROW} shards · consensus", ["seconds", "peak_gb", "added_gb"]])
with sb.track(f"{K_ROW} shards · full prior in each"):
untempered = fit_shards(LOGIT, row_pieces, ["beta"], "full prior", seed=2)
combined = {"consensus": consensus(tempered.flat), "full prior in each": consensus(untempered.flat)}
def density(ax, x, color, label, lw=2.0, ls="-", fill=False):
grid = np.linspace(*np.quantile(x, [0.001, 0.999]), 200)
y = stats.gaussian_kde(x)(grid)
ax.plot(grid, y, color=color, lw=lw, ls=ls, label=label)
if fill:
ax.fill_between(grid, y, color=color, alpha=0.12)
fig, axes = plt.subplots(1, 2, figsize=(12.5, 3.9))
for ax, j in zip(axes, (4, 1)):
density(ax, full_row[:, j], INK, "all rows", fill=True)
density(ax, combined["consensus"][:, j], BLUE, "8 shards, prior to the power 1/8")
density(ax, combined["full prior in each"][:, j], RED, "8 shards, the whole prior in each", ls="--")
ax.axvline(BETA[j], color=MUTED, lw=1, ls=":")
ax.set_xlabel(f"coefficient of {NAMES[j]}")
ax.set_yticks([])
tidy(ax, grid=None)
axes[0].legend(frameon=False, fontsize=9, loc="upper left")
axes[0].set_title("Priority slot: eight priors pull it towards zero", loc="left", fontsize=10.5)
axes[1].set_title("Distance: enough data to shrug them off", loc="left", fontsize=10.5)
wrong = (combined["full prior in each"].mean(axis=0) - full_row.mean(axis=0)) / full_row.std(axis=0)
print("shift of the mean, in posterior standard deviations, with the whole prior in each shard:",
dict(zip(NAMES, np.round(wrong, 2))));
shift of the mean, in posterior standard deviations, with the whole prior in each shard: {'intercept': np.float64(0.28), 'distance': np.float64(-0.1), 'load': np.float64(-0.07), 'peak': np.float64(-0.28), 'priority': np.float64(0.76)}
The dotted lines mark the truth. For the distance the two combinations sit close to the posterior of all the rows: forty thousand flights say so much about that coefficient that eight priors or one make little difference. For the priority slot the red curve has moved towards zero by three quarters of a posterior standard deviation and has become a tenth narrower, which is the wrong direction to be wrong in: it is an answer that looks better determined than the right one. The size of the pull is simple arithmetic. A prior $\mathcal{N}(0, 1)$ counted $K$ times has precision $K$, and the data's precision for this coefficient is about 40, so the estimate is drawn a share $K/(K+40)$ of the way to zero: a sixth of the way with 8 shards, and more than half the way with 64. Nothing in the fits announces it, since each shard's sampler ran cleanly on a perfectly proper model. The mistake is only in the count of priors.
The choice. Each shard samples under the prior to the power $1/K$, here a Normal with $\sqrt{K}$ times the standard deviation. Rejected: the model as it is on every shard, which counts the prior $K$ times and shrinks every weakly identified coefficient, and the opposite shortcut, no prior at all in the shards, which is harmless here and improper as soon as a shard cannot identify a parameter (part 5). What would change our mind: a prior that has no convenient $1/K$ power; then the likelihood is raised to the power $K$ instead, which is the second family below.
3 · Stitch
Four rules
Consensus Monte Carlo. Take the $s$-th draw of every shard and average them with weights $W_k = \Sigma_k^{-1}$, the inverse covariance of the shard's draws: $\theta_s = (\sum_k W_k)^{-1}\sum_k W_k\,\theta_{k,s}$. If each sub-posterior is $\mathcal{N}(\mu_k, \Sigma_k)$, this weighted average has exactly the mean and covariance of the product of the $K$ Gaussians, so the rule is exact for Gaussian sub-posteriors. Scott et al. also give a cheaper version, which weights each coordinate by the inverse of its own variance.
Gaussian product. Fit a Gaussian to each shard's draws and multiply the densities: $\Sigma = (\sum_k \Sigma_k^{-1})^{-1}$, $\mu = \Sigma \sum_k \Sigma_k^{-1}\mu_k$, then draw from $\mathcal{N}(\mu, \Sigma)$. It has the same mean and covariance as consensus by construction. The two differ only in shape: consensus keeps whatever skewness survives the averaging, and the product is Gaussian by decree. Neiswanger et al. also propose rules that multiply kernel density estimates of the sub-posteriors, which are exact in the limit of many draws; we do not run them here.
Both rules need sub-posteriors with a tempered prior. The next two need the other dial: the whole prior and the shard's likelihood to the power $K$, which Minsker et al. call a stochastic approximation of the full posterior. A shard that has seen each of its rows $K$ times is about as sure of itself as the full data would be, and centred on its own estimate.
Wasserstein barycentre. Average the $K$ noisy copies as distributions. In one dimension the barycentre has a closed form, the distribution whose quantile function is the average of the $K$ quantile functions, so for a single parameter we sort each shard's draws and average the sorted columns. Li, Srivastava and Dunson (2017) recommend exactly this for intervals of one-dimensional quantities, and it needs no optimal-transport solver. For a picture in two dimensions we compute the barycentre of the point clouds themselves by a fixed-point iteration: match the current points to each cloud by solving an assignment problem, and move each point to the mean of its $K$ partners.
Median posterior. Embed the $K$ empirical distributions in a reproducing-kernel Hilbert space and take their geometric median with Weiszfeld's algorithm. The result is a weighted mixture of the sub-posteriors themselves, with weights below $1/(2K)$ set to zero, as Minsker et al. do. The kernel is ours to choose, and we take a Gaussian one whose unit of length is the spread of all the draws. The median is built to resist a minority of corrupted shards, which is a different aim from reproducing the full posterior.
def gaussian_product(draws, rng, size=None):
"""The parametric rule of Neiswanger et al.: multiply the K Gaussian fits, then draw from the product."""
W = np.stack([np.linalg.inv(np.atleast_2d(np.cov(d, rowvar=False))) for d in draws])
V = np.linalg.inv(W.sum(axis=0))
mean = V @ np.einsum("kij,kj->i", W, draws.mean(axis=1))
return rng.multivariate_normal(mean, V, size=size or draws.shape[1])
def barycentre(draws):
"""One-dimensional Wasserstein barycentres: the average of the K sorted samples, one parameter at a time.
``draws`` has shape (K, S, d) and comes from sub-posteriors with the likelihood to the power K.
Each column of the result is a valid marginal; the pairing between columns is lost.
"""
return np.sort(draws, axis=1).mean(axis=0)
def barycentre_cloud(draws, n=300, iterations=10, seed=0):
"""Barycentre of K point clouds in any dimension, with n free points (for pictures of two parameters)."""
g = np.random.default_rng([RANDOM_SEED, seed])
K, S, d = draws.shape
clouds = draws[:, g.choice(S, n, replace=False)]
scale = clouds.reshape(-1, d).std(axis=0)
z = clouds / scale
x = z[0].copy()
for _ in range(iterations):
partners = np.zeros_like(x)
for k in range(K): # optimal matching of the n points to cloud k
cost = ((x[:, None, :] - z[k][None, :, :]) ** 2).sum(axis=2)
partners += z[k][linear_sum_assignment(cost)[1]]
x, previous = partners / K, x
if np.abs(x - previous).max() < 1e-9:
break
return x * scale
def median_weights(draws, n=200, tolerance=1e-7, iterations=1000):
"""Weiszfeld weights of the geometric median of K empirical distributions, with a Gaussian kernel."""
K, S, d = draws.shape
z = draws[:, :: max(1, S // n)] / draws.reshape(-1, d).std(axis=0) # unit: the spread of all the draws
m = z.shape[1]
flat = z.reshape(K * m, d)
square = (flat**2).sum(axis=1)
gram = np.empty((K, K))
for k in range(K): # inner products of the kernel mean embeddings
d2 = square[k * m:(k + 1) * m, None] + square[None, :] - 2 * flat[k * m:(k + 1) * m] @ flat.T
gram[k] = np.exp(-d2 / 2).reshape(m, K, m).mean(axis=(0, 2))
w = np.full(K, 1.0 / K)
for _ in range(iterations):
distance = np.sqrt(np.maximum(w @ gram @ w - 2 * gram @ w + np.diag(gram), 1e-18))
w, previous = (1 / distance) / (1 / distance).sum(), w
if np.abs(w - previous).max() < tolerance:
break
w = np.where(w >= 1 / (2 * K), w, 0.0) # the thresholding step of Minsker et al.
return w / w.sum()
def median_posterior(draws, rng):
"""Draws from the median posterior: a mixture of the K sub-posteriors with the Weiszfeld weights."""
K, S, _ = draws.shape
w = median_weights(draws)
return draws[rng.choice(K, size=S, p=w), rng.integers(S, size=S)], w
Before trusting them on a regression we try the four functions where the answers are known. Eight Gaussian sub-posteriors with arbitrary means and covariances have an exact product, an exact one-dimensional barycentre (the Normal with the average mean and the average standard deviation), and, in two dimensions, a barycentre that is again Gaussian with a covariance $S$ solving $S = \frac{1}{K}\sum_k (S^{1/2}\Sigma_k S^{1/2})^{1/2}$ (Agueh and Carlier 2011).
def matrix_sqrt(a):
values, vectors = np.linalg.eigh(a)
return (vectors * np.sqrt(np.maximum(values, 0))) @ vectors.T
check = np.random.default_rng([RANDOM_SEED, 4])
A = check.normal(size=(8, 3, 3))
covs = np.einsum("kij,klj->kil", A, A) + 0.5 * np.eye(3)
means = check.normal(size=(8, 3))
toy = np.stack([check.multivariate_normal(m, c, 4000) for m, c in zip(means, covs)])
W = np.linalg.inv(covs)
V = np.linalg.inv(W.sum(axis=0))
exact_mean, exact_sd = V @ np.einsum("kij,kj->i", W, means), np.sqrt(np.diag(V))
for name, out in (("consensus", consensus(toy)), ("Gaussian product", gaussian_product(toy, check))):
print(f"{name:17s} mean off by {np.abs(out.mean(axis=0) - exact_mean).max() / exact_sd.min():.3f} sd at most, "
f"sd ratio {np.round(out.std(axis=0) / exact_sd, 3)}")
b1 = barycentre(toy)
print(f"barycentre, 1-D mean off by {np.abs(b1.mean(axis=0) - means.mean(axis=0)).max():.3f}, sd over the average sd "
f"{np.round(b1.std(axis=0) / np.sqrt(np.einsum('kii->ki', covs)).mean(axis=0), 3)}")
S2 = np.eye(2)
for _ in range(200): # the fixed point for Gaussian barycentres
root = matrix_sqrt(S2)
inner = np.mean([matrix_sqrt(root @ c[:2, :2] @ root) for c in covs], axis=0)
S2 = np.linalg.solve(root, np.linalg.solve(root, inner @ inner).T)
b2 = barycentre_cloud(toy[:, :, :2])
print("barycentre, 2-D covariance of the point cloud", np.round(np.cov(b2, rowvar=False)[[0, 0, 1], [0, 1, 1]], 2),
"against the Gaussian fixed point", np.round(S2[[0, 0, 1], [0, 1, 1]], 2))
print("median posterior weights on eight shards:", np.round(median_posterior(toy, check)[1], 2))
consensus mean off by 0.024 sd at most, sd ratio [1.002 0.988 0.99 ] Gaussian product mean off by 0.044 sd at most, sd ratio [1.008 1.007 1.002] barycentre, 1-D mean off by 0.017, sd over the average sd [1.002 0.996 0.999]
barycentre, 2-D covariance of the point cloud [ 3.33 -0.55 3.35] against the Gaussian fixed point [ 3.15 -0.53 3.56] median posterior weights on eight shards: [0.13 0.12 0.08 0.14 0.16 0.08 0.18 0.11]
The two product rules return the exact product to within a few hundredths of a standard deviation, which is the Monte Carlo error of 4,000 draws. The one-dimensional barycentre has the average mean and the average standard deviation, and the cloud of 300 points has the covariance of the Gaussian barycentre to within its sampling error. The median spreads its weight over all eight shards: with sub-posteriors scattered around a common centre and none of them corrupted, the geometric median is not far from an even mixture.
The clouds
Now the regression. We fit the eight shards a second time with the other dial, the whole prior and the likelihood to the eighth power, and draw both sets of sub-posteriors for a pair of coefficients: the distance, which every shard knows well, and the priority slot, which none does.
with sb.track(f"{K_ROW} shards · barycentre"):
powered = fit_shards(LOGIT, row_pieces, ["beta"], "powered", seed=3)
sb.add(f"{K_ROW} shards · median", **sb.table().loc[f"{K_ROW} shards · barycentre", ["seconds", "peak_gb", "added_gb"]])
g3 = np.random.default_rng([RANDOM_SEED, 5])
combined.update({"Gaussian product": gaussian_product(tempered.flat, g3), "barycentre": barycentre(powered.flat)})
combined["median"], median_w = median_posterior(powered.flat, g3)
print(f"likelihood to the power {K_ROW}: {powered.seconds.sum():.1f} s summed, {powered.seconds.max():.2f} s for the slowest; "
f"{powered.divergences} divergences, largest r_hat {powered.rhat:.3f}")
print("median posterior, weights on the shards:", np.round(median_w, 2))
def mass_contours(ax, xy, color, levels=(0.5, 0.9), lw=1.8, ls="-", zorder=3):
"""Contours enclosing the given shares of a cloud of points (kernel density on a grid)."""
xy = xy[:: max(1, len(xy) // 800)]
lo, hi = np.quantile(xy, [0.002, 0.998], axis=0)
pad = 0.35 * (hi - lo)
gx, gy = np.meshgrid(np.linspace(lo[0] - pad[0], hi[0] + pad[0], 70), np.linspace(lo[1] - pad[1], hi[1] + pad[1], 70))
z = stats.gaussian_kde(xy.T)(np.vstack([gx.ravel(), gy.ravel()])).reshape(gx.shape)
ordered = np.sort(z.ravel())[::-1]
share = np.cumsum(ordered) / ordered.sum()
ax.contour(gx, gy, z, levels=sorted(ordered[np.searchsorted(share, level)] for level in levels), colors=[color],
linewidths=lw, linestyles=ls, zorder=zorder)
def shard_clouds(ax, subs, pair, points=220, alpha=0.4):
"""One colour per shard: a thinned scatter of its sub-posterior draws for a pair of parameters."""
colors = plt.cm.turbo(np.linspace(0.08, 0.92, len(subs)))
for k, draws in enumerate(subs):
thin = draws[:: max(1, len(draws) // points)]
ax.scatter(thin[:, pair[0]], thin[:, pair[1]], s=6, color=colors[k], alpha=alpha, lw=0, zorder=1)
def handle(color, label, ls="-", lw=1.8):
return plt.Line2D([], [], color=color, ls=ls, lw=lw, label=label)
PAIR = (1, 4)
fig, axes = plt.subplots(1, 3, figsize=(14.5, 4.6))
for ax, subs, title in ((axes[0], tempered.flat, "Tempered prior: wide, overlapping clouds"),
(axes[1], powered.flat, "Likelihood to the 8th power: narrow copies")):
shard_clouds(ax, subs, PAIR)
mass_contours(ax, full_row[:, PAIR], INK)
ax.set_title(title, loc="left", fontsize=10.5)
ax = axes[2]
mass_contours(ax, full_row[:, PAIR], INK, lw=2.6)
mass_contours(ax, combined["consensus"][:, PAIR], BLUE)
mass_contours(ax, combined["Gaussian product"][:, PAIR], ORANGE, ls=":")
mass_contours(ax, barycentre_cloud(powered.flat[:, :, PAIR]), VIOLET, ls="--")
ax.set_title("Stitched, over all rows (zoomed in)", loc="left", fontsize=10.5)
ax.legend(handles=[handle(INK, "all rows", lw=2.6), handle(BLUE, "consensus"), handle(ORANGE, "Gaussian product", ls=":"),
handle(VIOLET, "barycentre", ls="--")], frameon=False, fontsize=9, loc="lower left")
axes[0].legend(handles=[handle(INK, "all rows: 50% and 90% of the posterior")], frameon=False, fontsize=9, loc="lower left")
for ax in axes:
ax.set_xlabel("coefficient of distance")
tidy(ax, grid="both")
axes[0].set_ylabel("coefficient of the priority slot")
axes[1].set_xlim(axes[0].get_xlim())
axes[2].set_xlim(*np.quantile(full_row[:, 1], [0.0005, 0.9995]) + np.array([-0.03, 0.03]))
axes[2].set_ylim(*np.quantile(full_row[:, 4], [0.0005, 0.9995]) + np.array([-0.45, 0.25]));
likelihood to the power 8: 3.3 s summed, 0.43 s for the slowest; 0 divergences, largest r_hat 1.002 median posterior, weights on the shards: [0.13 0.12 0.14 0.11 0.11 0.13 0.12 0.13]

This is the picture the method is named for, and the two families look nothing alike. Under the tempered prior, on the left, each shard's cloud is far wider than the black contours of the full posterior, and all eight overlap: the answer is their product, the small region where all of them put mass at once. With the likelihood raised to the eighth power, in the middle, each cloud is about as wide as the full posterior in the horizontal direction and sits wherever its own five thousand rows put it: the answer is their average position and their average shape. Along the vertical axis the clouds are not ellipses. Each shard has three to eight late departures among its priority flights, so its sub-posterior has a longer tail towards very negative coefficients.
On the right, the three stitched posteriors are laid over the one from all rows. Along the distance axis they agree with it and with each other. Along the priority axis they are close, and not identical, which the scoreboard puts in numbers.
def compare(draws, full):
"""Per parameter: shift of the mean in full-posterior standard deviations, and the ratio of 90% widths."""
shift = (draws.mean(axis=0) - full.mean(axis=0)) / full.std(axis=0)
width = np.ptp(np.quantile(draws, [0.05, 0.95], axis=0), axis=0) / np.ptp(np.quantile(full, [0.05, 0.95], axis=0), axis=0)
return shift, width
chained = combined["consensus"].reshape(tempered.chains.shape[1:]) # consensus keeps the chains' order
sb.score(f"{K_ROW} shards · consensus", as_posterior(chained))
for rule, label in (("Gaussian product", "Gaussian product"), ("full prior in each", "full prior in each"),
("barycentre", "barycentre"), ("median", "median")):
sb.score(f"{K_ROW} shards · {label}", {"beta": combined[rule]})
shard_time = {"consensus": tempered, "Gaussian product": tempered, "full prior in each": untempered,
"barycentre": powered, "median": powered}
against = {}
for rule, draws in combined.items():
shift, width = compare(draws, full_row)
against[f"{K_ROW} shards · {rule}"] = {
"slowest shard (s)": shard_time[rule].seconds.max(), "shift, common (sd)": shift[np.abs(shift[:4]).argmax()],
"shift, priority (sd)": shift[4], "width ratio, common": width[:4].mean(), "width ratio, priority": width[4]}
shift, width = compare(alone.reshape(-1, len(NAMES)), full_row)
against["one shard alone"] = {"slowest shard (s)": sb.table().loc["one shard alone", "seconds"],
"shift, common (sd)": shift[np.abs(shift[:4]).argmax()], "shift, priority (sd)": shift[4],
"width ratio, common": width[:4].mean(), "width ratio, priority": width[4]}
board = sb.table()
print(board.round(3).to_string())
print()
print(pd.DataFrame(against).T.reindex(board.index[1:]).round(2).to_string())
seconds peak_gb added_gb ess ess_per_s rmse coverage width
method
all rows · NUTS 5.003 0.457 0.013 2150.924 429.902 0.065 1.0 0.155
one shard alone 0.607 0.751 0.000 2705.297 4453.834 0.230 1.0 0.396
8 shards · consensus 3.335 0.752 0.002 1161.636 348.349 0.074 0.8 0.158
8 shards · Gaussian product 3.335 0.752 0.002 NaN NaN 0.074 0.8 0.158
8 shards · full prior in each 3.298 0.745 0.000 NaN NaN 0.118 0.8 0.146
8 shards · barycentre 3.289 0.702 0.000 NaN NaN 0.056 0.8 0.158
8 shards · median 3.289 0.702 0.000 NaN NaN 0.072 1.0 0.438
slowest shard (s) shift, common (sd) shift, priority (sd) width ratio, common width ratio, priority
method
one shard alone 0.61 -3.63 2.30 2.86 2.42
8 shards · consensus 0.47 -0.14 0.13 1.00 1.03
8 shards · Gaussian product 0.47 -0.12 0.13 1.02 1.02
8 shards · full prior in each 0.42 0.28 0.76 1.02 0.91
8 shards · barycentre 0.43 -0.13 -0.14 1.02 1.02
8 shards · median 0.43 -0.20 0.10 2.50 3.04sb.plot(highlight=[f"{K_ROW} shards · full prior in each"], figsize=(15.5, 4.2));

The first table is the scoreboard against the simulated truth, the second holds each row against the posterior of all the rows, which is the fairer test of a method whose job is to reproduce it. The seconds of a shard row are summed over the eight fits, which is what one machine pays; the column slowest shard is what eight machines would wait for, a projection from fits run in turn. The memory columns say nothing at this size, where a shard and the whole table both fit in a rounding error and the peak is whatever the kernel already held; the table of part 1 is where memory is measured.
Consensus and the Gaussian product are the same answer to the second decimal, as they must be, and they sit within a seventh of a posterior standard deviation of the full posterior on every coefficient, with the right widths. The barycentre does as well, and what little it misses on the priority slot it misses in the other direction. Against the truth, four of the five intervals of each stitched posterior hold it, where the full posterior holds all five; with five intervals that is not a difference to read much into. The median posterior is the odd one out: its intervals are two and a half to three times as wide as the posterior's. That is what its authors report too (their Table 1 has median-posterior intervals two to three times as long as the full posterior's), and it follows from what it is, a mixture of the scattered copies in the middle panel above. It answers a question about robustness, which we will put to it in part 5. As an approximation to the full posterior it is not in the running, and we leave it out of the sweeps.
The row one shard alone is the honest alternative to all of this: fit an eighth of the data and stop. Its intervals are about 2.8 times as wide, they cover, and its centre is wherever an eighth of the data puts it, several of the full posterior's standard deviations away. Every stitched row has to beat that to be worth eight machines, and at $K = 8$ the three rules do.
The choice. Consensus with matrix weights as the default, the barycentre beside it as a second opinion that makes different assumptions. Rejected: the Gaussian product as a separate method (it has the mean and covariance of consensus by construction, and throws the shape away), and the median posterior as a stand-in for the full posterior (its width is the scatter of the shards). What would change our mind: shards that may be corrupted, where a median is the point, and a parameter of high dimension, where a $d \times d$ weight matrix estimated from draws becomes the weak link and scalar weights are the fallback.
4 · How many shards?
Eight shards of five thousand rows worked. The useful question is where that stops, and to answer it we need hundreds of shard fits at many values of $K$. At a second per fit that is out of reach, so we move to a test bench: the same model on a coarser record. Distance is logged in five bands, the load factor in four, and the table has 256,000 flights. With every covariate on a short list of values the rows fall into 80 cells, a shard's likelihood is 80 binomial terms whatever the number of its rows, and a fit costs a twentieth of a second. A table like this should be compressed and never split, as E126 argued. We split it anyway, because the rules cannot tell how a sub-posterior was computed, and here its full-data posterior comes free.
The bench also has a clock. The rows are in order of time, the mix of distances drifts over the period, and the priority slot is only introduced for its last quarter. None of that matters while the rows are dealt at random, as they are in this part. It will in the next.
N_A = 256_000
def simulate_coarse(n, seed):
"""Flights in order of time, on a coarse record: every row falls in one of a few dozen cells."""
g = np.random.default_rng([RANDOM_SEED, seed])
t = np.sort(g.random(n)) # position in the period: the order of the file
distance = g.binomial(4, 0.35 + 0.3 * t) - 2.0 # five bands; long flights become more common
load = g.integers(0, 4, n) - 1.5 # four bands
peak = g.random(n) < 0.3
priority = (t > 0.75) & (g.random(n) < 0.016) # introduced for the last quarter only
X = np.column_stack([np.ones(n), distance, load, peak, priority]).astype(float)
return X, (g.random(n) < special.expit(X @ BETA)).astype(float)
X_a, late_a = simulate_coarse(N_A, 6)
LEVELS_A, cell_a = np.unique(X_a, axis=0, return_inverse=True)
def cell_piece(rows):
"""The rows of a shard as binomial cells: the data the compiled model is refilled with."""
flights = np.bincount(cell_a[rows], minlength=len(LEVELS_A))
late = np.bincount(cell_a[rows], weights=late_a[rows], minlength=len(LEVELS_A))
keep = flights > 0
return dict(X=LEVELS_A[keep], late=late[keep], flights=flights[keep].astype(float))
full_a, info_a = fit_one(LOGIT, cell_piece(np.arange(N_A)), ["beta"], draws=2000, tune=500, seed=RANDOM_SEED)
full_a = full_a.reshape(-1, len(NAMES))
prio_a = X_a[:, 4] == 1
print(f"{N_A:,} flights in {len(LEVELS_A)} cells; {prio_a.sum():,} priority flights, {int(late_a[prio_a].sum())} of them late; "
f"full-data fit {info_a['seconds']:.2f} s, r_hat {info_a['rhat']:.3f}")
print(pd.DataFrame({"truth": BETA, "posterior mean": full_a.mean(axis=0), "sd": full_a.std(axis=0),
"skewness": stats.skew(full_a, axis=0)}, index=NAMES).round(3).to_string())
256,000 flights in 80 cells; 993 priority flights, 86 of them late; full-data fit 0.06 s, r_hat 1.000
truth posterior mean sd skewness
intercept -2.0 -1.995 0.008 0.009
distance 0.5 0.506 0.006 0.033
load 0.4 0.405 0.005 0.014
peak 0.6 0.591 0.012 0.042
priority -1.0 -0.931 0.116 -0.102With 256,000 flights the full posterior is Gaussian in every coordinate, the priority slot included: it rests on 86 late departures now. By the hypothesis this is the easy case. We sweep $K$ from 2 to 64, so that a shard holds between 128,000 and 4,000 flights, and at each $K$ we fit every shard twice, once with each dial, and stitch.
We measure the distance from the full posterior with two numbers per parameter: the shift of the mean, in standard deviations of the full posterior, and the width ratio of the central 90% intervals. We call a combination broken for a parameter when the shift exceeds half a standard deviation or the width is off by more than a factor of 1.5 either way. The threshold is a convention, fixed before looking at the results: half a standard deviation is where a reported interval visibly moves, and it is several times the Monte Carlo noise of these comparisons, which is about a tenth.
KS = (2, 4, 8, 16, 32, 64)
BROKEN_SHIFT, BROKEN_WIDTH = 0.5, 1.5
def stitch(tempered, powered, seed, scalar=False):
"""Every rule on its own kind of sub-posterior: draws of shape (S, d) per rule."""
g = np.random.default_rng([RANDOM_SEED, 100 + seed])
out = {"consensus": consensus(tempered)}
if scalar:
out["consensus, scalar weights"] = consensus(tempered, weights="scalar")
out["Gaussian product"] = gaussian_product(tempered, g)
out["barycentre"] = barycentre(powered)
return out
def sweep(compiled, names, pieces, full, labels, Ks=KS, keep=(), seed=0, select=slice(None), scalar=False, **kwargs):
"""For each K: fit the shards with each dial, stitch, and measure the distance from the full posterior.
``pieces(K)`` returns the data of the K shards. Returns one row per (K, rule, parameter), a log of
time and sampler health per K, and the draws at the values of K named in ``keep``.
"""
rows, log, kept = [], [], {}
for K in Ks:
parts = pieces(K)
temp = fit_shards(compiled, parts, names, "tempered", seed=10 * seed + K, **kwargs)
powd = fit_shards(compiled, parts, names, "powered", seed=10 * seed + K + 1, **kwargs)
t, p = temp.flat[:, :, select], powd.flat[:, :, select]
stitched = stitch(t, p, seed + K, scalar=scalar)
for rule, draws in stitched.items():
shift, width = compare(draws, full)
rows += [dict(K=K, rule=rule, parameter=label, shift=s, width=w) for label, s, w in zip(labels, shift, width)]
log.append({"K": K, "shard fits": 2 * K, "seconds, summed": temp.seconds.sum() + powd.seconds.sum(),
"slowest shard (s)": max(temp.seconds.max(), powd.seconds.max()),
"divergences": temp.divergences + powd.divergences, "largest r_hat": max(temp.rhat, powd.rhat)})
if K in keep:
kept[K] = (t, p, stitched)
table = pd.DataFrame(rows)
table["broken"] = (table["shift"].abs() > BROKEN_SHIFT) | (table["width"] > BROKEN_WIDTH) | (table["width"] < 1 / BROKEN_WIDTH)
return table, pd.DataFrame(log).set_index("K"), kept
def worst(table, parameters):
"""Per (K, rule): the shift farthest from 0 and the width ratio farthest from 1 among some parameters."""
part = table[table["parameter"].isin(parameters)]
grouped = part.groupby(["rule", "K"], sort=False)
return pd.DataFrame({"shift": grouped["shift"].agg(lambda s: s.loc[s.abs().idxmax()]),
"width": grouped["width"].agg(lambda s: s.loc[np.log(s).abs().idxmax()]),
"broken": grouped["broken"].any()})
def breaking_point(table, parameters, Ks=KS):
"""Per rule: the first K of the sweep at which the combination is broken for one of the parameters.
If the rule is back inside the band at a larger K, the entry says so: that K was an excursion.
"""
off = worst(table, parameters)["broken"]
out = {}
for rule in off.index.get_level_values("rule").unique():
bad = [K for K in Ks if off[rule].get(K, False)]
back = [K for K in Ks if bad and K > bad[0] and not off[rule].get(K, False)]
out[rule] = f"none to {max(Ks)}" if not bad else str(bad[0]) + (f" (inside again at {back[0]})" if back else "")
return pd.Series(out)
def shift_axis(ax, values):
"""A symmetric-log axis for shifts, with ticks that can be read."""
top = max(1.6, 1.4 * np.abs(np.asarray(values, dtype=float)).max())
ticks = [t for t in (0.5, 1, 3, 10, 30) if t < top]
ax.set_yscale("symlog", linthresh=1.0)
ax.set_ylim(-top, top)
ax.set_yticks([-t for t in ticks[::-1]] + [0] + ticks, [f"{-t:g}" for t in ticks[::-1]] + ["0"] + [f"{t:g}" for t in ticks])
ax.minorticks_off()
def sweep_panels(axes, table, parameters, title, Ks=KS, legend=False, ls=None, label_suffix=""):
"""Shift (upper axis) and width ratio (lower axis) against K, one line per rule."""
part = worst(table, parameters)
for rule in part.index.get_level_values("rule").unique():
style = dict(RULE_STYLE[rule], lw=1.8, ms=5)
if ls is not None:
style["ls"] = ls
axes[0].plot(part.loc[rule].index, part.loc[rule]["shift"], label=rule + label_suffix, **style)
axes[1].plot(part.loc[rule].index, part.loc[rule]["width"], **style)
axes[0].axhspan(-BROKEN_SHIFT, BROKEN_SHIFT, color=LIGHT, alpha=0.45, lw=0)
axes[1].axhspan(1 / BROKEN_WIDTH, BROKEN_WIDTH, color=LIGHT, alpha=0.45, lw=0)
shift_axis(axes[0], part["shift"])
axes[1].set_yscale("log")
axes[1].set_yticks([0.125, 0.25, 0.5, 1, 2, 4, 8], ["1/8", "1/4", "1/2", "1", "2", "4", "8"])
axes[1].minorticks_off()
for ax in axes:
ax.set_xscale("log", base=2)
ax.set_xticks(list(Ks), [str(K) for K in Ks])
tidy(ax)
axes[0].set_title(title, loc="left", fontsize=10.5)
axes[1].set_xlabel("number of shards K")
if legend:
axes[0].legend(frameon=False, fontsize=8.5, loc="best")
deal_a = np.random.default_rng([RANDOM_SEED, 7]).permutation(N_A)
COMMON, FLAG = NAMES[:4], NAMES[4:]
t0 = time.perf_counter()
sweep_a, log_a, _ = sweep(LOGIT, ["beta"], lambda K: [cell_piece(i) for i in np.array_split(deal_a, K)], full_a,
NAMES, seed=1, scalar=True, draws=1000)
print(f"{log_a['shard fits'].sum()} shard fits in {time.perf_counter() - t0:.0f} s")
print(log_a.round(3).to_string())
252 shard fits in 9 s
shard fits seconds, summed slowest shard (s) divergences largest r_hat
K
2 4 0.153 0.039 0 1.001
4 8 0.303 0.039 0 1.002
8 16 0.594 0.038 0 1.002
16 32 1.177 0.039 0 1.002
32 64 2.290 0.038 1 1.003
64 128 4.598 0.131 0 1.004fig, axes = plt.subplots(2, 2, figsize=(13.5, 6.4), sharex=True)
sweep_panels(axes[:, 0], sweep_a, COMMON, "The four common coefficients (the worst of them)", legend=True)
sweep_panels(axes[:, 1], sweep_a, FLAG, "The priority slot")
axes[0, 0].set_ylabel("shift of the mean (posterior sd)")
axes[1, 0].set_ylabel("width ratio of 90% intervals")
zero_events = [int(sum(p["late"][p["X"][:, 4] == 1].sum() == 0 for p in [cell_piece(i) for i in np.array_split(deal_a, K)]))
for K in KS]
print("shards with no late priority flight at all, for K =", dict(zip(KS, zero_events)))
print("\nthe first K at which each rule is broken:")
BREAKS = {"common coefficients, rows at random": breaking_point(sweep_a, COMMON),
"priority slot, rows at random": breaking_point(sweep_a, FLAG)}
print(pd.DataFrame(BREAKS).T.to_string())
print("\nthe priority slot, K by K:")
print(sweep_a[sweep_a["parameter"] == "priority"].pivot(index="K", columns="rule", values=["shift", "width"]).round(2).to_string());
shards with no late priority flight at all, for K = {2: 0, 4: 0, 8: 0, 16: 1, 32: 2, 64: 14}
the first K at which each rule is broken:
consensus consensus, scalar weights Gaussian product barycentre
common coefficients, rows at random none to 64 none to 64 none to 64 none to 64
priority slot, rows at random 16 16 16 8
the priority slot, K by K:
shift width
rule Gaussian product barycentre consensus consensus, scalar weights Gaussian product barycentre consensus consensus, scalar weights
K
2 -0.03 -0.05 -0.03 -0.02 1.01 0.98 0.98 0.99
4 0.17 -0.20 0.19 0.20 0.99 1.01 1.01 1.01
8 0.30 -0.59 0.29 0.34 1.01 1.05 1.01 1.02
16 0.52 -1.63 0.53 0.62 1.05 1.20 1.05 1.05
32 0.61 -2.19 0.60 0.68 1.09 1.24 1.09 1.09
64 1.01 -4.80 0.98 1.02 1.16 1.62 1.15 1.15
The grey bands are the region we agreed to call unbroken. On the left, the common coefficients: all four rules stay inside it from 2 shards to 64, with the right widths. The one that wanders furthest is consensus with scalar weights, which reaches the edge of the band at 64. The coefficients of a regression are correlated (the intercept with the peak hour and with the priority slot), and a rule that weights each coordinate on its own ignores that. Matrix weights cost a $5\times5$ inverse per shard and are worth it.
On the right, the priority slot, and the first break. With 2 and 4 shards everything agrees. At 8 the barycentre has left the band on the low side, and from there it sinks: nearly five standard deviations too low at 64. Consensus and the Gaussian product leave at 16, in the opposite direction, and are a standard deviation too high at 64. The line printed under the figure says why. The whole table holds 86 late priority flights, so at 16 shards a shard has five of them on average, at 64 barely more than one, and by then fourteen shards have none. A shard with no event knows only that the coefficient is very negative; its sub-posterior is a long tail held up by the prior. With the likelihood raised to the 64th power that shard is certain of a hugely negative coefficient, and the barycentre, which gives every shard the same say, is dragged down. Under the tempered prior the same shard has an enormous variance, so the precision weights all but ignore it, and what it knew, that late departures are rare there, is lost: the answer drifts up.
So the full posterior was Gaussian throughout, and the rules still broke. What has to be Gaussian is the sub-posterior, and that depends on how much each shard knows about the parameter, which for a rare flag is a count of events and has little to do with the number of rows.
The same failure in closed form, two thousand times
One data set could be unlucky. For a single rare event rate everything is available in closed form, so we can repeat the experiment on two thousand data sets and count how often the 90% interval holds the truth. Take $N = 51{,}200$ flights that are late with probability $\theta = 0.0025$, about 128 events, and a uniform prior on $\theta$. The posterior is a Beta distribution, and so is every sub-posterior:
- likelihood to the power $K$: $\mathrm{Beta}(1 + K y_k,\; 1 + K(n_k - y_k))$;
- prior to the power $1/K$: the uniform prior is its own power, so $\mathrm{Beta}(1 + y_k,\; 1 + n_k - y_k)$.
We stitch on the log-odds scale, where a regression lives, using exact means, variances and quantiles of the Beta distributions, so there is no Monte Carlo error at all. The second bullet hides a trap. The prior was tempered as a density of $\theta$, and we are about to multiply densities of the log-odds $u$. A density picks up the Jacobian $\theta(1-\theta)$ when it moves to the log-odds scale, each of the $K$ sub-posteriors carries it once, and the product carries it $K$ times where the posterior has it once. Tempering and combining have to happen on the same scale. On the log-odds scale the uniform prior has density $\theta(1-\theta)$, its $1/K$ power is $[\theta(1-\theta)]^{1/K}$, and the sub-posterior is $\mathrm{Beta}(1/K + y_k,\; 1/K + n_k - y_k)$. Scott et al. use exactly this prior, $\mathrm{Beta}(0.01, 0.01)$ for a hundred shards, in their own binomial example, and remark that the procedure is sensitive to the scale of the analysis.
N_LAB, THETA_LAB, REPS = 51_200, 0.0025, 2000
Z90 = stats.norm.ppf(0.95)
truth_lab = special.logit(THETA_LAB)
def logodds_moments(a, b):
"""Mean and variance of the log-odds of a Beta(a, b) variable."""
return special.digamma(a) - special.digamma(b), special.polygamma(1, a) + special.polygamma(1, b)
def logodds_interval(a, b):
return special.logit(stats.beta.ppf(0.05, a, b)), special.logit(stats.beta.ppf(0.95, a, b))
lab = []
g_lab = np.random.default_rng([RANDOM_SEED, 8])
for K in (1, 2, 4, 8, 16, 32, 64, 128, 256):
n = N_LAB // K
y = g_lab.binomial(n, THETA_LAB, size=(REPS, K))
total = y.sum(axis=1)
full_mean, full_var = logodds_moments(1 + total, 1 + N_LAB - total)
full_lo, full_hi = logodds_interval(1 + total, 1 + N_LAB - total)
results = {"all rows (exact)": (full_mean, full_lo, full_hi)}
for name, prior in (("Gaussian product, prior tempered on the rate scale", 1.0),
("Gaussian product, prior tempered on the log-odds scale", 1.0 / K)):
mean, var = logodds_moments(prior + y, prior + n - y)
centre, sd = (mean / var).sum(axis=1) / (1 / var).sum(axis=1), np.sqrt(1 / (1 / var).sum(axis=1))
results[name] = (centre, centre - Z90 * sd, centre + Z90 * sd)
a, b = 1 + K * y, 1 + K * (n - y)
lo, hi = logodds_interval(a, b)
results["barycentre, on the log-odds scale"] = (logodds_moments(a, b)[0].mean(axis=1), lo.mean(axis=1), hi.mean(axis=1))
rate_lo, rate_hi = stats.beta.ppf(0.05, a, b).mean(axis=1), stats.beta.ppf(0.95, a, b).mean(axis=1)
results["barycentre, on the rate scale"] = (special.logit((a / (a + b)).mean(axis=1)), special.logit(rate_lo), special.logit(rate_hi))
for name, (centre, lo, hi) in results.items():
lab.append({"K": K, "events per shard": N_LAB * THETA_LAB / K, "rule": name,
"coverage": np.mean((lo <= truth_lab) & (truth_lab <= hi)),
"shift": np.median((centre - full_mean) / np.sqrt(full_var)),
"width": np.median((hi - lo) / (full_hi - full_lo)), "shards with no event": np.mean(y == 0)})
lab = pd.DataFrame(lab)
LAB_STYLE = {"all rows (exact)": dict(color=INK, ls="-", marker=""),
"Gaussian product, prior tempered on the rate scale": dict(color=RED, ls="--", marker="x"),
"Gaussian product, prior tempered on the log-odds scale": dict(color=BLUE, ls="-", marker="o"),
"barycentre, on the log-odds scale": dict(color=VIOLET, ls="-", marker="D"),
"barycentre, on the rate scale": dict(color=VIOLET, ls=":", marker="d")}
fig, axes = plt.subplots(1, 2, figsize=(13.5, 4.3), sharex=True)
for name, style in LAB_STYLE.items():
part = lab[lab["rule"] == name]
axes[0].plot(part["events per shard"], part["coverage"], lw=1.8, ms=5, label=name, **style)
axes[1].plot(part["events per shard"], part["shift"], lw=1.8, ms=5, **style)
axes[0].axhline(0.9, color=MUTED, lw=1, ls=":")
axes[0].set_ylabel("coverage of the truth by the 90% interval")
axes[0].set_title(f"Coverage over {REPS:,} data sets", loc="left")
axes[0].legend(frameon=False, fontsize=8.5, loc="lower right")
axes[1].axhspan(-BROKEN_SHIFT, BROKEN_SHIFT, color=LIGHT, alpha=0.45, lw=0)
shift_axis(axes[1], lab["shift"])
axes[1].set_ylabel("median shift of the centre (posterior sd)")
axes[1].set_title("Where the stitched posterior sits", loc="left")
for ax in axes:
ax.set_xscale("log", base=2)
ax.invert_xaxis()
ax.set_xlabel("expected events per shard (128 events in all; more shards to the right)")
tidy(ax)
pivot = lab.pivot(index="K", columns="rule", values="coverage")[list(LAB_STYLE)]
pivot.insert(0, "events per shard", N_LAB * THETA_LAB / pivot.index)
pivot.insert(1, "shards with no event", lab.groupby("K")["shards with no event"].first())
lab_trap = pivot.loc[8, "Gaussian product, prior tempered on the rate scale"]
lab_right = pivot.loc[8, "Gaussian product, prior tempered on the log-odds scale"]
print(pivot.round(3).rename(columns=lambda c: c.replace("Gaussian product, prior tempered", "product,")).to_string());
rule events per shard shards with no event all rows (exact) product, on the rate scale product, on the log-odds scale barycentre, on the log-odds scale barycentre, on the rate scale K 1 128.0 0.000 0.900 0.910 0.910 0.900 0.900 2 64.0 0.000 0.904 0.904 0.904 0.902 0.904 4 32.0 0.000 0.894 0.876 0.898 0.890 0.894 8 16.0 0.000 0.895 0.829 0.890 0.878 0.895 16 8.0 0.001 0.901 0.648 0.894 0.811 0.900 32 4.0 0.019 0.892 0.176 0.872 0.470 0.878 64 2.0 0.135 0.894 0.000 0.655 0.012 0.868 128 1.0 0.368 0.886 0.000 0.088 0.000 0.804 256 0.5 0.606 0.894 0.000 0.000 0.000 0.711

The horizontal axis is the quantity that mattered in the regression, the number of events a shard can expect, and it runs from 64 on the left to half an event on the right. The black line is the exact posterior, at 90% throughout.
The red line is the trap. With the prior tempered on one scale and the draws combined on another, the interval is down to 83% at 16 events per shard and to 18% at 4, in a problem where every sub-posterior is a perfectly ordinary Beta distribution. This is the mistake a PyMC user is invited to make, because the sampler works on the log-odds or the log scale by itself, and it is natural to combine the draws there while writing the prior on the natural scale.
The blue line is the same rule with the prior tempered where the draws are combined. It holds its coverage down to 4 events per shard, and then fails for the reason seen in the regression: shards with one event or none have sub-posteriors that no Gaussian describes. The solid violet line is the barycentre on the log-odds scale, which fails earlier, at 8 events per shard, and in the opposite direction, too low. Both orders agree with the regression above. Srivastava, Li and Dunson (2018) show the same breakdown of their own method on rare events, with a hundred shards most of which see no event.
The dotted violet line is the barycentre again, computed on the rate itself, and it does much better. On that scale a shard's estimate is its share of late flights, which is unbiased however few the events, so the average of the shards is centred correctly; what goes wrong is only the width. Neither family is invariant to the scale, and Li, Srivastava and Dunson (2017) say as much of the first: the factorisation obtained by splitting the prior changes with the parameterisation. The product rules want the scale on which the sub-posteriors are most nearly Gaussian, with the prior tempered there. The barycentre wants the scale on which a small shard's estimate is unbiased. For a rate these are two different scales, and for a regression coefficient only the first is on offer.
The choice. For regression coefficients, any of the three rules up to the $K$ at which a shard still sees a dozen or more events for every coefficient; here that is 4 shards for the priority slot and at least 64 for the rest. Rejected: judging $K$ by rows per shard (4,000 rows were plenty for four coefficients and too few for the fifth), and scalar weights. What would change our mind: a count of events per shard and per coefficient is cheap to make before any fit, and that is the number to look at.
5 · Who gets which rows
Until now the rows were dealt at random. Real tables do not arrive that way. They arrive as files by day or by region, and the obvious way to split them is to give each machine a run of files. Our bench has a clock, so we can do exactly that: the same 256,000 flights, the same full-data posterior, cut into $K$ consecutive stretches of time. The priority slot exists only in the last quarter of the period, so for most machines the fifth column of the design matrix is all zeros and its coefficient is not identified at all. With eight shards, five have no priority flight and a sixth has a handful.
t0 = time.perf_counter()
sweep_t, log_t, kept_t = sweep(LOGIT, ["beta"], lambda K: [cell_piece(i) for i in np.array_split(np.arange(N_A), K)], full_a,
NAMES, keep=(8,), seed=2, scalar=True, draws=1000)
print(f"{log_t['shard fits'].sum()} shard fits in {time.perf_counter() - t0:.0f} s; largest r_hat {log_t['largest r_hat'].max():.3f}, "
f"{log_t['divergences'].sum()} divergences")
BREAKS["common coefficients, rows by time"] = breaking_point(sweep_t, COMMON)
BREAKS["priority slot, rows by time"] = breaking_point(sweep_t, FLAG)
temp8, pow8, stitched8 = kept_t[8]
g5 = np.random.default_rng([RANDOM_SEED, 9])
median8, w8 = median_posterior(pow8, g5)
no_flag = np.array([p["X"][:, 4].sum() == 0 for p in [cell_piece(i) for i in np.array_split(np.arange(N_A), 8)]])
fig = plt.figure(figsize=(14.5, 8.2))
grid = fig.add_gridspec(2, 6)
for col, (subs, title) in enumerate(((temp8, "By time, tempered prior: most shards know nothing"),
(pow8, "By time, likelihood to the 8th power"))):
ax = fig.add_subplot(grid[0, 2 * col:2 * col + 2])
shard_clouds(ax, subs, PAIR, alpha=0.35)
mass_contours(ax, full_a[:, PAIR], INK, lw=2.2)
ax.set_title(title, loc="left", fontsize=10.5)
ax.set_xlabel("coefficient of distance")
ax.set_ylabel("coefficient of the priority slot")
tidy(ax, grid="both")
ax = fig.add_subplot(grid[0, 4:])
density(ax, full_a[:, 4], INK, "all rows", fill=True)
density(ax, stitched8["consensus"][:, 4], BLUE, "consensus")
density(ax, stitched8["barycentre"][:, 4], VIOLET, "barycentre", ls="--")
density(ax, median8[:, 4], MAGENTA, "median posterior", ls="-.")
ax.set_xlim(-2.6, 2.6)
ax.set_ylim(0, 1.25 * stats.gaussian_kde(full_a[:, 4])(full_a[:, 4].mean())[0])
ax.set_yticks([])
ax.set_xlabel("coefficient of the priority slot")
ax.set_title("Stitched, K = 8 by time", loc="left", fontsize=10.5)
ax.legend(frameon=False, fontsize=9, loc="upper right")
tidy(ax, grid=None)
lower = [fig.add_subplot(grid[1, :3]), fig.add_subplot(grid[1, 3:])]
part_t, part_r = worst(sweep_t, FLAG), worst(sweep_a, FLAG)
for ax, column, label in zip(lower, ("shift", "width"), ("shift of the mean (posterior sd)", "width ratio of 90% intervals")):
for rule in ("consensus", "barycentre"):
style = dict(color=RULE_STYLE[rule]["color"], marker=RULE_STYLE[rule]["marker"], lw=1.8, ms=5)
ax.plot(part_t.loc[rule].index, part_t.loc[rule][column], ls="-", label=f"{rule}, rows by time", **style)
ax.plot(part_r.loc[rule].index, part_r.loc[rule][column], ls=":", mfc="white", label=f"{rule}, rows at random", **style)
ax.set_xscale("log", base=2)
ax.set_xticks(list(KS), [str(K) for K in KS])
ax.set_xlabel("number of shards K")
ax.set_ylabel(label)
tidy(ax)
lower[0].axhspan(-BROKEN_SHIFT, BROKEN_SHIFT, color=LIGHT, alpha=0.45, lw=0)
shift_axis(lower[0], pd.concat([part_t["shift"], part_r["shift"]]))
lower[0].set_title("The priority slot, by time and at random", loc="left", fontsize=10.5)
lower[0].legend(frameon=False, fontsize=8.5)
lower[1].axhspan(1 / BROKEN_WIDTH, BROKEN_WIDTH, color=LIGHT, alpha=0.45, lw=0)
lower[1].set_yscale("log")
lower[1].set_yticks([0.5, 1, 2, 4, 8, 16], ["1/2", "1", "2", "4", "8", "16"])
lower[1].minorticks_off()
rows8 = {rule: compare(draws, full_a) for rule, draws in {**stitched8, "median": median8}.items()}
table8 = pd.DataFrame({rule: {"shift, common": s[np.abs(s[:4]).argmax()], "shift, priority": s[4],
"width, common": w[:4].mean(), "width, priority": w[4]} for rule, (s, w) in rows8.items()}).T
print(f"shards without a single priority flight at K = 8: {no_flag.sum()} of 8; median-posterior weights: {np.round(w8, 2)}")
print(table8.round(2).to_string())
print("\nthe first K at which each rule is broken:")
print(pd.DataFrame(BREAKS).T.to_string());
252 shard fits in 9 s; largest r_hat 1.005, 0 divergences
shards without a single priority flight at K = 8: 5 of 8; median-posterior weights: [0.15 0.13 0.13 0.13 0.15 0.11 0.1 0.1 ]
shift, common shift, priority width, common width, priority
consensus 0.10 0.03 1.01 0.97
consensus, scalar weights -0.14 0.08 1.03 0.98
Gaussian product 0.10 0.01 1.00 1.00
barycentre 0.17 3.60 1.03 6.22
median 0.47 4.17 3.09 10.22
the first K at which each rule is broken:
consensus consensus, scalar weights Gaussian product barycentre
common coefficients, rows at random none to 64 none to 64 none to 64 none to 64
priority slot, rows at random 16 16 16 8
common coefficients, rows by time none to 64 none to 64 none to 64 none to 64
priority slot, rows by time none to 64 none to 64 none to 64 2
The upper left panel shows what a machine without the flag reports under the tempered prior: clouds that span the whole height of the panel, because for them the coefficient has no likelihood and their sub-posterior is the tempered prior, a Normal with standard deviation $\sqrt{8}$. That is a Gaussian statement of ignorance, and precision weighting is made for it. Those shards get almost no weight on that coordinate, the ones that have the flag decide, and consensus lands on the full posterior as well as it did with rows at random: in the lower panels the solid blue line stays inside the band up to 64 shards. It does better than at random, in fact, because a shard that has the flag at all has many flights with it, and none is left with a handful of events.
The upper middle panel is the same split seen by the other family. With the likelihood raised to the eighth power and the whole prior, a shard without the flag returns the prior, $\mathcal{N}(0, 1)$, as its copy of the full posterior. The barycentre averages eight copies with equal say, five of which are the prior, and the result on the upper right is a wide lump centred near zero: shifted by three to four standard deviations and five to seven times too wide, at every $K$ from 2 upwards. The median posterior fares no better, and this is the lesson about robustness that was promised: a median protects against a minority of bad shards, and here the uninformed shards are the majority, so the median sides with them.
Nothing in this failure is about the shape of a posterior. The sub-posteriors are Gaussian in both families. What differs is what each rule does with a shard that knows nothing, and the expected lesson needs amending: how the rows are dealt can matter more than the rule and more than the shape. Dealt at random, the barycentre was sound up to 4 shards. Dealt by time, it is wrong with two.
The choice. Deal the rows at random if we control the split. If the shards are files by time or by region, use consensus with matrix weights and the tempered prior, which turns "this shard cannot tell" into a wide Gaussian that the weights discount. Rejected: the barycentre and the median on shards that are not exchangeable, because both give an uninformed shard a full vote. What would change our mind: a count, per shard, of the rows that carry each coefficient; any coefficient with a zero somewhere rules the barycentre out.
6 · A group-level standard deviation
The next posterior is skewed even with all the data. An operations team follows 64 stations. Each has about two thousand flights and a station effect on some measured delay, and the questions are the network's mean $\mu$ and the spread $\tau$ between stations:
$$y_{ij} \sim \mathcal{N}(\mu + b_j,\ 1), \qquad b_j \sim \mathcal{N}(0, \tau).$$
The 131,000 rows reduce exactly to 64 station means with their standard errors (E126 again), and the station effects integrate out by hand: $\bar y_j \sim \mathcal{N}(\mu,\ \tau^2 + 1/n_j)$. Two parameters are left. What makes $\tau$ different from a regression coefficient is where its information comes from: 64 stations tell us about $\tau$, and a million more rows at the same stations would add nothing. We put the prior on $\log\tau$ directly, a Normal, so that tempering and combining happen on one scale and the trap of part 4 cannot open.
There are two ways to deal this table. By station: each machine gets whole stations, as Scott et al. prescribe for hierarchical models, where no group may be split across machines. By row: each machine gets a random share of every station's rows and runs the same model on its own station means, which looks harmless and is not.
J, N_J, MU, TAU = 64, 2048, 1.0, 0.4
g6 = np.random.default_rng([RANDOM_SEED, 10])
effects = g6.normal(0, TAU, J)
micro = MU + effects[:, None] + g6.normal(0, np.sqrt(64 / N_J), (J, 64)) # each station's mean in 64 random row shards
ybar, se = micro.mean(axis=1), np.full(J, 1 / np.sqrt(N_J))
def station_model():
with pm.Model() as model:
y = pm.Data("ybar", np.zeros(2))
s = pm.Data("se", np.ones(2))
prior_scale = pm.Data("prior_scale", 1.0)
power = pm.Data("power", 1.0)
mu = pm.Normal("mu", 0.0, 5.0 * prior_scale)
log_tau = pm.Normal("log_tau", np.log(0.5), 1.0 * prior_scale) # the prior lives on the scale we combine on
spread = pt.sqrt(pt.exp(2 * log_tau) + s**2)
pm.Potential("loglik", power * pm.logp(pm.Normal.dist(mu, spread), y).sum())
return model
STATION = nutpie.compile_pymc_model(station_model())
HIER = ["mu", "log_tau"]
full_h, info_h = fit_one(STATION, dict(ybar=ybar, se=se), HIER, draws=2000, tune=500, seed=RANDOM_SEED, target_accept=0.9)
full_h = full_h.reshape(-1, 2)
print(f"all 64 stations: mu {full_h[:, 0].mean():.3f} +- {full_h[:, 0].std():.3f} (truth {MU}), tau {np.exp(full_h[:, 1]).mean():.3f} "
f"+- {np.exp(full_h[:, 1]).std():.3f} (truth {TAU}); skewness of tau {stats.skew(np.exp(full_h[:, 1])):.2f}, "
f"of log tau {stats.skew(full_h[:, 1]):.2f}; {info_h['divergences']} divergences")
stations = g6.permutation(J)
def by_station(K):
return [dict(ybar=ybar[s], se=se[s]) for s in np.array_split(stations, K)]
def by_row(K):
means = micro.reshape(J, K, 64 // K).mean(axis=2) # each shard's own mean of every station
return [dict(ybar=means[:, k], se=se * np.sqrt(K)) for k in range(K)]
t0 = time.perf_counter()
sweep_g, log_g, kept_g = sweep(STATION, HIER, by_station, full_h, HIER, keep=(4, 16), seed=3, draws=1000, target_accept=0.9)
sweep_r, log_r, _ = sweep(STATION, HIER, by_row, full_h, HIER, seed=4, draws=1000, target_accept=0.9)
print(f"{log_g['shard fits'].sum() + log_r['shard fits'].sum()} shard fits in {time.perf_counter() - t0:.0f} s")
print("\nshards by station:")
print(log_g.assign(**{"stations per shard": J // log_g.index})[["stations per shard", "seconds, summed", "divergences", "largest r_hat"]]
.round(3).to_string())
BREAKS["station mean, shards by station"] = breaking_point(sweep_g, ["mu"])
BREAKS["station sd, shards by station"] = breaking_point(sweep_g, ["log_tau"])
BREAKS["station mean and sd, shards by row"] = breaking_point(sweep_r, HIER)
all 64 stations: mu 1.035 +- 0.046 (truth 1.0), tau 0.375 +- 0.033 (truth 0.4); skewness of tau 0.37, of log tau 0.11; 0 divergences
504 shard fits in 15 s
shards by station:
stations per shard seconds, summed divergences largest r_hat
K
2 32 0.119 0 1.002
4 16 0.226 0 1.002
8 8 0.443 0 1.001
16 4 0.896 0 1.006
32 2 1.779 201 1.032
64 1 4.379 11387 3.434fig = plt.figure(figsize=(14.5, 8.4))
grid = fig.add_gridspec(2, 3)
for col, K in enumerate((4, 16)):
ax = fig.add_subplot(grid[0, col])
t, p, stitched = kept_g[K]
shard_clouds(ax, t, (0, 1), alpha=0.3)
mass_contours(ax, full_h, INK, lw=2.4)
mass_contours(ax, stitched["consensus"], BLUE)
mass_contours(ax, barycentre_cloud(p, seed=K), VIOLET, ls="--")
ax.set_xlim(full_h[:, 0].mean() - 0.75, full_h[:, 0].mean() + 0.75)
ax.set_ylim(full_h[:, 1].mean() - 2.3, full_h[:, 1].mean() + 1.5)
ax.set_xlabel("network mean $\\mu$")
ax.set_ylabel("$\\log\\tau$")
ax.set_title(f"K = {K}: {J // K} stations per shard", loc="left", fontsize=10.5)
tidy(ax, grid="both")
if col == 0:
ax.legend(handles=[handle(INK, "all stations", lw=2.4), handle(BLUE, "consensus"), handle(VIOLET, "barycentre", ls="--")],
frameon=False, fontsize=9, loc="lower left")
ax = fig.add_subplot(grid[0, 2])
density(ax, np.exp(full_h[:, 1]), INK, "all stations", fill=True)
for K, ls in ((4, "-"), (16, "--")):
density(ax, np.exp(kept_g[K][2]["consensus"][:, 1]), BLUE, f"consensus, K = {K}", ls=ls)
density(ax, np.exp(kept_g[K][2]["barycentre"][:, 1]), VIOLET, f"barycentre, K = {K}", ls=ls)
ax.axvline(TAU, color=MUTED, lw=1, ls=":")
ax.set_xlim(0.2, 0.75)
ax.set_yticks([])
ax.set_xlabel("spread between stations $\\tau$")
ax.set_title("The station spread, stitched", loc="left", fontsize=10.5)
ax.legend(frameon=False, fontsize=8.5)
tidy(ax, grid=None)
lower = [fig.add_subplot(grid[1, 0]), fig.add_subplot(grid[1, 1]), fig.add_subplot(grid[1, 2])]
sweep_panels(lower[:2][::1], sweep_g, ["log_tau"], "", legend=False)
lower[0].set_title("$\\log\\tau$, shards by station: shift of the mean", loc="left", fontsize=10.5)
lower[0].set_xlabel("number of shards K")
lower[0].set_ylabel("posterior sd")
lower[0].legend(frameon=False, fontsize=8.5, loc="lower left")
lower[1].set_title("$\\log\\tau$, shards by station: width ratio", loc="left", fontsize=10.5)
part = worst(sweep_r, HIER)
for rule in ("consensus", "barycentre"):
lower[2].plot(part.loc[rule].index, part.loc[rule]["width"], lw=1.8, ms=5, label=rule,
**{k: v for k, v in RULE_STYLE[rule].items()})
lower[2].plot(KS, 1 / np.sqrt(KS), color=MUTED, lw=1, ls=":", label="$1/\\sqrt{K}$")
lower[2].axhspan(1 / BROKEN_WIDTH, BROKEN_WIDTH, color=LIGHT, alpha=0.45, lw=0)
lower[2].set_xscale("log", base=2)
lower[2].set_yscale("log")
lower[2].set_xticks(list(KS), [str(K) for K in KS])
lower[2].set_yticks([0.125, 0.25, 0.5, 1], ["1/8", "1/4", "1/2", "1"])
lower[2].minorticks_off()
lower[2].set_xlabel("number of shards K")
lower[2].set_title("Shards by row: width ratio, $\\mu$ and $\\log\\tau$", loc="left", fontsize=10.5)
lower[2].legend(frameon=False, fontsize=8.5)
tidy(lower[2])
print("shards by station, distance from the full posterior:")
print(sweep_g.pivot_table(index=["parameter", "K"], columns="rule", values=["shift", "width"], sort=False).round(2).to_string())
print("\nthe first K at which each rule is broken:")
print(pd.DataFrame(BREAKS).T.iloc[-3:].dropna(axis=1).to_string());
shards by station, distance from the full posterior:
shift width
rule consensus Gaussian product barycentre consensus Gaussian product barycentre
parameter K
mu 2 -0.10 -0.12 0.01 1.02 1.04 1.01
4 -0.22 -0.21 0.01 1.07 1.10 1.00
8 0.11 0.14 -0.00 1.05 1.04 0.93
16 0.06 0.10 -0.00 1.29 1.34 0.87
32 0.17 0.17 0.00 0.48 0.56 0.62
64 -6.38 -6.34 0.01 7.09 10.36 0.06
log_tau 2 0.08 0.08 -0.19 1.06 1.05 1.02
4 0.27 0.29 -0.36 1.06 1.08 1.01
8 -0.02 -0.03 -1.42 1.13 1.14 1.02
16 0.94 0.93 -2.56 1.41 1.38 1.02
32 3.87 3.85 -9.78 2.09 2.06 1.21
64 -1.66 -1.53 -48.10 6.74 5.88 3.96
the first K at which each rule is broken:
Gaussian product barycentre consensus
station mean, shards by station 32 32 32
station sd, shards by station 16 8 16
station mean and sd, shards by row 4 4 4
Start with the shards by station, the two upper left panels. With sixteen stations in a shard the tempered sub-posteriors are wide and already lopsided in $\log\tau$, with a tail towards small spreads. With four stations they fill the panel. Over them, the stitched posteriors: at $K = 4$ consensus sits on the black contours and the barycentre has slipped down a little; at $K = 16$ both have left, in opposite directions. The upper right panel shows the same thing as densities of $\tau$.
The lower panels follow $\log\tau$ over the whole sweep. The barycentre goes first, and by a mechanism that owes nothing to skewness. Each shard estimates the spread from its own few stations, and an estimate of a standard deviation from few groups is biased low. Raising the likelihood to the power $K$ makes each shard certain of its low value, and averaging $K$ estimates that are all biased the same way removes the noise and keeps the bias. With 16 stations per shard the barycentre is a third of a standard deviation low, with 8 it is one and a half low, and it stays as narrow as the true posterior all the way. Consensus and the Gaussian product last one doubling longer, because their sub-posteriors are honest about how little eight stations say, and fail with four stations per shard, at the Gaussian approximation of a sub-posterior that has become a long ridge. The network mean $\mu$ holds down to four stations per shard, for every rule. With one station per shard the spread is not identified at all, and the samplers say so: the divergences in the table above run into the thousands.
Each of these shards holds between 2,000 and 65,000 rows. The $K$ at which the station spread breaks was set by the stations per shard: fewer than sixteen was too few for the barycentre, and fewer than eight for consensus. On the hypothesis we started from, this is a second amendment. Consensus was expected to fail first on a skewed variance parameter, and here it is the barycentre that does.
The last panel is the other way of dealing. Every shard gets a random share of each station's rows and fits the same two-parameter model. Nothing is skewed and no sampler complains, and every rule returns intervals too narrow by a factor $\sqrt{K}$, for the mean and for the spread alike. Our convention only calls that broken from 4 shards, where the intervals are half as wide as they should be; it is lenient about widths, and at 2 shards the intervals are already 30% too narrow. The factorisation this whole notebook rests on needs the shards to be independent given the parameters. Here they are not: all $K$ machines see the same 64 station effects, each treats them as its own independent sample of stations, and the stitched posterior believes it has seen $64K$ stations. It is failure 1 in another form, with the hierarchical prior $p(b \mid \tau)$ counted $K$ times. Dealing rows at random, the right thing to do for the regression of part 5, is the wrong thing to do for this model.
The choice. Keep every group on one machine, and choose $K$ so that a shard holds at least sixteen groups if the spread between groups matters, with consensus rather than the barycentre. Rejected: random rows with the model as it is (intervals $\sqrt{K}$ too narrow), and judging the split by rows per shard. What would change our mind: station effects kept as parameters shared by all shards and tempered with the rest of the prior, which restores the factorisation at the price of a 66-dimensional combination; that is exercise 2.
7 · Two modes
The last test bench is the case the hypothesis names outright. Ground handlers record 64,000 turnaround times, standardised and rounded to one decimal. A quarter of them come from a fast regime and the rest from a slow one, each Normal with unit spread, and the two centres are only 1.25 apart, so the mixture has a single hump with a shoulder. The parameters are the share $w$ of the fast regime and the two centres. Rounded values compress to counts, about a hundred of them, so again the full posterior is cheap and a shard's fit takes a tenth of a second.
A mixture written with two exchangeable centres has two posteriors for the price of one: swap the labels and nothing changes. We write the model both ways, with two free centres, and with the second centre as the first plus a positive gap, which picks one labelling.
N_M, W_M, MU1_M, GAP_M = 64_000, 0.25, -1.0, 1.25
g7 = np.random.default_rng([RANDOM_SEED, 11])
fast = g7.random(N_M) < W_M
turnaround = np.round(np.where(fast, g7.normal(MU1_M, 1, N_M), g7.normal(MU1_M + GAP_M, 1, N_M)), 1)
VALUES = np.round(np.arange(-80, 100) / 10, 1)
code_m = np.clip(np.round((turnaround + 8.0) * 10).astype(int), 0, len(VALUES) - 1)
def count_piece(rows):
counts = np.bincount(code_m[rows], minlength=len(VALUES))
return dict(value=VALUES[counts > 0], count=counts[counts > 0].astype(float))
def mixture_model(ordered):
with pm.Model() as model:
value = pm.Data("value", np.zeros(3))
count = pm.Data("count", np.ones(3))
prior_scale = pm.Data("prior_scale", 1.0)
power = pm.Data("power", 1.0)
w = pm.Uniform("w", 0.0, 1.0) # uniform is its own 1/K power, on the scale of w
if ordered:
mu1 = pm.Normal("mu1", 0.0, 3.0 * prior_scale)
gap = pm.HalfNormal("gap", 3.0 * prior_scale)
centres = pt.stack([mu1, mu1 + gap])
else:
centres = pm.Normal("mu", 0.0, 3.0 * prior_scale, shape=2)
parts = pm.logp(pm.Normal.dist(centres[None, :], 1.0), value[:, None]) + pt.log(pt.stack([w, 1 - w]))[None, :]
pm.Potential("loglik", power * (count * pt.logsumexp(parts, axis=1)).sum())
return model
MIX, MIX_FREE = nutpie.compile_pymc_model(mixture_model(True)), nutpie.compile_pymc_model(mixture_model(False))
MIXED, FREE = ["w", "mu1", "gap"], ["w", "mu"]
everything = count_piece(np.arange(N_M))
full_m, info_m = fit_one(MIX, everything, MIXED, draws=2000, tune=500, seed=RANDOM_SEED)
full_m = full_m.reshape(-1, 3)
free_m, info_f = fit_one(MIX_FREE, everything, FREE, draws=500, tune=500, seed=RANDOM_SEED)
print(f"{N_M:,} turnaround times as {len(everything['value'])} counts")
print(f"ordered model, all rows: r_hat {info_m['rhat']:.3f}; means {dict(zip(MIXED, np.round(full_m.mean(axis=0), 3)))}, "
f"sd {np.round(full_m.std(axis=0), 3)}, skewness {np.round(stats.skew(full_m, axis=0), 2)}")
print(f"free centres, all rows: r_hat {info_f['rhat']:.2f}; each chain's mean of (w, centre 1, centre 2):")
print(np.round(free_m.mean(axis=1), 2))
64,000 turnaround times as 91 counts
ordered model, all rows: r_hat 1.001; means {'w': np.float64(0.268), 'mu1': np.float64(-0.968), 'gap': np.float64(1.244)}, sd [0.013 0.03 0.021], skewness [ 0.09 -0.12 0.16]
free centres, all rows: r_hat 31.47; each chain's mean of (w, centre 1, centre 2):
[[ 0.27 -0.97 0.28]
[ 0.27 -0.97 0.28]
[ 0.73 0.27 -0.97]
[ 0.27 -0.97 0.27]]With the ordering, the 64,000 times give a clean posterior, nearly Gaussian in all three parameters. With free centres the four chains of the same fit split between the two labellings: a share near one quarter with centres at $-1$ and $0.3$ in some chains, three quarters with the centres swapped in the others, and $\hat R$ is far above 1. For a single fit this is a well-known nuisance, and each chain is still a correct picture of one mode. For a split it is fatal, as the next cell shows with eight shards, the tempered prior and two chains per shard, run three times with different seeds of the sampler.
deal_m = g7.permutation(N_M)
def mixture_pieces(K):
return [count_piece(i) for i in np.array_split(deal_m, K)]
free_runs = []
for run in range(3): # the same eight shards, three seeds of the sampler
shards = fit_shards(MIX_FREE, mixture_pieces(8), FREE, "tempered", seed=50 + run, chains=2, draws=1000, tune=500)
swapped = (shards.chains[:, :, :, 1] > shards.chains[:, :, :, 2]).mean(axis=2) > 0.5 # which labelling each chain chose
stitched = consensus(shards.flat)
free_runs.append((shards, stitched))
print(f"seed {run}: chains with the labels swapped, per shard {swapped.sum(axis=1)} of 2; consensus: w = {stitched[:, 0].mean():.2f} "
f"+- {stitched[:, 0].std():.3f}, centres {np.round(stitched[:, 1:].mean(axis=0), 2)} +- {np.round(stitched[:, 1:].std(axis=0), 3)}")
free8 = free_runs[0][0]
t0 = time.perf_counter()
sweep_m, log_m, kept_m = sweep(MIX, MIXED, mixture_pieces, full_m, MIXED, keep=(8, 16, 64), seed=5, draws=1000, tune=400)
print(f"\nordered model: {log_m['shard fits'].sum()} shard fits in {time.perf_counter() - t0:.0f} s")
print(log_m.assign(**{"rows per shard": N_M // log_m.index})[["rows per shard", "seconds, summed", "divergences", "largest r_hat"]]
.round(3).to_string())
BREAKS["mixture, ordered centres"] = breaking_point(sweep_m, MIXED)
seed 0: chains with the labels swapped, per shard [1 2 2 1 1 0 1 1] of 2; consensus: w = 0.51 +- 0.005, centres [0.32 0.17] +- [0.01 0.013]
seed 1: chains with the labels swapped, per shard [0 1 1 1 1 1 1 2] of 2; consensus: w = 0.49 +- 0.006, centres [0.17 0.14] +- [0.014 0.014]
seed 2: chains with the labels swapped, per shard [1 0 2 2 1 0 0 2] of 2; consensus: w = 0.50 +- 0.004, centres [0.23 0.26] +- [0.008 0.008]
ordered model: 252 shard fits in 21 s
rows per shard seconds, summed divergences largest r_hat
K
2 32000 0.356 0 1.008
4 16000 0.704 0 1.008
8 8000 1.477 0 1.011
16 4000 2.753 0 1.013
32 2000 5.390 0 1.015
64 1000 10.514 56 1.066fig = plt.figure(figsize=(14.5, 8.2))
grid = fig.add_gridspec(2, 3)
ax = fig.add_subplot(grid[0, 0])
shard_clouds(ax, free8.flat, (1, 2), alpha=0.35)
for (shards, stitched), marker in zip(free_runs, ("x", "+", "*")):
ax.scatter(*stitched[:, 1:].mean(axis=0), s=110, color=RED, marker=marker, lw=1.8, zorder=4)
ax.plot([-1.7, 1.0], [-1.7, 1.0], color=MUTED, lw=0.8, ls=":")
ax.scatter([], [], s=60, color=RED, marker="x", lw=1.8, label="consensus, three sampler seeds")
ax.legend(frameon=False, fontsize=9, loc="lower left")
ax.set_xlabel("centre 1")
ax.set_ylabel("centre 2")
ax.set_title("Free centres, K = 8: two labellings", loc="left", fontsize=10.5)
tidy(ax, grid="both")
for col, K in ((1, 8), (2, 64)):
ax = fig.add_subplot(grid[0, col])
t, p, stitched = kept_m[K]
shard_clouds(ax, t, (0, 2), alpha=0.35 if K == 8 else 0.2, points=220 if K == 8 else 60)
mass_contours(ax, full_m[:, [0, 2]], INK, lw=2.4)
ax.set_xlim(0, 1)
ax.set_ylim(0, 3.2)
ax.set_xlabel("share of the fast regime $w$")
ax.set_ylabel("gap between the centres")
ax.set_title(f"Ordered centres, K = {K}: {N_M // K:,} rows per shard", loc="left", fontsize=10.5)
tidy(ax, grid="both")
if col == 1:
ax.legend(handles=[handle(INK, "all rows: 50% and 90%", lw=2.4)], frameon=False, fontsize=9, loc="upper right")
lower = [fig.add_subplot(grid[1, 0]), fig.add_subplot(grid[1, 1])]
sweep_panels(lower, sweep_m, MIXED, "", legend=False)
lower[0].set_title("Ordered centres, worst of three parameters: shift", loc="left", fontsize=10.5)
lower[0].set_xlabel("number of shards K")
lower[0].set_ylabel("posterior sd")
lower[0].legend(frameon=False, fontsize=8.5, loc="upper left")
lower[1].set_title("Width ratio", loc="left", fontsize=10.5)
ax = fig.add_subplot(grid[1, 2])
density(ax, full_m[:, 0], INK, "all rows", fill=True)
for K, ls in ((16, "-"), (64, "--")):
density(ax, kept_m[K][2]["consensus"][:, 0], BLUE, f"consensus, K = {K}", ls=ls)
density(ax, kept_m[K][2]["barycentre"][:, 0], VIOLET, f"barycentre, K = {K}", ls=ls)
ax.axvline(W_M, color=MUTED, lw=1, ls=":")
ax.set_yticks([])
ax.set_xlabel("share of the fast regime $w$")
ax.set_title("The share, stitched", loc="left", fontsize=10.5)
ax.legend(frameon=False, fontsize=8.5)
tidy(ax, grid=None)
print(sweep_m.pivot_table(index=["parameter", "K"], columns="rule", values=["shift", "width"], sort=False).round(2).to_string())
print("\nthe first K at which each rule is broken:", dict(BREAKS["mixture, ordered centres"]));
shift width
rule consensus Gaussian product barycentre consensus Gaussian product barycentre
parameter K
w 2 0.04 0.04 0.02 0.99 0.99 1.00
4 -0.15 -0.13 0.06 0.97 0.99 1.02
8 -0.43 -0.41 0.03 0.97 0.92 1.01
16 0.01 0.05 0.15 0.92 0.88 1.03
32 0.46 0.44 0.60 0.84 0.84 1.00
64 1.92 1.92 1.54 0.82 0.80 1.07
mu1 2 0.05 0.03 -0.01 0.99 1.02 1.01
4 -0.15 -0.13 0.00 0.99 0.98 1.02
8 -0.53 -0.52 -0.15 0.97 0.94 1.03
16 -0.15 -0.11 -0.21 0.91 0.89 1.05
32 0.25 0.23 -0.43 0.82 0.80 1.02
64 1.03 1.03 -0.13 0.76 0.77 1.02
gap 2 -0.06 -0.04 0.02 1.02 1.04 1.00
4 0.12 0.11 0.03 1.03 0.99 1.02
8 0.51 0.49 0.25 0.97 0.98 1.05
16 0.20 0.17 0.42 0.93 0.93 1.07
32 -0.19 -0.17 1.04 0.88 0.85 1.05
64 -0.44 -0.41 1.15 0.84 0.84 1.06
the first K at which each rule is broken: {'consensus': '8 (inside again at 16)', 'Gaussian product': '8 (inside again at 16)', 'barycentre': '32'}
The upper left panel is the failure with free centres. The clouds are the sub-posteriors of the eight shards, in two symmetric corners: each chain of each shard picks a labelling on its own, and the printout above counts how many of a shard's two chains chose the swapped one. Consensus averages them, and the three red marks are where it lands with three seeds of the sampler: near the diagonal between the corners, with a share of one half and two centres that are nearly equal. That is a mixture with no mixture in it, reported with a standard deviation of a few thousandths. Nothing about this needs small shards. It happens at any $K$, because the rule averages draws that describe the same thing under different names.
With ordered centres (upper middle and right) the labels agree, and at 8,000 rows per shard the sub-posteriors are tidy ellipses. At 1,000 rows per shard they are not ellipses any more. A shard that small can explain its hump almost as well with a small share and a wide gap, or with a large share and a narrow one, so its cloud bends into a banana that reaches across the panel. The lower panels locate the break. The barycentre leaves the band at 32 shards and stays out. Consensus and the Gaussian product are just outside at 8, back inside at 16 and 32, and far outside at 64, with intervals that have shrunk by a fifth. The excursion at 8 does not go away when the draws are doubled (we tried), so it belongs to that particular deal of the rows, and it is a fair warning: with sub-posteriors that are only roughly Gaussian, half a standard deviation of error can appear at 8,000 rows per shard. In direction the rules differ, as in part 4: at 64 shards the stitched share is too high for both, by different amounts and with different widths. The samplers themselves run cleanly until the last step of the sweep, where a few dozen divergences appear.
The choice. Identify the model before splitting it (an ordering, here), and keep enough rows in a shard for the weakest direction of the posterior, which for this mixture is several thousand rows. Rejected: trusting a clean sampler report as a sign that the split is sound. What would change our mind: the kernel-product rules of Neiswanger et al., which multiply density estimates and can in principle follow a banana; we have not run them, and their cost grows quickly with the dimension.
8 · A real month, file by file
Now real flights: the domestic flights the reporting carriers filed for January 2024, from the on-time performance data of the Bureau of Transportation Statistics, as stored in this repository for E87. Each row has a flag (the flight arrived more than 30 minutes late, or was cancelled), the day of the month and a carrier code. The codes are shuffled integers without names; nothing below needs to know which carrier 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(int)
day = archive["day"].astype(int) - 1
carrier = archive["carrier"].astype(int)
DAYS, CARRIERS = day.max() + 1, carrier.max() + 1
flights_dc = np.bincount(day * CARRIERS + carrier, minlength=DAYS * CARRIERS).reshape(DAYS, CARRIERS)
late_dc = np.bincount(day * CARRIERS + carrier, weights=late_real, minlength=DAYS * CARRIERS).reshape(DAYS, CARRIERS)
share_by_day = late_dc.sum(axis=1) / flights_dc.sum(axis=1)
print(f"\n{len(late_real):,} flights, {CARRIERS} carriers, {DAYS} days; late or cancelled {late_real.mean():.1%} overall, "
f"between {share_by_day.min():.1%} and {share_by_day.max():.1%} by day")
print(f"smallest carrier-day cell: {flights_dc.min()} flights; cells with fewer than 5 late flights: {(late_dc < 5).sum()} of {late_dc.size}; "
f"the file changes carrier {np.sum(np.diff(carrier) != 0)} times in {len(carrier):,} rows")
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, 31 days; late or cancelled 18.7% overall, between 5.3% and 48.6% by day smallest carrier-day cell: 19 flights; cells with fewer than 5 late flights: 3 of 465; the file changes carrier 15 times in 547,271 rows
The month is the shape of a real split: it comes as 31 days, and the days are nothing like one another. The share of late flights runs from about 5% on the quietest day to nearly half on the worst. E126 fitted these flights with carrier, airport and weekday effects and found the model too sure of itself, because flights are late together on bad days. The term it lacked is a day effect, so that is the model here:
$$\mathrm{logit}\,p_{cd} = a + \gamma_c + \delta_d, \qquad \delta_d \sim \mathcal{N}(0, \tau),$$
with carrier effects $\gamma_c$ that sum to zero. The spread $\tau$ between days is a quantity of direct interest (how different is a bad day?), it rests on 31 days however many flights they hold, and its posterior is skewed. It is the group-level standard deviation of part 6 in real data.
To integrate the day effects out, as both families of rules require, we work with the logit of each carrier-day share and its standard error: $z_{cd} \sim \mathcal{N}(a + \gamma_c + \delta_d,\ s_{cd}^2)$ with $z_{cd}$ the empirical logit of the cell and $s_{cd}^2 = 1/\text{late} + 1/\text{on time}$. With between 19 and a few thousand flights in a cell this normal approximation of a binomial is good for all but a few cells, and it buys an exact marginal likelihood for each day. The file itself is in order of carrier, so its first rows would be a third kind of split; we set that aside and deal whole days, in two ways: as consecutive blocks, the way files would be handed out, and at random.
z_dc = np.log((late_dc + 0.5) / (flights_dc - late_dc + 0.5)) # empirical logit of each carrier-day cell
w_dc = 1 / (1 / (late_dc + 0.5) + 1 / (flights_dc - late_dc + 0.5)) # its precision
def month_model():
with pm.Model(coords={"carrier": np.arange(CARRIERS)}) as model:
z = pm.Data("z", np.zeros((2, CARRIERS)))
w = pm.Data("w", np.ones((2, CARRIERS)))
prior_scale = pm.Data("prior_scale", 1.0)
power = pm.Data("power", 1.0)
a = pm.Normal("a", 0.0, 2.0 * prior_scale)
gamma = pm.ZeroSumNormal("gamma", sigma=1.0 * prior_scale, dims="carrier")
log_tau = pm.Normal("log_tau", np.log(0.5), 1.0 * prior_scale)
tau2 = pt.exp(2 * log_tau)
r = z - a - gamma[None, :]
s0, s1, s2 = w.sum(axis=1), (w * r).sum(axis=1), (w * r**2).sum(axis=1)
# each day's cells with the day effect integrated out: a Normal with covariance diag(1/w) + tau^2
pm.Potential("loglik", power * (-0.5 * s2 + 0.5 * tau2 * s1**2 / (1 + tau2 * s0) - 0.5 * pt.log1p(tau2 * s0)).sum())
return model
MONTH = nutpie.compile_pymc_model(month_model())
REAL = ["a", "log_tau", "gamma"]
KEEP = slice(0, 2 + CARRIERS - 1) # the last carrier effect is minus the others
REAL_LABELS = ["a", "log_tau"] + [f"carrier {c}" for c in range(CARRIERS - 1)]
CARRIER_LABELS = REAL_LABELS[2:]
sb_real = Scoreboard()
with sb_real.track("all 31 days · NUTS"):
full_chains, info_real = fit_one(MONTH, dict(z=z_dc, w=w_dc), REAL, draws=2000, tune=500, seed=RANDOM_SEED, target_accept=0.9)
full_real = full_chains[:, :, KEEP].reshape(-1, len(REAL_LABELS))
reference = {"theta": full_real.mean(axis=0)}
sb_real.truth = reference
sb_real.score("all 31 days · NUTS", xr.Dataset({"theta": (("chain", "draw", "coef"), full_chains[:, :, KEEP])}))
tau_real = np.exp(full_real[:, 1])
print(f"all 31 days: {info_real['seconds']:.2f} s, {info_real['divergences']} divergences, r_hat {info_real['rhat']:.3f}")
print(f"level a {full_real[:, 0].mean():.2f} +- {full_real[:, 0].std():.2f}; day spread tau {tau_real.mean():.2f} +- {tau_real.std():.2f}, "
f"skewness {stats.skew(tau_real):.2f}; carrier effects from {full_real[:, 2:].mean(axis=0).min():.2f} to "
f"{full_real[:, 2:].mean(axis=0).max():.2f}, each known to about {np.median(full_real[:, 2:].std(axis=0)):.3f}")
all 31 days: 0.09 s, 0 divergences, r_hat 1.000 level a -1.52 +- 0.14; day spread tau 0.77 +- 0.10, skewness 0.74; carrier effects from -0.61 to 0.77, each known to about 0.019
KS_REAL = (2, 4, 8, 16, 31)
dealt_days = np.random.default_rng([RANDOM_SEED, 12]).permutation(DAYS)
def day_pieces(order):
return lambda K: [dict(z=z_dc[d], w=w_dc[d]) for d in np.array_split(order, K)]
t0 = time.perf_counter()
real = {}
for name, order, seed in (("consecutive blocks", np.arange(DAYS), 6), ("days at random", dealt_days, 7)):
real[name] = sweep(MONTH, REAL, day_pieces(order), full_real, REAL_LABELS, Ks=KS_REAL, keep=(4,), seed=seed, select=KEEP,
draws=1000, tune=500, target_accept=0.9)
BREAKS[f"real month, level and day spread, {name}"] = breaking_point(real[name][0], ["a", "log_tau"], KS_REAL)
BREAKS[f"real month, carrier effects, {name}"] = breaking_point(real[name][0], CARRIER_LABELS, KS_REAL)
print(f"{sum(r[1]['shard fits'].sum() for r in real.values())} shard fits in {time.perf_counter() - t0:.0f} s")
for name, (table, log, kept) in real.items():
print(f"\n{name}:")
print(log.assign(**{"days per shard": [f"{DAYS // K}-{-(-DAYS // K)}" for K in log.index]})
[["days per shard", "seconds, summed", "slowest shard (s)", "divergences", "largest r_hat"]].round(3).to_string())
for rule in ("consensus", "barycentre"):
draws = kept[4][2][rule]
label = f"4 shards, {name} · {rule}"
sb_real.add(label, seconds=log.loc[4, "seconds, summed"] / 2)
sb_real.score(label, {"theta": draws})
244 shard fits in 16 s consecutive blocks: days per shard seconds, summed slowest shard (s) divergences largest r_hat K 2 15-16 0.196 0.050 0 1.001 4 7-8 0.370 0.047 0 1.001 8 3-4 0.771 0.061 0 1.018 16 1-2 1.842 0.084 100 1.025 31 1-1 4.459 0.139 2449 1.480 days at random: days per shard seconds, summed slowest shard (s) divergences largest r_hat K 2 15-16 0.192 0.049 0 1.001 4 7-8 0.372 0.048 0 1.000 8 3-4 0.747 0.062 0 1.006 16 1-2 1.864 0.182 8 1.119 31 1-1 4.450 0.187 3924 2.100
fig = plt.figure(figsize=(14.5, 8.2))
grid = fig.add_gridspec(2, 3)
ax = fig.add_subplot(grid[0, 0])
shade = plt.cm.turbo(np.linspace(0.08, 0.92, 4))
for k, block in enumerate(np.array_split(np.arange(DAYS), 4)):
ax.bar(block + 1, share_by_day[block], color=shade[k], alpha=0.75, width=0.85)
ax.set_xlabel("day of January 2024 (colours: four consecutive blocks)")
ax.set_ylabel("share late or cancelled")
ax.set_title("31 files that are not alike", loc="left", fontsize=10.5)
tidy(ax)
for col, name in ((1, "consecutive blocks"), (2, "days at random")):
ax = fig.add_subplot(grid[0, col])
density(ax, tau_real, INK, "all 31 days", fill=True)
for rule, ls in (("consensus", "-"), ("barycentre", "--")):
density(ax, np.exp(real[name][2][4][2][rule][:, 1]), RULE_STYLE[rule]["color"], rule, ls=ls)
ax.set_xlim(0.3, 1.25)
ax.set_yticks([])
ax.set_xlabel("spread between days $\\tau$")
ax.set_title(f"K = 4, {name}", loc="left", fontsize=10.5)
ax.legend(frameon=False, fontsize=9)
tidy(ax, grid=None)
for col, (parameters, title) in enumerate(((["log_tau"], "$\\log\\tau$: shift of the mean"), (["a"], "level $a$: shift of the mean"),
(CARRIER_LABELS, "carrier effects (the worst of 14): shift"))):
ax = fig.add_subplot(grid[1, col])
for name, ls, fill in (("consecutive blocks", "-", None), ("days at random", ":", "white")):
part = worst(real[name][0], parameters)
for rule in ("consensus", "barycentre"):
ax.plot(part.loc[rule].index, part.loc[rule]["shift"], color=RULE_STYLE[rule]["color"], marker=RULE_STYLE[rule]["marker"],
ls=ls, mfc=fill, lw=1.8, ms=5, label=f"{rule}, {name}")
ax.axhspan(-BROKEN_SHIFT, BROKEN_SHIFT, color=LIGHT, alpha=0.45, lw=0)
shift_axis(ax, pd.concat([worst(real[name][0], parameters)["shift"] for name in real]))
ax.set_xscale("log", base=2)
ax.set_xticks(list(KS_REAL), [str(K) for K in KS_REAL])
ax.set_xlabel("number of shards K (31 = one day each)")
ax.set_ylabel("posterior sd")
ax.set_title(title, loc="left", fontsize=10.5)
tidy(ax)
if col == 0:
fig.legend(*ax.get_legend_handles_labels(), frameon=False, fontsize=9, loc="outside lower center", ncols=4)
for name, (table, log, kept) in real.items():
print(f"{name}: shift of the mean (posterior sd) and width ratio")
summary = {}
for label, parameters in (("log tau", ["log_tau"]), ("level a", ["a"]), ("carriers, worst", CARRIER_LABELS)):
part = worst(table, parameters)
for rule in ("consensus", "barycentre"):
summary[label, rule, "shift"] = part.loc[rule]["shift"]
summary[label, rule, "width"] = part.loc[rule]["width"]
print(pd.DataFrame(summary).round(2).to_string(), "\n")
print("the first K at which each rule is broken:")
print(pd.DataFrame(BREAKS).T.iloc[-4:].dropna(axis=1).to_string());
consecutive blocks: shift of the mean (posterior sd) and width ratio
log tau level a carriers, worst
consensus barycentre consensus barycentre consensus barycentre
shift width shift width shift width shift width shift width shift width
K
2 -0.34 1.04 -0.79 1.03 -1.00 0.92 -0.16 0.92 1.54 0.98 -3.61 1.03
4 -3.21 1.11 -3.32 1.01 -0.89 0.74 -0.41 0.66 1.37 0.96 -3.80 1.10
8 -2.30 1.34 -6.54 1.04 -0.31 0.70 -0.76 0.47 1.25 0.95 -9.31 1.24
16 -1.65 1.99 -12.89 1.32 0.05 0.36 -1.08 0.35 -0.70 1.03 -11.61 1.34
31 -14.34 5.07 -35.38 2.88 -1.68 1.90 -1.13 0.05 1.06 0.97 -14.91 1.52
days at random: shift of the mean (posterior sd) and width ratio
log tau level a carriers, worst
consensus barycentre consensus barycentre consensus barycentre
shift width shift width shift width shift width shift width shift width
K
2 0.00 1.01 -0.05 0.99 -0.11 1.04 0.00 0.99 0.80 1.05 -0.38 1.04
4 0.61 1.12 -0.21 0.99 0.74 1.19 -0.08 0.97 -0.80 0.97 -2.36 1.06
8 -0.93 1.27 -2.11 1.02 -1.08 0.96 -0.35 0.83 -0.74 0.97 -4.30 1.12
16 2.11 1.68 -6.27 1.15 -0.41 1.59 -0.76 0.63 -1.06 0.97 6.28 1.18
31 -18.08 5.04 -35.41 2.91 1.37 1.71 -1.13 0.05 -1.35 0.96 -14.91 1.51
the first K at which each rule is broken:
Gaussian product barycentre consensus
real month, level and day spread, consecutive blocks 2 2 2
real month, carrier effects, consecutive blocks 2 2 2
real month, level and day spread, days at random 4 8 4
real month, carrier effects, days at random 2 4 2
The upper left panel is the month, coloured by the four consecutive blocks that a split by files would make. The bad days come in runs: the second block holds most of them, and the first and the last hold almost none.
The other two upper panels are the spread between days, stitched from four shards. With consecutive blocks both rules put $\tau$ near 0.5, where the posterior of the whole month is centred near 0.75, three of its standard deviations away. With the same days dealt at random the barycentre sits on it and consensus is a little high and wide. The model says that days are exchangeable draws from one distribution, and the full posterior takes it at its word: it does not care in which order the days come. A split by blocks does. Days that follow each other resemble each other, so the spread inside a block is smaller than the spread of the month, every machine reports a small $\tau$, and no rule can average its way back. This is the bias of part 6 with a cause that part 6 did not have: the groups in a shard are not a random sample of the groups.
The lower panels follow three quantities over $K$. In consecutive blocks, already at 2 shards consensus is a standard deviation off on the level and the barycentre 0.8 off on the spread, and it gets worse from there. With days at random, 2 shards are fine for both rules. At 4, with seven or eight days each, the barycentre is still inside and consensus is 0.6 to 0.7 of a standard deviation out. From 8 shards on nothing holds, and with one day per shard the samplers report thousands of divergences. Thirty-one days will carry a split in two, and no more.
The third lower panel is the surprise. The carrier effects are regression coefficients, each known to about 0.02 and identified within every single day, with sub-posteriors that are Gaussian. By parts 4 and 5 they should be the easy part. Consensus is between 0.7 and 1.5 standard deviations off on the worst of the fourteen, at every $K$ and with either deal, and the barycentre is far worse everywhere except at 2 shards of days dealt at random. The next cell asks why.
def exact_carrier_product(blocks):
"""Carrier effects by generalised least squares within each block of days, and the exact product of the blocks."""
def normal_equations(days):
A, b = np.zeros((CARRIERS, CARRIERS)), np.zeros(CARRIERS)
for d in days: # the day's mean projected out: within-day contrasts only
P = np.diag(w_dc[d]) - np.outer(w_dc[d], w_dc[d]) / w_dc[d].sum()
A, b = A + P, b + P @ z_dc[d]
return A, b
parts = [normal_equations(days) for days in blocks]
A, b = sum(p[0] for p in parts), sum(p[1] for p in parts)
estimate = np.linalg.pinv(A) @ b
apart = [np.linalg.pinv(p[0]) @ p[1] for p in parts]
sds = [np.sqrt(np.diag(np.linalg.pinv(p[0]))) for p in parts]
return estimate - estimate.mean(), np.array(apart) - np.array(apart).mean(axis=1, keepdims=True), np.array(sds)
blocks4 = np.array_split(np.arange(DAYS), 4)
exact, apart, apart_sd = exact_carrier_product(blocks4)
carrier_mean, carrier_sd = full_real[:, 2:].mean(axis=0), full_real[:, 2:].std(axis=0)
gap = np.abs(apart[:, None, :] - apart[None, :, :]) / np.sqrt(apart_sd[:, None, :] ** 2 + apart_sd[None, :, :] ** 2)
sampled = real["consecutive blocks"][2][4][2]["consensus"][:, 2:].mean(axis=0)
print(f"carrier effects, 4 consecutive blocks: the blocks disagree with each other by up to {gap.max():.0f} of their own standard errors")
print(f"the exact product of the four blocks is off the full posterior mean by {np.abs(exact[:-1] - carrier_mean).max() / carrier_sd.min():.2f} sd "
f"at most; consensus on 4,000 draws per shard is off by {np.abs((sampled - carrier_mean) / carrier_sd).max():.2f} sd at most")
print()
print(sb_real.table()[["seconds", "ess", "rmse", "coverage", "width"]].round(3).to_string())
carrier effects, 4 consecutive blocks: the blocks disagree with each other by up to 21 of their own standard errors
the exact product of the four blocks is off the full posterior mean by 0.05 sd at most; consensus on 4,000 draws per shard is off by 1.37 sd at most
seconds ess rmse coverage width
method
all 31 days · NUTS 0.089 11951.796 0.000 1.000 0.108
4 shards, consecutive blocks · consensus 0.185 NaN 0.109 0.938 0.104
4 shards, consecutive blocks · barycentre 0.185 NaN 0.115 0.500 0.101
4 shards, days at random · consensus 0.186 NaN 0.033 1.000 0.116
4 shards, days at random · barycentre 0.186 NaN 0.028 0.812 0.108For the carrier effects the model is linear and Gaussian once each day's mean is projected out, so the product of the sub-posteriors can be computed without sampling: weighted least squares within each block, then the product of the four Gaussians. That exact product reproduces the full posterior to 0.05 of a standard deviation. The rule is right and the factorisation holds. What fails is the Monte Carlo. The four blocks disagree about a carrier's effect by up to 21 of their own standard errors, because a carrier's bad days are not the network's bad days. The model has no term for that, which is the misspecification E126 pointed to, and a split by days lays it bare. Consensus weights each block by an inverse covariance matrix estimated from 4,000 draws, which is good to a per cent or two, and a per cent or two of a disagreement of 21 standard errors is a large part of one. With shards that agree to within a standard error or two, as in parts 3 and 4, the same error in the weights disappears. The barycentre has no weights to get wrong and is worse off for it: it gives each block an equal say, and the blocks are not equally informative.
That suggests a check which costs nothing and which we did not have at the start. Before stitching, measure how far apart the sub-posteriors are, in their own standard errors. Under the tempered prior they should overlap. When they are ten or twenty apart, the model is telling each shard a different story, the stitched answer hangs on the last digits of the weights, and the split has found a problem that the full fit had averaged over.
The scoreboard of this part takes the posterior means of all 31 days as the reference, since there
is no truth to score against: rmse is the distance of a stitched posterior's means from them over
the sixteen parameters, and coverage the share of its 90% intervals that hold them. Four shards of
days dealt at random are three to four times closer than four consecutive blocks, with either rule.
The choice. For this month: two shards, with whole days dealt at random, if the spread between days is wanted, and a look at the distance between sub-posteriors before believing any stitched carrier effect. Rejected: a shard per daily file (the spread is not identified in a shard, and the samplers diverge), consecutive blocks of days at any $K$, and splitting rows within a day, which breaks the independence between shards as in part 6. What would change our mind: more months, which means more days per shard, and a model with a carrier-by-day term, under which the shards would stop contradicting each other. And one fact outranks all of this: the month compresses to 465 cells, the full fit takes a tenth of a second, and nobody needs to split it.
9 · Which one, when?
RULE_ORDER = ["consensus", "consensus, scalar weights", "Gaussian product", "barycentre"]
breaks = pd.DataFrame(BREAKS).T[RULE_ORDER].fillna("not run")
print("the first K at which each rule is broken (shift above half a posterior sd, or widths off by more than 1.5):")
print(breaks.to_string())
the first K at which each rule is broken (shift above half a posterior sd, or widths off by more than 1.5):
consensus consensus, scalar weights Gaussian product barycentre
common coefficients, rows at random none to 64 none to 64 none to 64 none to 64
priority slot, rows at random 16 16 16 8
common coefficients, rows by time none to 64 none to 64 none to 64 none to 64
priority slot, rows by time none to 64 none to 64 none to 64 2
station mean, shards by station 32 not run 32 32
station sd, shards by station 16 not run 16 8
station mean and sd, shards by row 4 not run 4 4
mixture, ordered centres 8 (inside again at 16) not run 8 (inside again at 16) 32
real month, level and day spread, consecutive blocks 2 not run 2 2
real month, carrier effects, consecutive blocks 2 not run 2 2
real month, level and day spread, days at random 4 not run 4 8
real month, carrier effects, days at random 2 not run 2 4def at(label, rule):
value = breaks.loc[label, rule].split(" ")[0]
return f"at K = {value}" if value.isdigit() else "not up to K = 64"
BOXES = [
("Do the rows reduce to cells or sums?\n(covariates on short lists, or a Gaussian likelihood)",
"Compress them, and do not split",
f"exact, and cheaper than one shard: {N_A:,} flights are {len(LEVELS_A)} cells,\nfitted in {info_a['seconds']:.2f} s (E126)"),
("Is a spread between groups a parameter?\n(stations, days)",
"Whole groups on each machine, sixteen\nor more of them; consensus",
f"64 stations: spread first broken {at('station sd, shards by station', 'consensus')} (consensus), "
f"{at('station sd, shards by station', 'barycentre')} (barycentre)\nrows at random, model as it is: intervals too narrow by $\\sqrt{{K}}$\n"
f"real month, 31 days: broken {at('real month, level and day spread, days at random', 'consensus')} "
f"with days at random,\n{at('real month, level and day spread, consecutive blocks', 'consensus')} in consecutive blocks"),
("Are the shards files by time or by region,\nso that some cannot see a coefficient?",
"Tempered prior and consensus with\nmatrix weights; no barycentre",
f"flag missing from most shards: barycentre broken {at('priority slot, rows by time', 'barycentre')},\n"
f"consensus {at('priority slot, rows by time', 'consensus')}"),
("Rows dealt at random: does every shard pin\ndown every parameter, close to a Gaussian?",
"Split. Consensus with matrix weights,\nthe barycentre as a second opinion",
f"common coefficients: no rule broken up to K = 64\nrare flag: barycentre broken {at('priority slot, rows at random', 'barycentre')}, "
f"consensus {at('priority slot, rows at random', 'consensus')}\nmixture: consensus first broken {at('mixture, ordered centres', 'consensus')}, "
f"barycentre {at('mixture, ordered centres', 'barycentre')}"),
]
fig, ax = plt.subplots(figsize=(14.5, 7.6))
for row, (question, action, numbers) in enumerate(BOXES):
y = 6.1 - 1.5 * row
ax.add_patch(FancyBboxPatch((0.1, y - 0.5), 3.9, 1.0, boxstyle="round,pad=0.02,rounding_size=0.08", fc="#f4f3ee", ec=MUTED, lw=1.1))
ax.text(2.05, y, question, ha="center", va="center", fontsize=9.4, color=INK, linespacing=1.3)
ax.add_patch(FancyArrowPatch((4.05, y), (4.85, y), arrowstyle="-|>", mutation_scale=13, color=BLUE, lw=1.6))
ax.text(4.45, y + 0.13, "yes", ha="center", fontsize=9, color=BLUE)
ax.add_patch(FancyBboxPatch((4.9, y - 0.5), 3.5, 1.0, boxstyle="round,pad=0.02,rounding_size=0.08", fc="#cde2fb", ec=BLUE, lw=1.4))
ax.text(6.65, y, action, ha="center", va="center", fontsize=9.4, color=INK, linespacing=1.3, fontweight="bold")
ax.text(8.6, y, numbers, ha="left", va="center", fontsize=8.8, color=INK, linespacing=1.35)
ax.add_patch(FancyArrowPatch((2.05, y - 0.53), (2.05, y - 0.97), arrowstyle="-|>", mutation_scale=13, color=MUTED, lw=1.4))
ax.text(2.17, y - 0.76, "no", fontsize=9, color=MUTED, va="center")
y = 6.1 - 1.5 * len(BOXES)
ax.add_patch(FancyBboxPatch((0.1, y - 0.5), 8.3, 1.0, boxstyle="round,pad=0.02,rounding_size=0.08", fc="#fbe9e1", ec=ORANGE, lw=1.4))
ax.text(4.25, y, "A shard that cannot pin a parameter down (a handful of events, a few groups, a second mode)\n"
"is not mended by any rule. Use fewer and larger shards, or leave the family: E125, E126.", ha="center", va="center",
fontsize=9.4, color=INK, linespacing=1.35)
ax.text(8.6, y, f"always: temper the prior on the scale you combine on\n(coverage {lab_trap:.0%} against {lab_right:.0%} at 16 events per shard),\n"
"and compare with one shard fitted alone", ha="left", va="center", fontsize=8.8, color=INK, linespacing=1.35)
ax.set_xlim(0, 14.4)
ax.set_ylim(-0.7, 6.9)
ax.axis("off")
ax.set_title("When to split, and how to stitch: ask in this order", loc="left");

The table gathers the breaking points of every sweep, and the chart puts the questions in the order in which they should be asked. The first is E126's, and it comes first because every test bench of this notebook was a problem that should not have been split. The second and third are about who gets which rows, which decided more than the choice of rule did. Only the last is the question the literature mostly discusses, whether the sub-posteriors are Gaussian enough, and its practical form is a count that can be made before any fit: events per shard for a coefficient, groups per shard for a spread, rows per shard for a mixture.
The hypothesis was that the rules agree on Gaussian-shaped posteriors and part ways on skewed or multimodal ones. Half of it held. The rules did agree wherever every sub-posterior was close to a Gaussian, and each problem did have a $K$ at which the stitching broke. The other half needs three corrections. It is the sub-posterior that has to be Gaussian, and the priority slot broke the rules under a full posterior that was Gaussian throughout. The rules did not wait for skewness to disagree: with a flag missing from most shards the barycentre failed at two shards on Gaussian sub-posteriors, and consensus did not fail at all. And on the skewed parameter, the spread between groups, it was the barycentre that went first, where we had expected consensus to.
Summary
- The factorisation is exact and the stitching is not. The posterior is the product of $K$ sub-posteriors, each a shard's likelihood under the prior to the power $1/K$. On 40,000 flights with continuous covariates and 8 shards, consensus, the Gaussian product and the barycentre all landed within a seventh of a posterior standard deviation of the full posterior, with the right widths. One machine pays the same sampling work as for the whole table and saves memory, which is the table itself at 56 bytes a row plus little; eight machines would wait for the slowest shard. Limit: one $K$, shards of 5,000 rows, a parallel time that is projected from fits run in turn.
- Temper the prior, on the scale on which the draws are combined. The whole prior in each of 8 shards moved the weakest coefficient three quarters of a standard deviation towards zero and made it look better determined. A prior tempered on the rate scale and combined on the log-odds scale gave 83% coverage at 16 events per shard and 18% at 4, where tempering on the log-odds scale gave 89% and 87%.
- Two families, two kinds of sub-posterior. Consensus and the Gaussian product want the prior to the power $1/K$, have the same mean and covariance by construction, and weight by precision. The barycentre and the median posterior want the likelihood to the power $K$ and give every shard the same say. The median posterior is a mixture of the shards' copies, two and a half to three times too wide here: built for robustness, and no substitute for the full posterior.
- What has to be Gaussian is the sub-posterior. With 256,000 flights no rule broke on the common coefficients up to 64 shards. On a rare flag with 86 events in all, the barycentre broke at 8 shards and the product rules at 16, in opposite directions, under a full posterior that was Gaussian throughout. Over 2,000 data sets in closed form the barycentre lost its coverage at 8 events per shard and the product rules at 2. Limit: the thresholds are a convention (half a standard deviation, a factor 1.5 in width) and each sweep is one deal of the rows.
- Who gets which rows mattered more than the rule. With shards by time and a flag that most of them never saw, consensus with matrix weights was as good as with rows at random, and the barycentre was wrong from 2 shards on, three to four standard deviations off and five to seven times too wide; the median posterior did no better. Their sub-posteriors were Gaussian; an uninformed shard had been given a full vote.
- A spread between groups is limited by the groups in a shard. With 64 stations and whole stations per shard, the barycentre broke at 8 stations per shard, biased low, and consensus at 4, whatever the thousands of rows in each. Dealing rows at random under the same model made every interval too narrow by $\sqrt{K}$, without a single warning.
- A model with two labellings has to be identified first. With free centres, consensus returned a mixture with a share of one half and equal centres, at any $K$. With ordered centres the barycentre broke at 32 shards and the product rules for good at 64, after an excursion at 8.
- The real month would carry a split in two. With 31 days, consecutive blocks put the spread between days three standard deviations low at 4 shards, because bad days come in runs; days dealt at random were fine at 2 shards and unreliable from 4. The carrier effects, an exactly Gaussian problem whose exact product matched the full posterior to 0.05 standard deviations, came out one standard deviation off from draws, because the shards disagreed by 21 of their standard errors and the weights were estimated. Limit: one month, and a normal approximation to each carrier-day share.
- The sampler's diagnostics saw only the grossest of this. Divergences appeared when a shard could not identify a parameter at all (one or two groups per shard). Every other failure above came from clean fits, and was found by holding the stitched posterior against the full one, which a real application does not have. What it does have are counts per shard, the distance between sub-posteriors, and one shard fitted alone.
Try it yourself
- A dozen events. In part 4, change the share of priority flights in
simulate_coarsefrom 0.016 to 0.004 and to 0.064, and rerun the sweep. Does each rule break at the same number of late priority flights per shard as before, or at the same $K$? Then count, for a split of your own data, the events per shard behind its rarest coefficient. - Station effects as parameters. Part 6 integrated the station effects out, which forces whole
stations onto one machine. Write the model with the 64 effects as parameters (
pm.Flatand apm.Potentialfor $p(b \mid \tau)$), deal the rows at random, and build both kinds of sub-posterior: for the product rules, the hierarchical prior to the power $1/K$ like the rest of the prior; for the barycentre, the whole prior and the shard's likelihood to the power $K$. Combine $(\mu, \log\tau, b)$ jointly. Which family recovers $\tau$ now, and up to which $K$? - Follow the banana. Implement the nonparametric rule of Neiswanger, Wang and Xing (2014): a kernel density estimate of each sub-posterior, and a sampler for the product of the $K$ estimates. Apply it to the pair (share, gap) of the ordered mixture at 16, 32 and 64 shards. Does it stay on the full posterior where the Gaussian product leaves it, and what does it cost as $K$ grows?
print(f"total run time: {time.time() - T_START:.0f} s")
total run time: 117 s