Skip to main content

AI and machine learning · Advanced · 26 min

Tell whether a prompt change really helped, with paired evals and confidence intervals

By Padding · Updated 18 Nov 2026
python:3.15-slim · Python 3.15 · NumPy 2.5.5 · SciPy 1.18.1 · statsmodels 0.15.0

You will take recorded pass and fail results for two prompt versions on the same 60 test cases, compute the difference with a paired bootstrap confidence interval and McNemar's test, measure run-to-run noise, work out how many cases a 5-point change needs, and end with a written decision rule that prints adopt, keep or undecided.

On this page

You change a prompt, rerun your eval, and the pass rate goes from 75% to 78.3%. That looks like a win. On 60 cases it is two cases, and the same prompt run twice can move by more than that. Before you ship the change, you want to know whether the gain would survive a different sample of cases and a different run of the model.

The tool for this is a paired comparison. Both prompts ran on the same cases, so the question is not "is 78.3 bigger than 75" but "on the cases where the two prompts disagree, which one wins more often, and by how much could that be chance". You will answer it four ways:

  • the difference in pass rate with a paired bootstrap confidence interval
  • McNemar's test, which looks only at the cases where the prompts disagree
  • a look at run-to-run variance, by comparing three runs of each prompt
  • a sample size estimate for detecting a 5-point change

Then you write a decision rule before you look at the next result, so the numbers decide and not your hopes.

The results are a fixed file you create, so every number here is reproducible. In your own work they come from your eval runner: one row per case, prompt and run. The scripts need no API key and no network after the install, which keeps them cheap to rerun on a metered connection.

Step 1 · Create the project and the recorded results

Make a throwaway project and add NumPy, SciPy and statsmodels at exact versions:

Bash
mkdir -p ~/paired-eval-demo
cd ~/paired-eval-demo
uv init --no-package
uv add "numpy==2.5.5" "scipy==1.18.1" "statsmodels==0.15.0"
rm main.py

The eval graded 60 cases for a support-reply feature with prompt A (the current prompt) and prompt B (the candidate), three runs each. To keep the page short, each run is written as a string of 60 ones and zeros, and a script expands them into the long format a real runner writes: case_id,prompt,run,passed.

Bash
cat > make_results.py <<'PY'
import csv
from pathlib import Path

# One string per prompt and run. Character i is case i + 1: 1 = passed, 0 = failed.
# Spaces split the 60 cases into groups of ten and are ignored.
RUNS = {
    ("A", 1): "1111111111 1111111111 1111111111 1111111111 0000001111 0000001000",
    ("A", 2): "1111111111 1111111111 1111111111 1111111111 0000001111 0000001110",
    ("A", 3): "1111111111 1111111111 1111111111 1111111111 0000001111 0000000000",
    ("B", 1): "1111111111 1111111111 1111111111 1111111111 1111110000 0000000100",
    ("B", 2): "1111111111 1111111111 1111111111 1111111111 1111110000 0000001000",
    ("B", 3): "1111111111 1111111111 1111111111 1111111111 1111110000 0000001111",
}

