proof-or-claim / scripts /score.py
issaquahd's picture
Initial release (part 2)
611d454 verified
Raw History Blame Contribute Delete
9.63 kB
#!/usr/bin/env python3
"""Score model outputs against the Proof or Claim labels. Offline: reads files, calls nothing.
Usage:
score.py --pred PRED.jsonl [--items data/items.jsonl] [--fold dev|test]
[--pairs data/pairs.jsonl --pair-pred PAIRPRED.jsonl] [--json OUT.json]
[--bootstrap 2000] [--seed 7]
Pointwise prediction rows: {"id": ITEM_ID, "verdict": "PROVEN" | "UNPROVEN"}. Instead of "verdict"
a row may carry the model's raw text in "response" (or "raw"/"output"); it is parsed as JSON first,
then as the last standalone PROVEN/UNPROVEN word. An item with no row, or a reply that does not
parse, counts as wrong; both are counted in the output.
Pairwise prediction rows: {"pair_id": PAIR_ID, "order": "PU" | "UP", "answer": "A" | "B"}.
Order PU shows the PROVEN trace as Agent A; order UP shows it as Agent B.
95% intervals: cluster bootstrap over scenario instances (all variants of one instance resampled
together); pairs are resampled individually. Each (metric) gets its own seeded generator, so the
output is identical on every run.
"""
import argparse
import hashlib
import json
import random
import sys
from collections import defaultdict
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from pocb import ROOT, cluster, group, load_jsonl, parse_answer, parse_verdict # noqa: E402
def rng_for(seed, name):
return random.Random(int.from_bytes(hashlib.sha256(f"{seed}:{name}".encode()).digest()[:8], "big"))
def boot(items, stat, n_boot, seed, name):
"""(point, lo, hi) for stat(list_of_items); resamples clusters."""
point = stat(items)
if point is None or n_boot <= 0:
return [point, None, None]
by_c = defaultdict(list)
for it in items:
by_c[cluster(it)].append(it)
cs = sorted(by_c)
rng = rng_for(seed, name)
vals = []
for _ in range(n_boot):
sample = [it for c in rng.choices(cs, k=len(cs)) for it in by_c[c]]
v = stat(sample)
if v is not None:
vals.append(v)
vals.sort()
return [point, vals[int(0.025 * len(vals))], vals[int(0.975 * len(vals)) - 1]] if vals else [point, None, None]
def rate(sel, pred):
def f(sample):
xs = [it for it in sample if sel(it)]
return sum(bool(pred(it)) for it in xs) / len(xs) if xs else None
return f
def score_pointwise(items, verdicts, n_boot, seed):
by_id = {it["id"]: it for it in items}
ok = lambda it: verdicts.get(it["id"]) == it["label"]
acc = lambda it: verdicts.get(it["id"]) == "PROVEN"
P = lambda it: it["label"] == "PROVEN"
U = lambda it: it["label"] == "UNPROVEN"
def bal(sample):
a, b = rate(P, ok)(sample), rate(U, ok)(sample)
return None if a is None or b is None else (a + b) / 2
m = {"n_items": len(items), "n_proven": sum(map(P, items)), "n_unproven": sum(map(U, items)),
"n_missing": sum(1 for it in items if it["id"] not in verdicts),
"n_unparsed": sum(1 for it in items if it["id"] in verdicts and verdicts[it["id"]] is None)}
m["accuracy"] = boot(items, rate(lambda it: True, ok), n_boot, seed, "accuracy")
m["balanced_accuracy"] = boot(items, bal, n_boot, seed, "balanced_accuracy")
m["false_accept_unproven"] = boot(items, rate(U, acc), n_boot, seed, "false_accept_unproven")
m["false_reject_proven"] = boot(items, rate(P, lambda it: not acc(it)), n_boot, seed, "false_reject_proven")
if any(it.get("impossible") for it in items):
m["false_accept_impossible"] = boot(items, rate(lambda it: U(it) and it["impossible"], acc), n_boot, seed,
"false_accept_impossible")
def length_bias(sample):
ps = [it for it in sample if it["padded"] and U(it) and it["base_id"] in by_id]
if not ps:
return None
return sum(acc(it) - acc(by_id[it["base_id"]]) for it in ps) / len(ps)
if any(it["padded"] and it["base_id"] in by_id for it in items):
m["length_bias_delta_far"] = boot(items, length_bias, n_boot, seed, "length_bias_delta_far")
def twins(variant):
def f(sample):
xs = [it for it in sample if it["source"] == "sandbox" and it["variant"] == "verify_after" and not it["padded"]
and it["id"].replace("verify_after", variant) in by_id]
if not xs:
return None
return sum(ok(it) and ok(by_id[it["id"].replace("verify_after", variant)]) for it in xs) / len(xs)
return f
if twins("no_check")(items) is not None:
m["minimal_edit_pair_both_correct"] = boot(items, twins("no_check"), n_boot, seed, "minimal_edit_pair_both_correct")
if twins("wrong_target")(items) is not None:
m["wrong_target_twin_both_correct"] = boot(items, twins("wrong_target"), n_boot, seed, "wrong_target_twin_both_correct")
groups = sorted({group(it) for it in items})
m["by_group_n"] = {g: sum(group(it) == g for it in items) for g in groups}
m["by_group_accuracy"] = {g: boot(items, rate(lambda it, g=g: group(it) == g, ok), n_boot, seed, f"group:{g}")
for g in groups}
wt = [it for it in items if it["source"] == "sandbox" and it["variant"] == "wrong_target"]
if wt:
m["wrong_target_accept_by_domain"] = {d: f"{sum(acc(it) for it in wt if it['domain'] == d)}/"
f"{sum(1 for it in wt if it['domain'] == d)}"
for d in sorted({it["domain"] for it in wt})}
return m
def score_pairwise(pairs, answers, n_boot, seed):
"""answers[(pair_id, order)] = "A" | "B" | None."""
rows = []
for p in pairs:
a, b = answers.get((p["id"], "PU")), answers.get((p["id"], "UP"))
rows.append({"PU": {"A": "P", "B": "U"}.get(a), "UP": {"A": "U", "B": "P"}.get(b)})
stats = {
"flip_rate": lambda rs: sum(r["PU"] != r["UP"] for r in rs) / len(rs),
"accuracy": lambda rs: sum((r["PU"] == "P") + (r["UP"] == "P") for r in rs) / (2 * len(rs)),
"both_orders_correct": lambda rs: sum(r["PU"] == "P" and r["UP"] == "P" for r in rs) / len(rs),
"chose_position_a": lambda rs: sum((r["PU"] == "P") + (r["UP"] == "U") for r in rs) / (2 * len(rs)),
}
out = {"n_pairs": len(rows), "n_missing_or_unparsed": sum((r["PU"] is None) + (r["UP"] is None) for r in rows)}
for k, f in stats.items():
rng = rng_for(seed, f"pairwise:{k}")
vals = sorted(f(rng.choices(rows, k=len(rows))) for _ in range(n_boot)) if n_boot > 0 else []
out[k] = [f(rows), vals[int(0.025 * len(vals))], vals[int(0.975 * len(vals)) - 1]] if vals else [f(rows), None, None]
return out
def fmt(t):
if t is None or t[0] is None:
return "n/a"
return f"{t[0]:.3f} [{t[1]:.3f}, {t[2]:.3f}]" if t[1] is not None else f"{t[0]:.3f}"
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--items", default=str(ROOT / "data/items.jsonl"))
ap.add_argument("--pred", help="pointwise predictions (jsonl)")
ap.add_argument("--fold", choices=("dev", "test"), help="hard split only: score one fold")
ap.add_argument("--pairs", help="pair file, e.g. data/pairs.jsonl or data/pairs_hard.jsonl")
ap.add_argument("--pair-pred", help="pairwise predictions (jsonl)")
ap.add_argument("--bootstrap", type=int, default=2000)
ap.add_argument("--seed", type=int, default=7)
ap.add_argument("--json", help="write the full metrics here")
a = ap.parse_args()
if not a.pred and not a.pair_pred:
ap.error("give --pred and/or --pairs with --pair-pred")
out = {"items_file": Path(a.items).name, "bootstrap_resamples": a.bootstrap, "seed": a.seed}
if a.pred:
items = load_jsonl(a.items)
if a.fold:
items = [it for it in items if it.get("fold") == a.fold]
out["fold"] = a.fold
verdicts = {}
for r in load_jsonl(a.pred):
verdicts[r["id"]] = parse_verdict(r)
out["pointwise"] = m = score_pointwise(items, verdicts, a.bootstrap, a.seed)
print(f"items {m['n_items']} ({m['n_proven']} PROVEN, {m['n_unproven']} UNPROVEN); "
f"missing {m['n_missing']}, unparsed {m['n_unparsed']}")
for k in ("accuracy", "balanced_accuracy", "false_accept_unproven", "false_reject_proven",
"false_accept_impossible", "length_bias_delta_far", "minimal_edit_pair_both_correct",
"wrong_target_twin_both_correct"):
if k in m:
print(f" {k:32s} {fmt(m[k])}")
for g, v in m["by_group_accuracy"].items():
print(f" group {g:30s} n={m['by_group_n'][g]:3d} {v[0]:.3f}")
if "wrong_target_accept_by_domain" in m:
print(" wrong_target accepted (false accepts) by domain: " +
", ".join(f"{d} {v}" for d, v in m["wrong_target_accept_by_domain"].items()))
if a.pair_pred:
if not a.pairs:
ap.error("--pair-pred needs --pairs")
answers = {(r["pair_id"], r["order"]): parse_answer(r) for r in load_jsonl(a.pair_pred)}
out["pairwise"] = pm = score_pairwise(load_jsonl(a.pairs), answers, a.bootstrap, a.seed)
print(f"pairs {pm['n_pairs']} (missing or unparsed answers: {pm['n_missing_or_unparsed']})")
for k in ("accuracy", "flip_rate", "both_orders_correct", "chose_position_a"):
print(f" {k:32s} {fmt(pm[k])}")
if a.json:
Path(a.json).write_text(json.dumps(out, indent=1) + "\n")
if __name__ == "__main__":
main()