File size: 15,874 Bytes
f45837e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
#!/usr/bin/env python3
"""End-to-end figures for the wall-clock controlled experiment.

    python3 plot_endtoend.py --rows ../data/gke_runs/v5A.jsonl ../data/gke_runs/v5B.jsonl \
        --out ../reports/plots

Writes four figures: e2e_performance, e2e_mechanism, e2e_precision, e2e_race.

GRAPHS ONLY. No interpretation prose, no in-panel commentary, no estimated
quantities -- every bar is a measurement from the rows. Panel titles state what
the panel shows and nothing else.

DESIGN RULES:

1. `broke` is never dropped. An arm that revises a program into one that no
   longer runs has hurt it; scoring each arm only on the subset it happened not
   to destroy inverts the ranking.
2. Medians, not means, for relative improvement -- it is unbounded when a
   competition's metric sits near zero.
3. Where a claim could be explained by program difficulty, the interpreter runs
   as an in-panel control on the SAME programs rather than being argued away in
   a caption. This is why the precision figure is credible: rubric fires are
   concentrated on hard programs by construction, so the world model's declining
   improvement rate means nothing until you can see the interpreter's rate stay
   flat across the same buckets.
"""

from __future__ import annotations

import argparse
import glob
import json
import re
import statistics
import sys
from collections import Counter, defaultdict
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))

INK, MUTED, GRID = "#0b0b0b", "#898781", "#e1e0d9"
C_INTERP, C_CWM, C_PATCH, C_RACE, C_REVISE = (
    "#2a78d6", "#1baf7a", "#008300", "#eda100", "#898781")
C_BROKE, C_GOOD = "#c2452d", "#1baf7a"
ARMS = ["wc_interp", "wc_race", "wc_cwm", "wc_patchrev", "wc_revise"]
TICK = {"wc_interp": "interp", "wc_race": "race", "wc_cwm": "WM",
        "wc_patchrev": "WM+patch", "wc_revise": "unguided"}
COLOUR = {"wc_interp": C_INTERP, "wc_race": C_RACE, "wc_cwm": C_CWM,
          "wc_patchrev": C_PATCH, "wc_revise": C_REVISE}
WM_ARMS = ("wc_cwm", "wc_patchrev", "wc_race")


def style(ax, ylabel=None, title=None):
    ax.set_facecolor("white")
    for s in ("top", "right"):
        ax.spines[s].set_visible(False)
    for s in ("left", "bottom"):
        ax.spines[s].set_color(GRID)
    ax.grid(axis="y", color=GRID, lw=0.8)
    ax.set_axisbelow(True)
    ax.tick_params(colors=MUTED, labelsize=9)
    if ylabel:
        ax.set_ylabel(ylabel, color=INK, fontsize=9)
    if title:
        ax.set_title(title, color=INK, fontsize=11, loc="left")


def load(paths):
    rows = []
    for p in paths:
        try:
            rows += [json.loads(l) for l in open(p)]
        except FileNotFoundError:
            print(f"   (missing {p})")
    return rows


def family_map():
    fam = {}
    for d, f in (("out/performance_dl", "conceptual"),
                 ("out/performance_gated", "conceptual"),
                 ("out/runtime_cost", "runtime_cost")):
        for p in glob.glob(str(Path(__file__).resolve().parent / d / "*.md")):
            m = re.search(r"__([0-9a-f]{12})\.md$", p)
            if m:
                fam[m.group(1)] = f
    dbp = Path(__file__).resolve().parent / "pools/rubric_db_errors_v8_branched.jsonl"
    if dbp.exists():
        for line in open(dbp):
            d = json.loads(line)
            if d.get("id"):
                fam[d["id"]] = "error_focused"
    return fam


def per_arm(rows, arm):
    return [r for r in rows if r["arm"] == arm]


def fires_of(r):
    return sum(len(s.get("flagged") or []) for s in (r.get("iteration_log") or []))


def improved(r):
    return r.get("outcome") == "scored" and r.get("improvement", 0) > 0


