Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
170 lines
9.6 KiB
Python
170 lines
9.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Report of the long-context Codex cells of the 245k study (docs/quality-gate.md). Offline; reads the cell directories written by q245_codex_job.sh
|
|
(cell.json, proxy/rounds.jsonl and the gzip request / response bodies of the logging proxy). Python >= 3.8, stdlib only.
|
|
|
|
usage: q245_codex_report.py RUN_DIR [RUN_DIR ...] [--json OUT] [--arms vanilla,reply,off]
|
|
Layout read: RUN_DIR/<arm>/<task>-r<rep>/ ; smoke cells (rep 0) are listed apart and never enter a table.
|
|
|
|
Per cell: accepted (the task's own acceptance), termination, wall time, model requests (rounds), failed rounds (HTTP status != 200, outcome != ok or a stream that does
|
|
not end in response.completed), function calls and how many are intact (arguments parse as a JSON object, the tool is one the request declared, a call id is present),
|
|
context peak (largest input_tokens) and the cached share of the input. Per (arm, task) the mean / sd / CV of the rounds and the completions; per arm the pooled
|
|
CV (rounds divided by the task's mean over all arms). Between arms the first round at which the action sequences of the same task and repetition differ, next to the
|
|
same measure between two repetitions of one arm (the run-to-run floor: greedy sessions are not reproducible with an adaptive tier and a prefix cache).
|
|
"""
|
|
import argparse, glob, json, math, os, sys
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
for cand in (os.path.join(HERE, "..", "e2e", "codex", "delta"), "/data/leleka-e2e/quality-245k/codex/delta"):
|
|
if os.path.isdir(cand):
|
|
sys.path.insert(0, cand)
|
|
import index as ix # noqa: E402
|
|
|
|
|
|
def declared(req):
|
|
names = set()
|
|
for t in req.get("tools") or []:
|
|
if isinstance(t, dict):
|
|
if t.get("name"):
|
|
names.add(t["name"])
|
|
fn = t.get("function")
|
|
if isinstance(fn, dict) and fn.get("name"):
|
|
names.add(fn["name"])
|
|
for sub in t.get("tools") or []: # namespace tools
|
|
if isinstance(sub, dict) and sub.get("name"):
|
|
names.add(sub["name"])
|
|
return names
|
|
|
|
|
|
def cell_metrics(d):
|
|
info = json.load(open(os.path.join(d, "cell.json")))
|
|
rs = ix.cell_rounds(d)
|
|
acts = ix.build_actions(d, rs)
|
|
m = {"dir": d, "accepted": bool(info.get("accepted")), "termination": info.get("termination"), "wall_s": info.get("wall_s"), "rounds": len(rs),
|
|
"failed": 0, "calls": 0, "bad_json": 0, "unknown_tool": 0, "no_call_id": 0, "ctx_peak": 0, "first_in": None, "cached_share": [], "msgs": 0, "reasoning_only": 0}
|
|
for a in acts:
|
|
rec, u = a["rec"], (a["rec"].get("resp") or {})
|
|
if rec.get("status") != 200 or rec.get("outcome") not in (None, "ok") or u.get("terminal") not in (None, "response.completed"):
|
|
m["failed"] += 1
|
|
inp = u.get("input_tokens") or 0
|
|
m["ctx_peak"] = max(m["ctx_peak"], inp)
|
|
if m["first_in"] is None:
|
|
m["first_in"] = inp
|
|
elif inp and u.get("cached_tokens") is not None:
|
|
m["cached_share"].append(u["cached_tokens"] / inp)
|
|
names = declared(a["req"])
|
|
for it in a["out"]:
|
|
if it.get("type") == "function_call":
|
|
m["calls"] += 1
|
|
try:
|
|
args = json.loads(it.get("arguments") or "")
|
|
if not isinstance(args, dict):
|
|
raise ValueError("not an object")
|
|
except ValueError:
|
|
m["bad_json"] += 1
|
|
if names and it.get("name") not in names:
|
|
m["unknown_tool"] += 1
|
|
if not it.get("call_id"):
|
|
m["no_call_id"] += 1
|
|
elif it.get("type") == "message":
|
|
m["msgs"] += 1
|
|
m["cached_share_median"] = sorted(m["cached_share"])[len(m["cached_share"]) // 2] if m["cached_share"] else None
|
|
del m["cached_share"]
|
|
return m, acts
|
|
|
|
|
|
def mean(xs):
|
|
return sum(xs) / len(xs) if xs else float("nan")
|
|
|
|
|
|
def sd(xs):
|
|
if len(xs) < 2:
|
|
return float("nan")
|
|
mu = mean(xs)
|
|
return math.sqrt(sum((x - mu) ** 2 for x in xs) / (len(xs) - 1))
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("runs", nargs="+")
|
|
ap.add_argument("--json", default="")
|
|
ap.add_argument("--arms", default="")
|
|
a = ap.parse_args()
|
|
want = [x for x in a.arms.split(",") if x]
|
|
cells, acts_of, smoke = {}, {}, []
|
|
for run in a.runs:
|
|
for cj in sorted(glob.glob(os.path.join(run, "*", "*-r*", "cell.json"))):
|
|
d = os.path.dirname(cj)
|
|
arm = os.path.basename(os.path.dirname(d))
|
|
if want and arm not in want:
|
|
continue
|
|
task, rep = os.path.basename(d).rsplit("-r", 1)
|
|
rep = int(rep)
|
|
m, acts = cell_metrics(d)
|
|
m.update({"arm": arm, "task": task, "rep": rep})
|
|
if rep == 0:
|
|
smoke.append(m)
|
|
continue
|
|
cells[(arm, task, rep)] = m
|
|
acts_of[(arm, task, rep)] = acts
|
|
arms = sorted({k[0] for k in cells})
|
|
tasks = sorted({k[1] for k in cells})
|
|
print("cells:", len(cells), "arms:", arms, "tasks:", tasks)
|
|
if smoke:
|
|
print("smoke cells (not in the tables):", [(s["arm"], s["first_in"], s["rounds"], s["accepted"]) for s in smoke])
|
|
print("\nPER CELL")
|
|
print("%-8s %-15s %3s %5s %-9s %6s %6s %6s %5s %5s %5s %7s %7s %6s" % ("arm", "task", "rep", "acc", "term", "wall_s", "rounds", "failed", "calls", "badJ", "unkT", "ctxpeak", "first", "cached"))
|
|
for k in sorted(cells):
|
|
m = cells[k]
|
|
print("%-8s %-15s %3d %5s %-9s %6.0f %6d %6d %5d %5d %5d %7d %7s %6s" % (m["arm"], m["task"], m["rep"], "yes" if m["accepted"] else "NO", m["termination"], m["wall_s"] or 0,
|
|
m["rounds"], m["failed"], m["calls"], m["bad_json"], m["unknown_tool"], m["ctx_peak"], m["first_in"], ("%.2f" % m["cached_share_median"]) if m["cached_share_median"] is not None else "-"))
|
|
print("\nPER ARM AND TASK (n, accepted, rounds mean +- sd (CV), failed rounds, intact calls)")
|
|
table = {}
|
|
for arm in arms:
|
|
for task in tasks:
|
|
cs = [cells[k] for k in sorted(cells) if k[0] == arm and k[1] == task]
|
|
if not cs:
|
|
continue
|
|
rd = [c["rounds"] for c in cs]
|
|
row = {"n": len(cs), "accepted": sum(c["accepted"] for c in cs), "rounds_mean": mean(rd), "rounds_sd": sd(rd), "rounds_cv": sd(rd) / mean(rd) if len(rd) > 1 else float("nan"),
|
|
"failed": sum(c["failed"] for c in cs), "calls": sum(c["calls"] for c in cs), "bad_json": sum(c["bad_json"] for c in cs), "unknown_tool": sum(c["unknown_tool"] for c in cs),
|
|
"ctx_peak_max": max(c["ctx_peak"] for c in cs), "terminations": sorted({c["termination"] for c in cs})}
|
|
table[(arm, task)] = row
|
|
print("%-8s %-15s n=%d accepted %d/%d rounds %.1f +- %.1f (CV %.0f%%) failed rounds %d calls %d bad JSON %d unknown tool %d ctx peak max %d %s" % (
|
|
arm, task, row["n"], row["accepted"], row["n"], row["rounds_mean"], row["rounds_sd"], 100 * row["rounds_cv"], row["failed"], row["calls"], row["bad_json"], row["unknown_tool"],
|
|
row["ctx_peak_max"], row["terminations"]))
|
|
print("\nPER ARM (pooled)")
|
|
task_mean = {t: mean([c["rounds"] for k, c in cells.items() if k[1] == t]) for t in tasks}
|
|
pooled = {}
|
|
for arm in arms:
|
|
cs = [c for k, c in cells.items() if k[0] == arm]
|
|
norm = [c["rounds"] / task_mean[c["task"]] for c in cs]
|
|
pooled[arm] = {"n": len(cs), "accepted": sum(c["accepted"] for c in cs), "rounds_rel_mean": mean(norm), "rounds_rel_cv": sd(norm) / mean(norm) if len(norm) > 1 else float("nan"),
|
|
"failed": sum(c["failed"] for c in cs), "calls": sum(c["calls"] for c in cs), "bad_json": sum(c["bad_json"] for c in cs), "unknown_tool": sum(c["unknown_tool"] for c in cs),
|
|
"no_call_id": sum(c["no_call_id"] for c in cs)}
|
|
p = pooled[arm]
|
|
print("%-8s cells %d accepted %d (%.0f%%) rounds relative to the task mean %.2f (pooled CV %.0f%%) failed rounds %d, function calls %d: bad JSON %d, unknown tool %d, no call id %d" % (
|
|
arm, p["n"], p["accepted"], 100.0 * p["accepted"] / max(1, p["n"]), p["rounds_rel_mean"], 100 * p["rounds_rel_cv"], p["failed"], p["calls"], p["bad_json"], p["unknown_tool"], p["no_call_id"]))
|
|
print("\nFIRST DIVERGENCE OF THE ACTION SEQUENCE (round number; same task)")
|
|
div = {}
|
|
for task in tasks:
|
|
for arm in arms:
|
|
reps = sorted(k[2] for k in cells if k[0] == arm and k[1] == task)
|
|
for i in range(len(reps)):
|
|
for j in range(i + 1, len(reps)):
|
|
r = ix.first_divergence(acts_of[(arm, task, reps[i])], acts_of[(arm, task, reps[j])])
|
|
div[("within", arm, task, reps[i], reps[j])] = r[0] if r else None
|
|
for i, a1 in enumerate(arms):
|
|
for a2 in arms[i + 1:]:
|
|
for rep in sorted({k[2] for k in cells if k[0] == a1 and k[1] == task} & {k[2] for k in cells if k[0] == a2 and k[1] == task}):
|
|
r = ix.first_divergence(acts_of[(a1, task, rep)], acts_of[(a2, task, rep)])
|
|
div[("between", a1 + "~" + a2, task, rep, rep)] = r[0] if r else None
|
|
for k, v in sorted(div.items(), key=lambda kv: str(kv[0])):
|
|
print(" %-8s %-14s %-15s r%d~r%d first differing round: %s" % (k[0], k[1], k[2], k[3], k[4], "none (identical)" if v is None else v))
|
|
if a.json:
|
|
json.dump({"cells": {"/".join(map(str, k)): v for k, v in cells.items()}, "table": {"/".join(k): v for k, v in table.items()}, "pooled": pooled,
|
|
"divergence": {"/".join(map(str, k)): v for k, v in div.items()}}, open(a.json, "w"), indent=1, default=str)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|