Skip to content

Official Codebase of 3DCodeVerse

Python

bench: one stats module — the t-interval, the sign test, the correlation

gaoypeng8d099c12cfd3
diff --git a/eval/bench/_ab_report.py b/eval/bench/_ab_report.py
index d3796072..c30f6e16 100644
--- a/eval/bench/_ab_report.py
+++ b/eval/bench/_ab_report.py
@@ -14,7 +14,6 @@ report can never be argued into "keep" by hand.
from __future__ import annotations
import json
-import math
import statistics
from datetime import datetime
from pathlib import Path
@@ -22,6 +21,7 @@ from pathlib import Path
from pydantic import BaseModel, Field
from bench._compare_report import CellResult
+from bench.stats import mean_ci, n_to_resolve, sign_test
CONTROL = "control"
VARIANT = "variant"
@@ -36,24 +36,19 @@ KEEP_DELTA = 0.02
REVERT_DELTA = -0.02
#: this many regressing prompts is a revert even when the mean looks fine
REVERT_REGRESSIONS = 2
-#: how many standard errors the mean delta must clear before the rig claims to have
-#: SEPARATED the change from run-to-run noise. 2 is the usual ~95 % two-sided band.
-#:
-#: This is reported, never enforced: the keep/revert rule above is the protocol
-#: (docs/EVAL.md §8) and a report must not be able to argue itself out of it. But the
-#: rule alone is dangerously confident. Measured 2026-08-24 with two A/A runs — arms
-#: identical by construction — on the SAME prompt (`ctrl_med_dining_chair`, rounds 1):
-#:
-#: 0.591 vs 0.934 -> delta +0.344 -> verdict **keep**
-#: 0.700 vs 0.600 -> delta -0.100 -> verdict **revert**
-#:
-#: Nothing was under test either time, and the rule returned opposite decisions. Those
-#: four same-code measurements of one prompt have sd 0.160, so a paired delta has
-#: sd ~0.226 and an 8-prompt mean has a 2 SE band of ±0.16 — eight times the ±0.02 the
-#: decision turns on. The generator is stochastic; a paired delta carries the spread of
-#: two independent generations, not the judge's ±0.02 sampling noise. So every summary
-#: states the spread beside the verdict, and says plainly when the threshold is inside it.
-NOISE_SIGMAS = 2.0
+# The keep/revert rule above is the protocol (docs/EVAL.md §8) and a report must not be
+# able to argue itself out of it — but the rule alone is dangerously confident. Measured
+# 2026-08-24 with two A/A runs — arms identical by construction — on the SAME prompt
+# (`ctrl_med_dining_chair`, rounds 1):
+#
+# 0.591 vs 0.934 -> delta +0.344 -> verdict **keep**
+# 0.700 vs 0.600 -> delta -0.100 -> verdict **revert**
+#
+# Nothing was under test either time, and the rule returned opposite decisions. The
+# generator is stochastic; a paired delta carries the spread of two independent
+# generations, not the judge's ±0.02 sampling noise. So every summary states the paired
+# 95 % t-interval beside the verdict (``bench/stats.py``), reported, never enforced, and
+# says plainly when the threshold is inside it.
class PairOutcome(BaseModel):
@@ -79,8 +74,9 @@ class Verdict(BaseModel):
reason: str = ""
sd_delta: float | None = Field(default=None, description="stdev of the paired deltas — the rig's own noise (None at n<2)")
se_delta: float | None = Field(default=None, description="standard error of the mean delta, sd/sqrt(n)")
- separated: bool = Field(default=False, description="|mean delta| >= NOISE_SIGMAS * se: the decision is outside the noise")
- n_for_power: int | None = Field(default=None, description="pairs this spread needs for NOISE_SIGMAS*se to fit inside KEEP_DELTA")
+ ci_half: float | None = Field(default=None, description="half-width of the 95 % t-interval, t(0.975, n-1) * se")
+ separated: bool = Field(default=False, description="the 95 % t-interval excludes zero: the decision is outside the noise")
+ n_for_power: int | None = Field(default=None, description="pairs this spread needs for the t-interval to fit inside KEEP_DELTA")
n_up: int = Field(default=0, description="pairs where the variant scored higher (delta > 0)")
n_down: int = Field(default=0, description="pairs where the variant scored lower (delta < 0)")
sign_p: float | None = Field(default=None, description="two-sided exact sign test on n_up vs n_down; None with no non-zero deltas")
@@ -97,7 +93,7 @@ class Verdict(BaseModel):
if self.separated:
return ""
need = f"~{self.n_for_power} paired prompts" if self.n_for_power else "more paired prompts"
- return (f"NOT separated from noise: |mean delta| < {NOISE_SIGMAS:g} SE ({NOISE_SIGMAS * self.se_delta:+.3f}). "
+ return (f"NOT separated from noise: the 95 % t-interval (±{self.ci_half:.3f}) includes zero. "
f"At this spread {need} would be needed to resolve {KEEP_DELTA:+.2f}. Treat the decision as a screen.")
@@ -143,8 +139,16 @@ def verdict_of(pairs: list[PairOutcome]) -> Verdict:
return Verdict(decision="inconclusive", n_pairs=0, mean_delta=None, median_delta=None,
reason="no prompt has both arms scored")
mean, median = round(statistics.fmean(deltas), 4), round(statistics.median(deltas), 4)
+ # the noise block: reported, never enforced. The SIGN of each delta is far cheaper to
+ # move than the mean — 7 of 8 in one direction is p = 0.07, a bar an eight-prompt
+ # battery can clear where a ±0.02 mean at a paired sd near 0.23 never will.
+ ci = mean_ci(deltas)
+ up, down, sign_p = sign_test(deltas)
v = Verdict(decision="inconclusive", n_pairs=len(deltas), mean_delta=mean, median_delta=median,
- regressions=regressions, **_spread(deltas, mean), **_sign_test(deltas))
+ regressions=regressions, n_up=up, n_down=down, sign_p=sign_p, separated=ci.separated)
+ if ci.sd is not None: # one pair has no spread to state
+ v.sd_delta, v.se_delta, v.ci_half = round(ci.sd, 4), round(ci.se, 4), round(ci.half, 4)
+ v.n_for_power = n_to_resolve(ci.sd, KEEP_DELTA)
if mean <= REVERT_DELTA or len(regressions) >= REVERT_REGRESSIONS:
v.decision, v.reason = "revert", (f"mean delta {mean:+.3f} <= {REVERT_DELTA:+.2f}" if mean <= REVERT_DELTA
else f"{len(regressions)} regressions (>= {REVERT_REGRESSIONS})")
@@ -156,43 +160,6 @@ def verdict_of(pairs: list[PairOutcome]) -> Verdict:
return v
-def _sign_test(deltas: list[float]) -> dict[str, object]:
- """How CONSISTENT the change is, as opposed to how big its mean is.
-
- The mean is hostage to the generation spread (see :data:`NOISE_SIGMAS`): at a paired
- sd near 0.23 an eight-prompt mean cannot resolve 0.02 and never will. The SIGN of
- each paired delta is far cheaper to move — a real improvement tends to help most
- prompts a little, and 7 of 8 in one direction is p = 0.07 on the exact two-sided sign
- test, a bar an eight-prompt battery can actually clear. Reported, not enforced: the
- keep/revert rule is the protocol. Zero deltas are dropped, as the test requires.
- """
- up = sum(d > 0 for d in deltas)
- down = sum(d < 0 for d in deltas)
- n = up + down
- if n == 0:
- return {"n_up": 0, "n_down": 0, "sign_p": None}
- k = max(up, down)
- tail = sum(math.comb(n, i) for i in range(k, n + 1)) / 2 ** n
- return {"n_up": up, "n_down": down, "sign_p": round(min(1.0, 2 * tail), 4)}
-
-
-def _spread(deltas: list[float], mean: float) -> dict[str, object]:
- """The noise block of a :class:`Verdict`: how wide the paired deltas are, and what
- that width does to the decision.
-
- ``n_for_power`` inverts the standard error: to get ``NOISE_SIGMAS * sd/sqrt(n)`` down
- to ``KEEP_DELTA`` you need ``n = (NOISE_SIGMAS*sd/KEEP_DELTA)**2`` pairs. It is the
- honest answer to "would one more prompt settle this?" and it is usually brutal.
- """
- if len(deltas) < 2:
- return {"sd_delta": None, "se_delta": None, "separated": False, "n_for_power": None}
- sd = statistics.stdev(deltas)
- se = sd / math.sqrt(len(deltas))
- return {"sd_delta": round(sd, 4), "se_delta": round(se, 4),
- "separated": abs(mean) >= NOISE_SIGMAS * se,
- "n_for_power": math.ceil((NOISE_SIGMAS * sd / KEEP_DELTA) ** 2) if sd > 0 else 1}
-
-
class ArmSummary(BaseModel):
arm: str
n: int
@@ -256,8 +223,8 @@ def render_summary(pairs: list[PairOutcome], rows: list[CellResult], *, title: s
f"median delta {_fmt(v.median_delta, True)} · regressions (delta <= {REGRESSION_DELTA:+.2f}): "
f"{', '.join(v.regressions) or 'none'}", "",
"## Confidence", "",
- f"paired sd {_fmt(v.sd_delta)} · SE {_fmt(v.se_delta)} · {NOISE_SIGMAS:g} SE band "
- f"{_fmt(v.mean_delta, True)} ± {_fmt(NOISE_SIGMAS * v.se_delta if v.se_delta else None)} · "
+ f"paired sd {_fmt(v.sd_delta)} · SE {_fmt(v.se_delta)} · 95 % t-interval "
+ f"{_fmt(v.mean_delta, True)} ± {_fmt(v.ci_half)} · "
f"separated from noise: {'yes' if v.separated else 'NO'}",
f"sign consistency: {v.n_up} up / {v.n_down} down · exact two-sided sign test p = "
f"{'—' if v.sign_p is None else f'{v.sign_p:.3f}'} — the signal an 8-prompt battery can actually carry",
@@ -292,7 +259,7 @@ def write_report(out: Path, rows: list[CellResult], prompt_order: list[tuple[str
return v
-__all__ = ["ARMS", "CONTROL", "KEEP_DELTA", "NOISE_SIGMAS", "REGRESSION_DELTA", "REVERT_DELTA",
+__all__ = ["ARMS", "CONTROL", "KEEP_DELTA", "REGRESSION_DELTA", "REVERT_DELTA",
"REVERT_REGRESSIONS", "VARIANT",
"ArmSummary", "PairOutcome", "Verdict", "arm_summary", "pair_up", "render_summary", "verdict_of",
"write_report"]
diff --git a/eval/bench/ab_plan.py b/eval/bench/ab_plan.py
index ada1d7a6..e2d4c15a 100644
--- a/eval/bench/ab_plan.py
+++ b/eval/bench/ab_plan.py
@@ -38,8 +38,8 @@ arm regenerates instead of resuming its old answer (:func:`archive_cell`).
What the verdict does NOT tell you: the generator is stochastic, so a paired delta carries
the spread of two independent generations, not the judge's ±0.02 sampling noise. Run
``--aa`` (both arms identical) on the same battery to measure that floor; every summary
-prints the paired sd, the 2 SE band and how many pairs this spread would need before
-±0.02 is resolvable (``bench/_ab_report.NOISE_SIGMAS``). Measured 2026-08-24: two A/A
+prints the paired sd, the 95 % t-interval and how many pairs this spread would need
+before ±0.02 is resolvable (``bench/stats.py``). Measured 2026-08-24: two A/A
runs of one prompt came back +0.344 and -0.100 — "keep" and "revert" from identical code.
Layout of ``--out``: ``ab.json`` (the arms, options and variant env) ·
@@ -236,7 +236,7 @@ def child_env(arm: str, opts: AbOptions, base: dict[str, str] | None = None) ->
Under ``--aa`` the variant arm gets the CONTROL environment: the two arms then run
byte-identical code and the measured delta is the rig's own noise floor, which is the
- number every A/B verdict has to be read against (``bench/_ab_report.NOISE_SIGMAS``).
+ number every A/B verdict has to be read against (the Confidence block of ``summary.md``).
"""
env = dict(os.environ if base is None else base)
for k in opts.variant_env:
diff --git a/eval/bench/ab_view.py b/eval/bench/ab_view.py
index 21715636..6cd4b8eb 100644
--- a/eval/bench/ab_view.py
+++ b/eval/bench/ab_view.py
@@ -30,6 +30,7 @@ from pathlib import Path
for _p in (Path(__file__).resolve().parents[2] / "harness", Path(__file__).resolve().parents[1]):
sys.path.insert(0, str(_p)) # this tree's codeverse3d (harness/) + the `bench` package (eval/)
+from bench.stats import mean_ci # noqa: E402
from codeverse3d.addons import select # noqa: E402
SHEET_W = 1100
@@ -95,35 +96,44 @@ def load_run(run_dir: Path, arm: str) -> Run:
return r
-#: scored runs per arm below which this function will not name a winner, whatever the
-#: numbers say. A reference harness on the same model tier measured a run-to-run score
-#: sd of 0.159 against a re-judge sd of 0.013, giving a minimum detectable effect of
-#: 0.081 at n=30 — and it published, then retracted, several prompt findings because a
-#: promising first replicate turned out to be noise pointing the right way
-#: (interpenetration −0.40 in replicate 1, +0.03 in replicate 2, pooled p=0.405).
-MIN_RUNS_PER_ARM = 3
+#: scored pairs below which this function will not name a winner, whatever the numbers
+#: say. A reference harness on the same model tier measured a run-to-run score sd of
+#: 0.159 against a re-judge sd of 0.013, giving a minimum detectable effect of 0.081 at
+#: n=30 — and it published, then retracted, several prompt findings because a promising
+#: first replicate turned out to be noise pointing the right way (interpenetration −0.40
+#: in replicate 1, +0.03 in replicate 2, pooled p=0.405).
+MIN_PAIRS = 3
+
+
+def paired_by_brief(a: list[Run], b: list[Run]) -> dict[str, tuple[Run | None, Run | None]]:
+ """``{brief: (A run, B run)}`` — the pairing the page shows and the verdict reads. A
+ brief run twice in one arm (a redo) is its LAST run, the rule of every bench journal."""
+ ka: dict[str, Run] = {}
+ kb: dict[str, Run] = {}
+ for rs, by in ((a, ka), (b, kb)):
+ for r in rs:
+ by[r.brief or r.slug] = r
+ return {k: (ka.get(k), kb.get(k)) for k in {**ka, **kb}}
def verdict(a: list[Run], b: list[Run]) -> tuple[str, str]:
- """(headline, why) — refuses to call a winner the sample cannot support."""
- sa = [x.picked for x in a if x.picked is not None]
- sb = [x.picked for x in b if x.picked is not None]
- if len(sa) < MIN_RUNS_PER_ARM or len(sb) < MIN_RUNS_PER_ARM:
- return ("Inconclusive — not enough scored runs",
- f"arm A scored {len(sa)} of {len(a)} runs, arm B {len(sb)} of {len(b)}; this needs "
- f"at least {MIN_RUNS_PER_ARM} per arm before a winner is named. A run that died "
- "before it scored is not an observation about the arm — it is a missing one.")
- ma, mb = statistics.mean(sa), statistics.mean(sb)
- # WITHIN-arm spread: how much runs of the SAME arm disagree. Pooling both arms would
- # fold the effect being measured into the yardstick and flatter any real difference.
- within = max(statistics.pstdev(sa), statistics.pstdev(sb), 1e-9)
- if abs(mb - ma) < within:
- return (f"Inconclusive — Δ {mb - ma:+.3f} is inside the within-arm spread ({within:.3f})",
- f"A {ma:.3f} (n={len(sa)}) vs B {mb:.3f} (n={len(sb)}). Runs of the same arm differ "
- "by more than the arms differ from each other, so this is not evidence.")
- return (f"B {'wins' if mb > ma else 'loses'} by {mb - ma:+.3f}",
- f"A {ma:.3f} (n={len(sa)}) vs B {mb:.3f} (n={len(sb)}); within-arm spread {within:.3f}. "
- "Worth a confirming replicate before it is believed.")
+ """(headline, why): B − A per paired brief and the 95 % t-interval of its mean
+ (``bench/stats.py``) — no winner unless that interval excludes zero."""
+ deltas = [rb.picked - ra.picked for ra, rb in paired_by_brief(a, b).values()
+ if ra is not None and rb is not None and ra.picked is not None and rb.picked is not None]
+ if len(deltas) < MIN_PAIRS:
+ scored_a, scored_b = (sum(x.picked is not None for x in rs) for rs in (a, b))
+ return ("Inconclusive — not enough scored pairs",
+ f"{len(deltas)} brief(s) scored in both arms (arm A scored {scored_a} of {len(a)} runs, arm B "
+ f"{scored_b} of {len(b)}); this needs at least {MIN_PAIRS} before a winner is named. A run that "
+ "died before it scored is not an observation about the arm — it is a missing one.")
+ ci = mean_ci(deltas)
+ if not ci.separated:
+ return (f"Inconclusive — Δ {ci.mean:+.3f} ± {ci.half:.3f} includes zero",
+ f"B − A over {ci.n} paired briefs: the 95 % t-interval of the mean includes zero — the pairs "
+ "disagree with each other by more than the mean moved, so this is not evidence.")
+ return (f"B {'wins' if ci.mean > 0 else 'loses'} by {ci.mean:+.3f} ± {ci.half:.3f}",
+ f"B − A over {ci.n} paired briefs, 95 % t-interval. Worth a confirming replicate before it is believed.")
def _num(v: object) -> str:
@@ -192,16 +202,11 @@ def build(runs_dir: Path, a_prefix: str, b_prefix: str, *, title: str,
a = [load_run(d, "A") for d in sorted(runs_dir.iterdir()) if d.is_dir() and d.name.startswith(a_prefix)]
b = [load_run(d, "B") for d in sorted(runs_dir.iterdir()) if d.is_dir() and d.name.startswith(b_prefix)]
head, why = verdict(a, b)
-
- # pair on the brief — the only thing that makes two runs comparable
- by_brief: dict[str, dict[str, Run]] = {}
- for r in a + b:
- by_brief.setdefault(r.brief or r.slug, {})[r.arm] = r
pairs = []
- for i, (brief, arms) in enumerate(by_brief.items()):
+ for i, (brief, (ra, rb)) in enumerate(paired_by_brief(a, b).items()):
# deterministic side-swap so the eye is not primed, stable across reloads
flip = bool(sum(ord(c) for c in brief) % 2)
- pairs.append(_pair(i, brief, arms.get("A"), arms.get("B"), flip))
+ pairs.append(_pair(i, brief, ra, rb, flip))
return TEMPLATE.format(
title=html.escape(title), head=html.escape(head), why=html.escape(why),
diff --git a/eval/bench/bestofk_report.py b/eval/bench/bestofk_report.py
index ed0d1799..a5f58544 100644
--- a/eval/bench/bestofk_report.py
+++ b/eval/bench/bestofk_report.py
@@ -38,6 +38,7 @@ from pathlib import Path
for _p in (Path(__file__).resolve().parents[2] / "harness", Path(__file__).resolve().parents[1]):
sys.path.insert(0, str(_p)) # this tree's codeverse3d (harness/) + the `bench` package (eval/)
+from bench.stats import mean_ci # noqa: E402
from codeverse3d.proc import read_jsonl_lenient # noqa: E402
#: judge repeatability on the calibration set (docs/PAPER_WRITING.md §2), used only to
@@ -125,13 +126,10 @@ def curve(one: dict[str, list[float]], harness: dict[str, float], ks: list[int])
if not pairs:
continue
deltas = [h - b for _, b, h in pairs]
- wins = sum(1 for d in deltas if d > 0)
- losses = sum(1 for d in deltas if d < 0)
- mean = statistics.mean(deltas)
- se = statistics.stdev(deltas) / math.sqrt(len(deltas)) if len(deltas) > 1 else 0.0
+ ci = mean_ci(deltas)
out.append({"k": k, "n": len(pairs), "best_of_k": statistics.mean(b for _, b, _ in pairs),
- "harness": statistics.mean(h for _, _, h in pairs), "delta": mean,
- "ci": 1.96 * se, "wins": wins, "losses": losses,
+ "harness": statistics.mean(h for _, _, h in pairs), "delta": ci.mean,
+ "ci": ci.half, "wins": sum(d > 0 for d in deltas), "losses": sum(d < 0 for d in deltas),
"curse": JUDGE_SIGMA * math.sqrt(2 * math.log(k)) if k > 1 else 0.0})
return out
@@ -161,9 +159,9 @@ def report(root: Path, against: Path, *, baseline_prefix: str = "oneshot:") -> s
"", "| k | n | best-of-k | harness | harness − best-of-k | 95 % CI | W/L | curse bound |",
"|--:|--:|--:|--:|--:|---|---|--:|"]
for row in curve(one, harness, ks):
+ ci = "—" if row["ci"] is None else f"[{row['delta'] - row['ci']:+.3f}, {row['delta'] + row['ci']:+.3f}]"
lines.append(f"| {row['k']} | {row['n']} | {row['best_of_k']:.3f} | {row['harness']:.3f} | "
- f"{row['delta']:+.3f} | [{row['delta'] - row['ci']:+.3f}, {row['delta'] + row['ci']:+.3f}] | "
- f"{row['wins']}/{row['losses']} | {row['curse']:+.3f} |")
+ f"{row['delta']:+.3f} | {ci} | {row['wins']}/{row['losses']} | {row['curse']:+.3f} |")
counts = sorted({len(v) for v in one.values()})
lines += ["", f"reps per prompt: {counts[0]}–{counts[-1]}"]
return "\n".join(lines)
diff --git a/eval/bench/complexity_report.py b/eval/bench/complexity_report.py
index 00eb1dfb..9c926eba 100644
--- a/eval/bench/complexity_report.py
+++ b/eval/bench/complexity_report.py
@@ -24,7 +24,6 @@ from __future__ import annotations
import argparse
import csv
import json
-import math
import sys
from collections.abc import Iterable, Sequence
from pathlib import Path
@@ -33,8 +32,8 @@ from typing import Any
for _p in (Path(__file__).resolve().parents[2] / "harness", Path(__file__).resolve().parents[1]):
sys.path.insert(0, str(_p)) # this tree's codeverse3d (harness/) + the `bench` package (eval/)
+from bench.stats import correlation # noqa: E402
from codeverse3d.addons import select # noqa: E402
-from codeverse3d.addons.calibration import _ranks # noqa: E402 — tie-averaged ranks, one copy
from codeverse3d.contracts.run import RunId # noqa: E402
from codeverse3d.proc import read_json_or_none # noqa: E402
from codeverse3d.record.record import find_run_dirs # noqa: E402
@@ -198,32 +197,13 @@ def _pairs(rows: Sequence[Row], x: str, y: str) -> tuple[list[float], list[float
return xs, ys
-def pearson(xs: Sequence[float], ys: Sequence[float]) -> float | None:
- n = len(xs)
- if n < 3:
- return None
- mx, my = sum(xs) / n, sum(ys) / n
- sxy = sum((a - mx) * (b - my) for a, b in zip(xs, ys, strict=False))
- sxx = sum((a - mx) ** 2 for a in xs)
- syy = sum((b - my) ** 2 for b in ys)
- if sxx <= 0 or syy <= 0:
- return None
- return sxy / math.sqrt(sxx * syy)
-
-
-def spearman(xs: Sequence[float], ys: Sequence[float]) -> float | None:
- if len(xs) < 3:
- return None
- return pearson(_ranks(xs), _ranks(ys))
-
-
def correlations(rows: Sequence[Row], targets: Sequence[str], predictors: Sequence[str]) -> list[dict[str, Any]]:
out = []
for t in targets:
entry: dict[str, Any] = {"target": t}
for p in predictors:
xs, ys = _pairs(rows, p, t)
- entry[p] = (pearson(xs, ys), spearman(xs, ys), len(xs))
+ entry[p] = (correlation(xs, ys), correlation(xs, ys, ranked=True), len(xs))
out.append(entry)
return out
diff --git a/eval/bench/h2h_glb.py b/eval/bench/h2h_glb.py
index 9c153840..9bd88811 100644
--- a/eval/bench/h2h_glb.py
+++ b/eval/bench/h2h_glb.py
@@ -46,8 +46,8 @@ for _p in (Path(__file__).resolve().parents[2] / "harness", Path(__file__).resol
sys.path.insert(0, str(_p)) # this tree's codeverse3d (harness/) + the `bench` package (eval/)
from bench._fixed_eval import RUBRIC # noqa: E402
-from bench.h2h_scene import sign_test # noqa: E402
from bench.run_bench import Battery, BenchPrompt # noqa: E402
+from bench.stats import sign_test # noqa: E402
from codeverse3d.addons import select # noqa: E402
JUDGE_MODEL = "gemini:gemini-3.1-pro-preview"
@@ -224,10 +224,9 @@ def _stats(rows: list[Row], *, visual: bool = False) -> str:
if not d:
return "n=0 (no pair judged on both sides)"
sd = statistics.stdev(d) if len(d) > 1 else 0.0
- wins, losses = sum(x > 0 for x in d), sum(x < 0 for x in d)
- n_nz, _, p = sign_test(d)
+ wins, losses, p = sign_test(d)
return (f"n={len(d)} mean Δ(ours−theirs)={statistics.mean(d):+.3f} sd={sd:.3f} "
- f"wins/losses/ties={wins}/{losses}/{len(d) - wins - losses} sign-test p={'n/a' if n_nz == 0 else f'{p:.3f}'}")
+ f"wins/losses/ties={wins}/{losses}/{len(d) - wins - losses} sign-test p={'n/a' if p is None else f'{p:.3f}'}")
def summary_md(rows: list[Row]) -> str:
diff --git a/eval/bench/h2h_scene.py b/eval/bench/h2h_scene.py
index e30a00f8..f4ccd58d 100644
--- a/eval/bench/h2h_scene.py
+++ b/eval/bench/h2h_scene.py
@@ -28,7 +28,6 @@ from __future__ import annotations
import argparse
import json
-import math
import statistics
import sys
from datetime import datetime
@@ -42,6 +41,7 @@ for _p in (Path(__file__).resolve().parents[2] / "harness", Path(__file__).resol
sys.path.insert(0, str(_p)) # this tree's codeverse3d (harness/) + the `bench` package (eval/)
from bench.run_bench import Battery, BenchPrompt # noqa: E402
+from bench.stats import sign_test # noqa: E402
from codeverse3d.addons import select # noqa: E402
from codeverse3d.contracts.artifacts import RenderSet, RenderView # noqa: E402
from codeverse3d.contracts.common import Language, Track # noqa: E402
@@ -220,17 +220,6 @@ def sheet(row_id: str, theirs: list[Path], ours: list[Path], out_png: Path, thum
# ----------------------------------------------------------------------------- summary
-def sign_test(deltas: list[float]) -> tuple[int, int, float]:
- """(n_nonzero, n_positive, two-sided exact binomial p) for ours − theirs."""
- nz = [d for d in deltas if d != 0]
- n, k = len(nz), sum(1 for d in nz if d > 0)
- if n == 0:
- return 0, 0, 1.0
- cdf = lambda m: sum(math.comb(n, i) for i in range(m + 1)) / 2 ** n # noqa: E731
- p = min(1.0, 2 * min(cdf(k), 1 - cdf(k - 1)))
- return n, k, p
-
-
def summary_md(rows: list[Row]) -> str:
done = [r for r in rows if r.ours is not None and r.delta is not None]
lines = ["# h2h_scene_v1 — scene track vs scene_multifile(_graphics)", "",
@@ -245,10 +234,10 @@ def summary_md(rows: list[Row]) -> str:
f"{t.duration_s / 60:.1f} / {t.cost_usd:.2f} | {f'{o.minutes:.1f} / {o.cost_usd:.2f}' if o else '—'} | {t.n_views}/{o.n_views if o else 0} |")
if done:
d = [r.delta for r in done if r.delta is not None]
- n, k, p = sign_test(d)
+ up, down, p = sign_test(d)
sd = statistics.stdev(d) if len(d) > 1 else 0.0
lines += ["", f"**Paired (n={len(d)})**: mean Δ = {statistics.mean(d):+.3f}, sd = {sd:.3f}, "
- f"sign test: ours better on {k}/{n} (two-sided p = {p:.3f}).",
+ f"sign test: ours better on {up}/{up + down} (two-sided p = {'n/a' if p is None else f'{p:.3f}'}).",
f"Mean minutes/scene: theirs {statistics.mean(r.theirs.duration_s for r in done) / 60:.1f}, ours {statistics.mean(r.ours.minutes for r in done if r.ours):.1f}; "
f"mean $/scene: theirs {statistics.mean(r.theirs.cost_usd for r in done):.2f}, ours {statistics.mean(r.ours.cost_usd for r in done if r.ours):.2f}."]
else:
diff --git a/eval/bench/paired_compare.py b/eval/bench/paired_compare.py
index a657be1a..cf6d2b71 100644
--- a/eval/bench/paired_compare.py
+++ b/eval/bench/paired_compare.py
@@ -21,7 +21,6 @@ from __future__ import annotations
import argparse
import json
-import math
import statistics
import sys
from collections import defaultdict
@@ -35,27 +34,9 @@ for _p in (REPO, Path(__file__).resolve().parents[1]): # its codeverse3d +
sys.path.insert(0, str(_p))
from bench._ab_report import _fmt as _f # noqa: E402
-from bench._ab_report import _sign_test # noqa: E402
from bench._compare_report import CellResult # noqa: E402
from bench._jsonl import read_jsonl # noqa: E402
-
-# two-sided 97.5 % Student-t quantiles by degrees of freedom (df 1..30, then 40/60/120, ∞);
-# a table, not scipy: the [urdf] extra is optional and this must run on a [dev] install
-_T975 = {1: 12.706, 2: 4.303, 3: 3.182, 4: 2.776, 5: 2.571, 6: 2.447, 7: 2.365, 8: 2.306, 9: 2.262,
- 10: 2.228, 11: 2.201, 12: 2.179, 13: 2.160, 14: 2.145, 15: 2.131, 16: 2.120, 17: 2.110,
- 18: 2.101, 19: 2.093, 20: 2.086, 21: 2.080, 22: 2.074, 23: 2.069, 24: 2.064, 25: 2.060,
- 26: 2.056, 27: 2.052, 28: 2.048, 29: 2.045, 30: 2.042, 40: 2.021, 60: 2.000, 120: 1.980}
-
-
-def t975(df: int) -> float:
- if df <= 0:
- return math.nan
- if df in _T975:
- return _T975[df]
- for bound in (40, 60, 120):
- if df < bound:
- return _T975[bound]
- return 1.960
+from bench.stats import mean_ci, sign_test # noqa: E402
class PairedStats(BaseModel):
@@ -147,27 +128,22 @@ def paired(cells: dict[tuple[str, str], CellResult], harness_arm: str, oneshot_a
if st.n == 0:
st.verdict = "too few pairs"
return st
- deltas = list(st.deltas.values())
+ ci = mean_ci(list(st.deltas.values()))
st.mean_harness = round(statistics.fmean(hs), 4)
st.mean_oneshot = round(statistics.fmean(os_), 4)
- st.mean_delta = round(statistics.fmean(deltas), 4)
- st.wins = sum(d > 0 for d in deltas)
- st.losses = sum(d < 0 for d in deltas)
+ st.mean_delta = round(ci.mean, 4)
+ st.wins, st.losses, st.sign_p = sign_test(list(st.deltas.values()))
st.ties = st.n - st.wins - st.losses
- st.sign_p = _sign_test(deltas)["sign_p"] # type: ignore[assignment]
st.pass_rate_harness = round(sum(hp) / len(hp), 4) if hp else None
st.pass_rate_oneshot = round(sum(op) / len(op), 4) if op else None
st.build_ok_harness = round(sum(hb) / st.n, 4)
st.build_ok_oneshot = round(sum(ob) / st.n, 4)
- if st.n >= 2:
- sd = statistics.stdev(deltas)
- se = sd / math.sqrt(st.n)
- half = t975(st.n - 1) * se
- st.sd_delta, st.se_delta = round(sd, 4), round(se, 4)
- st.ci95_low, st.ci95_high = round(st.mean_delta - half, 4), round(st.mean_delta + half, 4)
- st.verdict = "supported" if (st.ci95_low > 0 or st.ci95_high < 0) else "unsupported"
- else:
+ if ci.half is None:
st.verdict = "too few pairs"
+ return st
+ st.sd_delta, st.se_delta = round(ci.sd, 4), round(ci.se, 4)
+ st.ci95_low, st.ci95_high = round(st.mean_delta - ci.half, 4), round(st.mean_delta + ci.half, 4)
+ st.verdict = "supported" if ci.separated else "unsupported"
return st
diff --git a/eval/bench/rejudge_offline.py b/eval/bench/rejudge_offline.py
index 8d57ed4c..343e88dd 100644
--- a/eval/bench/rejudge_offline.py
+++ b/eval/bench/rejudge_offline.py
@@ -43,18 +43,22 @@ from pathlib import Path
from pydantic import BaseModel, Field
-from codeverse3d.addons.calibration import _run_label
-from codeverse3d.contracts.artifacts import GateReport, Severity
-from codeverse3d.contracts.plan import AcceptanceItem
-from codeverse3d.contracts.run import RoundRecord
-from codeverse3d.judges.rubrics import (
+for _p in (Path(__file__).resolve().parents[2] / "harness", Path(__file__).resolve().parents[1]):
+ sys.path.insert(0, str(_p)) # this tree's codeverse3d (harness/) + the `bench` package (eval/)
+
+from bench.stats import correlation # noqa: E402
+from codeverse3d.addons.calibration import _run_label # noqa: E402
+from codeverse3d.contracts.artifacts import GateReport, Severity # noqa: E402
+from codeverse3d.contracts.plan import AcceptanceItem # noqa: E402
+from codeverse3d.contracts.run import RoundRecord # noqa: E402
+from codeverse3d.judges.rubrics import ( # noqa: E402
SCORING_VERSION,
JudgeOutput,
Rubric,
aggregate_samples,
load_rubric,
)
-from codeverse3d.proc import read_json_or_none
+from codeverse3d.proc import read_json_or_none # noqa: E402
TOL = 1e-9
@@ -204,12 +208,6 @@ def replay_round(path: Path, rubric: Rubric | None = None) -> ReplayRow | None:
)
-def _pearson(xs: list[float], ys: list[float]) -> float | None:
- if len(xs) < 3 or len(set(xs)) < 2 or len(set(ys)) < 2:
- return None
- return round(statistics.correlation(xs, ys), 4)
-
-
def replay_corpus(roots: list[Path], *, rubric_name: str, rubric: Rubric | None = None,
kinds: set[str] | None = None) -> ReplayReport:
rows: list[ReplayRow] = []
@@ -255,7 +253,7 @@ def replay_corpus(roots: list[Path], *, rubric_name: str, rubric: Rubric | None
spike_600_after=sum(1 for v in after if abs(v - 0.6) < 1e-6),
sd_before=round(statistics.pstdev(before), 4) if len(before) > 1 else 0.0,
sd_after=round(statistics.pstdev(after), 4) if len(after) > 1 else 0.0,
- pearson_errors_before=_pearson(errs, before), pearson_errors_after=_pearson(errs, after),
+ pearson_errors_before=correlation(errs, before), pearson_errors_after=correlation(errs, after),
cap_counts_before=dict(caps_b), cap_counts_after=dict(caps_a),
defect_counts_before=dict(def_b), defect_counts_after=dict(def_a),
overridden_counts=dict(Counter(d for r in ok for d in r.overridden)),
diff --git a/eval/bench/skill_targets.py b/eval/bench/skill_targets.py
index 0169df66..6f03dc85 100644
--- a/eval/bench/skill_targets.py
+++ b/eval/bench/skill_targets.py
@@ -33,6 +33,7 @@ from typing import Any
for _p in (Path(__file__).resolve().parents[2] / "harness", Path(__file__).resolve().parents[1]):
sys.path.insert(0, str(_p)) # this tree's codeverse3d (harness/) + the `bench` package (eval/)
+from bench.stats import mean_ci, n_to_resolve # noqa: E402
from codeverse3d.addons.skill_targets import ( # noqa: E402
SRC_ARTIFACT,
SRC_BUILD,
@@ -313,20 +314,19 @@ def ab_rows(arms: dict[str, Path], targets: list[Target], *, which: str,
def confidence(deltas: list[float], control_mean: float, effect: float = 0.25) -> dict[str, Any]:
- """Paired sd, the 2 SE band, and how many pairs a given effect would need.
+ """Paired sd, the 95 % t-interval's half-width, and how many pairs a given effect needs.
- Same shape as the Confidence block ``bench/ab_plan.py`` prints for the judged score
- (docs/EVAL.md §8), because the question is the same one and the answer is not: a
- deterministic count has its own sd and it is NOT zero. ``effect`` is the fraction of
- the control mean that counts as a real move.
+ The same rule as the Confidence block ``bench/ab_plan.py`` prints for the judged score
+ (``bench/stats.py``, docs/EVAL.md §8), because the question is the same one and the
+ answer is not: a deterministic count has its own sd and it is NOT zero. ``effect`` is
+ the fraction of the control mean that counts as a real move.
"""
- if len(deltas) < 2:
+ ci = mean_ci(deltas)
+ if ci.sd is None:
return {"sd": None, "se": None, "ci95": None, "n_to_resolve": None}
- sd = statistics.stdev(deltas)
- se = sd / len(deltas) ** 0.5
want = abs(control_mean) * effect
- n = None if not want or not sd else max(2, int(round((2 * sd / want) ** 2)))
- return {"sd": sd, "se": se, "ci95": 2 * se, "n_to_resolve": n,
+ return {"sd": ci.sd, "se": ci.se, "ci95": ci.half,
+ "n_to_resolve": n_to_resolve(ci.sd, want) if want and ci.sd else None,
"resolvable_effect": want}
@@ -351,7 +351,7 @@ def print_battery(rows: list[dict], per_run: bool) -> None:
def print_ab(rows: list[dict], per_run: bool) -> None:
print(f"{'skill':<28} {'metric':<28} {'dir':<5} {'n':>4} {'control':>9} {'variant':>9} "
- f"{'delta':>9} b/w/t {'sd':>8} {'+/-2SE':>8} n to resolve 25%")
+ f"{'delta':>9} b/w/t {'sd':>8} {'+/-95%t':>8} n to resolve 25%")
for r in rows:
if not r["n"]:
print(f"{r['skill']:<28} {r['metric']:<28} {r['direction']:<5} 0 (no paired run)")
diff --git a/eval/bench/stats.py b/eval/bench/stats.py
new file mode 100644
index 00000000..536dac2b
--- /dev/null
+++ b/eval/bench/stats.py
@@ -0,0 +1,101 @@
+"""The statistics the bench reports state — one rule each, so two reports never disagree
+about the same numbers.
+
+* **The interval** is the Student-t one: ``mean ± t(0.975, n−1) · sd/√n``. A battery is
+ 3–40 pairs, and there the normal ``1.96`` or a round ``2`` is too narrow: at n = 8
+ (t = 2.365) they understate the 95 % half-width by 17 % / 15 %, at n = 4 (t = 3.182) by
+ 38 % / 37 %. t tends to 1.96 as n grows, so it is the one rule that is right at both
+ ends. A change is *separated* from noise when its interval excludes zero.
+* **The sign test** is exact and two-sided over the non-zero deltas: how CONSISTENT a
+ change is, which an 8-prompt battery can show when its mean cannot.
+* **Correlation** is ``statistics.correlation`` (Pearson; Spearman with ``ranked``), and
+ ``None`` below three points or on a constant input, where an r means nothing.
+
+The binomial rate interval (Wilson) and Fisher's exact test stay in
+``plan_stage_report.py``, the one report that states a rate.
+"""
+
+from __future__ import annotations
+
+import math
+import statistics
+from collections.abc import Sequence
+from dataclasses import dataclass
+
+# two-sided 97.5 % Student-t quantiles by degrees of freedom (df 1..30, then 40/60/120, ∞);
+# a table, not scipy: the [urdf] extra is optional and this must run on a [dev] install
+_T975 = {1: 12.706, 2: 4.303, 3: 3.182, 4: 2.776, 5: 2.571, 6: 2.447, 7: 2.365, 8: 2.306, 9: 2.262,
+ 10: 2.228, 11: 2.201, 12: 2.179, 13: 2.160, 14: 2.145, 15: 2.131, 16: 2.120, 17: 2.110,
+ 18: 2.101, 19: 2.093, 20: 2.086, 21: 2.080, 22: 2.074, 23: 2.069, 24: 2.064, 25: 2.060,
+ 26: 2.056, 27: 2.052, 28: 2.048, 29: 2.045, 30: 2.042, 40: 2.021, 60: 2.000, 120: 1.980}
+
+
+def t975(df: int) -> float:
+ """The 97.5 % Student-t quantile (between table rows, the next row up: conservative)."""
+ if df <= 0:
+ return math.nan
+ if df in _T975:
+ return _T975[df]
+ for bound in (40, 60, 120):
+ if df < bound:
+ return _T975[bound]
+ return 1.960
+
+
+@dataclass(frozen=True)
+class MeanCI:
+ """A mean with its 95 % t-interval; ``sd`` / ``se`` / ``half`` are None below two values."""
+
+ n: int
+ mean: float
+ sd: float | None = None
+ se: float | None = None
+ half: float | None = None
+
+ @property
+ def separated(self) -> bool:
+ """The interval excludes zero: the change is outside the run-to-run noise."""
+ return self.half is not None and abs(self.mean) > self.half
+
+
+def mean_ci(xs: Sequence[float]) -> MeanCI:
+ """The mean of ``xs`` (at least one value) and its 95 % t-interval."""
+ mean = statistics.fmean(xs)
+ if len(xs) < 2:
+ return MeanCI(n=len(xs), mean=mean)
+ sd = statistics.stdev(xs)
+ se = sd / math.sqrt(len(xs))
+ return MeanCI(n=len(xs), mean=mean, sd=sd, se=se, half=t975(len(xs) - 1) * se)
+
+
+def n_to_resolve(sd: float, width: float) -> int:
+ """How many pairs a spread of ``sd`` needs before the t-interval's half-width fits
+ inside ``width`` — the honest answer to "would one more prompt settle this?"."""
+ if sd <= 0:
+ return 2
+ n = max(2, math.ceil((1.96 * sd / width) ** 2)) # the large-n answer; t only adds to it
+ while t975(n - 1) * sd / math.sqrt(n) > width:
+ n += 1
+ return n
+
+
+def sign_test(deltas: Sequence[float]) -> tuple[int, int, float | None]:
+ """``(up, down, p)``: the exact two-sided sign test on the non-zero deltas, ``p``
+ rounded to 4 places and None when every delta is zero."""
+ up = sum(d > 0 for d in deltas)
+ down = sum(d < 0 for d in deltas)
+ n = up + down
+ if n == 0:
+ return 0, 0, None
+ tail = sum(math.comb(n, i) for i in range(max(up, down), n + 1)) / 2 ** n
+ return up, down, round(min(1.0, 2 * tail), 4)
+
+
+def correlation(xs: Sequence[float], ys: Sequence[float], *, ranked: bool = False) -> float | None:
+ """Pearson r, or Spearman ρ with ``ranked`` (ties share their average rank)."""
+ if len(xs) < 3 or len(set(xs)) < 2 or len(set(ys)) < 2:
+ return None
+ return statistics.correlation(xs, ys, method="ranked" if ranked else "linear")
+
+
+__all__ = ["MeanCI", "correlation", "mean_ci", "n_to_resolve", "sign_test", "t975"]
diff --git a/eval/tests/test_ab_plan.py b/eval/tests/test_ab_plan.py
index 07541dc7..e8fea592 100644
--- a/eval/tests/test_ab_plan.py
+++ b/eval/tests/test_ab_plan.py
@@ -15,7 +15,6 @@ if str(REPO) not in sys.path:
from bench._ab_report import ( # noqa: E402
CONTROL,
KEEP_DELTA,
- NOISE_SIGMAS,
VARIANT,
PairOutcome,
arm_summary,
@@ -42,6 +41,7 @@ from bench.ab_plan import ( # noqa: E402
worker_argv,
)
from bench.run_bench import Battery # noqa: E402
+from bench.stats import n_to_resolve, t975 # noqa: E402
BATTERY = REPO / "bench" / "prompts" / "compare_v1.yaml"
@@ -128,9 +128,10 @@ def test_a_verdict_states_the_spread_it_was_decided_on():
"keep" — so the report has to carry the noise beside the word."""
v = verdict_of(_pairs(0.30, -0.20, 0.10, 0.05, -0.10, 0.25, 0.02, -0.15))
assert v.sd_delta is not None and v.se_delta == pytest.approx(v.sd_delta / 8 ** 0.5, abs=1e-3)
+ assert v.ci_half == pytest.approx(t975(7) * v.se_delta, abs=1e-3), "the 95 % t-interval, n - 1 = 7 df"
assert not v.separated and "NOT separated from noise" in v.caution
# the honest answer to "would one more prompt settle this?": at this spread, hundreds
- assert v.n_for_power == pytest.approx((NOISE_SIGMAS * v.sd_delta / KEEP_DELTA) ** 2, rel=0.01)
+ assert v.n_for_power == pytest.approx(n_to_resolve(v.sd_delta, KEEP_DELTA), rel=0.01)
assert v.n_for_power > 100
diff --git a/eval/tests/test_complexity_report.py b/eval/tests/test_complexity_report.py
index 61b49d75..c1c539c6 100644
--- a/eval/tests/test_complexity_report.py
+++ b/eval/tests/test_complexity_report.py
@@ -9,6 +9,7 @@ from pathlib import Path
import pytest
from bench import complexity_report as CR
+from bench.stats import correlation
from codeverse3d.contracts.artifacts import Measurement
REPO = Path(__file__).resolve().parents[1]
@@ -59,8 +60,8 @@ def test_collect_and_report_over_a_battery(tmp_path: Path) -> None:
assert rows[0]["plan_parts"] == 2 and rows[0]["n_materials"] == 3
# the whole point of the study: a monotone fall shows up as a strong negative r
xs, ys = CR._pairs(rows, "index", "overall")
- assert CR.pearson(xs, ys) < -0.98
- assert CR.spearman(xs, ys) == pytest.approx(-1.0)
+ assert correlation(xs, ys) < -0.98
+ assert correlation(xs, ys, ranked=True) == pytest.approx(-1.0)
money = CR.dollars_per_point(rows)
assert money["runs"] == 3 and money["total_usd"] == pytest.approx(5.0)
assert money["usd_per_point"] == pytest.approx(5.0 / (100 * (0.35 + 0.55 + 0.75)), abs=5e-5)
diff --git a/eval/tests/test_infra_failures.py b/eval/tests/test_infra_failures.py
index bc9ab72f..0f207af0 100644
--- a/eval/tests/test_infra_failures.py
+++ b/eval/tests/test_infra_failures.py
@@ -310,25 +310,37 @@ def test_stream_attempt_budget_and_504_are_infra():
def test_the_ab_viewer_refuses_to_call_a_winner_it_cannot_support():
+ """B − A per brief — the pairs the page shows — and the 95 % t-interval of its mean."""
from bench.ab_view import Run, verdict
def arm(name, *scores):
- return [Run(slug=f"{name}{i}", arm=name, picked=s, status="max_rounds") for i, s in enumerate(scores)]
+ return [Run(slug=f"{name}{i}", arm=name, brief=f"brief {i}", picked=s, status="max_rounds")
+ for i, s in enumerate(scores)]
cases = [
- ((0.7,), (0.9,), "Inconclusive"),
- ((0.70, 0.72), (0.74, 0.76), "Inconclusive"),
- ((0.50, 0.70, 0.90), (0.56, 0.76, 0.96), "Inconclusive"),
+ ((0.7,), (0.9,), "Inconclusive"), # one pair
+ ((0.70, 0.72), (0.74, 0.76), "Inconclusive"), # two pairs
+ ((0.50, 0.70, 0.90), (0.56, 0.66, 0.96), "Inconclusive"), # +0.06 / -0.04 / +0.06
((0.30, 0.32, 0.31), (0.80, 0.82, 0.81), "B wins"),
+ # the same +0.06 on every brief is a consistent paired gain: the unpaired rule this
+ # replaced called it noise because the BRIEFS differ by more than 0.06 — the very
+ # variance pairing on the brief removes
+ ((0.50, 0.70, 0.90), (0.56, 0.76, 0.96), "B wins"),
]
for a_scores, b_scores, expected in cases:
head, _ = verdict(arm("a", *a_scores), arm("b", *b_scores))
assert head.startswith(expected), head
# a run that never scored must not be counted as an observation
- a = arm("a", 0.5, 0.5) + [Run(slug="a9", arm="a", picked=None, status="failed")]
+ a = arm("a", 0.5, 0.5) + [Run(slug="a9", arm="a", brief="brief 9", picked=None, status="failed")]
head, why = verdict(a, arm("b", 0.5))
- assert head.startswith("Inconclusive") and "1 of 1" in why
+ assert head.startswith("Inconclusive") and "1 of 1" in why and "2 of 3" in why
+
+ # a brief run twice in one arm is its LAST run, as on the page; a brief only one arm ran is no pair
+ b = arm("b", 0.1, 0.1, 0.1) + [Run(slug="b0r", arm="b", brief="brief 0", picked=0.9),
+ Run(slug="bx", arm="b", brief="brief x", picked=0.0)]
+ head, why = verdict(arm("a", 0.5, 0.5, 0.5), b)
+ assert head.startswith("Inconclusive") and "over 3 paired briefs" in why
def test_the_default_generator_and_the_cost_router_name_the_same_model():
"""`3dcode cost` prints the default=True GENERATOR route as "the default"; if it disagrees with
diff --git a/eval/tests/test_paired_compare.py b/eval/tests/test_paired_compare.py
index e43f4d45..9da16936 100644
--- a/eval/tests/test_paired_compare.py
+++ b/eval/tests/test_paired_compare.py
@@ -11,7 +11,8 @@ if str(REPO) not in sys.path:
sys.path.insert(0, str(REPO))
from bench._compare_report import CellResult # noqa: E402
-from bench.paired_compare import analyse, latest_cells, main, paired, t975 # noqa: E402
+from bench.paired_compare import analyse, latest_cells, main, paired # noqa: E402
+from bench.stats import t975 # noqa: E402
HA, OA = "harness:gemini-cli:gemini-3.6-flash", "oneshot:gemini:x"
@@ -53,11 +54,6 @@ def test_interval_crossing_zero_is_unsupported_and_tiers_split():
assert by["easy"].n == 2 and by["hard"].n == 2 and by["hard"].wins == 1 and by["hard"].losses == 1
-def test_t_quantiles_are_monotone_and_end_at_normal():
- assert t975(1) > t975(5) > t975(30) > t975(59) > t975(1000) == 1.96
- assert t975(0) != t975(0) # nan for no degrees of freedom
-
-
def test_cli_writes_paired_md_and_json(tmp_path):
rows = [_cell("p0", HA, 0.8), _cell("p0", OA, 0.5), _cell("p1", HA, 0.7), _cell("p1", OA, 0.6)]
(tmp_path / "results.jsonl").write_text("\n".join(json.dumps(r.model_dump(mode="json")) for r in rows) + "\n")
diff --git a/eval/tests/test_skill_targets_readout.py b/eval/tests/test_skill_targets_readout.py
index 1191e4fb..e30c08e3 100644
--- a/eval/tests/test_skill_targets_readout.py
+++ b/eval/tests/test_skill_targets_readout.py
@@ -118,12 +118,13 @@ def test_the_cli_runs_over_a_synthetic_battery(tmp_path, capsys):
def test_the_confidence_block_says_how_many_pairs_an_effect_needs():
from bench.skill_targets import confidence
+ from bench.stats import t975
c = confidence([-1.0, 1.0, -1.0, 1.0], control_mean=4.0)
assert c["sd"] == pytest.approx(1.1547, rel=1e-3)
- assert c["ci95"] == pytest.approx(2 * c["se"])
+ assert c["ci95"] == pytest.approx(t975(3) * c["se"]) # the 95 % t-interval, 3 df
assert c["resolvable_effect"] == 1.0 # 25% of a control mean of 4
- assert c["n_to_resolve"] == 5 # (2*1.1547/1.0)^2
+ assert c["n_to_resolve"] == 8 # first n with t(n-1)*1.1547/sqrt(n) <= 1.0
assert confidence([1.0], control_mean=4.0)["sd"] is None
diff --git a/eval/tests/test_stats.py b/eval/tests/test_stats.py
new file mode 100644
index 00000000..e49a1fea
--- /dev/null
+++ b/eval/tests/test_stats.py
@@ -0,0 +1,41 @@
+"""``bench/stats.py``: the one interval, sign test and correlation every bench report states."""
+
+from __future__ import annotations
+
+import math
+
+import pytest
+
+from bench.stats import correlation, mean_ci, n_to_resolve, sign_test, t975
+
+
+def test_t_quantiles_are_monotone_and_end_at_normal():
+ assert t975(1) > t975(5) > t975(30) > t975(59) > t975(1000) == 1.96
+ assert t975(0) != t975(0) # nan for no degrees of freedom
+
+
+def test_the_interval_is_t_times_se_and_separation_means_it_excludes_zero():
+ ci = mean_ci([0.10, 0.11, 0.09, 0.12])
+ assert ci.se == pytest.approx(ci.sd / 2) and ci.half == pytest.approx(t975(3) * ci.se)
+ assert ci.separated
+ assert not mean_ci([0.3, -0.2, 0.1, -0.1]).separated
+ one = mean_ci([0.344])
+ assert (one.sd, one.se, one.half, one.separated) == (None, None, None, False), "one pair has no interval"
+
+
+def test_n_to_resolve_is_the_first_n_whose_interval_fits():
+ n = n_to_resolve(0.226, 0.02)
+ assert t975(n - 1) * 0.226 / math.sqrt(n) <= 0.02 < t975(n - 2) * 0.226 / math.sqrt(n - 1)
+ assert n_to_resolve(1.1547, 1.0) == 8 and n_to_resolve(0.0, 0.02) == 2
+
+
+def test_the_sign_test_is_exact_two_sided_and_drops_zeros():
+ assert sign_test([0.1] * 8) == (8, 0, round(2 / 2 ** 8, 4))
+ assert sign_test([0.2, 0.1, -0.1, 0.0]) == (2, 1, 1.0)
+ assert sign_test([0.0, 0.0]) == (0, 0, None)
+
+
+def test_correlation_needs_three_points_and_a_spread():
+ assert correlation([1, 2, 3], [2, 4, 6.5]) == pytest.approx(4.5 / math.sqrt(2 * 61 / 6))
+ assert correlation([1, 2, 3], [3, 1, 2], ranked=True) == pytest.approx(-0.5)
+ assert correlation([1, 2], [1, 2]) is None and correlation([1, 1, 1], [1, 2, 3]) is None