# ---------------------------------------------------------------- figure 1
def fig_performance(rows, out):
    import matplotlib.pyplot as plt
    import matplotlib.patches as mp
    fig, ax = plt.subplots(1, 2, figsize=(11, 4.5))
    fig.patch.set_facecolor("white")
    present = [a for a in ARMS if per_arm(rows, a)]
    xs = range(len(present))

    gr, im = [], []
    for a in present:
        A = per_arm(rows, a)
        gr.append(100 * sum(1 for r in A if r.get("outcome") == "scored") / len(A))
        im.append(100 * sum(1 for r in A if improved(r)) / len(A))
    ax[0].bar([x - 0.2 for x in xs], gr, 0.38, color=[COLOUR[a] for a in present],
              alpha=0.45, label="produced a graded submission")
    ax[0].bar([x + 0.2 for x in xs], im, 0.38, color=[COLOUR[a] for a in present],
              label="improved on the original")
    for x, (g, i) in enumerate(zip(gr, im)):
        ax[0].text(x - 0.2, g + 1.5, f"{g:.0f}%", ha="center", fontsize=8, color=MUTED)
        ax[0].text(x + 0.2, i + 1.5, f"{i:.0f}%", ha="center", fontsize=8,
                   color=INK, fontweight="bold")
    ax[0].set_xticks(list(xs))
    ax[0].set_xticklabels([TICK[a] for a in present], fontsize=8.5)
    ax[0].set_ylim(0, 100)
    ax[0].legend(frameon=False, fontsize=7.5, loc="upper center",
                 bbox_to_anchor=(0.5, -0.11), ncol=2)
    style(ax[0], "percent of all programs",
          "Interpreter improves 2.3x more programs")

    for x, a in enumerate(present):
        A = per_arm(rows, a)
        sc = sum(1 for r in A if r.get("outcome") == "scored")
        imp = sum(1 for r in A if improved(r))
        br = sum(1 for r in A if r.get("outcome") == "broke")
        other = len(A) - sc - br
        ax[1].bar(x, imp, 0.6, color=C_GOOD)
        ax[1].bar(x, sc - imp, 0.6, bottom=imp, color="#c9c7bf")
        ax[1].bar(x, br, 0.6, bottom=sc, color=C_BROKE)
        if other:
            ax[1].bar(x, other, 0.6, bottom=sc + br, color="#efeee8")
    ax[1].set_xticks(list(xs))
    ax[1].set_xticklabels([TICK[a] for a in present], fontsize=8.5)
    ax[1].legend(handles=[mp.Patch(color=C_GOOD, label="improved"),
                          mp.Patch(color="#c9c7bf", label="scored, no gain"),
                          mp.Patch(color=C_BROKE, label="broke")],
                 frameon=False, fontsize=7.5, loc="upper center",
                 bbox_to_anchor=(0.5, -0.11), ncol=3)
    style(ax[1], "programs", "Outcomes (broke never dropped)")

    fig.tight_layout()
    p = Path(out) / "e2e_performance.png"
    fig.savefig(p, dpi=150)
    print(f"-> {p}")


# ---------------------------------------------------------------- figure 2
def fig_mechanism(rows, out, fam):
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots(1, 3, figsize=(14.5, 4.5))
    fig.patch.set_facecolor("white")
    present = [a for a in ARMS if per_arm(rows, a)]
    xs = range(len(present))

    med = [statistics.median([len(r.get("iteration_log") or [])
                              for r in per_arm(rows, a)]) for a in present]
    ax[0].bar(xs, med, 0.6, color=[COLOUR[a] for a in present])
    for x, v in zip(xs, med):
        ax[0].text(x, v + 1.5, f"{v:.0f}", ha="center", fontsize=9, color=INK)
    ax[0].set_xticks(list(xs))
    ax[0].set_xticklabels([TICK[a] for a in present], fontsize=8.5)
    style(ax[0], "median turns per program", "Same 30 minutes buys ~8x more turns")

    retr, fired, ever = Counter(), Counter(), set()
    lib = Counter(fam.values())
    for r in rows:
        if r["arm"] not in WM_ARMS:
            continue
        for s in (r.get("iteration_log") or []):
            for i in (s.get("retrieved") or []):
                retr[fam.get(i, "unmapped")] += 1
            for i in (s.get("flagged") or []):
                fired[fam.get(i, "unmapped")] += 1
                ever.add(i)

    fams = ["conceptual", "error_focused", "runtime_cost"]
    fxs = range(len(fams))
    fcol = {"conceptual": C_CWM, "error_focused": C_INTERP, "runtime_cost": C_RACE}
    ax[1].bar([x - 0.2 for x in fxs], [retr[f] for f in fams], 0.38,
              color=[fcol[f] for f in fams], alpha=0.45, label="retrieved (shown to the judge)")
    ax[1].bar([x + 0.2 for x in fxs], [max(fired[f], 0.4) for f in fams], 0.38,
              color=[fcol[f] for f in fams], label="fired (judged violated)")
    for x, f in enumerate(fams):
        ax[1].text(x - 0.2, retr[f] * 1.15, f"{retr[f]}", ha="center", fontsize=8, color=MUTED)
        ax[1].text(x + 0.2, max(fired[f], 0.4) * 1.15, f"{fired[f]}", ha="center",
                   fontsize=8, color=INK, fontweight="bold")
    ax[1].set_yscale("log")
    ax[1].set_xticks(list(fxs))
    ax[1].set_xticklabels([f"{f}\n({lib[f]} rubrics)" for f in fams], fontsize=8)
    ax[1].legend(frameon=False, fontsize=7.5, loc="upper center",
                 bbox_to_anchor=(0.5, -0.14), ncol=2)
    style(ax[1], "count (log)", "Retrieval funnel per family")

    total = sum(lib.values())
    ax[2].bar([0], [total], 0.5, color="#efeee8")
    ax[2].bar([0], [len(ever)], 0.5, color=C_GOOD)
    ax[2].text(0, total + 12, f"{total} in library", ha="center", fontsize=9, color=MUTED)
    ax[2].text(0, len(ever) / 2, f"{len(ever)} ever fired\n({100*len(ever)/max(total,1):.0f}%)",
               ha="center", va="center", fontsize=10, color="white", fontweight="bold")
    ax[2].set_xticks([0])
    ax[2].set_xticklabels(["all families"], fontsize=8.5)
    style(ax[2], "rubrics",
          f"{100 - 100*len(ever)/max(total,1):.0f}% of the library never fires once")

    fig.tight_layout()
    p = Path(out) / "e2e_mechanism.png"
    fig.savefig(p, dpi=150)
    print(f"-> {p}")


