Download code/rubric_gen/plot_wallclock.py from EdwardoSunny/agent-cwm-rubrics-debug: direct link, hf CLI and curl.
- Browser
- Download file 13.3 kB
-
https://huggingface.co/datasets/EdwardoSunny/agent-cwm-rubrics-debug/resolve/main/code/rubric_gen/plot_wallclock.py
- Command line
-
hf download hf://datasets/EdwardoSunny/agent-cwm-rubrics-debug/code/rubric_gen/plot_wallclock.py
-
curl -L -o plot_wallclock.py https://huggingface.co/datasets/EdwardoSunny/agent-cwm-rubrics-debug/resolve/main/code/rubric_gen/plot_wallclock.py
13.3 kB
| #!/usr/bin/env python3 | |
| """Plots for the wall-clock controlled experiment. | |
| python3 plot_wallclock.py --rows ../data/gke_runs/wcN1.jsonl \ | |
| ../data/gke_runs/wcS2.jsonl --out reports/plots | |
| Four figures, in the order the argument has to be made: | |
| 1. TURNS PER ARM -- the mechanism. Equalising wall clock instead of turns is | |
| the whole design, so the first thing to show is that it actually bought the | |
| execution-free arms more iterations. | |
| 2. WHERE THE BUDGET WENT -- why. An arm that spends most of its 1800s waiting | |
| on the interpreter is the finding, not a footnote. | |
| 3. OUTCOMES -- scored / improved / broke, stacked. `broke` is a real loss and | |
| is never dropped: an arm that revises a program into one that no longer | |
| runs has hurt it, and hiding that would score each arm only on the subset | |
| it happened not to destroy. | |
| 4. ADVANTAGE vs EXECUTION COST -- the actual hypothesis. The claim is that an | |
| execution-free channel wins where execution is expensive, so the headline | |
| is the RELATIONSHIP, not a pooled mean that mixes regimes. | |
| Medians, not means, wherever an outlier could dominate: relative improvement | |
| is unbounded when a competition's metric sits near zero (measured live, | |
| dogs-vs-cats log-loss 0.0444 -> 8.0075 is a real degradation but reads as | |
| -17955%, and one such row moves a 20-program mean by ~900 points). | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import statistics | |
| import sys | |
| from collections import defaultdict | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from common import read_jsonl | |
| # The repo's validated reference palette (codeworld-gym/scripts/make_report_plots.py). | |
| INK = "#0b0b0b" | |
| MUTED = "#898781" | |
| GRID = "#e1e0d9" | |
| ARM_COLOUR = { | |
| "wc_interp": "#2a78d6", # the baseline that has ground truth | |
| "wc_cwm": "#1baf7a", # the execution-free world model | |
| "wc_patchrev": "#008300", # world model + surgical diffs | |
| "wc_race": "#eda100", # world model raced against the interpreter | |
| "wc_revise": "#898781", # unguided control: deliberately grey, it is a floor | |
| } | |
| ARM_LABEL = { | |
| "wc_interp": "interpreter", "wc_cwm": "world model", | |
| "wc_patchrev": "WM + patch", "wc_race": "WM ⚡ race", | |
| "wc_revise": "unguided (floor)", | |
| } | |
| OUTLIER_ABS = 10.0 | |
| def _style(ax): | |
| ax.spines[["top", "right"]].set_visible(False) | |
| ax.spines[["left", "bottom"]].set_color(GRID) | |
| ax.tick_params(colors=MUTED, labelsize=9) | |
| ax.yaxis.grid(True, color=GRID, lw=0.8) | |
| ax.set_axisbelow(True) | |
| def load(paths: list[str]) -> list[dict]: | |
| rows, seen = [], set() | |
| for p in paths: | |
| for r in read_jsonl(p): | |
| k = (r.get("state_id"), r.get("arm")) | |
| if not r.get("arm") or k in seen: | |
| continue | |
| seen.add(k) | |
| rows.append(r) | |
| return rows | |
| def fig_turns(rows, ax): | |
| arms = [a for a in ARM_COLOUR if any(r["arm"] == a for r in rows)] | |
| data = [[r["iterations"] for r in rows | |
| if r["arm"] == a and r.get("iterations") is not None] for a in arms] | |
| ax.bar([ARM_LABEL[a] for a in arms], | |
| [statistics.median(d) if d else 0 for d in data], | |
| color=[ARM_COLOUR[a] for a in arms], width=0.62) | |
| for i, d in enumerate(data): | |
| if d: | |
| ax.text(i, statistics.median(d), f" {statistics.median(d):.0f}", | |
| ha="center", va="bottom", fontsize=9, color=INK) | |
| ax.set_title("Turns taken inside the same 30-minute budget", | |
| fontsize=11, color=INK, loc="left") | |
| ax.set_ylabel("median turns", fontsize=9, color=MUTED) | |
| _style(ax) | |
| def fig_budget(rows, ax): | |
| arms = [a for a in ARM_COLOUR if any(r["arm"] == a for r in rows)] | |
| cats = ["execution", "race_interp", "wm_judge", "wm_judge_final", | |
| "retrieval", "patch_edit", "coder"] | |
| shades = {"execution": "#e34948", "race_interp": "#e87ba4", | |
| "wm_judge": "#1baf7a", "wm_judge_final": "#7ee08a", | |
| "retrieval": "#2a78d6", "patch_edit": "#008300", | |
| "coder": "#c3c2b7"} | |
| bottom = [0.0] * len(arms) | |
| for c in cats: | |
| vals = [] | |
| for a in arms: | |
| xs = [(r.get("budget") or {}).get("spent_by_category", {}).get(c, 0.0) | |
| for r in rows if r["arm"] == a] | |
| vals.append(statistics.fmean(xs) if xs else 0.0) | |
| if not any(vals): | |
| continue | |
| ax.bar([ARM_LABEL[a] for a in arms], vals, bottom=bottom, | |
| color=shades[c], label=c, width=0.62) | |
| bottom = [b + v for b, v in zip(bottom, vals)] | |
| ax.set_title("Where each arm's budget went (mean seconds)", | |
| fontsize=11, color=INK, loc="left") | |
| ax.legend(fontsize=7, frameon=False, ncol=2) | |
| _style(ax) | |
| def fig_outcomes(rows, ax): | |
| arms = [a for a in ARM_COLOUR if any(r["arm"] == a for r in rows)] | |
| imp, flat, broke = [], [], [] | |
| for a in arms: | |
| sub = [r for r in rows if r["arm"] == a] | |
| sc = [r for r in sub if r.get("outcome") == "scored"] | |
| imp.append(sum(1 for r in sc if r.get("improvement", 0) > 0)) | |
| flat.append(len(sc) - imp[-1]) | |
| broke.append(sum(1 for r in sub if r.get("outcome") == "broke")) | |
| lbl = [ARM_LABEL[a] for a in arms] | |
| ax.bar(lbl, imp, color="#1baf7a", label="improved", width=0.62) | |
| ax.bar(lbl, flat, bottom=imp, color="#c3c2b7", label="scored, no gain", | |
| width=0.62) | |
| ax.bar(lbl, broke, bottom=[i + f for i, f in zip(imp, flat)], | |
| color="#e34948", label="broke the program", width=0.62) | |
| ax.set_title("Outcomes per arm (broke is a real loss, never dropped)", | |
| fontsize=11, color=INK, loc="left") | |
| ax.set_ylabel("programs", fontsize=9, color=MUTED) | |
| ax.legend(fontsize=8, frameon=False) | |
| _style(ax) | |
| def fig_advantage(rows, ax, control="wc_interp"): | |
| """Paired advantage over the interpreter, against execution cost.""" | |
| cost = defaultdict(list) | |
| for r in rows: | |
| if r["arm"] not in ("wc_interp", "wc_race"): | |
| continue | |
| cat = (r.get("budget") or {}).get("spent_by_category") or {} | |
| secs = cat.get("execution", 0.0) or cat.get("race_interp", 0.0) | |
| n = r.get("iterations") or 0 | |
| if secs and n: | |
| cost[r["competition"]].append(secs / n) | |
| cost = {k: statistics.fmean(v) for k, v in cost.items()} | |
| by_state = defaultdict(dict) | |
| comp_of = {} | |
| for r in rows: | |
| if r.get("outcome") == "scored": | |
| by_state[r["state_id"]][r["arm"]] = r["relative_improvement"] | |
| comp_of[r["state_id"]] = r["competition"] | |
| plotted = False | |
| for a in ("wc_cwm", "wc_patchrev", "wc_race"): | |
| xs, ys = [], [] | |
| for sid, v in by_state.items(): | |
| if a in v and control in v and comp_of[sid] in cost: | |
| d = v[a] - v[control] | |
| if abs(d) > OUTLIER_ABS: | |
| continue # metric artifact, see module docstring | |
| xs.append(cost[comp_of[sid]]) | |
| ys.append(100 * d) | |
| if xs: | |
| ax.scatter(xs, ys, s=42, color=ARM_COLOUR[a], label=ARM_LABEL[a], | |
| alpha=0.85, edgecolor="white", linewidth=0.6) | |
| plotted = True | |
| ax.axhline(0, color=INK, lw=1) | |
| ax.set_xscale("log") | |
| ax.set_xlabel("seconds per real execution (log)", fontsize=9, color=MUTED) | |
| ax.set_ylabel("advantage over interpreter (pp)", fontsize=9, color=MUTED) | |
| ax.set_title("The hypothesis: does the execution-free channel win where\n" | |
| "execution is expensive?", fontsize=11, color=INK, loc="left") | |
| if plotted: | |
| ax.legend(fontsize=8, frameon=False) | |
| else: | |
| ax.text(0.5, 0.5, "no paired states yet", ha="center", va="center", | |
| transform=ax.transAxes, color=MUTED, fontsize=10) | |
| _style(ax) | |
| def fig_library(un, ga, ax_out, ax_use, arm="wc_cwm"): | |
| """Gated vs ungated library, on the programs run under BOTH. | |
| Restricting to the common set is not cosmetic. The two libraries scored | |
| different subsets (9 vs 12 of 19), so a pooled median silently compares | |
| different programs -- and the gated library's extra scored programs are | |
| exactly the hard ones the ungated library destroyed, which biases the | |
| comparison AGAINST gating on any metric conditioned on scoring. | |
| """ | |
| UN = {r["state_id"]: r for r in un if r["arm"] == arm} | |
| GA = {r["state_id"]: r for r in ga if r["arm"] == arm} | |
| common = sorted(set(UN) & set(GA)) | |
| # Left: outcome shift. `broke` is the cost of a wrong fire, so it is the | |
| # quantity precision gating is supposed to move. | |
| labels = ["ungated\n430 rubrics", "gated\n22 rubrics"] | |
| scored = [sum(1 for s in common if UN[s].get("outcome") == "scored"), | |
| sum(1 for s in common if GA[s].get("outcome") == "scored")] | |
| broke = [len(common) - scored[0], len(common) - scored[1]] | |
| x = range(2) | |
| ax_out.bar(x, scored, 0.55, color="#1baf7a", label="scored") | |
| ax_out.bar(x, broke, 0.55, bottom=scored, color="#c2452d", label="broke") | |
| # Segments are labelled in place rather than via a legend: a legend box in | |
| # this panel lands on top of a full-height bar and its swatch disappears | |
| # against the fill. | |
| for i, (s, b) in enumerate(zip(scored, broke)): | |
| ax_out.text(i, s / 2, f"{s} scored" if i == 0 else str(s), | |
| ha="center", va="center", color="white", | |
| fontsize=11, fontweight="bold") | |
| ax_out.text(i, s + b / 2, f"{b} broke" if i == 0 else str(b), | |
| ha="center", va="center", color="white", | |
| fontsize=11, fontweight="bold") | |
| ax_out.set_xticks(list(x)) | |
| ax_out.set_xticklabels(labels, fontsize=9) | |
| ax_out.set_ylabel(f"programs (n={len(common)} run under both)") | |
| ax_out.set_title("Precision gating breaks fewer programs", fontsize=11, | |
| color=INK, loc="left") | |
| _style(ax_out) | |
| # Right: the cost of gating. Fires collapse -- which is the point -- but so | |
| # does budget utilisation, and that is the constraint gating cannot fix. | |
| def fires(rows): | |
| a = [r for r in rows if r["arm"] == arm] | |
| f = sum(len(s.get("flagged") or []) for r in a | |
| for s in (r.get("iteration_log") or [])) | |
| t = sum(len(r.get("iteration_log") or []) for r in a) | |
| used = statistics.fmean([(r.get("budget") or {}).get("elapsed_seconds", 0) | |
| for r in a] or [0]) | |
| return 100 * f / max(t, 1), 100 * used / 1800 | |
| (fu, bu), (fg, bg) = fires(un), fires(ga) | |
| xs = [0, 1] | |
| ax_use.bar([i - 0.19 for i in xs], [fu, fg], 0.36, color="#2a78d6", | |
| label="fire rate (% of turns)") | |
| ax_use.bar([i + 0.19 for i in xs], [bu, bg], 0.36, color="#eda100", | |
| label="budget used (% of 1800s)") | |
| for i, v in zip([-0.19, 0.81], [fu, fg]): | |
| ax_use.text(i, v + 1.5, f"{v:.1f}%", ha="center", fontsize=8, color=INK) | |
| for i, v in zip([0.19, 1.19], [bu, bg]): | |
| ax_use.text(i, v + 1.5, f"{v:.0f}%", ha="center", fontsize=8, color=INK) | |
| ax_use.set_xticks(xs) | |
| ax_use.set_xticklabels(labels, fontsize=9) | |
| ax_use.set_ylabel("percent") | |
| ax_use.set_title("...but runs out of things to say (17% of budget)", | |
| fontsize=11, color=INK, loc="left") | |
| ax_use.legend(frameon=False, fontsize=8) | |
| _style(ax_use) | |
| def main() -> int: | |
| ap = argparse.ArgumentParser(description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--rows", required=True, nargs="+") | |
| ap.add_argument("--gated-rows", nargs="*", default=[], | |
| help="Rows from the causally-gated library run; adds the " | |
| "library-comparison figure.") | |
| ap.add_argument("--out", default="reports/plots") | |
| ap.add_argument("--tag", default="wallclock") | |
| args = ap.parse_args() | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| rows = load(args.rows) | |
| if not rows: | |
| raise SystemExit("no rows") | |
| out = Path(args.out) | |
| out.mkdir(parents=True, exist_ok=True) | |
| fig, axes = plt.subplots(2, 2, figsize=(13, 9)) | |
| fig.patch.set_facecolor("white") | |
| fig_turns(rows, axes[0][0]) | |
| fig_budget(rows, axes[0][1]) | |
| fig_outcomes(rows, axes[1][0]) | |
| fig_advantage(rows, axes[1][1]) | |
| progs = len({r["state_id"] for r in rows}) | |
| fig.suptitle(f"Wall-clock controlled experiment — {len(rows)} arm-runs, " | |
| f"{progs} held-out programs, 1800s per arm", | |
| fontsize=13, color=INK, x=0.02, ha="left") | |
| fig.tight_layout(rect=(0, 0, 1, 0.96)) | |
| p = out / f"{args.tag}.png" | |
| fig.savefig(p, dpi=160) | |
| print(f"-> {p}") | |
| if args.gated_rows: | |
| ga = load(args.gated_rows) | |
| f2, ax2 = plt.subplots(1, 2, figsize=(11, 4.4)) | |
| f2.patch.set_facecolor("white") | |
| fig_library(rows, ga, ax2[0], ax2[1]) | |
| f2.suptitle("Causally gated vs ungated rubric library — the two levers " | |
| "are multiplicative", | |
| fontsize=12, color=INK, x=0.02, ha="left") | |
| f2.tight_layout(rect=(0, 0, 1, 0.93)) | |
| p2 = out / f"{args.tag}_library.png" | |
| f2.savefig(p2, dpi=160) | |
| print(f"-> {p2}") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |