Jerry999's picture
Add files using upload-large-folder tool
158258b verified
Raw History Blame Contribute Delete
12.7 kB
#!/usr/bin/env python3
"""Head-to-head comparison between the Claude Code and Codex SDK sweeps.
Both swept the same 28 cells (7 benchmarks x 4 base models) with the same
10-hour budget on the same hardware, so the cells pair exactly. Claude has
reruns on 20 cells; for a paired comparison each cell contributes its latest
analysed run, which is also how the sweep's own results table is built.
python analysis/compare.py # tables + json
python analysis/compare.py --figures
Writes `analysis/out/compare.json`, the comparison tables into the report at
`docs/results/agent_trace_comparison_2026-10.md`, and figures under
`docs/results/figures/compare/`.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from collections import defaultdict
from statistics import mean
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from run_analysis import AGENT_ROOTS, OUT_DIR, ROOT, build # noqa: E402
AGENTS = ("claude", "codex")
def latest_per_cell(feats) -> dict[tuple[str, str], object]:
"""One run per (task, base model): the most recent analysed one."""
best: dict[tuple[str, str], object] = {}
for f in feats:
if f.cohort not in ("primary", "recovered"):
continue
key = (f.task, f.base_model)
if key not in best or f.run_id > best[key].run_id: # stamps sort lexically
best[key] = f
return best
def _avg(xs):
xs = [x for x in xs if x is not None]
return round(mean(xs), 4) if xs else None
def headline(cells: dict[str, dict]) -> list[dict]:
"""The per-run metrics that actually differ between the two scaffolds."""
spec = [
("accuracy", "final accuracy", 3),
("wall_h", "wall clock (h)", 2),
("turns", "turns", 0),
("tool_calls", "tool calls", 0),
("n_distinct_model_versions", "model versions evaluated", 1),
("n_eval_calls", "official eval invocations", 1),
("n_observed_scores", "distinct scores observed", 1),
("first_eval_h", "first eval (h)", 3),
("machine_busy_frac", "machine busy fraction", 3),
("dead_air_h", "idle hours", 2),
("tail_idle_h", "hours after best score", 2),
("bg_tasks", "background jobs launched", 1),
("tool_errors", "tool errors", 1),
("output_tokens", "output tokens", 0),
("thinking_chars", "readable reasoning chars", 0),
("narration_chars", "visible narration chars", 0),
("final_message_chars", "final report chars", 0),
("time_awareness_calls", "timer.sh checks", 1),
]
rows = []
for field, label, nd in spec:
row = {"metric": label}
for a in AGENTS:
v = _avg([getattr(f, field) for f in cells[a].values()])
row[a] = round(v, nd) if v is not None and nd else (int(v) if v is not None else None) if nd == 0 else v
rows.append(row)
return rows
def paired_accuracy(cells: dict[str, dict]) -> list[dict]:
keys = sorted(set(cells["claude"]) & set(cells["codex"]))
rows = []
for task, model in keys:
c = cells["claude"][(task, model)].accuracy
x = cells["codex"][(task, model)].accuracy
rows.append(
{
"task": task,
"base_model": model.split("/")[-1],
"claude": round(c, 4) if c is not None else None,
"codex": round(x, 4) if x is not None else None,
"delta": round(c - x, 4) if None not in (c, x) else None,
}
)
return rows
def per_task_accuracy(rows: list[dict]) -> list[dict]:
by: defaultdict[str, list[dict]] = defaultdict(list)
for r in rows:
by[r["task"]].append(r)
out = []
for task, g in sorted(by.items()):
out.append(
{
"task": task,
"claude": _avg([r["claude"] for r in g]),
"codex": _avg([r["codex"] for r in g]),
"delta": _avg([r["delta"] for r in g]),
"claude_wins": sum(1 for r in g if (r["delta"] or 0) > 0),
"n": len(g),
}
)
return out
def prose_compare(summaries: dict[str, dict]) -> list[dict]:
"""Only the surfaces both SDKs expose.
`said_` is report + narration; the plain report-only rows understate
Codex (340-character sign-offs) and the `anywhere_` rows flatter it
(only Codex exposes readable extended thinking), so neither is usable
across agents.
"""
probes = summaries["claude"]["prose_probes"]
keys = [k for k in probes if k.startswith("said_")] + [
k for k in probes if not k.startswith(("said_", "anywhere_")) and probes[k]["surface"] == "narration"
]
rows = []
for k in keys:
row = {"habit": k.replace("said_", "")}
for a in AGENTS:
p = summaries[a]["prose_probes"].get(k)
row[a] = f"{p['runs_with_evidence']}/{p['of']} ({p['pct']}%)" if p else ""
row["surface"] = (summaries["claude"]["prose_probes"].get(k) or {}).get("surface", "")
rows.append(row)
return rows
def md_table(rows: list[dict], cols: list[tuple[str, str]]) -> str:
out = ["| " + " | ".join(h for _, h in cols) + " |", "|" + "---|" * len(cols)]
for r in rows:
cells = []
for k, _ in cols:
v = r.get(k)
cells.append("" if v is None else (f"{v:g}" if isinstance(v, float) else str(v)))
out.append("| " + " | ".join(cells) + " |")
return "\n".join(out)
# --- figures ----------------------------------------------------------------
def make_figures(cells, paired, per_task):
import numpy as np
from trace_analysis.figures import C, GRID, INK2, MUTED, SURFACE, _save
import matplotlib.pyplot as plt
# 1. accuracy by benchmark, paired
fig, ax = plt.subplots(figsize=(9, 4.2))
tasks = [r["task"] for r in per_task]
y = np.arange(len(tasks))
h = 0.34
ax.barh(y - h / 2, [r["claude"] for r in per_task], height=h, color=C[0], label="Claude Code (opus-5)", edgecolor=SURFACE, linewidth=1.5)
ax.barh(y + h / 2, [r["codex"] for r in per_task], height=h, color=C[1], label="Codex SDK (gpt-5.6-sol)", edgecolor=SURFACE, linewidth=1.5)
for i, r in enumerate(per_task):
ax.text(max(r["claude"], r["codex"]) + 0.012, i, f"Δ{r['delta']:+.3f}", va="center", fontsize=8.5, color=INK2)
ax.set_yticks(y, tasks)
ax.invert_yaxis()
ax.set_xlim(0, 1.08)
ax.set_xlabel("mean final accuracy over the 4 base models")
ax.set_title("Same 28 cells, two scaffolds")
ax.grid(axis="x", lw=0.6)
ax.set_axisbelow(True)
ax.legend(frameon=False, ncol=2, loc="upper center", bbox_to_anchor=(0.5, -0.16), fontsize=9)
_save(fig, "accuracy_by_task.png", "compare")
# 2. progress curves overlaid
fig, ax = plt.subplots(figsize=(7.5, 4.2))
grid = np.linspace(0, 1, 101)
for a, col in zip(AGENTS, (C[0], C[1])):
curves = []
for f in cells[a].values():
if not f.observed_scores or (f.observed_gain or 0) <= 0.01:
continue
xs = np.array([t / 3600 / max(f.wall_h, 1e-6) for t, _ in f.observed_scores])
ys = np.maximum.accumulate([v for _, v in f.observed_scores])
lo, hi = ys[0], ys.max()
if hi <= lo:
continue
curves.append(np.interp(grid, xs, (ys - lo) / (hi - lo), left=0.0, right=1.0))
med = np.median(np.vstack(curves), axis=0)
half = grid[np.argmax(med >= 0.5)] * 100
ax.plot(grid * 100, med * 100, lw=2.5, color=col, label=f"{a} (n={len(curves)}, half by {half:.0f}%)")
ax.plot([0, 100], [0, 100], lw=1.5, ls=(0, (4, 3)), color=MUTED, label="if progress were uniform")
ax.set_xlabel("% of the run's wall clock elapsed")
ax.set_ylabel("% of the run's total score gain captured")
ax.set_title("Both front-load their gains")
ax.grid(lw=0.6)
ax.set_axisbelow(True)
ax.legend(frameon=False, loc="lower right", fontsize=9)
_save(fig, "progress_curve.png", "compare")
# 3. loop shape: iterations vs time spent
fig, ax = plt.subplots(figsize=(7, 4.4))
for a, col in zip(AGENTS, (C[0], C[1])):
xs = [f.wall_h for f in cells[a].values()]
ys = [f.n_distinct_model_versions for f in cells[a].values()]
ax.scatter(xs, ys, s=58, color=col, edgecolor=SURFACE, linewidth=1.5, label=a, zorder=3)
ax.set_xlabel("wall clock used (h, of a 10 h budget)")
ax.set_ylabel("distinct model versions evaluated")
ax.set_title("Codex iterates faster and stops earlier")
ax.grid(lw=0.6)
ax.set_axisbelow(True)
ax.legend(frameon=False, fontsize=9, loc="upper left")
_save(fig, "loop_shape.png", "compare")
# 4. what the trace exposes about the agent's own reasoning
fig, ax = plt.subplots(figsize=(7, 3.6))
labels = ["readable reasoning", "visible narration", "final report"]
vals = {
a: [
_avg([f.thinking_chars for f in cells[a].values()]),
_avg([f.narration_chars for f in cells[a].values()]),
_avg([f.final_message_chars for f in cells[a].values()]),
]
for a in AGENTS
}
y = np.arange(len(labels))
h = 0.34
for i, (a, col) in enumerate(zip(AGENTS, (C[0], C[1]))):
v = [x or 0 for x in vals[a]]
ax.barh(y + (i - 0.5) * h, v, height=h, color=col, label=a, edgecolor=SURFACE, linewidth=1.5)
for j, x in enumerate(v):
ax.text(x + 600, y[j] + (i - 0.5) * h, f"{x:,.0f}", va="center", fontsize=8, color=INK2)
ax.set_yticks(y, labels)
ax.invert_yaxis()
ax.set_xlabel("characters per run")
ax.set_title("How much of its own thinking each trace preserves")
ax.grid(axis="x", lw=0.6)
ax.set_axisbelow(True)
ax.legend(frameon=False, ncol=2, fontsize=9, loc="lower right")
_save(fig, "reasoning_visibility.png", "compare")
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--figures", action="store_true")
args = ap.parse_args()
cells, summaries = {}, {}
for a in AGENTS:
_, feats = build(AGENT_ROOTS[a])
cells[a] = latest_per_cell(feats)
summaries[a] = json.load(open(os.path.join(OUT_DIR, a, "summary.json")))
print(f"{a}: {len(cells[a])} paired cells")
paired = paired_accuracy(cells)
per_task = per_task_accuracy(paired)
head = headline(cells)
result = {
"paired_cells": len(paired),
"headline": head,
"per_task_accuracy": per_task,
"paired_accuracy": paired,
"overall": {
a: _avg([f.accuracy for f in cells[a].values()]) for a in AGENTS
},
"cells_claude_wins": sum(1 for r in paired if (r["delta"] or 0) > 0),
"prose": prose_compare(summaries),
"risks": {a: summaries[a]["risk_run_counts"] for a in AGENTS},
"errors": {a: summaries[a]["error_run_counts"] for a in AGENTS},
"verification": {a: summaries[a]["final_verification"] for a in AGENTS},
"dev_drop": {a: summaries[a]["dev_to_harness_drop"] for a in AGENTS},
"techniques": {a: summaries[a]["technique_run_counts"] for a in AGENTS},
"actions": {a: summaries[a]["action_totals"] for a in AGENTS},
"tools": {a: summaries[a]["tool_totals"] for a in AGENTS},
}
with open(os.path.join(OUT_DIR, "compare.json"), "w") as fh:
json.dump(result, fh, indent=1)
print(f"wrote {os.path.join(OUT_DIR, 'compare.json')}")
tables = [
"## 每 run 行为画像",
"",
md_table(head, [("metric", "指标(每 run 均值)"), ("claude", "Claude Code"), ("codex", "Codex SDK")]),
"",
"## 各 benchmark 准确率(同样 4 个 base model 取均值)",
"",
md_table(
per_task,
[("task", "benchmark"), ("claude", "Claude"), ("codex", "Codex"), ("delta", "Δ(C−X)"), ("claude_wins", "Claude 胜出格数"), ("n", "格数")],
),
"",
"## 逐格配对",
"",
md_table(paired, [("task", "benchmark"), ("base_model", "base model"), ("claude", "Claude"), ("codex", "Codex"), ("delta", "Δ")]),
"",
"## 文本习惯",
"",
md_table(prose_compare(summaries), [("habit", "习惯"), ("claude", "Claude"), ("codex", "Codex"), ("surface", "出现在")]),
"",
]
tpath = os.path.join(OUT_DIR, "compare_tables.md")
with open(tpath, "w") as fh:
fh.write("\n".join(tables))
print(f"wrote {tpath}")
if args.figures:
make_figures(cells, paired, per_task)
if __name__ == "__main__":
main()