"""Figures for the trace-analysis report. Rendered as PNG for embedding in the markdown report. Colour follows the reference categorical palette in fixed slot order (never cycled), sequential work uses a single hue, and every multi-series panel carries a legend so identity is never colour-alone. """ from __future__ import annotations import os from collections import defaultdict import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt # noqa: E402 import numpy as np # noqa: E402 # Categorical slots, fixed order (light mode). C = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#4a3aa7", "#e34948"] SURFACE = "#fcfcfb" INK = "#0b0b0b" INK2 = "#52514e" MUTED = "#8a8982" GRID = "#e4e3df" FIG_ROOT = os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "docs", "results", "figures", ) plt.rcParams.update( { "figure.facecolor": SURFACE, "axes.facecolor": SURFACE, "savefig.facecolor": SURFACE, "axes.edgecolor": GRID, "axes.labelcolor": INK2, "text.color": INK, "xtick.color": INK2, "ytick.color": INK2, "grid.color": GRID, "font.size": 10, "axes.titlesize": 12, "axes.titleweight": "bold", "axes.spines.top": False, "axes.spines.right": False, "figure.dpi": 150, } ) def _save(fig, name: str, agent: str) -> str: out = os.path.join(FIG_ROOT, agent) os.makedirs(out, exist_ok=True) path = os.path.join(out, name) fig.tight_layout() fig.savefig(path, bbox_inches="tight") plt.close(fig) print(f" wrote {path}") return path def _inc(feats): return [f for f in feats if f.cohort in ("primary", "recovered")] # --- 1. where the ten hours went ------------------------------------------- def fig_time_budget(feats, agent: str): """Stacked hours per benchmark, split by what was running. Each category sums its background-task time and its foreground-command time, because the two scaffolds put the same work in different places: Claude launches training with `run_in_background` and polls (so a foreground-only accounting shows almost no training), while Codex runs everything as a blocking command (so a background-only accounting shows nothing at all). Blocking waits are excluded from both -- they sit on top of a background job that is already counted. """ inc = _inc(feats) # label -> (background categories, foreground action labels) parts = [ ("training", ("bg_train",), ("train",)), ("generation", ("bg_generate",), ("generate",)), ("evaluation", ("bg_eval",), ("eval_official", "eval_custom")), ("data prep", ("bg_data",), ("data_prep", "contamination_check")), ("other jobs", ("bg_other",), ("python_inline", "shell_other")), ] by_task: defaultdict[str, list] = defaultdict(list) for f in inc: by_task[f.task].append(f) tasks = sorted(by_task) mat = np.zeros((len(tasks), len(parts) + 1)) for i, t in enumerate(tasks): g = by_task[t] for j, (_, bgs, acts) in enumerate(parts): mat[i, j] = np.mean( [ sum(f.bg_time_s.get(b, 0.0) for b in bgs) / 3600 + sum(f.action_time_s.get(a, 0.0) for a in acts) / 3600 for f in g ] ) mat[i, -1] = np.mean([f.dead_air_h or 0.0 for f in g]) fig, ax = plt.subplots(figsize=(9, 4.2)) left = np.zeros(len(tasks)) y = np.arange(len(tasks)) labels = [p[0] for p in parts] + ["idle (nothing running)"] for j, (lab, col) in enumerate(zip(labels, C[:5] + [MUTED])): ax.barh(y, mat[:, j], left=left, height=0.62, color=col, label=lab, edgecolor=SURFACE, linewidth=2) left += mat[:, j] ax.set_yticks(y, tasks) ax.invert_yaxis() ax.set_xlabel("mean job-hours per run (concurrent jobs may overlap)") ax.set_title(f"Where a 10-hour run goes — {agent}") ax.grid(axis="x", lw=0.6) ax.set_axisbelow(True) ax.legend(frameon=False, ncol=6, loc="upper center", bbox_to_anchor=(0.5, -0.22), fontsize=8.5) return _save(fig, "time_budget_by_task.png", agent) # --- 2. score trajectories --------------------------------------------------- def fig_score_trajectories(feats, agent: str): """Every score the agent observed, over time, one panel per benchmark.""" inc = [f for f in _inc(feats) if f.observed_scores] by_task: defaultdict[str, list] = defaultdict(list) for f in inc: by_task[f.task].append(f) tasks = sorted(by_task) ncol = 4 nrow = (len(tasks) + ncol - 1) // ncol fig, axes = plt.subplots(nrow, ncol, figsize=(13, 3.1 * nrow), sharex=True) axes = np.atleast_1d(axes).ravel() for ax, task in zip(axes, tasks): for f in by_task[task]: xs = [t / 3600 for t, _ in f.observed_scores] ys = [v for _, v in f.observed_scores] ax.plot(xs, ys, lw=2, color=C[0], alpha=0.45, marker="o", ms=4) if f.accuracy is not None: ax.plot([f.wall_h], [f.accuracy], marker="*", ms=12, color=C[1], zorder=5) ax.set_title(task) ax.grid(lw=0.6) ax.set_axisbelow(True) ax.set_ylim(-0.03, 1.0) for ax in axes[len(tasks):]: ax.set_visible(False) for ax in axes[: len(tasks)]: ax.set_xlabel("hours into the run") axes[0].set_ylabel("score the agent saw") fig.suptitle( "Self-measured score over time (blue) vs the harness' final grade (orange star)", y=1.0, fontsize=12, fontweight="bold", ) return _save(fig, "score_trajectories.png", agent) # --- 3. diminishing returns -------------------------------------------------- def fig_progress_curve(feats, agent: str): """Fraction of a run's total gain captured by fraction of time elapsed. Each run is normalised to its own first and best observed score, so runs on different benchmarks can be averaged. The question this answers: how much of the ten hours actually bought anything? """ inc = [f for f in _inc(feats) if f.observed_scores and (f.observed_gain or 0) > 0.01] grid = np.linspace(0, 1, 101) curves = [] for f in inc: xs = np.array([t / 3600 / max(f.wall_h, 1e-6) for t, _ in f.observed_scores]) ys = np.array([v for _, v in f.observed_scores]) running = np.maximum.accumulate(ys) lo, hi = running[0], running.max() if hi <= lo: continue frac = (running - lo) / (hi - lo) curves.append(np.interp(grid, xs, frac, left=0.0, right=1.0)) arr = np.vstack(curves) med = np.median(arr, axis=0) q1, q3 = np.percentile(arr, [25, 75], axis=0) fig, ax = plt.subplots(figsize=(7.5, 4.2)) ax.fill_between(grid * 100, q1 * 100, q3 * 100, color=C[0], alpha=0.18, lw=0) ax.plot(grid * 100, med * 100, lw=2.5, color=C[0], label=f"median of {len(curves)} runs") ax.plot([0, 100], [0, 100], lw=1.5, ls=(0, (4, 3)), color=MUTED, label="if progress were uniform") half = grid[np.argmax(med >= 0.5)] * 100 ax.axvline(half, lw=1.5, color=C[1]) ax.annotate( f"half the total gain\nby {half:.0f}% of the budget", xy=(half, 50), xytext=(half + 6, 32), color=C[1], fontsize=9, arrowprops=dict(arrowstyle="-", color=C[1], lw=1.2), ) ax.set_xlabel("% of the run's wall clock elapsed") ax.set_ylabel("% of the run's total score gain captured") ax.set_title("Progress is front-loaded: the last hours buy little") ax.grid(lw=0.6) ax.set_axisbelow(True) ax.legend(frameon=False, loc="lower right", fontsize=9) return _save(fig, "progress_curve.png", agent) # --- 4. what the agent spends its actions on --------------------------------- def fig_action_mix(feats, agent: str): inc = _inc(feats) counts: defaultdict[str, float] = defaultdict(float) for f in inc: for k, v in f.action_counts.items(): counts[k] += v / len(inc) order = sorted(counts, key=lambda k: -counts[k])[:12] fig, ax = plt.subplots(figsize=(7.5, 4.2)) y = np.arange(len(order)) ax.barh(y, [counts[k] for k in order], height=0.62, color=C[0], edgecolor=SURFACE, linewidth=2) for i, k in enumerate(order): ax.text(counts[k] + 0.5, i, f"{counts[k]:.0f}", va="center", fontsize=9, color=INK2) ax.set_yticks(y, order) ax.invert_yaxis() ax.set_xlabel("mean tool calls per run") ax.set_title("What the agent actually does with its turns") ax.grid(axis="x", lw=0.6) ax.set_axisbelow(True) return _save(fig, "action_mix.png", agent) # --- 5. rerun spread vs the differences being chased ------------------------- def fig_rerun_spread(feats, rows, agent: str): """Only meaningful when a cell was run more than once. The Codex sweep ran each cell exactly once, so there is no noise floor to draw and the figure is skipped rather than emitted blank. """ rows = [r for r in rows if r["n"] >= 2] if not rows: print(f"[{agent}] no repeated cells; skipping rerun_spread") return None fig, ax = plt.subplots(figsize=(8, 4.6)) y = np.arange(len(rows)) for i, r in enumerate(rows): ax.plot([r["min"], r["max"]], [i, i], lw=2.5, color=C[0], solid_capstyle="round", zorder=2) ax.plot([r["min"]], [i], "o", ms=7, color=C[0], mec=SURFACE, mew=1.5, zorder=3) ax.plot([r["max"]], [i], "o", ms=7, color=C[1], mec=SURFACE, mew=1.5, zorder=3) if r["spread"] > 0.02: ax.text(r["max"] + 0.012, i, f"+{r['spread']:.3f}", va="center", fontsize=8, color=C[1]) ax.set_yticks(y, [f"{r['task']} / {r['base_model'].split('/')[-1]}" for r in rows], fontsize=8) ax.invert_yaxis() ax.set_xlabel("final accuracy") ax.set_title("Two runs of the identical cell: the single-seed noise floor") ax.grid(axis="x", lw=0.6) ax.set_axisbelow(True) ax.plot([], [], "o", color=C[0], label="worse run") ax.plot([], [], "o", color=C[1], label="better run") ax.legend(frameon=False, ncol=2, loc="upper center", bbox_to_anchor=(0.5, -0.14), fontsize=9) return _save(fig, "rerun_spread.png", agent) # --- 6. calibration ---------------------------------------------------------- def fig_calibration(feats, agent: str): inc = [f for f in _inc(feats) if f.claim_confident and f.accuracy is not None] fig, ax = plt.subplots(figsize=(5.6, 5.4)) ax.plot([0, 1], [0, 1], lw=1.5, ls=(0, (4, 3)), color=MUTED, zorder=1) ax.scatter( [f.accuracy for f in inc], [f.claimed_score for f in inc], s=58, color=C[0], edgecolor=SURFACE, linewidth=1.5, zorder=3, ) for f in inc: if abs(f.honesty_gap or 0) > 0.06: ax.annotate(f.task, (f.accuracy, f.claimed_score), fontsize=7.5, color=INK2, xytext=(4, 4), textcoords="offset points") ax.set_xlabel("accuracy the harness measured") ax.set_ylabel("accuracy the agent claimed in its summary") ax.set_title(f"Self-reported vs graded ({len(inc)} runs with a verifiable claim)") ax.set_xlim(0, 1) ax.set_ylim(0, 1) ax.grid(lw=0.6) ax.set_axisbelow(True) return _save(fig, "calibration.png", agent) # --- 7. iteration count vs relative outcome ---------------------------------- def fig_iterations_vs_outcome(feats, z, agent: str): inc = [f for f in _inc(feats) if f.run_id in z] fig, ax = plt.subplots(figsize=(7, 4.2)) xs = [f.n_distinct_model_versions for f in inc] ys = [z[f.run_id] for f in inc] ax.axhline(0, lw=1, color=GRID) ax.scatter(xs, ys, s=52, color=C[0], edgecolor=SURFACE, linewidth=1.5, zorder=3) if len(set(xs)) > 1: k, b = np.polyfit(xs, ys, 1) gx = np.linspace(min(xs), max(xs), 10) ax.plot(gx, k * gx + b, lw=2, color=C[1], label=f"fit: {k:+.3f} z per extra version") ax.legend(frameon=False, fontsize=9, loc="lower right") ax.set_xlabel("distinct model versions the agent evaluated") ax.set_ylabel("final accuracy, z-scored within its benchmark") ax.set_title("More iterations, barely better results") ax.grid(lw=0.6) ax.set_axisbelow(True) return _save(fig, "iterations_vs_outcome.png", agent) def make_all(runs, feats, agent: str): from .stats import rerun_variance, within_task_z inc = _inc(feats) print(f"[{agent}] figures:") fig_time_budget(feats, agent) fig_score_trajectories(feats, agent) fig_progress_curve(feats, agent) fig_action_mix(feats, agent) fig_rerun_spread(feats, rerun_variance(inc), agent) fig_calibration(feats, agent) fig_iterations_vs_outcome(feats, within_task_z(inc), agent)