Path("results").mkdir(exist_ok=True)
with open("results/runs.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["case_id", "prompt", "run", "passed"])
    for (prompt, run), outcomes in RUNS.items():
        outcomes = outcomes.replace(" ", "")
        assert len(outcomes) == 60, (prompt, run, len(outcomes))
        for i, passed in enumerate(outcomes, start=1):
            writer.writerow([f"t{i:02d}", prompt, run, passed])
print("wrote results/runs.csv")
PY
uv run python make_results.py

Look at the pattern before any statistics. Cases t01 to t40 pass under both prompts every time. B fixes six cases (t41 to t46) and breaks four (t47 to t50). Six cases fail under both. The last four, t57 to t60, change from run to run.

Check it worked

Bash
wc -l results/runs.csv
head -3 results/runs.csv

The file has 361 lines: a header and 6 runs of 60 cases. The first rows are case_id,prompt,run,passed, t01,A,1,1 and t02,A,1,1.

Step 2 · Measure the difference with a paired bootstrap interval

A confidence interval answers "if I had drawn a different 60 cases of the same kind, how far could this difference move". The bootstrap estimates it by resampling: draw 60 cases with replacement from the ones you have, recompute B minus A, repeat 10,000 times, and take the middle 95% of the results.

The word that matters is paired. Each resample draws whole cases, so case t12's result under A stays next to its result under B. Easy cases that both prompts pass then cancel out, and only the disagreements move the difference. If you resample A and B separately you throw that information away and get an interval that is too wide.

Put the shared code in evalstats.py. load_runs also refuses a file where one run is missing cases, since a paired comparison on different cases is meaningless:

Bash
cat > evalstats.py <<'PY'
import csv
from collections import defaultdict

import numpy as np


def load_runs(path):
    """Return (case_ids, {prompt: array of shape (runs, cases)}) from a results CSV."""
    by_run = defaultdict(dict)
    with open(path, newline="") as f:
        for row in csv.DictReader(f):
            by_run[(row["prompt"], int(row["run"]))][row["case_id"]] = int(row["passed"])
    cases = sorted(next(iter(by_run.values())))
    grouped = defaultdict(list)
    for (prompt, run), scores in sorted(by_run.items()):
        if sorted(scores) != cases:
            raise ValueError(f"prompt {prompt} run {run} does not cover the same cases")
        grouped[prompt].append([scores[c] for c in cases])
    return cases, {p: np.array(rows, dtype=float) for p, rows in grouped.items()}


def paired_bootstrap(a, b, n_boot=10_000, seed=2026):
    """95% interval for mean(b - a), resampling whole cases so each pair stays together."""
    rng = np.random.default_rng(seed)
    idx = rng.integers(0, len(a), size=(n_boot, len(a)))
    diffs = (b[idx] - a[idx]).mean(axis=1)
    return np.percentile(diffs, [2.5, 97.5])


def unpaired_bootstrap(a, b, n_boot=10_000, seed=2026):
    """The same interval if you wrongly treat A and B as unrelated samples."""
    rng = np.random.default_rng(seed)
    ia = rng.integers(0, len(a), size=(n_boot, len(a)))
    ib = rng.integers(0, len(b), size=(n_boot, len(b)))
    diffs = b[ib].mean(axis=1) - a[ia].mean(axis=1)
    return np.percentile(diffs, [2.5, 97.5])


def pts(x):
    """Format a proportion as signed percentage points."""
    return f"{x * 100:+.1f}"
PY

Now compare the first run of each prompt. The script also counts the four kinds of case, which you need in the next step:

Bash
cat > compare.py <<'PY'
import sys

from statsmodels.stats.contingency_tables import mcnemar

from evalstats import load_runs, paired_bootstrap, pts, unpaired_bootstrap

path = sys.argv[1] if len(sys.argv) > 1 else "results/runs.csv"
cases, runs = load_runs(path)
a, b = runs["A"][0], runs["B"][0]  # first run of each prompt

print(f"cases: {len(cases)}")
print(f"A pass rate: {a.mean():.1%}")
print(f"B pass rate: {b.mean():.1%}")
print(f"B - A: {pts(b.mean() - a.mean())} points")

both = int(((a == 1) & (b == 1)).sum())
a_only = int(((a == 1) & (b == 0)).sum())
b_only = int(((a == 0) & (b == 1)).sum())
neither = int(((a == 0) & (b == 0)).sum())
print(f"both pass {both}, A only {a_only}, B only {b_only}, both fail {neither}")

lo, hi = paired_bootstrap(a, b)
print(f"paired 95% CI: {pts(lo)} to {pts(hi)} points")
lo_u, hi_u = unpaired_bootstrap(a, b)
print(f"unpaired 95% CI (wrong here): {pts(lo_u)} to {pts(hi_u)} points")
PY
uv run python compare.py

Check it worked

The output starts with A pass rate: 75.0%, B pass rate: 78.3% and B - A: +3.3 points, then both pass 40, A only 5, B only 7, both fail 8. The paired interval is -8.3 to +15.0 points, and the unpaired one is wider, -11.7 to +18.3 points.

The interval runs from a loss of several points to a gain of more than ten. Zero is comfortably inside it. On these 60 cases, the +3.3 is not evidence that B is better; it is equally consistent with B being a little worse.

Step 3 · Run McNemar's test on the disagreements

The 40 cases both prompts pass and the 8 both fail say nothing about which prompt is better. McNemar's test uses only the 12 cases where the prompts disagree. If the prompts were equally good, each of those 12 would be a coin flip between "A only" and "B only". The exact test asks how surprising a 7 to 5 split is under that coin flip. It uses the binomial distribution, which is the right choice when the disagreements are few (as a rule of thumb, under 25).

Append the test to compare.py. The table is the 2 by 2 count of outcomes, with A in the rows and B in the columns:

Bash
cat >> compare.py <<'PY'

table = [[both, a_only], [b_only, neither]]  # rows: A pass, A fail; columns: B pass, B fail
result = mcnemar(table, exact=True)
print(f"McNemar exact: {a_only} vs {b_only} disagreements, p = {result.pvalue:.3f}")
PY
uv run python compare.py

Check it worked

The last line is McNemar exact: 5 vs 7 disagreements, p = 0.774. A p-value that high means a split at least this uneven turns up about three times in four when the prompts are equally good. The test and the interval agree: no evidence of a difference.

Two readings to avoid. A high p-value does not prove the prompts are equal; 60 cases cannot see small differences, as a later step shows. And a low p-value would not tell you the gain is big enough to matter; the interval does that.

Step 4 · Measure how much the model varies between runs

The bootstrap covers the choice of cases. It does not cover the model giving a different answer to the same case on another run, which many hosted models do even at temperature 0. Your results file has three runs of each prompt. Compare them:

Bash
cat > runs.py <<'PY'
from evalstats import load_runs, paired_bootstrap, pts

cases, runs = load_runs("results/runs.csv")
a_runs, b_runs = runs["A"], runs["B"]

for i, (a, b) in enumerate(zip(a_runs, b_runs), start=1):
    print(f"run {i}: A {a.mean():.1%}  B {b.mean():.1%}  B - A {pts(b.mean() - a.mean())}")

for name, r in runs.items():
    flaky = [c for c, col in zip(cases, r.T) if 0 < col.mean() < 1]
    print(f"{name} flaky cases: {len(flaky)} {' '.join(flaky)}")

a, b = a_runs.mean(axis=0), b_runs.mean(axis=0)  # each case's pass rate over its runs
lo, hi = paired_bootstrap(a, b)
print(f"averaged over {len(a_runs)} runs: B - A {pts(b.mean() - a.mean())} points, "
      f"95% CI {pts(lo)} to {pts(hi)}")
PY
uv run python runs.py

Check it worked

You see three lines like run 1: A 75.0% B 78.3% B - A +3.3. Run 2 shows +0.0 and run 3 shows +10.0. Prompt A alone moves between 73.3% and 78.3% with nothing changed. Then A flaky cases: 3 t57 t58 t59 and B flaky cases: 4 t57 t58 t59 t60, and the averaged line averaged over 3 runs: B - A +4.4 points, 95% CI -6.1 to +15.0.

So if you had run each prompt once and happened to get run 3, you would have reported a 10-point gain. Averaging each case over runs before the bootstrap removes some of that noise, because a flaky case now counts as 0.33 or 0.67 instead of a random 0 or 1. The interval still spans zero.

Practical rules that follow:

  • Run each prompt at least three times on the full set, and compare the averages, not one run against one run.
  • Look at the flaky cases by hand. A case that flips on every run is often a vague grading rule, not a model problem. Fixing the grader cuts noise for every future comparison.
  • If a run costs real money, three runs of 60 cases is still cheaper than a wrong prompt in production.

Step 5 · Work out how many cases a 5-point change needs

How many paired cases would McNemar's test need to detect a real 5-point gain? It depends on how often the prompts disagree. In run 1 they disagreed on 12 of 60 cases, a rate of 0.20. The standard formula for the paired design (Connor, 1987) gives the number of cases for a test at the 5% level with 80% power, meaning an 80% chance of detecting a real gain of that size.

Formulas like this are approximations, so the script checks each answer by simulation: it generates 2,000 fake evals of that many cases where the gain is real and counts how often the test finds it.

Bash
cat > sample_size.py <<'PY'
import math

import numpy as np
from scipy.stats import norm
from statsmodels.stats.contingency_tables import mcnemar

P_DISAGREE = 0.20  # share of cases where A and B disagree: 12 of 60 in run 1
ALPHA, POWER = 0.05, 0.80


def cases_needed(delta, p_disagree=P_DISAGREE, alpha=ALPHA, power=POWER):
    """Paired cases McNemar needs to detect a true gain of `delta` (Connor, 1987)."""
    za, zb = norm.ppf(1 - alpha / 2), norm.ppf(power)
    n = (za * math.sqrt(p_disagree) + zb * math.sqrt(p_disagree - delta**2)) ** 2 / delta**2
    return math.ceil(n)


def simulated_power(n, delta, p_disagree=P_DISAGREE, trials=2000, seed=7):
    """Share of simulated evals of n cases in which McNemar finds the gain."""
    rng = np.random.default_rng(seed)
    b_only, a_only = (p_disagree + delta) / 2, (p_disagree - delta) / 2
    hits = 0
    for _ in range(trials):
        bo, ao, _same = rng.multinomial(n, [b_only, a_only, 1 - p_disagree])
        if mcnemar([[0, ao], [bo, 0]], exact=True).pvalue < ALPHA:
            hits += 1
    return hits / trials


for delta in (0.10, 0.05):
    n = cases_needed(delta)
    print(f"{delta * 100:.0f}-point gain: {n} cases (simulated power {simulated_power(n, delta):.0%})")
print(f"power with 60 cases for a 5-point gain: {simulated_power(60, 0.05):.0%}")
PY
uv run python sample_size.py

It takes a few seconds.

Check it worked

The output is 10-point gain: 155 cases (simulated power 76%), 5-point gain: 626 cases (simulated power 78%) and power with 60 cases for a 5-point gain: 8%.

The simulated power lands a little under the 80% target, because the formula is an approximation; treat its answer as a minimum. Your 60-case set has roughly a one-in-twelve chance of noticing a real 5-point gain. To see one reliably you need about ten times as many cases. Two cheaper levers help as well: fewer disagreements (a more consistent grader and fewer flaky cases lower P_DISAGREE, and the required number falls with it), and deciding in advance that you only care about larger gains. Halving the gain you want to detect roughly quadruples the cases you need.

Writing 600 cases by hand is a lot. If your users write in several languages, such as English, Pidgin and Hausa for a Nigerian product, adding real messages in each is a good way to grow the set and to find the cases where prompts disagree.

Step 6 · Write the decision rule down before the next result

Statistics only protect you if you decide what counts as a win before you see the numbers. Otherwise it is easy to rerun until one run looks good, or to move the threshold after the fact. Write the rule as code, commit it, and change it only in a reviewed commit.

The rule here has three outcomes, based on the averaged paired interval and a minimum gain that would be worth a prompt change:

  • Adopt B when the whole interval is above zero.
  • Keep A when even the top of the interval is below the minimum worthwhile gain.
  • Undecided otherwise: the data cannot tell yet, so add cases and runs.

It also lists cases that A always passes and B always fails. Even an adopted prompt should not ship without a person reading those regressions.

Bash
cat > decide.py <<'PY'
import sys

from evalstats import load_runs, paired_bootstrap, pts

# Written down before looking at the results. Change these only in a reviewed commit.
MIN_GAIN = 0.02  # a gain smaller than 2 points is not worth a prompt change

path = sys.argv[1] if len(sys.argv) > 1 else "results/runs.csv"
cases, runs = load_runs(path)
a_runs, b_runs = runs["A"], runs["B"]
a, b = a_runs.mean(axis=0), b_runs.mean(axis=0)
lo, hi = paired_bootstrap(a, b)
print(f"{len(cases)} cases, {len(a_runs)} run(s): B - A {pts(b.mean() - a.mean())} points, "
      f"95% CI {pts(lo)} to {pts(hi)}")

if lo > 0:
    verdict = "ADOPT B: the gain is above zero across the whole interval"
elif hi < MIN_GAIN:
    verdict = f"KEEP A: any gain is under {MIN_GAIN * 100:.0f} points"
else:
    verdict = "UNDECIDED: the interval spans zero and a worthwhile gain; add cases"
print(verdict)

broken = [c for c, x, y in zip(cases, a_runs.min(axis=0), b_runs.max(axis=0)) if x == 1 and y == 0]
print(f"cases A always passes and B always fails: {' '.join(broken) or 'none'}")
PY
uv run python decide.py

To see the rule say yes, give it a set where B really is better. This script makes 800 cases with A passing 75% and B passing 83%:

Bash
cat > simulate_win.py <<'PY'
import csv

import numpy as np

# 800 made-up cases where B is truly 8 points better: A passes 75%, B 83%.
rng = np.random.default_rng(11)
kinds = rng.choice(4, size=800, p=[0.69, 0.06, 0.14, 0.11])  # both, A only, B only, neither
a = np.isin(kinds, [0, 1]).astype(int)
b = np.isin(kinds, [0, 2]).astype(int)
with open("results/simulated-win.csv", "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["case_id", "prompt", "run", "passed"])
    for prompt, scores in (("A", a), ("B", b)):
        for i, passed in enumerate(scores, start=1):
            w.writerow([f"s{i:03d}", prompt, 1, passed])
print("wrote results/simulated-win.csv")
PY
uv run python simulate_win.py
uv run python decide.py results/simulated-win.csv

Check it worked

On your recorded results, decide.py prints the averaged interval, UNDECIDED: the interval spans zero and a worthwhile gain; add cases, and cases A always passes and B always fails: t47 t48 t49 t50. Those four cases are where to start reading.

On the simulated set it prints 800 cases, 1 run(s): B - A +6.1 points, 95% CI +3.1 to +9.0 and then ADOPT B: the gain is above zero across the whole interval. The sample's gain is 6.1 points rather than the true 8, which is the sampling noise the interval allows for. With 800 cases the interval is six points wide instead of twenty.

When you are done, remove the project with rm -r ~/paired-eval-demo.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.