flashfacts / significance.py
Jainamshahhh's picture
Upload significance.py with huggingface_hub
1d38eee verified
Raw
History Blame Contribute Delete
9.65 kB
"""Exact paired significance tests for every entry in the portfolio.
python significance.py # every entry with verdicts on disk
python significance.py molperceive # one entry
python significance.py --stage # regenerate the verdict files first
WHAT IS TESTED, AND WHY THIS TEST
---------------------------------
Every eval in this portfolio is a PAIRED design: the same held-out row is answered by the
base and by the tuned model, in one process, under identical greedy decoding. Paired binary
outcomes call for McNemar's test, and because some of our discordant counts are small (and
because an exact test needs no large-sample assumption to defend), this uses the EXACT
McNemar test rather than the chi-square approximation.
Concordant rows carry no information about which model is better: a row both models get
right, or both get wrong, is equally likely under either hypothesis. So the test conditions
on the DISCORDANT rows, of which there are n = b + c:
b = base correct, tuned wrong (evidence for the base)
c = base wrong, tuned correct (evidence for the tuned model)
Under the null "the adapter is no better than the base", each discordant row is a fair coin,
so c ~ Binomial(n, 0.5). The two-sided exact p-value is
p = min(1, 2 * P(X >= max(b, c))) X ~ Binomial(n, 0.5)
computed with exact integer binomial coefficients, no floating-point survival function and
no normal approximation.
AgriReason is the one entry that is not scored by exact match. It was judged blind and
pairwise, so its verdicts are wins, losses and ties. Ties are DISCARDED rather than split,
which is the standard sign test and the conservative choice: splitting ties would inflate
the effective sample and flatter the result. The same binomial machinery then applies, with
b = base wins and c = tuned wins.
WHAT A SMALL p DOES AND DOES NOT MEAN
-------------------------------------
It means the measured difference is very unlikely to be sampling noise. It says nothing
about whether the held-out slice is representative, whether the labels are right, or
whether the task is worth doing. Those are argued elsewhere on each card and are not
statistical questions. A p-value cannot rescue a bad slice, and this file does not pretend
otherwise.
"""
from __future__ import annotations
import argparse
import json
import math
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
GEN = ROOT / "docs" / "eval" / "gcp"
EVAL = ROOT / "data" / "eval"
VER = ROOT / "docs" / "eval" / "significance"
PY = str(ROOT / ".venv" / "bin" / "python")
# entry -> list of (label, verdict file, field carrying the headline boolean)
# Verdict files carry one row per (row, column) pair with column in {base, tuned}.
PAIRED = {
"molperceive": [
("held-out, familiar scaffolds", "mp_v2__mp_held_seen.jsonl", "joint"),
("held-out, novel scaffolds", "mp_v2__mp_held_novel.jsonl", "joint"),
("real molecules, wwPDB CCD", "mp_v2__mp_real.jsonl", "joint"),
("hard shard, 4 to 9 rings", "mp_v2__mp_hard.jsonl", "joint"),
],
"flashfacts": [
("ff_held", "ff_v1__ff_held.jsonl", "strict_match"),
("ff_hard", "ff_v1__ff_hard.jsonl", "strict_match"),
("ff_ood", "ff_v1__ff_ood.jsonl", "strict_match"),
],
"chrono": [
("headline held-out", "chrono_v1__chrono_held.jsonl", "strict"),
("hard shard", "chrono_v1__chrono_held_hard.jsonl", "strict"),
("enumerated calendar", "chrono_v1__chrono_enumerated.jsonl", "strict"),
("range slice, 2031 to 2035", "chrono_v1__chrono_range.jsonl", "strict"),
],
"cashsage": [
("held-out", "cs_v2__cs_held.jsonl", "strict"),
("hard", "cs_v2__cs_hard.jsonl", "strict"),
("2026 rules", "cs_v2__cs_held_2026.jsonl", "strict"),
],
"hr": [
("held-out tool probes", "hr__hr_tool.jsonl", "overall"),
("harder probe set", "hr__hr_tool_hard.jsonl", "overall"),
],
"chart": [
("held-out ChartForge", "chart__chart_held.jsonl", "ok"),
],
}
def two_sided_exact_binomial(b: int, c: int) -> float:
"""Exact two-sided binomial test at p=0.5 on b+c discordant pairs.
Integer arithmetic throughout: the tail is summed as an exact integer count of
outcomes and divided once at the end, so a p-value of 1e-150 is not an artifact of
accumulated float error. Returns 1.0 when there is nothing to test.
"""
n = b + c
if n == 0:
return 1.0
k = max(b, c)
tail = sum(math.comb(n, i) for i in range(k, n + 1))
# 2 * tail / 2**n, computed as a ratio of exact integers before the float divide.
p = 2.0 * tail / (2 ** n) if n < 1000 else 2.0 * math.exp(
math.log(tail) - n * math.log(2))
return min(1.0, p)
def fmt_p(p: float) -> str:
if p == 0.0:
return "< 1e-300"
if p < 1e-4:
return f"{p:.1e}".replace("e-0", "e-")
return f"{p:.4f}"
def load_pairs(path: Path, field: str) -> tuple[list[bool], list[bool]]:
"""Two verdict shapes exist in this repo and both are read here rather than normalised.
LONG : one row per (id, column), column in {base, tuned}, headline at top level.
molperceive, chrono, cashsage.
WIDE : one row per id carrying nested {"base": {...}, "tuned": {...}}.
flashfacts.
Rewriting either scorer to agree with the other would change a released file to suit a
convenience script, which is backwards. The shape is detected per file instead.
"""
rows = [json.loads(l) for l in path.read_text().split("\n")
if l.strip() and not l.lstrip().startswith("#")]
if not rows:
return [], []
base: dict[str, bool] = {}
tuned: dict[str, bool] = {}
wide = isinstance(rows[0].get("base"), dict) and isinstance(rows[0].get("tuned"), dict)
for r in rows:
rid = str(r.get("id"))
if wide:
base[rid] = bool(r["base"].get(field))
tuned[rid] = bool(r["tuned"].get(field))
else:
col = r.get("column")
if col == "base":
base[rid] = bool(r.get(field))
elif col == "tuned":
tuned[rid] = bool(r.get(field))
ids = [i for i in tuned if i in base]
return [base[i] for i in ids], [tuned[i] for i in ids]
def mcnemar(base: list[bool], tuned: list[bool]) -> dict:
b = sum(1 for x, y in zip(base, tuned) if x and not y)
c = sum(1 for x, y in zip(base, tuned) if y and not x)
return {"n": len(base), "b_base_only": b, "c_tuned_only": c,
"p": two_sided_exact_binomial(b, c)}
def agri_sign_test() -> dict | None:
"""AgriReason: blind pairwise verdicts, decoded through the side mapping."""
v = ROOT / "docs" / "eval" / "held_verdicts.jsonl"
m = ROOT / "docs" / "eval" / "held_mapping.json"
if not (v.exists() and m.exists()):
return None
verdicts = [json.loads(l) for l in v.read_text().split("\n") if l.strip()]
mapping = json.loads(m.read_text())
tuned = base = tie = 0
for row in verdicts:
w, a_arm = row["winner"], mapping[row["id"]]
if w == "tie":
tie += 1
continue
arm = a_arm if w == "A" else ("base" if a_arm == "tuned" else "tuned")
if arm == "tuned":
tuned += 1
else:
base += 1
return {"n": tuned + base + tie, "b_base_only": base, "c_tuned_only": tuned,
"ties_discarded": tie, "p": two_sided_exact_binomial(base, tuned)}
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("entries", nargs="*")
ap.add_argument("--out", default=str(ROOT / "docs" / "eval" / "significance.json"))
args = ap.parse_args()
wanted = args.entries or (list(PAIRED) + ["agri"])
out: dict[str, dict] = {}
missing: list[str] = []
for entry in wanted:
if entry == "agri":
r = agri_sign_test()
if r is None:
missing.append("agri")
continue
out["agri"] = {"test": "exact sign test on decisive pairs, ties discarded",
"slices": {"held-out, blind pairwise": r}}
print(f"\n=== agri (exact sign test, ties discarded)")
print(f" {'held-out, blind pairwise':34} n={r['n']:4} "
f"tuned {r['c_tuned_only']:4} base {r['b_base_only']:4} "
f"ties {r['ties_discarded']:3} p {fmt_p(r['p'])}")
continue
if entry not in PAIRED:
print(f"unknown entry {entry}")
continue
print(f"\n=== {entry} (exact McNemar on discordant pairs)")
slices: dict[str, dict] = {}
for label, fname, field in PAIRED[entry]:
p = VER / fname
if not p.exists():
print(f" {label:34} NO VERDICT FILE ({fname})")
missing.append(f"{entry}:{fname}")
continue
base, tuned = load_pairs(p, field)
r = mcnemar(base, tuned)
slices[label] = r
print(f" {label:34} n={r['n']:4} tuned-only {r['c_tuned_only']:4} "
f"base-only {r['b_base_only']:4} p {fmt_p(r['p'])}")
if slices:
out[entry] = {"test": "exact McNemar, two-sided, null p=0.5 on discordant pairs",
"slices": slices}
Path(args.out).write_text(json.dumps(out, indent=1) + "\n")
print(f"\nwrote {args.out}")
if missing:
print(f"missing verdicts: {len(missing)} -> {missing[:6]}")
if __name__ == "__main__":
main()