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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact paired significance tests for every entry in the portfolio.
|
| 2 |
+
|
| 3 |
+
python significance.py # every entry with verdicts on disk
|
| 4 |
+
python significance.py molperceive # one entry
|
| 5 |
+
python significance.py --stage # regenerate the verdict files first
|
| 6 |
+
|
| 7 |
+
WHAT IS TESTED, AND WHY THIS TEST
|
| 8 |
+
---------------------------------
|
| 9 |
+
Every eval in this portfolio is a PAIRED design: the same held-out row is answered by the
|
| 10 |
+
base and by the tuned model, in one process, under identical greedy decoding. Paired binary
|
| 11 |
+
outcomes call for McNemar's test, and because some of our discordant counts are small (and
|
| 12 |
+
because an exact test needs no large-sample assumption to defend), this uses the EXACT
|
| 13 |
+
McNemar test rather than the chi-square approximation.
|
| 14 |
+
|
| 15 |
+
Concordant rows carry no information about which model is better: a row both models get
|
| 16 |
+
right, or both get wrong, is equally likely under either hypothesis. So the test conditions
|
| 17 |
+
on the DISCORDANT rows, of which there are n = b + c:
|
| 18 |
+
|
| 19 |
+
b = base correct, tuned wrong (evidence for the base)
|
| 20 |
+
c = base wrong, tuned correct (evidence for the tuned model)
|
| 21 |
+
|
| 22 |
+
Under the null "the adapter is no better than the base", each discordant row is a fair coin,
|
| 23 |
+
so c ~ Binomial(n, 0.5). The two-sided exact p-value is
|
| 24 |
+
|
| 25 |
+
p = min(1, 2 * P(X >= max(b, c))) X ~ Binomial(n, 0.5)
|
| 26 |
+
|
| 27 |
+
computed with exact integer binomial coefficients, no floating-point survival function and
|
| 28 |
+
no normal approximation.
|
| 29 |
+
|
| 30 |
+
AgriReason is the one entry that is not scored by exact match. It was judged blind and
|
| 31 |
+
pairwise, so its verdicts are wins, losses and ties. Ties are DISCARDED rather than split,
|
| 32 |
+
which is the standard sign test and the conservative choice: splitting ties would inflate
|
| 33 |
+
the effective sample and flatter the result. The same binomial machinery then applies, with
|
| 34 |
+
b = base wins and c = tuned wins.
|
| 35 |
+
|
| 36 |
+
WHAT A SMALL p DOES AND DOES NOT MEAN
|
| 37 |
+
-------------------------------------
|
| 38 |
+
It means the measured difference is very unlikely to be sampling noise. It says nothing
|
| 39 |
+
about whether the held-out slice is representative, whether the labels are right, or
|
| 40 |
+
whether the task is worth doing. Those are argued elsewhere on each card and are not
|
| 41 |
+
statistical questions. A p-value cannot rescue a bad slice, and this file does not pretend
|
| 42 |
+
otherwise.
|
| 43 |
+
"""
|
| 44 |
+
from __future__ import annotations
|
| 45 |
+
|
| 46 |
+
import argparse
|
| 47 |
+
import json
|
| 48 |
+
import math
|
| 49 |
+
import subprocess
|
| 50 |
+
import sys
|
| 51 |
+
from pathlib import Path
|
| 52 |
+
|
| 53 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 54 |
+
GEN = ROOT / "docs" / "eval" / "gcp"
|
| 55 |
+
EVAL = ROOT / "data" / "eval"
|
| 56 |
+
VER = ROOT / "docs" / "eval" / "significance"
|
| 57 |
+
PY = str(ROOT / ".venv" / "bin" / "python")
|
| 58 |
+
|
| 59 |
+
# entry -> list of (label, verdict file, field carrying the headline boolean)
|
| 60 |
+
# Verdict files carry one row per (row, column) pair with column in {base, tuned}.
|
| 61 |
+
PAIRED = {
|
| 62 |
+
"molperceive": [
|
| 63 |
+
("held-out, familiar scaffolds", "mp_v2__mp_held_seen.jsonl", "joint"),
|
| 64 |
+
("held-out, novel scaffolds", "mp_v2__mp_held_novel.jsonl", "joint"),
|
| 65 |
+
("real molecules, wwPDB CCD", "mp_v2__mp_real.jsonl", "joint"),
|
| 66 |
+
("hard shard, 4 to 9 rings", "mp_v2__mp_hard.jsonl", "joint"),
|
| 67 |
+
],
|
| 68 |
+
"flashfacts": [
|
| 69 |
+
("ff_held", "ff_v1__ff_held.jsonl", "strict_match"),
|
| 70 |
+
("ff_hard", "ff_v1__ff_hard.jsonl", "strict_match"),
|
| 71 |
+
("ff_ood", "ff_v1__ff_ood.jsonl", "strict_match"),
|
| 72 |
+
],
|
| 73 |
+
"chrono": [
|
| 74 |
+
("headline held-out", "chrono_v1__chrono_held.jsonl", "strict"),
|
| 75 |
+
("hard shard", "chrono_v1__chrono_held_hard.jsonl", "strict"),
|
| 76 |
+
("enumerated calendar", "chrono_v1__chrono_enumerated.jsonl", "strict"),
|
| 77 |
+
("range slice, 2031 to 2035", "chrono_v1__chrono_range.jsonl", "strict"),
|
| 78 |
+
],
|
| 79 |
+
"cashsage": [
|
| 80 |
+
("held-out", "cs_v2__cs_held.jsonl", "strict"),
|
| 81 |
+
("hard", "cs_v2__cs_hard.jsonl", "strict"),
|
| 82 |
+
("2026 rules", "cs_v2__cs_held_2026.jsonl", "strict"),
|
| 83 |
+
],
|
| 84 |
+
"hr": [
|
| 85 |
+
("held-out tool probes", "hr__hr_tool.jsonl", "overall"),
|
| 86 |
+
("harder probe set", "hr__hr_tool_hard.jsonl", "overall"),
|
| 87 |
+
],
|
| 88 |
+
"chart": [
|
| 89 |
+
("held-out ChartForge", "chart__chart_held.jsonl", "ok"),
|
| 90 |
+
],
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def two_sided_exact_binomial(b: int, c: int) -> float:
|
| 95 |
+
"""Exact two-sided binomial test at p=0.5 on b+c discordant pairs.
|
| 96 |
+
|
| 97 |
+
Integer arithmetic throughout: the tail is summed as an exact integer count of
|
| 98 |
+
outcomes and divided once at the end, so a p-value of 1e-150 is not an artifact of
|
| 99 |
+
accumulated float error. Returns 1.0 when there is nothing to test.
|
| 100 |
+
"""
|
| 101 |
+
n = b + c
|
| 102 |
+
if n == 0:
|
| 103 |
+
return 1.0
|
| 104 |
+
k = max(b, c)
|
| 105 |
+
tail = sum(math.comb(n, i) for i in range(k, n + 1))
|
| 106 |
+
# 2 * tail / 2**n, computed as a ratio of exact integers before the float divide.
|
| 107 |
+
p = 2.0 * tail / (2 ** n) if n < 1000 else 2.0 * math.exp(
|
| 108 |
+
math.log(tail) - n * math.log(2))
|
| 109 |
+
return min(1.0, p)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def fmt_p(p: float) -> str:
|
| 113 |
+
if p == 0.0:
|
| 114 |
+
return "< 1e-300"
|
| 115 |
+
if p < 1e-4:
|
| 116 |
+
return f"{p:.1e}".replace("e-0", "e-")
|
| 117 |
+
return f"{p:.4f}"
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def load_pairs(path: Path, field: str) -> tuple[list[bool], list[bool]]:
|
| 121 |
+
"""Two verdict shapes exist in this repo and both are read here rather than normalised.
|
| 122 |
+
|
| 123 |
+
LONG : one row per (id, column), column in {base, tuned}, headline at top level.
|
| 124 |
+
molperceive, chrono, cashsage.
|
| 125 |
+
WIDE : one row per id carrying nested {"base": {...}, "tuned": {...}}.
|
| 126 |
+
flashfacts.
|
| 127 |
+
|
| 128 |
+
Rewriting either scorer to agree with the other would change a released file to suit a
|
| 129 |
+
convenience script, which is backwards. The shape is detected per file instead.
|
| 130 |
+
"""
|
| 131 |
+
rows = [json.loads(l) for l in path.read_text().split("\n")
|
| 132 |
+
if l.strip() and not l.lstrip().startswith("#")]
|
| 133 |
+
if not rows:
|
| 134 |
+
return [], []
|
| 135 |
+
base: dict[str, bool] = {}
|
| 136 |
+
tuned: dict[str, bool] = {}
|
| 137 |
+
|
| 138 |
+
wide = isinstance(rows[0].get("base"), dict) and isinstance(rows[0].get("tuned"), dict)
|
| 139 |
+
for r in rows:
|
| 140 |
+
rid = str(r.get("id"))
|
| 141 |
+
if wide:
|
| 142 |
+
base[rid] = bool(r["base"].get(field))
|
| 143 |
+
tuned[rid] = bool(r["tuned"].get(field))
|
| 144 |
+
else:
|
| 145 |
+
col = r.get("column")
|
| 146 |
+
if col == "base":
|
| 147 |
+
base[rid] = bool(r.get(field))
|
| 148 |
+
elif col == "tuned":
|
| 149 |
+
tuned[rid] = bool(r.get(field))
|
| 150 |
+
ids = [i for i in tuned if i in base]
|
| 151 |
+
return [base[i] for i in ids], [tuned[i] for i in ids]
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def mcnemar(base: list[bool], tuned: list[bool]) -> dict:
|
| 155 |
+
b = sum(1 for x, y in zip(base, tuned) if x and not y)
|
| 156 |
+
c = sum(1 for x, y in zip(base, tuned) if y and not x)
|
| 157 |
+
return {"n": len(base), "b_base_only": b, "c_tuned_only": c,
|
| 158 |
+
"p": two_sided_exact_binomial(b, c)}
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def agri_sign_test() -> dict | None:
|
| 162 |
+
"""AgriReason: blind pairwise verdicts, decoded through the side mapping."""
|
| 163 |
+
v = ROOT / "docs" / "eval" / "held_verdicts.jsonl"
|
| 164 |
+
m = ROOT / "docs" / "eval" / "held_mapping.json"
|
| 165 |
+
if not (v.exists() and m.exists()):
|
| 166 |
+
return None
|
| 167 |
+
verdicts = [json.loads(l) for l in v.read_text().split("\n") if l.strip()]
|
| 168 |
+
mapping = json.loads(m.read_text())
|
| 169 |
+
tuned = base = tie = 0
|
| 170 |
+
for row in verdicts:
|
| 171 |
+
w, a_arm = row["winner"], mapping[row["id"]]
|
| 172 |
+
if w == "tie":
|
| 173 |
+
tie += 1
|
| 174 |
+
continue
|
| 175 |
+
arm = a_arm if w == "A" else ("base" if a_arm == "tuned" else "tuned")
|
| 176 |
+
if arm == "tuned":
|
| 177 |
+
tuned += 1
|
| 178 |
+
else:
|
| 179 |
+
base += 1
|
| 180 |
+
return {"n": tuned + base + tie, "b_base_only": base, "c_tuned_only": tuned,
|
| 181 |
+
"ties_discarded": tie, "p": two_sided_exact_binomial(base, tuned)}
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def main() -> None:
|
| 185 |
+
ap = argparse.ArgumentParser()
|
| 186 |
+
ap.add_argument("entries", nargs="*")
|
| 187 |
+
ap.add_argument("--out", default=str(ROOT / "docs" / "eval" / "significance.json"))
|
| 188 |
+
args = ap.parse_args()
|
| 189 |
+
|
| 190 |
+
wanted = args.entries or (list(PAIRED) + ["agri"])
|
| 191 |
+
out: dict[str, dict] = {}
|
| 192 |
+
missing: list[str] = []
|
| 193 |
+
|
| 194 |
+
for entry in wanted:
|
| 195 |
+
if entry == "agri":
|
| 196 |
+
r = agri_sign_test()
|
| 197 |
+
if r is None:
|
| 198 |
+
missing.append("agri")
|
| 199 |
+
continue
|
| 200 |
+
out["agri"] = {"test": "exact sign test on decisive pairs, ties discarded",
|
| 201 |
+
"slices": {"held-out, blind pairwise": r}}
|
| 202 |
+
print(f"\n=== agri (exact sign test, ties discarded)")
|
| 203 |
+
print(f" {'held-out, blind pairwise':34} n={r['n']:4} "
|
| 204 |
+
f"tuned {r['c_tuned_only']:4} base {r['b_base_only']:4} "
|
| 205 |
+
f"ties {r['ties_discarded']:3} p {fmt_p(r['p'])}")
|
| 206 |
+
continue
|
| 207 |
+
|
| 208 |
+
if entry not in PAIRED:
|
| 209 |
+
print(f"unknown entry {entry}")
|
| 210 |
+
continue
|
| 211 |
+
print(f"\n=== {entry} (exact McNemar on discordant pairs)")
|
| 212 |
+
slices: dict[str, dict] = {}
|
| 213 |
+
for label, fname, field in PAIRED[entry]:
|
| 214 |
+
p = VER / fname
|
| 215 |
+
if not p.exists():
|
| 216 |
+
print(f" {label:34} NO VERDICT FILE ({fname})")
|
| 217 |
+
missing.append(f"{entry}:{fname}")
|
| 218 |
+
continue
|
| 219 |
+
base, tuned = load_pairs(p, field)
|
| 220 |
+
r = mcnemar(base, tuned)
|
| 221 |
+
slices[label] = r
|
| 222 |
+
print(f" {label:34} n={r['n']:4} tuned-only {r['c_tuned_only']:4} "
|
| 223 |
+
f"base-only {r['b_base_only']:4} p {fmt_p(r['p'])}")
|
| 224 |
+
if slices:
|
| 225 |
+
out[entry] = {"test": "exact McNemar, two-sided, null p=0.5 on discordant pairs",
|
| 226 |
+
"slices": slices}
|
| 227 |
+
|
| 228 |
+
Path(args.out).write_text(json.dumps(out, indent=1) + "\n")
|
| 229 |
+
print(f"\nwrote {args.out}")
|
| 230 |
+
if missing:
|
| 231 |
+
print(f"missing verdicts: {len(missing)} -> {missing[:6]}")
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
if __name__ == "__main__":
|
| 235 |
+
main()
|