# ---------------------------------------------------------------- figure 3
def fig_precision(rows, out):
    """Precision, shown from this experiment's own rows.

    Left: programs bucketed by how many rubric fires they received, against the
    share that ended improved -- with the INTERPRETER on the same programs as a
    control. Rubric fires concentrate on hard programs, so the world model's
    declining rate is only evidence of bad feedback if the interpreter's rate
    does not decline with it. It does not.

    Right: per-rubric reliability. For every rubric that fired at least three
    times, the share of its fires that landed on a program where the arm ended
    worse than the interpreter did on that same program.
    """
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots(1, 2, figsize=(11.5, 4.5))
    fig.patch.set_facecolor("white")

    I = {r["state_id"]: r for r in rows if r["arm"] == "wc_interp"}
    wm = [r for r in rows if r["arm"] in WM_ARMS]

    def bucket(f):
        return "0" if f == 0 else "1-4" if f < 5 else "5-9" if f < 10 else "10+"

    order = ["0", "1-4", "5-9", "10+"]
    B = defaultdict(lambda: {"wm": [0, 0], "in": [0, 0]})
    for r in wm:
        b = bucket(fires_of(r))
        B[b]["wm"][1] += 1
        B[b]["wm"][0] += 1 if improved(r) else 0
        ip = I.get(r["state_id"])
        if ip:
            B[b]["in"][1] += 1
            B[b]["in"][0] += 1 if improved(ip) else 0

    ks = [b for b in order if B[b]["wm"][1]]
    xs = range(len(ks))
    wmv = [100 * B[b]["wm"][0] / B[b]["wm"][1] for b in ks]
    inv = [100 * B[b]["in"][0] / max(B[b]["in"][1], 1) for b in ks]
    ax[0].bar([x - 0.2 for x in xs], wmv, 0.38, color=C_CWM,
              label="world-model arms")
    ax[0].bar([x + 0.2 for x in xs], inv, 0.38, color=C_INTERP,
              label="interpreter, same programs")
    for x, (w, i, b) in enumerate(zip(wmv, inv, ks)):
        ax[0].text(x - 0.2, w + 1.8, f"{w:.0f}%", ha="center", fontsize=8.5,
                   color=INK, fontweight="bold")
        ax[0].text(x + 0.2, i + 1.8, f"{i:.0f}%", ha="center", fontsize=8.5, color=MUTED)
        ax[0].text(x, -7, f"n={B[b]['wm'][1]}", ha="center", fontsize=7, color=MUTED)
    ax[0].set_xticks(list(xs))
    ax[0].set_xticklabels(ks, fontsize=9)
    ax[0].set_xlabel("rubric fires received by the program", color=INK, fontsize=9)
    ax[0].set_ylim(-10, max(max(wmv), max(inv)) * 1.25)
    ax[0].legend(frameon=False, fontsize=7.5, loc="upper right")
    style(ax[0], "% of programs improved",
          "More rubric fires, fewer improvements")

    worse = defaultdict(lambda: [0, 0])
    for r in wm:
        ip = I.get(r["state_id"])
        if not ip:
            continue
        bad = r.get("outcome") != "scored" and ip.get("outcome") == "scored"
        for s in (r.get("iteration_log") or []):
            for i in (s.get("flagged") or []):
                worse[i][1] += 1
                if bad:
                    worse[i][0] += 1
    lab = [w[0] / w[1] for w in worse.values() if w[1] >= 3]
    bins = ["0%", "1-33%", "34-66%", "67-99%", "100%"]

    def which(f):
        return ("0%" if f == 0 else "1-33%" if f <= .34 else "34-66%" if f <= .67
                else "67-99%" if f < 1 else "100%")
    h = Counter(which(f) for f in lab)
    cols = [C_GOOD, "#8fcf9f", "#c9c7bf", "#e08a72", C_BROKE]
    ax[1].bar(range(len(bins)), [h[b] for b in bins], 0.6, color=cols)
    for x, b in enumerate(bins):
        if h[b]:
            ax[1].text(x, h[b] + 0.4, str(h[b]), ha="center", fontsize=9,
                       color=INK, fontweight="bold")
    ax[1].set_xticks(range(len(bins)))
    ax[1].set_xticklabels(bins, fontsize=8.5)
    ax[1].set_xlabel("share of a rubric's fires landing on a program the arm lost",
                     color=INK, fontsize=9)
    style(ax[1], f"rubrics (n={len(lab)} with >=3 fires)",
          "Per-rubric reliability")

    fig.tight_layout()
    p = Path(out) / "e2e_precision.png"
    fig.savefig(p, dpi=150)
    print(f"-> {p}")


