Many models in applied work have likelihoods that depend on the data only through a few summary numbers. When that holds, you can fit the model to the summaries instead of the rows and get the same posterior. The fit is faster because the sampler no longer touches every row on every step. In the notebooks below the gain ranges from about two times to a few hundred times, depending on how many rows the summaries replace.
This post collects the cases I have found useful. Each case has its own notebook. Every notebook does two things. It shows what the model’s output is used for, and it fits the same model twice, once on the raw rows and once on the summary, to check that the posteriors agree and to time both fits. The figures below are taken from those notebooks. In every figure, colour marks the category (arm, cause, source), a filled histogram or band is the raw-row fit, a solid line is the compressed fit, black dashed is an exact answer and thin grey is the true value. Intervals are 89%.
Why sufficiency saves computation
Suppose the likelihood factors as
\[p(y \mid \theta) = h(y)\, g\big(T(y) \mid \theta\big).\]
The factor \(h(y)\) does not depend on \(\theta\), so it cancels in Bayes’ rule. The posterior is then \(p(\theta \mid y) \propto p(\theta)\, g(T(y) \mid \theta)\), and it depends on the data only through \(T(y)\). This is the Fisher–Neyman factorisation. A statistic \(T\) with this property is called sufficient.
The computational gain comes from how Hamiltonian Monte Carlo works. Each leapfrog step evaluates the log-likelihood and its gradient. A likelihood written over \(N\) rows costs \(N\) row evaluations per step, and a fit takes thousands of steps per chain. A likelihood written over \(T(y)\) costs only as much as \(T(y)\) is large.
Exponential families always have such a statistic. Their densities take the form \(h(y)\exp\{\eta(\theta)^\top T(y) - A(\theta)\}\), and the sum of \(T\) over independent observations is sufficient, with a dimension that does not grow with \(n\). The Pitman–Koopman–Darmois theorem gives the converse. If the support of the distribution does not depend on \(\theta\), only exponential families have a sufficient statistic of fixed dimension. Binomial, Poisson, Normal and multinomial models qualify. Student-\(t\) errors and mixtures do not.
For computation, sufficiency for \(y\) is not quite enough. In a logistic regression the outcome enters the log-likelihood only through \(X^\top y\), so \(X^\top y\) is sufficient for the coefficients. But the log-likelihood also contains the term \(\sum_i \log(1 + e^{x_i^\top\beta})\), which needs every row’s covariates. What we need is a fixed-size summary of the whole likelihood as a function of the parameters. There are two common ways to get one:
- Shared covariates. If rows fall into cells with identical covariates, the likelihood depends on each cell only through a few counts. The Binomial, Poisson and multinomial cases below work this way.
- A quadratic log-likelihood. In the Gaussian linear model the log-likelihood is quadratic in the coefficients, so the covariates enter only through cross-products. The linear regression case works this way.
The last case in the catalogue fits neither pattern. There the summary is an approximation.
What compression gives up
The posterior is unchanged, but the individual rows are gone. Any check that needs the rows is no longer possible. If revenue becomes \((n, \bar y, SS)\), you cannot see a large share of zero-revenue users that a Normal model ignores. If sessions become transition counts, you cannot see whether the next step depends on more than the current page. Run these checks on the raw data, or on a sample of it, before you compress. Several notebooks below show such a check.
The covariates decide how much compression is possible. Each categorical covariate multiplies the number of cells. A continuous covariate usually gives each row its own cell, which removes the gain. Linear regression is the exception, for the algebraic reason above. A random effect shared by several rows, such as a user’s frailty across the periods they are observed, makes rows in the same cell no longer interchangeable, so the counts stop being sufficient.
A/B tests: counts and moments
In a conversion test each user is a Bernoulli trial. The likelihood for an arm is \(p^k(1-p)^{n-k}\), so the number of users \(n\) and the number of conversions \(k\) are sufficient. With a Beta prior the posterior is a Beta distribution in closed form, and the decision quantities follow directly: the probability that treatment is better, and the expected loss of shipping it, \(E[\max(p_C - p_T, 0)]\). Because \((n, k)\) adds across days, both can be recomputed each day from running totals.
For a continuous outcome under a Normal model, the count, mean and sum of squared deviations \((n, \bar y, SS)\) are sufficient for \((\mu, \sigma)\). The notebook fits them with two observed distributions: \(\bar y \sim \mathcal N(\mu, \sigma/\sqrt n)\), with standard deviation \(\sigma/\sqrt n\), and \(SS \sim \text{Gamma}\big((n-1)/2, \text{rate} = 1/(2\sigma^2)\big)\). Their product is proportional to the full Normal likelihood. A pm.Bernoulli on 800,000 rows becomes a pm.Binomial on two, and a pm.Normal on 400,000 rows becomes two small observed variables. The posteriors match.
The three numbers \((n, \bar y, SS)\) describe a Normal sample completely and nothing else. The notebook constructs a zero-inflated revenue sample and a Normal sample with identical \((n, \bar y, SS)\); a model fitted to the summaries cannot tell them apart.
Notebook: 01_ab_tests_counts_and_moments.ipynb
Sequential tests: running counts
Checking a fixed-sample test repeatedly as data arrive inflates its false-positive rate. Lindon and Malek, Anytime-Valid Inference for Multinomial Count Data (NeurIPS 2022), give a test that can be checked after every event while keeping the type-I error below the nominal level. Such a test is called anytime-valid. Their test statistic is a Dirichlet–multinomial Bayes factor. By their Eq. 3, it depends on the event stream only through \(\mathbf S_n\), the running count of events in each arm.
This has two practical consequences. First, updating the test after an event means adding one to one count. Second, a shared time-varying baseline does not need to be modelled. Suppose each arm’s events arrive as a Poisson process with rate equal to an arm-specific multiplier times a common baseline \(\lambda(t)\). Given that an event occurred, the arm it came from is a multinomial draw whose probabilities do not involve \(\lambda(t)\). In the simulation the baseline has a daily cycle and a two-day promotion, and the test ignores both.
Because the statistic depends only on running counts, its behaviour is cheap to simulate. In 1,000 simulated A/A tests, where all arms are identical, the anytime-valid test checked after every event rejected 3.8% of the time. A chi-square test re-run every 250 events rejected 31% of the time. The figure shows 100 of those experiments.
The same simulation gives the distribution of stopping times for a range of true effects, and shows how the choice of Dirichlet mixing distribution changes them. The type-I guarantee holds for any choice.
For estimation, one pm.Multinomial on the final counts gives the same posterior as a categorical likelihood over every event and as the conjugate Dirichlet. The counts discard when events happened. To ask whether the effect changed during the promotion, keep the counts per day; the notebook does this.
Notebook: 02_sequential_multinomial.ipynb
Survival: events and exposure
A discrete-time survival model is fitted to a person-period table. It has one row for each subject in each period they are at risk, with a 0/1 flag for the event. With categorical covariates, all rows in a cell defined by period and covariate pattern share one hazard. The cell then reduces to its number of events and number at risk, \((d, r)\). This is the life table. The notebook uses the complementary log-log link, \(h = 1 - \exp(-e^{\eta})\), which makes the discrete model a grouped form of a proportional-hazards model.
The continuous-time version is the piecewise-exponential model. Each subject contributes their time at risk in each interval, and each cell reduces to its events and total exposure, \((d, E)\). Its likelihood is proportional to a Poisson likelihood with a log-exposure offset. That is why Poisson regression with an exposure offset can be used as a survival model. I used the same aggregation in the discrete-time survival notebook for Bambi on historical child-mortality data.
The fitted model gives survival curves for each stratum. Overlaying Kaplan–Meier estimates from the raw subjects is a check of the model. A one-number summary of a treatment effect on survival is the difference in restricted mean survival time (RMST): the expected event-free time up to a horizon, which is the area under the survival curve.
The cloglog and piecewise-exponential models are different models, but with censoring at period boundaries they estimate nearly the same hazards here. Each compressed fit agrees with its own raw-row fit. If subjects can be censored part-way through a period, the discrete model counts them as surviving that period, which biases its hazard down. The actuarial correction counts them as at risk for half the period, \(r - c/2\). The piecewise-exponential model handles this exactly through the exposure.
Notebook: 03_survival_person_period.ipynb
Competing risks: one event count per cause
In a competing-risks problem each subject can fail from one of \(K\) causes, and failure from one cause ends the risk of the others. The standard approach models a cause-specific hazard \(\lambda_k\) for each cause. Under a piecewise-exponential model the likelihood is
\[\prod_c \prod_k \lambda_{k,c}^{\,d_{k,c}} \exp(-\lambda_{k,c} E_c).\]
Each cell reduces to its total exposure and one event count per cause, \((E_c, d_{1,c}, \dots, d_{K,c})\). The likelihood is one Poisson term per cause, and all causes share the same exposures. In discrete time, each person-period row has \(K+1\) outcomes: no event, or an event of one of the causes. A cell reduces to its number at risk and its event counts, \((r, d_1, \dots, d_K)\), and the likelihood is a multinomial.
The quantity usually reported is the cumulative incidence function (CIF) of each cause: the probability of an event of that cause by time \(t\), with all causes acting. In each period it adds the probability of being event-free at the start of the period, times the probability of an event during it, times the share of the total hazard that belongs to the cause. Event-free survival and the CIFs add to one at every time.
A common shortcut treats events of the other cause as censored and reports \(1 - \text{KM}\) for each cause. That answers a different question: the risk of one cause in a world where the other did not exist. In that world patients who would have relapsed stay at risk of dying, so the naive curve for death is too high, and the naive curves for the two causes add up to more than the probability of any event.
The cause-specific hazards are proportional between arms. The CIFs are not, because each depends on both hazards. The stacked panels show where subjects are at each time.
Treatment lowers relapse incidence and raises death incidence. It raises death incidence by two routes: directly, through the higher death hazard, and indirectly, because preventing relapse keeps more subjects at risk of dying. Setting one treatment coefficient to zero at a time, in every posterior draw, separates the routes. In the simulation they contribute about equally.
The piecewise-exponential and multinomial-logit models have coefficients on different scales, but give nearly the same cumulative incidences. Each compressed fit matches its raw-row fit.
Two common extensions do not compress. Fine–Gray subdistribution hazards keep subjects who failed from another cause in the risk set, and with censoring those subjects need weights that vary by person and time. A shared frailty across causes makes rows within a cell no longer interchangeable.
Notebook: 07_competing_risks.ipynb
Markov chains and funnels: transition counts
A user session is a sequence of states, such as landing page, product page, cart, checkout, then purchase or exit. In a first-order Markov chain the next state depends only on the current one. The likelihood of a set of sessions is then \(\prod_{ij} P_{ij}^{N_{ij}}\), where \(N_{ij}\) counts the transitions from state \(i\) to state \(j\). The count matrix is sufficient. Each row of the transition matrix gets a multinomial likelihood and a Dirichlet prior over its allowed destinations.
The quantity of interest is often the probability that a session starting on the landing page ends in a purchase. Order the states with the four transient states first and the two absorbing states (purchase, exit) last. The transition matrix then has the block form
\[ P = \begin{pmatrix} Q & R \\ 0 & I \end{pmatrix}, \]
where \(Q\) holds the moves between transient states and \(R\) the moves into purchase or exit. Entry \((i, j)\) of \(Q^k\) is the probability of being in transient state \(j\) after \(k\) steps from state \(i\). Summing over \(k\) gives the expected number of visits to each state, return trips included:
\[ N = I + Q + Q^2 + \dots = (I - Q)^{-1}. \]
A session is absorbed into purchase from some transient state it visits, so the absorption probabilities are \(B = NR\). Only checkout leads to purchase, so the purchase probability is the expected number of checkout visits times the checkout conversion rate. Multiplying the forward step rates instead keeps only the term of the series for a session that goes straight through, and gives less than half the true purchase probability.
The same algebra shows which step is worth improving. Moving \(\delta\) of probability from exit to the step \(i \to j\) changes the purchase probability by approximately \(\delta\, N_{1i} B_{j,\text{purchase}}\): expected visits to state \(i\), times \(\delta\), times the purchase probability from \(j\). The notebook computes \(N\), \(B\) and the exact effect of each change inside the model with pt.linalg.inv, so their posteriors come straight from the sampler. Improving product → cart is worth about four times as much as improving checkout → purchase, because product pages are visited far more often than checkout.
The counts are sufficient only if the chain is first-order, and the raw sessions can test that before compressing. The notebook checks whether the probability of moving from cart to checkout depends on the state before the cart, and whether session lengths simulated from the posterior match the observed ones.
A funnel is the chain with no back-edges or repeats: a user can only advance one stage or leave. Each stage then becomes a binomial on head-counts, the number who reached stage \(k+1\) out of the number who reached stage \(k\). The notebook lets step conversion vary by weekly cohort with a hierarchical prior, which pulls each cohort’s rates toward the population mean. The compressed model has 36 rows.
Notebook: 04_funnels_markov_chains.ipynb
Linear regression: the Gram matrix
The Gaussian linear model compresses without grouping rows. Expand the residual sum of squares:
\[\lVert y - X\beta\rVert^2 = y^\top y - 2\beta^\top X^\top y + \beta^\top X^\top X\beta.\]
The likelihood for \((\beta, \sigma)\) needs only \(n\), \(X^\top X\), \(X^\top y\) and \(y^\top y\). \(X^\top X\) is the Gram matrix of cross-products between predictors. The predictors can be continuous. In the notebook, one million rows and ten predictors reduce to 112 stored numbers. The model is written with pm.Potential, because no standard distribution has these summaries as its observed value.
With a flat prior the posterior covariance of \(\beta\) is \(\hat\sigma^2 (X^\top X)^{-1}\), so the Gram matrix is, up to \(\hat\sigma^2\), the posterior precision. The summaries also add across subsets of the data: they can be computed on separate chunks, partitions or days and summed. The right panel shows the estimates after each of ten chunks.
Notebook: 05_linear_regression_gram.ipynb
Approximate sufficiency: logistic regression with offsets
The football factor model I built with Wyatt includes a logistic regression with a per-shot offset. Each shot has a pre-shot goal probability \(p_i\) from an expected-goals model. A player’s finishing skill \(\eta\) shifts the log-odds of every shot they take. Goals \(G = \sum_i y_i\) are sufficient for \(\eta\), but the normalising term sums over every shot’s offset, so neither exact route applies.
A second-order expansion of the log-likelihood around \(\eta = 0\) gives
\[\ell(\eta) \approx \ell(0) + (G - X)\,\eta - \tfrac12 V \eta^2,\]
with \(X = \sum_i p_i\) (expected goals) and \(V = \sum_i p_i(1 - p_i)\). Three numbers per player replace the shots. Completing the square gives a Gaussian pseudo-observation: \((G - X)/V\) is normally distributed with mean \(\eta\) and standard deviation \(1/\sqrt V\). This is the same form as the eight-schools meta-analysis, where each unit contributes an estimate and a standard error. It can be fitted with an ordinary pm.Normal. The quadratic matches the exact log-likelihood closely within about 0.3 log-odds units of zero, which covers realistic finishing effects.
The raw estimate of a player’s skill, goals minus expected goals, is noisy for players with few shots. The hierarchical model pulls each estimate toward zero in proportion to how little data the player has, and its estimates are closer to the true skills.
The notebook also tests a setting where skill varies far more than is realistic: two players four standard deviations apart differ by an odds ratio of about 25. Expanded around zero, the approximation overstates skill at both ends. Expanding each player around a one-step estimate of their own skill removes the error, at the cost of one more pass over the shots.
Notebook: 06_approximate_sufficiency.ipynb
Summary of cases
| Model family | Raw rows | Sufficient statistic | PyMC likelihood |
|---|---|---|---|
| Conversion test | Bernoulli per user | \((n, k)\) per arm | Binomial |
| Normal outcome | value per user | \((n, \bar y, SS)\) per arm | Normal on \(\bar y\) + Gamma on \(SS\) |
| Sequential multinomial | arm label per event | running counts \(\mathbf S_n\) | Multinomial / closed form |
| Discrete-time survival | person-period rows | \((d, r)\) per cell | Binomial (cloglog) |
| Piecewise exponential | person-interval rows | \((d, E)\) per cell | Poisson with exposure |
| Competing risks, piecewise exp. | person-interval rows | \((E, d_1, \dots, d_K)\) per cell | Poisson per cause |
| Competing risks, discrete time | person-period rows | \((r, d_1, \dots, d_K)\) per cell | Multinomial |
| Markov chain | transitions | counts \(N_{ij}\) | Multinomial per row |
| Funnel | user × stage rows | stage head-counts | Binomial |
| Linear regression | \(n \times p\) design | \((n, X^\top X, X^\top y, y^\top y)\) | Potential |
| Logistic with offsets | shots | \((G, X, V)\), approximate | Normal pseudo-observation |
Timings
The table is built from timing files that each notebook writes when it runs. Wall time includes compilation and uses the same sampler settings (nutpie, 4 chains, 1,000 tuning and 1,000 sampling iterations). Wall times vary by tens of percent between runs on the same laptop, so the effective samples per second, which measure sampling efficiency directly, are shown alongside. The ratios also depend on how many rows each notebook simulates. The general point is that computing the summaries takes one pass over the data, and after that the cost of sampling does not depend on the number of rows.
| Case | Rows → summary | Wall time | Speed-up | Min ESS/s |
|---|---|---|---|---|
| Conversion test | 800,000 → 2 | 42.4s → 0.6s | 76× | 98 → 6,847 |
| Normal outcome | 400,000 → 2 | 9.8s → 0.7s | 14× | 597 → 7,790 |
| Sequential multinomial | 106,072 → 1 | 5.2s → 0.9s | 5× | 410 → 2,115 |
| Discrete-time survival | 194,658 → 48 | 80.2s → 1.4s | 57× | 28 → 1,542 |
| Piecewise exponential | 194,658 → 48 | 32.9s → 1.3s | 25× | 67 → 1,600 |
| Markov chain | 58,669 → 8 | 17.3s → 3.8s | 5× | 178 → 722 |
| Funnel | 45,181 → 36 | 15.3s → 1.3s | 12× | 38 → 416 |
| Linear regression | 1,000,000 → 1 | 186.4s → 0.7s | 278× | 23 → 6,379 |
| Logistic with offsets | 68,675 → 400 | 61.2s → 1.0s | 61× | 23 → 1,342 |
| Logistic with offsets (stress test) | 63,867 → 400 | 59.0s → 1.2s | 49× | 12 → 744 |
| Logistic with offsets (stress test), re-centred | 63,867 → 400 | 59.0s → 0.8s | 72× | 12 → 853 |
| Competing risks, piecewise exp. | 91,483 → 48 | 40.3s → 2.1s | 19× | 55 → 1,039 |
| Competing risks, discrete time | 91,483 → 48 | 54.1s → 3.2s | 17× | 39 → 765 |
Practical notes
Run row-level checks before compressing. Compression removes the rows those checks need. You can keep a raw-data model, fitted to a sample, for diagnostics.
Use an observed distribution rather than pm.Potential when one exists. Binomial, Multinomial, Poisson, the Normal–Gamma pair for \((\bar y, SS)\) and the Gaussian pseudo-observation all keep a pointwise log-likelihood, so leave-one-out cross-validation still works. It now works at the level of the cell rather than the individual. The Gram-matrix model is the one case here that needs a Potential.
Counts, exposures and Gram matrices are additive. They can be summed across days, partitions or machines. This makes them well suited to streaming data and to data held in a warehouse, where the summaries can be computed in SQL.
Approximate summaries depend on their expansion point. They are accurate near that point and less accurate far from it. Summaries computed around different expansion points cannot be added together.
Each summary also states an assumption of the model. Writing down \((n, k)\) says which users are interchangeable. Writing down \((d, r)\) says which covariates define a risk set. Writing down \(N_{ij}\) says that the next step depends only on the current state. If one of those statements is false for your data, the compressed model is wrong in the same way the full model is, and it is cheaper to find out by checking the statement directly.
The notebooks are in the project folder. I plan to add more cases.
Citation
@online{forde2026,
author = {Forde, Nathaniel},
title = {Fewer {Rows,} {Same} {Posterior:} {Sufficient} {Statistics}
in {PyMC}},
date = {2026-11-15},
langid = {en}
}