Add protocol v3 and G3 judge calibration

No human rater exists, so protocol v3 makes the automatic score against the
XML answer the G3 reference; the kappa threshold of 0.6 is unchanged. A fixed
stratified sample of 100 free-text T4 answers is judged blind by session
subagents. Sonnet reaches kappa 0.98 and Haiku 0.90 against the automatic
score; T4 headline numbers remain automatic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 07:00:36 +00:00
parent c7e94aa2c9
commit cd7ff483b3
5 changed files with 461 additions and 0 deletions

124
scripts/18_m5_judge.py Normal file
View File

@@ -0,0 +1,124 @@
#!/usr/bin/env python3
"""G3 judge calibration under protocol v3 (session subagents as judges, no API key).
scripts/18_m5_judge.py prepare draw the fixed sample of free-text T4 answers, write judge batches
scripts/18_m5_judge.py status batches answered per judge
scripts/18_m5_judge.py collect validate verdicts, compare with the automatic score, decide G3
Judges read one batch file under outputs/m5/judge/batches/ and write outputs/m5/judge/answers/<model>/<batch>.json.
`collect` refuses to run unless configs/protocol_v3.yaml matches its checksum and records the sample and prompt hashes.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import sqlite3
from pathlib import Path
import pandas as pd
import yaml
from volve_dia import m5_judge as mj
from volve_dia.paths import outputs_dir
ROOT = Path(__file__).resolve().parents[1]
PROTOCOL = ROOT / "configs/protocol_v3.yaml"
STORE = "m34/v2/qa/vai-deepseek-v4-1-flash/rep0.sqlite"
SEED = 20261117
BATCH = 50
def load_questions(out):
return {q["id"]: q for q in map(json.loads, (out / "t4/questions.jsonl").read_text().splitlines())}
def prepare(out):
base, batch_dir, _ = mj.judge_dirs(out)
if (base / "sample.parquet").exists():
raise SystemExit("sample exists; the draw is fixed once (delete it only before protocol v3 is locked)")
store = out / STORE
pool = mj.candidates(load_questions(out), store)
sample = mj.draw(pool, SEED)
base.mkdir(parents=True, exist_ok=True)
sample.to_parquet(base / "sample.parquet", index=False)
sample.to_csv(base / "sample.csv", index=False)
names = mj.write_batches(sample, batch_dir, BATCH)
con = sqlite3.connect(f"file:{store}?mode=ro", uri=True)
provenance = con.execute("SELECT provenance FROM metadata").fetchone()[0]
con.close()
manifest = {
"seed": SEED, "source": STORE, "source_provenance_sha256": hashlib.sha256(provenance.encode()).hexdigest(),
"pool": {"n": len(pool), "by_stratum": {f"{k[0]}|{k[1]}": int(v) for k, v in
pool.groupby(["answer_type", "auto_correct"]).size().items()}},
"sample": {"n": len(sample), "sha256": mj.sha256_file(base / "sample.csv"),
"by_stratum": {f"{k[0]}|{k[1]}": int(v) for k, v in
sample.groupby(["answer_type", "auto_correct"]).size().items()},
"wells": int(sample["well"].nunique()), "templates": int(sample["template"].nunique()),
"by_mode": {f"{k[0]}|{k[1]}": int(v)
for k, v in sample.groupby(["mode", "modality"]).size().items()}},
"judge_instruction_sha256": mj.sha256_text(mj.JUDGE_INSTRUCTION),
"batches": {n: mj.sha256_file(batch_dir / f"{n}.json") for n in names},
}
(base / "manifest.json").write_text(json.dumps(manifest, indent=1))
print(json.dumps(manifest, indent=1))
def locked_protocol():
expected = (PROTOCOL.parent / (PROTOCOL.name + ".sha256")).read_text().split()[0]
if mj.sha256_file(PROTOCOL) != expected:
raise SystemExit("protocol_v3.yaml does not match its checksum")
return yaml.safe_load(PROTOCOL.read_text())
def status(out):
_, batch_dir, answer_dir = mj.judge_dirs(out)
names = sorted(p.stem for p in batch_dir.glob("batch_*.json"))
for model in ("sonnet", "haiku"):
done = [n for n in names if (answer_dir / model / f"{n}.json").exists()]
print(f"{model}: {len(done)}/{len(names)}")
def collect(out):
protocol = locked_protocol()
g3 = protocol["g3"]
base, _, answer_dir = mj.judge_dirs(out)
manifest = json.loads((base / "manifest.json").read_text())
if mj.sha256_file(base / "sample.csv") != g3["sample"]["sha256"]:
raise SystemExit("sample.csv does not match the hash locked in protocol v3")
if mj.sha256_text(mj.JUDGE_INSTRUCTION) != g3["judge_instruction_sha256"]:
raise SystemExit("judge instruction differs from the one locked in protocol v3")
sample = pd.read_parquet(base / "sample.parquet")
ids = set(sample["judge_id"])
verdicts = {m: mj.read_verdicts(answer_dir / m, ids) for m in g3["judges"] if (answer_dir / m).exists()}
if g3["primary_judge"] not in verdicts:
raise SystemExit(f"no verdicts from the primary judge {g3['primary_judge']}")
report, frame = mj.summarise(sample, verdicts, g3["primary_judge"], g3["min_kappa"],
g3["bootstrap"]["resamples"], g3["bootstrap"]["seed"])
report["protocol_v3_sha256"] = mj.sha256_file(PROTOCOL)
report["sample_sha256"] = manifest["sample"]["sha256"]
report["by_stratum"] = manifest["sample"]["by_stratum"]
(base / "report.json").write_text(json.dumps(report, indent=1))
frame.to_csv(base / "judged.csv", index=False)
cols = ["judge_id", "item", "mode", "modality", "template", "answer_type", "question", "reference", "candidate",
"unit", "auto", *sorted(verdicts)]
disagree = frame[(frame[sorted(verdicts)].ne(frame["auto"], axis=0)).any(axis=1)][cols]
disagree.to_csv(base / "disagreements.csv", index=False)
print(json.dumps({k: report[k] for k in ("n_items", "g3")}, indent=1))
for m, block in report["judges"].items():
print(m, "kappa", round(block["kappa"], 4), "ci", block["kappa_ci95"],
"agreement", round(block["agreement"], 4))
print("disagreements:", len(disagree))
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("stage", choices=("prepare", "status", "collect"))
args = parser.parse_args()
out = outputs_dir()
{"prepare": prepare, "status": status, "collect": collect}[args.stage](out)
if __name__ == "__main__":
main()