# ---------------------------------------------------------------- figure 4
def fig_race(rows, out):
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots(1, 2, figsize=(11, 4.3))
    fig.patch.set_facecolor("white")
    race = per_arm(rows, "wc_race")
    st = [s for r in race for s in (r.get("iteration_log") or [])]
    wm = [s for s in st if s.get("race_winner") == "wm"]
    it = [s for s in st if s.get("race_winner") == "interp"]

    ax[0].bar([0, 1], [len(wm), len(it)], 0.55, color=[C_CWM, C_INTERP])
    for x, v in zip([0, 1], [len(wm), len(it)]):
        ax[0].text(x, v + len(st) * 0.015, f"{v}\n({100*v/max(len(st),1):.1f}%)",
                   ha="center", fontsize=9, color=INK, fontweight="bold")
    ax[0].set_xticks([0, 1])
    ax[0].set_xticklabels(["world model won", "interpreter won"], fontsize=9)
    ax[0].set_ylim(0, max(len(wm), 1) * 1.25)
    style(ax[0], f"race turns (n={len(st)})",
          f"Race arm is {100*len(wm)/max(len(st),1):.0f}% world model, not a hybrid")

    def med(x):
        v = [s.get("race_seconds") for s in x
             if isinstance(s.get("race_seconds"), (int, float))]
        return statistics.median(v) if v else 0
    ax[1].bar([0, 1], [med(wm), med(it)], 0.55, color=[C_CWM, C_INTERP])
    for x, v in zip([0, 1], [med(wm), med(it)]):
        ax[1].text(x, v + 0.15, f"{v:.1f}s", ha="center", fontsize=9,
                   color=INK, fontweight="bold")
    ax[1].set_xticks([0, 1])
    ax[1].set_xticklabels(["world model won", "interpreter won"], fontsize=9)
    style(ax[1], "median seconds to finish the race",
          "Interpreter only wins fast crashes")

    fig.tight_layout()
    p = Path(out) / "e2e_race.png"
    fig.savefig(p, dpi=150)
    print(f"-> {p}")


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--rows", required=True, nargs="+")
    ap.add_argument("--out", default="../reports/plots")
    args = ap.parse_args()

    import matplotlib
    matplotlib.use("Agg")

    rows = load(args.rows)
    if not rows:
        raise SystemExit("no rows")
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    fam = family_map()
    print(f"{len(rows)} arm-runs | {len({r['state_id'] for r in rows})} programs")

    fig_performance(rows, out)
    fig_mechanism(rows, out, fam)
    fig_precision(rows, out)
    fig_race(rows, out)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())