13.6 Hypothesis tests: paired and two-sample permutation, McNemar, Holm
Once you can train real models, every change to one is a claim: “pre-LN trains better”, “this LoRA rank matches full fine-tuning”, “int8 quantization costs nothing”. The evidence is a score on a finite eval set, and two runs of the same model already differ by a few tenths of a point. The previous section, LLN, CLT, confidence intervals, bootstrap, put an interval on each number. This section answers the comparison question directly: is the gap between model A and model B on the same 200 prompts larger than the gap chance alone produces?
Concepts from other sections (9)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- pre-LN: with one final LN per stack; trains without warmup. Read more: 11.5 Encoder-decoder Transformer: post-LN and pre-LN, Noam, label smoothing in AI Engineering
- LoRA: a frozen Linear plus a trainable low-rank update . Read more: 12.6 LoRA: low-rank adaptation with PiSSA initialization and merging in AI Engineering
- Paired difference: the score of a template with one group term minus its score with the other, so template effects cancel. Read more: 36.1 Bias and safety evals in AI Engineering
- Standard normal: the distribution with density . Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
- Stable sort: a sort that keeps equal elements in their input order; heapsort is not one. Read more: 18.4 Binary heap in Programming and Algorithms
- Model zoo: the manifest-driven report that scores every model family in its own unit, one row per entry. Read more: 12.7 The evaluation harness and the model zoo in AI Engineering
- Standard error: , the estimated standard deviation of the sample mean. Read more: 13.5 LLN, CLT, confidence intervals, bootstrap
- Regression gate: a check that fails a head run only when it is worse than the base by more than a budget and the difference is unlikely under noise. Read more: 23.12 Run comparison and the regression gate in AI Engineering
- Paired comparison: building and running base and head alternately on the same machine, so machine speed cancels in the ratio. Read more: 3.4 Benchmarks and perf gates in Software Engineering
The model zoo in AI Engineering prints a p-value next to every comparison, the quantization and speculative decoding sections fail their “no regression” checks on one, and the zoo compares many models at once, which needs a correction or it will “discover” a winner by luck. All of these call the six functions you build here: a paired and a two-sample permutation test, McNemar’s test for classifiers, and Holm’s correction for many comparisons.
No code from earlier sections is needed. The reading background is the sampling distributions and intervals of the previous section and problem set C. The reference implementation is course/solutions/python/tinyllm/prob/tests.py, with its contract in tests.pyi; the generator behind rng is specified in spec/pcg32.md.
Learning objectives
- State what a p-value is and is not, and what type-I error rate a valid test promises.
- Implement paired and two-sample permutation tests with the add-one p-value, two-sidedness, and tie-safe comparison.
- Implement a correct Fisher-Yates shuffle and explain why the naive shuffle is biased.
- Compute McNemar’s exact and approximate p-values for two classifiers.
- Apply Holm’s step-down procedure and compute adjusted p-values.
Notation
Section titled “Notation”| Symbol | Meaning | Type / shape |
|---|---|---|
| the null hypothesis: “no difference” in a precise form (exchangeable labels) | ||
| the test statistic, larger meaning more extreme | float | |
| on the data as observed | float | |
| the p-value, | float in | |
| the significance level: reject when | float, often 0.05 | |
| the scores of models A and B on prompt (paired) | float64[n] | |
| paired differences | float64[n] | |
| a random sign per pair | ||
the number of random permutations, n_perm | int | |
| counts of examples where only A is right, and only B is right | int | |
| , | the number of tests in a family, and the -th smallest p-value () |
Testing as a thought experiment
Section titled “Testing as a thought experiment”Suppose B scores 0.8 points above A on 50 prompts. Two stories explain it: B is better, or the prompts happened to favour B. A test makes the second story precise as a null hypothesis , picks a statistic that is large when the data disagree with , and asks how often would produce a at least as large as the observed one. That probability is the p-value. A small p-value says the data would be surprising if were true; it is not the probability that is true, and a large one does not prove (the test may just lack data).
What a p-value promises
Section titled “What a p-value promises”The decision rule is to reject whenever . If is true, a valid p-value satisfies : a rejection is a false alarm (a type-I error) at most a fraction of the time. Not rejecting a false is a type-II error; the probability of rejecting when the effect is real is the power. A test that never rejects has a perfect type-I rate and no power, so a correct solution is judged on both. “Different” is usually two-sided: B worse is as interesting as B better, so is a magnitude, , and swapping A and B must not change .
The paired permutation test
Section titled “The paired permutation test”When both models answer the same prompts, compare them prompt by prompt: . Under (“which model produced which score of a pair is arbitrary”), each was as likely to come out as . So the null world is: flip each sign with probability . With and , the exact p-value is the fraction of all sign vectors with .
For that is vectors, so draw of them at random. The natural estimate can be 0, which no true p-value is. Counting the observed labelling as one more draw,
fixes that, and it is exactly valid: under the observed is one of exchangeable values, its rank is uniform, so . With , is exactly 0.1: the rate a type-I check measures. Pairing matters: prompt difficulty varies far more than the model gap, and pairing cancels it.
The two-sample permutation test
Section titled “The two-sample permutation test”Not every comparison is paired. When the two samples are not (latencies of two server builds, scores on different eval sets), says the group labels are arbitrary: all values come from one distribution. The null world deals the pooled values into two groups of the original sizes at random, and , by default the difference of means.
A uniformly random order of items comes from Fisher-Yates: for down to 1, pick uniformly in and swap positions and . Each of the orders comes out with probability . The tempting shortcut, uniform over all positions every time, produces equally likely swap sequences, which is not a multiple of , so some orders are more likely than others.
McNemar’s test
Section titled “McNemar’s test”Classifiers give right-or-wrong answers, and for those there is an exact test that needs no simulation. Two classifiers on the same examples give a 2 by 2 table: both right, both wrong, only A right (), only B right (). The examples where they agree say nothing about which is better. Under each disagreement is a fair coin, so , and the exact two-sided p-value doubles the smaller tail:
The doubling can exceed 1 when , hence the cap. For large the classic approximation is on one degree of freedom (the is Edwards’ continuity correction), with . With no disagreements at all there is no evidence: .
Many comparisons and Holm’s method
Section titled “Many comparisons and Holm’s method”Each test so far controls its own false-alarm rate. A table of comparisons needs more. Test true null hypotheses at and the chance of at least one false alarm is . The family-wise error rate (FWER) is that chance. Bonferroni tests each at , which bounds the FWER by (a union bound) but is needlessly strict.
Holm is uniformly better. Sort the p-values, compare the smallest with , the next with , and so on, rejecting while each passes and stopping at the first that does not. Once a hypothesis is rejected, only can still be true nulls, which is why the bar relaxes. The adjusted p-values make Holm a table column: reject exactly where . The running maximum keeps the order: a smaller raw p-value never gets a larger adjusted one.
Working it by hand
Section titled “Working it by hand”Paired. Model B minus model A on three prompts: , . All eight sign patterns:
| 6 | 0 | 4 | 2 | 0 | ||||
| yes | yes |
The exact p-value is : with three prompts, even a unanimous win is not convincing. Fed exactly these eight patterns as its permutations, the add-one estimate is .
McNemar. On 40 prompts, A alone is right on , B alone on . Then , , the tail is out of , and . Not significant at 0.05, despite 7 to 1. The approximation gives and .
Holm. Four comparisons with p-values at step down as follows.
| sorted | bar | reject? | adjusted | ||
|---|---|---|---|---|---|
| 0 | 0.005 | 0.0125 | yes | 0.02 | 0.02 |
| 1 | 0.01 | 0.0167 | yes | 0.03 | 0.03 |
| 2 | 0.02 | 0.025 | yes | 0.04 | 0.04 |
| 3 | 0.04 | 0.05 | yes | 0.04 | 0.04 |
Holm rejects all four; Bonferroni (every p against 0.0125) rejects only 0.005 and 0.01. In input order the adjusted values are . These are the first three test cases a correct implementation must reproduce.
Designing the interface
Section titled “Designing the interface”Six functions cover the section:
def mean_difference(a: NDArray, b: NDArray) -> float: ...def paired_permutation_test(a: ArrayLike, b: ArrayLike, n_perm: int, rng: UniformSource) -> float: ...def permutation_test(a: ArrayLike, b: ArrayLike, stat: Callable[[NDArray, NDArray], float], n_perm: int, rng: UniformSource) -> float: ...def mcnemar(b01: int, b10: int, exact: bool = True) -> float: ...def holm(pvalues: ArrayLike, alpha: float = 0.05) -> NDArray: ... # bool, True = rejecteddef holm_adjust(pvalues: ArrayLike) -> NDArray: ...The draw order is part of the contract, because the run comparison and regression gate reimplements the two-sample test in Go and must reproduce these p-values from the same seed. The paired test draws one uniform per pair per permutation ( flips). The two-sample test restarts from the identity order each permutation and runs Fisher-Yates from the end with . A permuted statistic counts as “at least as extreme” when it is at least , so rounding never splits a tie.
Building it step by step
Section titled “Building it step by step”Seven decisions produce the implementation.
- A permutation test is “count how often the null world is as extreme”. Compute once, draw relabellings the null says are harmless, count those with , return . Everything else is which relabelling and which .
- Two-sided means a magnitude. on both the observed and the permuted statistic, so swapping A and B (or negating the statistic) cannot change .
- Ties need a relative bar. Scores like 0.7 and 0.2 tie in exact arithmetic but their float sums can differ by an ulp depending on the order of addition. Comparing against counts those ties as “at least as extreme”, which is what the exact test does.
- Paired relabelling is a sign flip per pair, one uniform each. flips; uniforms in all, in pair order, so the stream is fixed.
- Two-sample relabelling is a fresh Fisher-Yates shuffle each time. Start from the identity, for down to 1 pick , swap; then the first are group A. uniforms per permutation. Restarting from the identity is what makes the permutation a function of its own uniforms only.
- McNemar exact is a binomial tail in integers. , with Python’s exact integers until one final division, so in the hundreds neither overflows nor underflows. The approximation applies Edwards’ and clamps at 0 so a tie gives , .
- Holm sorts, compares with a relaxing bar, and stops. Reject the -th smallest while ; break at the first failure. The adjusted p-values are the running maximum of , written back to input positions.
The paired test comes first:
TIE_RTOL = 1e-9
def paired_permutation_test(a, b, n_perm: int, rng) -> float: x, y = _vector(a, "a"), _vector(b, "b") # non-empty, 1-D, finite if x.shape != y.shape: raise ValueError(f"a and b must pair up, got lengths {x.size} and {y.size}") n_perm = _n_perm(n_perm) # an integer >= 1 d = x - y t_obs = abs(float(np.sum(d))) # two-sided: a magnitude bar = t_obs * (1.0 - TIE_RTOL) # ties a rounding error below still count count = 0 for _ in range(n_perm): # Under H0 the two scores of a pair could have come from either model: # each difference keeps or flips its sign with probability 1/2. s = np.array([-1.0 if rng.uniform() < 0.5 else 1.0 for _ in range(d.size)]) if abs(float(np.sum(s * d))) >= bar: count += 1 return (1 + count) / (1 + n_perm) # the observed labelling is one more drawWhen all differences are 0, , bar = 0, every permutation counts, and : no evidence, as it should be. With the hand example’s , bar is just below 6, and the patterns and count.
The two-sample test differs only in the relabelling:
def permutation_test(a, b, stat, n_perm: int, rng) -> float: x, y = _vector(a, "a"), _vector(b, "b") n_perm = _n_perm(n_perm) z = np.concatenate([x, y]) # the pooled values na, total = x.size, z.size t_obs = abs(float(stat(x, y))) bar = t_obs * (1.0 - TIE_RTOL) count = 0 for _ in range(n_perm): # Under H0 the group labels are arbitrary: deal the pooled values into # two groups of the original sizes, uniformly over all orders. idx = list(range(total)) # restart from the identity every time for i in range(total - 1, 0, -1): # Fisher-Yates from the end j = min(int(rng.uniform() * (i + 1)), i) # j uniform on {0, ..., i}; clamp guards rounding idx[i], idx[j] = idx[j], idx[i] p = z[idx] if abs(float(stat(p[:na], p[na:]))) >= bar: # same sizes as the data count += 1 return (1 + count) / (1 + n_perm)stat is any function of the two groups; mean_difference (np.mean(a) - np.mean(b)) is the default the callers pass. The absolute value is applied here, not inside stat, so a caller’s signed statistic still gives a two-sided test.
McNemar has an exact and an approximate branch:
def mcnemar(b01: int, b10: int, exact: bool = True) -> float: # (integer >= 0 checks elided) n = b01 + b10 if n == 0: return 1.0 # no disagreements: no evidence if exact: # Under H0 each discordant pair is a fair coin: b01 ~ Binomial(n, 1/2). # Two-sided: double the smaller tail. Integers until the one division. k = min(b01, b10) tail = sum(math.comb(n, i) for i in range(k + 1)) return min(1.0, 2 * tail / 2**n) # cap: doubling a tie's tail exceeds 1 chi2 = max(abs(b01 - b10) - 1, 0) ** 2 / n # Edwards' continuity correction, clamped return math.erfc(math.sqrt(chi2 / 2.0)) # chi-square(1) survival via the normalOn the hand example, tail = 1 + 8 = 9 and 2 * 9 / 256 = 9/128. The approximate branch gives and . The identity holds because is the square of a standard normal.
Holm and its adjustment share a stable sort:
def holm(pvalues, alpha: float = 0.05) -> NDArray: p = _pvalues(pvalues) # 1-D, every value in [0, 1] # (alpha check elided) m = p.size order = np.argsort(p, kind="stable") # stable: ties keep input order reject = np.zeros(m, dtype=bool) for k, i in enumerate(order): # The smallest p-value faces the strictest bar alpha / m; each # rejection removes one hypothesis from the family. if p[i] > alpha / (m - k): break # step-down: nothing after a failure is rejected reject[i] = True # equality rejects return reject
def holm_adjust(pvalues) -> NDArray: p = _pvalues(pvalues) m = p.size order = np.argsort(p, kind="stable") adj = np.empty(m, dtype=np.float64) running = 0.0 for k, i in enumerate(order): running = max(running, min(1.0, (m - k) * p[i])) # running max keeps the order adj[i] = running # written back in input order return adjThe hand example’s family sorts to with multipliers : , and in input order . holm(p, alpha) rejects exactly where holm_adjust(p) <= alpha. The full solution is tests.py.
Why this design
Section titled “Why this design”The paired test is time and uniforms; the two-sample test plus calls to stat, with uniforms. Exact McNemar is big-integer binomials; Holm and its adjustment are for the sort.
Permutation tests are chosen over -tests. A paired -test assumes roughly normal differences; per-prompt scores are 0/1, bounded, or heavy-tailed. The permutation test assumes only exchangeability under , which is exactly what “the models are equally good” means here, and its add-one p-value has an exact type-I guarantee at any .
Monte Carlo is chosen over exact enumeration. sign patterns or splits are out of reach for real eval sets; random relabellings give an unbiased estimate whose error shrinks like , and the add-one form remains valid for any .
Holm is chosen over Bonferroni. Holm controls the same family-wise error rate and rejects a superset of what Bonferroni rejects, at the cost of a sort. Benjamini-Hochberg would control the false discovery rate instead, a weaker promise than “no false winner in the table”.
The tradeoff accepted is speed. The scalar loops and a fixed draw order make the functions slower than vectorized numpy, in exchange for a stream that the Go port reproduces draw for draw.
What can go wrong
Section titled “What can go wrong”A correct solution reproduces the hand values, agrees with exact enumeration and with scipy, keeps its type-I promise, has power, and handles ties and edges. The full list:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| paired test by hand | unit | over the eight patterns | everyone agrees on the statistic and the add-one rule |
| McNemar by hand | unit | exact, approximate | classifier comparisons in the model zoo |
| Holm by hand | unit | all four rejected, adjusted | the zoo’s comparison table |
| paired against exact enumeration | golden | Monte Carlo within 4.5 standard errors of scipy’s exact enumeration | the estimate converges to the right number |
| two-sample against exact enumeration | golden | the same for 6 + 6, 7 + 5, 8 + 8 splits | latency and eval comparisons |
| replay of fixed seeds | golden | exact p-values for fixed seeds | the Go regression gate reproduces them |
| McNemar against scipy | golden | binomtest and the chi-square, up to 360 pairs | exact arithmetic, no overflow |
| Holm against a reference | golden | adjusted p and rejections on five families | ties, 0 and 1, a single test |
| paired type-I rate | statistical | under over 300 datasets | false alarms at the promised rate |
| two-sample type-I rate | statistical | the same with groups of 6 and 9 | the shuffle really mixes the groups |
| power | statistical | real shifts are detected at 0.05 | a test that never rejects is useless |
| draw counts | unit | and uniforms | one stream in every language |
| Fisher-Yates order | unit | is the identity, deals | the shuffle as specified |
| two-sidedness | property | swapping A and B, or negating the statistic, leaves unchanged | “different”, not “better” |
| add-one and degenerate data | boundary | always; no differences give | no “p = 0” in a report |
| rounding never splits a tie | boundary | counts 12 of 16 ties | decimal scores tie in exact arithmetic |
| Holm steps down and stops | property | stops at the first failure; equality rejects; superset of Bonferroni | the step-down rule |
| Holm adjustment is monotone and capped | property | adjusted p sorted like raw p, at most 1 | a trustworthy table column |
| McNemar edges | boundary | no disagreements or a tie give 1; symmetric | small eval sets |
| bad arguments | boundary | bad lengths, NaN, n_perm < 1, bad counts, p outside raise | bugs surface at the call |
The pitfalls group by the property they break.
Validity breaks first. Forgetting the makes a comparison one-sided by accident, so is near 1 when B is worse and too small when it is better; the solution applies abs(...) to both the observed and permuted statistic. Returning without the add-one puts “p = 0.000” in a report and breaks the type-I promise; the solution returns (1 + count) / (1 + n_perm). Comparing permuted statistics with a bare misses exact ties that land an ulp below, so is too small; bar = t_obs * (1.0 - TIE_RTOL) catches them.
Warning: The naive shuffle, drawn over the whole array, makes some orders more likely than others and produces a different stream from the Go port. Use
j = min(int(rng.uniform() * (i + 1)), i). Shuffling on from the previous permutation instead of restarting from the identity is still a valid test, but it is not the contract’s stream.
A relabelling that never mixes the groups makes every permutation equal the data: and no power. The solution runs a full Fisher-Yates over the pooled values, then splits at the original group sizes.
McNemar has three ways to go wrong: without doubling is halved, without the cap it can exceed 1, and without the continuity correction it is too small. The solution uses min(1.0, 2 * tail / 2**n) and max(abs(b01 - b10) - 1, 0).
Holm has three more. Using Bonferroni where Holm was meant misses real improvements; the bar is alpha / (m - k), not alpha / m. Not stopping at the first failure rejects a later hypothesis past a failed bar and breaks the FWER; the break prevents it. Computing adjusted p-values without the running maximum lets a smaller raw p get a larger adjusted one; running = max(running, ...) keeps them ordered.
Where this leads
Section titled “Where this leads”Problem set D works these tests by hand in its first four questions. In AI Engineering, the model zoo prints a paired p-value for each comparison against the baseline, Holm-adjusted over the table. Quantization claims “quantization costs nothing”, so a paired test on per-prompt losses must not reject. Speculative decoding must not change quality, checked with McNemar on exact-match outcomes. The run comparison and regression gate implements the two-sample test in Go for p50 and p99 latency comparisons, bit-identical to this one. The TinyStories capstone and the post-trained capstone use these tests for A/B ablation verdicts over seeds.
Further reading
Section titled “Further reading”- Wasserman, All of Statistics, chapter 10 (hypothesis testing and p-values).
- Good, Permutation, Parametric, and Bootstrap Tests of Hypotheses (2005), chapter 3.
- Phipson and Smyth, “Permutation p-values should never be zero” (2010).
- Holm, “A simple sequentially rejective multiple test procedure” (1979).
scipy.stats.permutation_test(scipy/stats/_resampling.py): vectorized batches, exact enumeration when it is small enough, one- and two-sided alternatives.statsmodels.stats.contingency_tables.mcnemar(statsmodels/stats/contingency_tables.py): the same two variants, plus Cochran’s Q for more than two classifiers.statsmodels.stats.multitest.multipletests(statsmodels/stats/multitest.py): Hochberg, Benjamini-Hochberg (false discovery rate), and others.- lm-evaluation-harness and HELM (
stderr_for_metricinlm_eval/api/metrics.py): bootstrap standard errors per task; paired comparisons across models. - Johari et al., “Peeking at A/B Tests” (2017): sequential testing with always-valid p-values, to stop an A/B test early without inflating false alarms.
Key terms
Section titled “Key terms”- Null hypothesis: the precise “no difference” claim a test tries to reject, here that labels are exchangeable.
- p-value: the probability under the null of a statistic at least as extreme as the one observed.
- Type-I error: rejecting a true null hypothesis; a valid test does so at rate at most .
- Power: the probability of rejecting the null when the effect is real.
- Permutation test: a test whose null distribution comes from relabelling the data in ways the null says are harmless.
- Fisher-Yates shuffle: the swap-from-the-end algorithm that produces each of the orders with equal probability.
- McNemar’s test: an exact binomial test on the examples two classifiers disagree on.
- Family-wise error rate: the probability of at least one false rejection in a family of tests.
- Holm’s method: a step-down correction that controls the FWER and rejects at least as much as Bonferroni.
Summary
Section titled “Summary”- A p-value is the probability, if nothing really changed, of a difference at least as large as the one observed; a valid test rejects a true null at rate .
- A permutation test builds that “nothing changed” world by relabelling: flip which model each paired score belongs to, or reshuffle two pools; no normality assumption.
- Count the observed labelling as one more permutation: is never 0 and keeps the type-I promise exactly.
- McNemar compares two classifiers on the same examples using only the pairs they disagree on: an exact binomial test.
- Ten comparisons at 0.05 give a false alarm 40% of the time; Holm controls the chance of any false alarm and rejects at least as much as Bonferroni.
Review questions
Section titled “Review questions”-
Why and not ?
Answer
Under the observed labelling is exchangeable with the random ones, so its statistic’s rank among all is uniform. The add-one p-value is exactly that rank’s upper-tail fraction, giving exactly. can be 0, which overstates the evidence (no true p-value is 0) and breaks the type-I promise for small .
-
Why compare the permuted statistic with
t_obs * (1 - 1e-9)rather thant_obs?Answer
Decimal scores tie in exact arithmetic but not always in floating point: and can round differently, landing an ulp below . A bare would miss those ties and report too small a p-value. The relative margin is far larger than rounding and far smaller than any real difference.
-
Why must Fisher-Yates pick from rather than from all positions?
Answer
Picking from at step gives equally likely swap sequences, one per order. Picking from all each time gives sequences, and since is not a multiple of for they cannot map evenly onto orders: some groupings become more likely, and the test’s null distribution is wrong. It also changes the uniform-to-order map the Go port reproduces.
-
Why does
holmbreakat the first failure instead of testing the rest?Answer
Holm’s FWER proof relies on stepping down: the bar is only justified once the smaller p-values were rejected. A later p-value can pass its looser bar after an earlier one failed (for example with : fails, would pass), and rejecting it would exceed the promised error rate.
-
Why does exact McNemar sum
math.combintegers and divide once by2**n?Answer
For in the hundreds, overflows float64 and underflows; computing each term as a float loses the tail or produces inf/inf. Python integers are exact at any size, so the tail is exact and the single division rounds once to the nearest float.