Download code/rubric_gen/make_causal_browser.py from EdwardoSunny/agent-cwm-rubrics-debug: direct link, hf CLI and curl.
- Browser
- Download file 9.37 kB
-
https://huggingface.co/datasets/EdwardoSunny/agent-cwm-rubrics-debug/resolve/main/code/rubric_gen/make_causal_browser.py
- Command line
-
hf download hf://datasets/EdwardoSunny/agent-cwm-rubrics-debug/code/rubric_gen/make_causal_browser.py
-
curl -L -o make_causal_browser.py https://huggingface.co/datasets/EdwardoSunny/agent-cwm-rubrics-debug/resolve/main/code/rubric_gen/make_causal_browser.py
9.37 kB
| #!/usr/bin/env python3 | |
| """Causal-vs-pair comparison plot + per-fire trace browser. Data only. | |
| python3 make_causal_browser.py --out causal_browser.html | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import base64 | |
| import html | |
| import io | |
| import json | |
| import re | |
| import time | |
| from collections import defaultdict | |
| from pathlib import Path | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| HERE = Path(__file__).resolve().parent | |
| plt.rcParams.update({"figure.facecolor": "#0f1115", "axes.facecolor": "#141822", | |
| "axes.edgecolor": "#2a2f3a", "text.color": "#e6e6e6", | |
| "axes.labelcolor": "#e6e6e6", "xtick.color": "#c8d0dc", | |
| "ytick.color": "#9aa4b2", "font.size": 11}) | |
| GREEN, BLUE = "#7ee08a", "#8ab4ff" | |
| def jl(name): | |
| try: | |
| return [json.loads(l) for l in (HERE / "data" / name).read_text().splitlines() if l.strip()] | |
| except OSError: | |
| return [] | |
| def jload(name): | |
| try: | |
| return json.loads((HERE / "data" / name).read_text()) | |
| except OSError: | |
| return None | |
| def compute() -> dict: | |
| noise = jload("noise_floor.json") | |
| floor = noise["global_rel_floor_p95"] | |
| pr = jload("pr_results.json") | |
| cf = jl("counterfactual_runs.jsonl") | |
| scored = [s for s in jl("eval_scored.jsonl") | |
| if (s.get("grading") or {}).get("graded")] | |
| g = {s["state_id"]: s for s in scored} | |
| best: dict[str, tuple] = {} | |
| for s in scored: | |
| c, lb, v = s["competition"], s["grading"]["is_lower_better"], s["grading"]["score"] | |
| if c not in best or (v < best[c][0]) == lb: | |
| best[c] = (v, lb) | |
| measured = [r for r in cf if r.get("outcome") == "measured"] | |
| for r in measured: | |
| r["rel"] = r["improvement"] / max(abs(r.get("score_before") or 1e-9), 1e-9) | |
| r["verdict"] = ("improved" if r["rel"] > floor | |
| else "harmed" if r["rel"] < -floor else "within_noise") | |
| improved = [r for r in measured if r["verdict"] == "improved"] | |
| tested = {r["state_id"] for r in measured} | |
| den = [sid for sid in tested if sid in g | |
| and abs(g[sid]["grading"]["score"] - best[g[sid]["competition"]][0]) | |
| / max(abs(best[g[sid]["competition"]][0]), 1e-9) > floor] | |
| num = {r["state_id"] for r in improved} & set(den) | |
| fam = (pr or {}).get("by_family", {}).get("conceptual", {}) | |
| return { | |
| "floor": floor, | |
| "pair_precision": fam.get("precision"), | |
| "pair_recall": fam.get("recall"), | |
| "causal_precision": len(improved) / len(measured) if measured else None, | |
| "causal_recall": len(num) / len(den) if den else None, | |
| "causal_recall_def": (f"states with ≥1 above-noise-improving fire " | |
| f"({len(num)}) / tested states with above-noise " | |
| f"gap to best ({len(den)})"), | |
| "causal_precision_def": (f"fires improving above noise ({len(improved)}) " | |
| f"/ tested fires ({len(measured)})"), | |
| "measured": measured, | |
| } | |
| def fig_comparison(m) -> str: | |
| fig, ax = plt.subplots(figsize=(7.2, 3.8)) | |
| groups = ["precision", "recall"] | |
| pair_vals = [m["pair_precision"], m["pair_recall"]] | |
| causal_vals = [m["causal_precision"], m["causal_recall"]] | |
| x = range(len(groups)) | |
| w = 0.34 | |
| b1 = ax.bar([i - w / 2 for i in x], pair_vals, w, color=BLUE, | |
| label="weak-vs-strong (pair annotation)") | |
| b2 = ax.bar([i + w / 2 for i in x], causal_vals, w, color=GREEN, | |
| label="causal (patch-and-rerun)") | |
| for bars in (b1, b2): | |
| for b in bars: | |
| ax.text(b.get_x() + b.get_width() / 2, b.get_height() + 0.008, | |
| f"{b.get_height():.3f}", ha="center", fontsize=10) | |
| ax.set_xticks(list(x)); ax.set_xticklabels(groups) | |
| ax.set_ylim(0, 0.62) | |
| ax.legend(frameon=False, loc="upper left") | |
| ax.set_title("Precision and recall under the two ground-truth standards " | |
| "(held-out competitions)") | |
| buf = io.BytesIO() | |
| fig.savefig(buf, format="png", dpi=135, bbox_inches="tight") | |
| plt.close(fig) | |
| return base64.b64encode(buf.getvalue()).decode() | |
| def rubric_meta() -> dict: | |
| """id-suffix -> (title, pattern, patch) from the written rubric files.""" | |
| out = {} | |
| for path in sorted((HERE / "out" / "conceptual").glob("*.md")): | |
| text = path.read_text() | |
| title = re.search(r"### P1 — (.+)", text) | |
| pattern = re.search(r"\*\*Pattern\*\*:\s*(.+)", text) | |
| out[path.stem] = { | |
| "title": title.group(1) if title else path.stem, | |
| "pattern": pattern.group(1) if pattern else "", | |
| } | |
| return out | |
| def trace_cards(m) -> str: | |
| lib = {} | |
| for row in jl("conceptual_applicable.jsonl"): | |
| lib[row["id"]] = row | |
| meta = rubric_meta() | |
| dec = {(d["rubric_id"], d["state_id"]): d for d in jl("pr_decisions.jsonl") | |
| if d.get("fires")} | |
| order = {"improved": 0, "harmed": 1, "within_noise": 2} | |
| cards = [] | |
| for r in sorted(m["measured"], key=lambda r: (order[r["verdict"]], -abs(r["rel"]))): | |
| rid = r["rubric_id"] | |
| cand = lib.get(rid.rsplit("__", 1)[-1], {}) | |
| info = meta.get(rid, {}) | |
| d = dec.get((rid, r["state_id"]), {}) | |
| v = r["verdict"] | |
| badge = {"improved": "g", "harmed": "r", "within_noise": "y"}[v] | |
| cards.append(f""" | |
| <details class=t data-v="{v}"><summary> | |
| <span class="badge {badge}">{v.replace('_', ' ')}</span> | |
| <span class=delta>{r['rel']:+.3%}</span> | |
| <span class=title>{html.escape(info.get('title', rid))}</span> | |
| <span class=comp>{html.escape(r['competition'])}</span></summary> | |
| <div class=body> | |
| <div class=kv><b>rubric</b> {html.escape(rid)}</div> | |
| <div class=kv><b>pattern</b> {html.escape(info.get('pattern', ''))}</div> | |
| <div class=kv><b>judge evidence for the fire</b> {html.escape(d.get('evidence', ''))}</div> | |
| <div class=kv><b>proposed fix applied</b> {html.escape(cand.get('proposed_patch', ''))}</div> | |
| <div class=kv><b>score</b> {r.get('score_before')} → {r.get('score_after')} | |
| (improvement {r['improvement']:+.6f}, relative {r['rel']:+.3%}, | |
| noise floor ±{m['floor']:.2%})</div> | |
| <div class=kv><b>state</b> {html.escape(r['state_id'])} · {html.escape(r.get('trajectory', ''))}</div> | |
| </div></details>""") | |
| return "\n".join(cards) | |
| def main() -> int: | |
| ap = argparse.ArgumentParser(description=__doc__) | |
| ap.add_argument("--out", default=str(HERE / "causal_browser.html")) | |
| args = ap.parse_args() | |
| m = compute() | |
| counts = defaultdict(int) | |
| for r in m["measured"]: | |
| counts[r["verdict"]] += 1 | |
| page = f"""<!doctype html><html><head><meta charset=utf-8> | |
| <title>causal traces — conceptual rubrics</title><style> | |
| body{{font-family:-apple-system,Segoe UI,Helvetica,sans-serif;background:#0f1115;color:#e6e6e6;margin:0}} | |
| header{{padding:20px 32px;background:#161a22;border-bottom:1px solid #2a2f3a}} | |
| h1{{margin:0;font-size:19px}} .sub{{color:#9aa4b2;font-size:12px;margin-top:4px}} | |
| main{{max-width:1050px;margin:0 auto;padding:22px 32px}} | |
| .card{{background:#141822;border:1px solid #2a2f3a;border-radius:8px;padding:14px;margin:12px 0}} | |
| img{{max-width:100%}} | |
| .filter button{{background:#161a22;color:#e6e6e6;border:1px solid #2a2f3a;border-radius:4px;padding:4px 12px;margin-right:6px;cursor:pointer}} | |
| .filter button.on{{background:#2a3550;border-color:#8ab4ff}} | |
| details.t{{border:1px solid #2a2f3a;border-radius:6px;margin:7px 0;background:#141822}} | |
| summary{{cursor:pointer;padding:9px 12px;display:flex;gap:12px;align-items:center;font-size:13px}} | |
| .badge{{padding:2px 8px;border-radius:10px;font-size:11px;min-width:86px;text-align:center}} | |
| .badge.g{{background:#153822;color:#7ee08a}} .badge.r{{background:#3a1820;color:#ff7d7d}} | |
| .badge.y{{background:#332b12;color:#ffd479}} | |
| .delta{{min-width:70px;font-variant-numeric:tabular-nums}} | |
| .title{{flex:1}} .comp{{color:#9aa4b2;font-size:12px}} | |
| .body{{padding:4px 16px 12px;font-size:13px;line-height:1.55}} | |
| .kv{{margin:5px 0}} .kv b{{color:#8ab4ff;display:inline-block;min-width:190px;font-weight:600}} | |
| </style> | |
| <script>function f(v,b){{document.querySelectorAll('.filter button').forEach(x=>x.classList.remove('on'));b.classList.add('on'); | |
| document.querySelectorAll('details.t').forEach(d=>d.style.display=(v==='all'||d.dataset.v===v)?'':'none');}}</script> | |
| </head><body> | |
| <header><h1>Conceptual rubrics — causal traces</h1> | |
| <div class=sub>pair standard: annotator marks rubrics explaining a weak-vs-strong gap · | |
| causal standard: patch the fire, re-run, re-grade · | |
| causal precision = {html.escape(m['causal_precision_def'])} · | |
| causal recall = {html.escape(m['causal_recall_def'])} · | |
| generated {time.strftime('%F %T UTC', time.gmtime())}</div></header> | |
| <main> | |
| <div class=card><img src="data:image/png;base64,{fig_comparison(m)}"></div> | |
| <div class="card filter"> | |
| <button class=on onclick="f('all',this)">all ({len(m['measured'])})</button> | |
| <button onclick="f('improved',this)">improved ({counts['improved']})</button> | |
| <button onclick="f('within_noise',this)">within noise ({counts['within_noise']})</button> | |
| <button onclick="f('harmed',this)">harmed ({counts['harmed']})</button> | |
| </div> | |
| {trace_cards(m)} | |
| </main></body></html>""" | |
| Path(args.out).write_text(page) | |
| print(f"-> {args.out}") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |