Download code/rubric_gen/compound_patch.py from EdwardoSunny/agent-cwm-rubrics-debug: direct link, hf CLI and curl.
- Browser
- Download file 7.57 kB
-
https://huggingface.co/datasets/EdwardoSunny/agent-cwm-rubrics-debug/resolve/main/code/rubric_gen/compound_patch.py
- Command line
-
hf download hf://datasets/EdwardoSunny/agent-cwm-rubrics-debug/code/rubric_gen/compound_patch.py
-
curl -L -o compound_patch.py https://huggingface.co/datasets/EdwardoSunny/agent-cwm-rubrics-debug/resolve/main/code/rubric_gen/compound_patch.py
7.57 kB
| #!/usr/bin/env python3 | |
| """Compound causal test: apply ALL fired rubrics' fixes to one program at once. | |
| python3 compound_patch.py --decisions data/canon_pr_decisions_lib38.jsonl \ | |
| --library data/canon_lib38_frozen.jsonl --out data/canon_compound.json | |
| WHY THIS EXISTS. The single-patch experiment (counterfactual.py) asks whether | |
| ONE rubric's fix moves the score. That is the right attribution standard for | |
| per-rubric precision, but it structurally under-credits two real situations: | |
| fixes that compound (each individually below the noise floor, jointly above | |
| it) and diagnostic fixes whose value is enabling the NEXT change. This runs | |
| the complementary experiment: for each held-out program, one editor pass | |
| applies every fix the judge fired on it, then one re-run and one official | |
| re-grade. Improvement above the floor means the fired set collectively | |
| explains a real part of the gap even where no single member does. | |
| Per-program, not per-rubric: a positive here cannot say WHICH rubric earned | |
| it. Report alongside, never instead of, the single-patch numbers. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import shutil | |
| import sys | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| import collect as collect_mod | |
| import split as split_mod | |
| from common import append_jsonl, read_jsonl, write_json | |
| from counterfactual import patched_program | |
| def main() -> int: | |
| ap = argparse.ArgumentParser(description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--decisions", default="data/canon_pr_decisions_lib38.jsonl") | |
| ap.add_argument("--pool", default="data/canon_eval_scored.jsonl") | |
| ap.add_argument("--library", default="data/canon_lib38_frozen.jsonl") | |
| ap.add_argument("--edit-model", default="claude-opus-5") | |
| ap.add_argument("--python", default=".venv/bin/python") | |
| ap.add_argument("--timeout", type=int, default=1500) | |
| ap.add_argument("--root", default="/tmp/rubric_gen_compound") | |
| ap.add_argument("--noise", default="data/noise_floor.json") | |
| ap.add_argument("--log", default="data/canon_compound_runs.jsonl") | |
| ap.add_argument("--out", default="data/canon_compound.json") | |
| ap.add_argument("--data-dir", default="/workspace/edwardosunny/mle-bench/data") | |
| args = ap.parse_args() | |
| import os | |
| python = os.path.abspath(shutil.which(args.python) or args.python) | |
| from mlebench.registry import registry as _registry | |
| registry = _registry.set_data_dir(Path(args.data_dir)) | |
| sp = split_mod.get() | |
| states = {s["state_id"]: s for s in read_jsonl(args.pool) | |
| if (s.get("grading") or {}).get("graded")} | |
| for comp in sorted({s["competition"] for s in states.values()}): | |
| sp.assert_evaluation_only(comp) | |
| library = {r["id"]: r for r in read_jsonl(args.library)} | |
| from eval_precision_recall import JUDGE_VERSION | |
| fires_by_state: dict[str, list[dict]] = {} | |
| for d in read_jsonl(args.decisions): | |
| if (d.get("fires") and d.get("judge_version") == JUDGE_VERSION | |
| and d.get("family") == "conceptual" | |
| and not d["rubric_id"].startswith("ctrl_") | |
| and d["state_id"] in states): | |
| cand = library.get(d["rubric_id"].rsplit("__", 1)[-1]) | |
| if cand and (cand.get("proposed_patch") or "").strip(): | |
| fires_by_state.setdefault(d["state_id"], []).append(cand) | |
| try: | |
| floor = json.loads(Path(args.noise).read_text())["global_rel_floor_p95"] | |
| except Exception: | |
| floor = 0.0154 | |
| done = {r["state_id"] for r in read_jsonl(args.log)} | |
| todo = [(sid, cands) for sid, cands in sorted(fires_by_state.items()) | |
| if sid not in done] | |
| print(f"{len(fires_by_state)} programs with fires; {len(todo)} to run") | |
| for sid, cands in todo: | |
| state = states[sid] | |
| criterion = (f"The following {len(cands)} issues were all identified " | |
| f"in this program:\n" + | |
| "\n".join(f"{i+1}. {c['criterion']}" | |
| for i, c in enumerate(cands))) | |
| patch = ("Apply ALL of the following fixes together:\n" + | |
| "\n".join(f"{i+1}. {c['proposed_patch']}" | |
| for i, c in enumerate(cands))) | |
| source = collect_mod.relocalize_submission(state["code"], state) | |
| new_code = patched_program(source, criterion, patch, | |
| model=args.edit_model, code_cap=16000) | |
| if new_code: | |
| new_code = collect_mod.relocalize_submission(new_code, state) | |
| row = {"state_id": sid, "competition": state["competition"], | |
| "n_fixes": len(cands), | |
| "rubric_ids": [c["id"] for c in cands]} | |
| if not new_code or new_code.strip() == source.strip(): | |
| row.update({"outcome": "edit_failed"}) | |
| append_jsonl(args.log, row); print(sid, "edit_failed"); continue | |
| workdir = Path(args.root) / state["competition"] / sid[:12] | |
| shutil.rmtree(workdir, ignore_errors=True) | |
| ex = collect_mod.execute(new_code, workdir, python=python, | |
| timeout=args.timeout) | |
| row.update({"seconds": ex.get("seconds"), | |
| "stderr_tail": (ex.get("stderr") or "")[-1200:]}) | |
| if not ex["clean"]: | |
| row.update({"outcome": "patched_run_failed", | |
| "exception": ex.get("exception_class")}) | |
| append_jsonl(args.log, row); print(sid, "run failed"); continue | |
| from mlebench.grade import grade_csv | |
| try: | |
| rep = grade_csv(workdir / "submission.csv", | |
| registry.get_competition(state["competition"])) | |
| except Exception as exc: | |
| row.update({"outcome": "grade_failed", "reason": str(exc)[:120]}) | |
| append_jsonl(args.log, row); continue | |
| before = state["grading"]["score"] | |
| lb = bool(rep.is_lower_better) | |
| delta = (before - rep.score) if lb else (rep.score - before) | |
| rel = delta / max(abs(before), 1e-9) | |
| row.update({"outcome": "measured", "score_before": before, | |
| "score_after": rep.score, "rel_improvement": round(rel, 6), | |
| "passes": rel > floor}) | |
| append_jsonl(args.log, row) | |
| print(f"{sid} {state['competition'][:22]} n={len(cands)} " | |
| f"{before:.4f}->{rep.score:.4f} rel={rel:+.4f} " | |
| f"{'PASS' if row['passes'] else ''}", flush=True) | |
| rows = read_jsonl(args.log) | |
| measured = [r for r in rows if r.get("outcome") == "measured"] | |
| passed = [r for r in measured if r["passes"]] | |
| report = {"programs_with_fires": len(fires_by_state), | |
| "measured": len(measured), "improved_above_floor": len(passed), | |
| "noise_floor": floor, | |
| "per_program": [{k: r.get(k) for k in | |
| ("state_id", "competition", "n_fixes", | |
| "outcome", "rel_improvement", "passes")} | |
| for r in rows], | |
| "note": "Compound test: all fired fixes applied at once, one " | |
| "re-run, official re-grade. Complements the per-rubric " | |
| "single-patch numbers; cannot attribute credit to " | |
| "individual rubrics."} | |
| write_json(args.out, report) | |
| print(json.dumps({k: v for k, v in report.items() if k != "per_program"}, | |
| indent=1)) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |