File size: 11,843 Bytes
06334ce | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 | #!/usr/bin/env python3
"""Official evaluation & scoring harness for the Selective Physical Undo Benchmark.
Zero required external dependencies beyond the Python 3.10+ standard library
(optional: `huggingface_hub` for `--download`).
Examples:
# 1. Verify installation & scorer logic across all 6 configs
python evaluate.py --self-test
# 2. Download the full benchmark (including .mp4 videos) from Hugging Face
python evaluate.py --download --out-dir ./selective-undo-benchmark
# 3. Score your model's predictions JSONL on any benchmark config
python evaluate.py --config real_matched_prefixes --predictions my_preds.jsonl
python evaluate.py --config sealed_ood_queries --predictions my_preds.jsonl --baseline direct_vlm.jsonl
"""
from __future__ import annotations
import argparse
import json
import math
import random
from collections import defaultdict
from pathlib import Path
from typing import Any
REPO_ID = "brandonbaek/selective-undo-benchmark"
CONFIG_SPLITS: dict[str, dict[str, str]] = {
"sim_marked": {
"train": "sim/development.jsonl",
"test": "sim/test.jsonl",
"challenge": "sim/challenge.jsonl",
},
"real_cases": {"test": "real/cases.jsonl"},
"real_matched_prefixes": {"test": "real/pairs.jsonl"},
"real_confirmation": {"test": "real/confirmation.jsonl"},
"sealed_ood_queries": {"test": "sealed/sealed_ood_queries.jsonl"},
"confirm_v2_queries": {"test": "sealed/confirm_v2_queries.jsonl"},
}
def load_jsonl(path: Path) -> list[dict[str, Any]]:
return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
def bootstrap_ci(correct_flags: list[int], n_boot: int = 5000, seed: int = 42) -> tuple[float, float]:
n = len(correct_flags)
if n == 0:
return (0.0, 0.0)
rng = random.Random(seed)
means = []
for _ in range(n_boot):
s = sum(correct_flags[rng.randrange(n)] for _ in range(n))
means.append(s / n)
means.sort()
return (means[int(0.025 * n_boot)], means[int(0.975 * n_boot)])
def exact_mcnemar_p(flags_a: list[int], flags_b: list[int]) -> dict[str, Any]:
"""Exact two-sided binomial McNemar test using stdlib math.comb."""
assert len(flags_a) == len(flags_b)
a_only = sum(1 for a, b in zip(flags_a, flags_b) if a == 1 and b == 0)
b_only = sum(1 for a, b in zip(flags_a, flags_b) if a == 0 and b == 1)
n_disc = a_only + b_only
if n_disc == 0:
p = 1.0
else:
k = min(a_only, b_only)
tail = sum(math.comb(n_disc, i) for i in range(k + 1)) / (2**n_disc)
p = min(1.0, 2.0 * tail)
return {
"a_only": a_only,
"b_only": b_only,
"discordant": n_disc,
"p_value": p,
"acc_a": sum(flags_a) / len(flags_a) if flags_a else 0.0,
"acc_b": sum(flags_b) / len(flags_b) if flags_b else 0.0,
"diff_pp": 100.0 * ((sum(flags_a) - sum(flags_b)) / len(flags_a)) if flags_a else 0.0,
}
def load_predictions(path: Path) -> dict[str, dict[str, Any]]:
preds: dict[str, dict[str, Any]] = {}
for row in load_jsonl(path):
key = str(row.get("query_id") or row.get("id") or "")
if not key:
raise ValueError(f"Prediction row missing 'id' or 'query_id': {row}")
preds[key] = row
return preds
def _get_pred_choice(pred_row: dict[str, Any] | None) -> str:
if not pred_row:
return ""
for k in ("prediction", "choice", "status", "answer"):
val = pred_row.get(k)
if val is not None and str(val).strip():
return str(val).strip()
return ""
def score_config(
rows: list[dict[str, Any]],
preds: dict[str, dict[str, Any]],
config: str,
) -> tuple[dict[str, Any], list[int]]:
flags: list[int] = []
missing = 0
if config == "sim_marked":
for r in rows:
rid = str(r["id"])
pr = preds.get(rid)
if pr is None:
missing += 1
pred_status = _get_pred_choice(pr)
ok = int(pred_status == str(r["status"]))
flags.append(ok)
ci_lo, ci_hi = bootstrap_ci(flags)
summary: dict[str, Any] = {
"config": config,
"n": len(rows),
"missing_predictions": missing,
"correct": sum(flags),
"accuracy": round(sum(flags) / len(rows), 4) if rows else 0.0,
"ci_95": [round(ci_lo, 4), round(ci_hi, 4)],
}
return summary, flags
# Real & sealed configs
by_cohort: dict[str, list[int]] = defaultdict(list)
by_pair: dict[str, list[int]] = defaultdict(list)
by_session_roles: dict[str, dict[str, int]] = defaultdict(dict)
early_total = 0
early_fp = 0
prot_total = 0
prot_viol = 0
always_repair = 0
always_no_change = 0
for r in rows:
key = str(r.get("query_id") or r.get("id"))
alt_key = str(r.get("id") or "")
pr = preds.get(key) or (preds.get(alt_key) if alt_key else None)
if pr is None:
missing += 1
pred = _get_pred_choice(pr)
gold = str(r["correct"])
ok = int(pred == gold)
flags.append(ok)
cohort = str(r.get("cohort") or config)
by_cohort[cohort].append(ok)
if "pair" in r and r["pair"]:
by_pair[str(r["pair"])].append(ok)
if "session" in r and r["session"]:
role = str(r.get("role", ""))
by_session_roles[str(r["session"])][role] = ok
role = str(r.get("role", ""))
if role in ("early", "restraint") and gold == "no_change":
early_total += 1
if pred == "repair":
early_fp += 1
if gold == "ask":
prot_total += 1
if pred == "repair":
prot_viol += 1
if gold == "repair":
always_repair += 1
if gold in ("no_change", "keep", "before"):
always_no_change += 1
ci_lo, ci_hi = bootstrap_ci(flags)
summary = {
"config": config,
"n": len(rows),
"missing_predictions": missing,
"correct": sum(flags),
"accuracy": round(sum(flags) / len(rows), 4) if rows else 0.0,
"ci_95": [round(ci_lo, 4), round(ci_hi, 4)],
"shortcut_ceilings": {
"always_repair": f"{always_repair}/{len(rows)} ({100.0 * always_repair / len(rows):.1f}%)" if rows else "0/0",
"always_no_change": f"{always_no_change}/{len(rows)} ({100.0 * always_no_change / len(rows):.1f}%)" if rows else "0/0",
},
}
if by_pair:
exact_pairs = sum(1 for vals in by_pair.values() if len(vals) >= 2 and all(vals))
summary["exact_pairs"] = f"{exact_pairs}/{len(by_pair)}"
if by_session_roles:
timing_ok = 0
timing_tot = 0
alt_ok = 0
alt_tot = 0
for _sess, rmap in by_session_roles.items():
pos = rmap.get("actionable", rmap.get("late"))
neg = rmap.get("restraint", rmap.get("early"))
alt = rmap.get("alternate")
if pos is not None and neg is not None:
timing_tot += 1
timing_ok += int(pos == 1 and neg == 1)
if pos is not None and alt is not None:
alt_tot += 1
alt_ok += int(pos == 1 and alt == 1)
summary["session_timing_state_pairs"] = f"{timing_ok}/{timing_tot}"
summary["session_alternate_target_pairs"] = f"{alt_ok}/{alt_tot}"
if early_total > 0:
summary["early_false_positives"] = f"{early_fp}/{early_total}"
if prot_total > 0:
summary["protected_barrier_violations"] = f"{prot_viol}/{prot_total}"
if len(by_cohort) > 1:
summary["by_cohort"] = {
c: f"{sum(v)}/{len(v)} ({100.0 * sum(v) / len(v):.1f}%)" for c, v in sorted(by_cohort.items())
}
return summary, flags
def run_self_test(data_dir: Path) -> int:
print("Running evaluate.py --self-test across all 6 configs...")
for cfg, splits in CONFIG_SPLITS.items():
for split_name, rel_path in splits.items():
rows = load_jsonl(data_dir / rel_path)
oracle_preds = {}
for r in rows:
key = str(r.get("query_id") or r.get("id"))
gold = str(r["status"] if cfg == "sim_marked" else r["correct"])
oracle_preds[key] = {"id": key, "prediction": gold}
rep, flags = score_config(rows, oracle_preds, cfg)
assert rep["correct"] == len(rows) and rep["missing_predictions"] == 0, f"Oracle failed on {cfg}/{split_name}"
if cfg in ("sealed_ood_queries", "confirm_v2_queries"):
bad_preds = {k: {"id": k, "prediction": "repair"} for k in oracle_preds}
bad_rep, bad_flags = score_config(rows, bad_preds, cfg)
mcn = exact_mcnemar_p(flags, bad_flags)
assert mcn["p_value"] < 1e-6, f"Unexpected McNemar p={mcn['p_value']}"
print(
f" [PASS] {cfg}/{split_name}: n={len(rows)}, oracle=100%, "
f"always_repair={bad_rep['correct']}/{len(rows)}, McNemar p={mcn['p_value']:.2e}"
)
else:
print(f" [PASS] {cfg}/{split_name}: n={len(rows)}, oracle=100%")
print("All self-tests passed!")
return 0
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--data-dir", type=Path, default=Path(__file__).resolve().parent, help="Local benchmark checkout directory")
parser.add_argument("--config", choices=sorted(CONFIG_SPLITS.keys()), help="Benchmark config to evaluate")
parser.add_argument("--split", default="test", help="Split name (e.g., train, test, challenge)")
parser.add_argument("--predictions", type=Path, help="Path to model predictions JSONL")
parser.add_argument("--baseline", type=Path, default=None, help="Optional baseline predictions JSONL for exact McNemar test")
parser.add_argument("--list-configs", action="store_true", help="List available benchmark configs and splits")
parser.add_argument("--download", action="store_true", help="Download benchmark repo (including .mp4 videos) from Hugging Face")
parser.add_argument("--out-dir", type=Path, default=Path("./selective-undo-benchmark"), help="Destination for --download")
parser.add_argument("--self-test", action="store_true", help="Verify scorer logic across all configs")
args = parser.parse_args()
if args.list_configs:
print(json.dumps(CONFIG_SPLITS, indent=2))
return 0
if args.download:
from huggingface_hub import snapshot_download
local = snapshot_download(repo_id=REPO_ID, repo_type="dataset", local_dir=str(args.out_dir))
print(f"Downloaded {REPO_ID} to: {local}")
return 0
if args.self_test:
return run_self_test(args.data_dir)
if not args.config or not args.predictions:
parser.error("Provide --config and --predictions (or use --self-test / --list-configs / --download).")
splits = CONFIG_SPLITS[args.config]
if args.split not in splits:
parser.error(f"Config '{args.config}' supports splits: {list(splits.keys())}")
rows = load_jsonl(args.data_dir / splits[args.split])
preds = load_predictions(args.predictions)
report, flags = score_config(rows, preds, args.config)
if args.baseline:
base_preds = load_predictions(args.baseline)
base_report, base_flags = score_config(rows, base_preds, args.config)
report["vs_baseline"] = exact_mcnemar_p(flags, base_flags)
report["baseline_accuracy"] = base_report["accuracy"]
print(json.dumps(report, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
|