176 lines
8.5 KiB
Python
176 lines
8.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Bench how a worker's step to a stronger model hands the chunk over: handoff_bench.py <work dir> start <case>-<n> ..., then run|grade <case>-<arm>-<n> ..., then summary
|
|
|
|
The question: when loop-claude steps a worker to a rung on another model, which handoff serves the stronger model
|
|
best? Each case is an archived chunk of this repo, as in advisor_bench.py, whose judge and files this bench shares.
|
|
- `start` runs WEAK on the item in the clone <work dir>/<case>-<n> until it has spent START_BUDGET, which
|
|
stands in for a run that ends asking for a higher rung. A worker that finishes within the budget leaves no
|
|
handoff, so `start` fails on it. It saves the change so far (<case>-start-<n>.diff), and a copy of the clone
|
|
(.tree) and of the session's transcript (.session.jsonl), which every arm starts from.
|
|
- `run` puts the clone and the session back as `start` left them, then continues on STRONG, one arm of a case at a
|
|
time. The resume arm resumes WEAK's session with handoff-resume-prompt.md. The compact arm does the same once WEAK
|
|
has compacted the session with `/compact`, whose stream it saves as <name>.compact.jsonl. The brief arm starts a
|
|
session that has the item and handoff-brief-prompt.md, and no transcript.
|
|
- `grade` is advisor_bench.py's, over these cases. `summary` counts an arm's cost and seconds from its own runs,
|
|
the compaction included, and leaves out the start, which the arms share.
|
|
Run each arm of each case once; the table shows a direction, not a significance.
|
|
"""
|
|
import concurrent.futures
|
|
import collections
|
|
import json
|
|
import pathlib
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import uuid
|
|
|
|
import advisor_bench
|
|
from advisor_bench import Arm
|
|
|
|
BENCH = pathlib.Path(__file__).resolve().parent
|
|
# The ladder's first step that changes the model: bin/model_routing/routing-ladder.json.
|
|
WEAK = Arm("claude-sonnet-5-5", "high")
|
|
STRONG = Arm("claude-opus-5-5", "medium")
|
|
ARMS = ("resume", "compact", "brief")
|
|
# Claude Code keeps a session's transcript at <CLAUDE_PROJECTS>/<the working directory's slug>/<session id>.jsonl.
|
|
CLAUDE_PROJECTS = pathlib.Path.home() / ".claude/projects"
|
|
# One per case and run number: its arms share one clone, so they run one at a time.
|
|
CLONE_LOCKS: collections.defaultdict = collections.defaultdict(threading.Lock)
|
|
# L 3 chunks, by todo item. advisor_bench's L 1 and L 2 chunks are too small: Sonnet 5.5 finished five of the six for
|
|
# under $0.20, before any handoff.
|
|
CASES = {
|
|
"143": ("45cb331a4", "545f3c347"),
|
|
"163": ("d4cf6e7fe", "d1b0fe3a4"),
|
|
"198": ("4a0ba5921", "fd60b6da"),
|
|
"210": ("4764d3d52", "dcbdc970"),
|
|
"227": ("eb7b50698", "3bde9cd6d"),
|
|
"239": ("d583f8d48", "47a40757"),
|
|
}
|
|
# Dollars WEAK may spend before the handoff. In a trial, $0.36 stopped Sonnet 5.5 on items 163 and 227 after 11 to 14
|
|
# turns, with about 250 lines of diff.
|
|
START_BUDGET = 0.36
|
|
CLAUDE_FLAGS = ["--setting-sources", "project", "--permission-mode", "bypassPermissions", "--output-format", "stream-json", "--verbose"]
|
|
|
|
|
|
def stopped_at_budget(lines):
|
|
"""Whether a claude stream's first result line, the worker's own, says the run stopped at --max-budget-usd."""
|
|
for line in lines:
|
|
try:
|
|
entry = json.loads(line)
|
|
except ValueError:
|
|
continue
|
|
if entry.get("type") == "result":
|
|
return entry.get("subtype") == "error_max_budget_usd"
|
|
return False
|
|
|
|
|
|
def run_prompt(case):
|
|
"""advisor_bench's prompt for the case's item, as the item's text stood at the start commit."""
|
|
base = CASES[case][0]
|
|
text = advisor_bench.item_text(advisor_bench.git(advisor_bench.REPO, "show", f"{base}:todo.md"), case)
|
|
return (BENCH / "advisor-run-prompt.md").read_text().format(base=base, item=case, text=text)
|
|
|
|
|
|
def claude(prompt, flags, clone, stream):
|
|
with stream.open("w") as out:
|
|
subprocess.run(["claude", "-p", prompt, *flags, *CLAUDE_FLAGS], cwd=clone, stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT)
|
|
|
|
|
|
def start(work, name):
|
|
"""WEAK's capped run of <case>-<n>, and the tree and session it leaves the arms; the files are in the module docstring."""
|
|
case, number = name.split("-")
|
|
base = CASES[case][0]
|
|
clone, saved = work / name, work / f"{case}-start-{number}"
|
|
if clone.exists():
|
|
raise ValueError(f"{name} already started: remove {clone}")
|
|
advisor_bench.fresh_clone(base, clone)
|
|
session = str(uuid.uuid4())
|
|
stream = saved.with_suffix(".jsonl")
|
|
claude(run_prompt(case), [*WEAK.flags(), "--session-id", session, "--max-budget-usd", str(START_BUDGET)], clone, stream)
|
|
if not stopped_at_budget(stream.read_text().splitlines()):
|
|
raise ValueError("the weak worker finished within its budget, or its run failed, so there is no handoff to bench")
|
|
transcripts = list(CLAUDE_PROJECTS.glob(f"*/{session}.jsonl"))
|
|
if len(transcripts) != 1:
|
|
raise ValueError(f"expected one transcript of session {session} under {CLAUDE_PROJECTS}, found {len(transcripts)}")
|
|
shutil.copy(transcripts[0], saved.with_suffix(".session.jsonl"))
|
|
saved.with_suffix(".session").write_text(str(transcripts[0]))
|
|
# The worker may have committed against the bench rules, so the arms get its whole change since base, uncommitted.
|
|
advisor_bench.git(clone, "add", "--all")
|
|
saved.with_suffix(".diff").write_text(advisor_bench.git(clone, "diff", "--cached", base))
|
|
advisor_bench.git(clone, "reset", "-q", "--mixed", base)
|
|
shutil.copytree(clone, saved.with_suffix(".tree"), symlinks=True)
|
|
return f"{name}: started"
|
|
|
|
|
|
def run(work, name):
|
|
"""STRONG's run of one arm, <case>-<arm>-<n>, from the tree and session `start` left."""
|
|
case, arm, number = advisor_bench.split_name(name)
|
|
if arm not in ARMS:
|
|
raise ValueError(f"the arm {arm!r} is none of {ARMS}")
|
|
clone, saved = work / f"{case}-{number}", work / f"{case}-start-{number}"
|
|
if not saved.with_suffix(".tree").exists():
|
|
raise ValueError(f"start {case}-{number} first")
|
|
stream = work / f"{name}.jsonl"
|
|
if stream.exists():
|
|
raise ValueError(f"{name} already ran: remove {stream}")
|
|
with CLONE_LOCKS[clone]:
|
|
shutil.rmtree(clone)
|
|
shutil.copytree(saved.with_suffix(".tree"), clone, symlinks=True)
|
|
transcript = pathlib.Path(saved.with_suffix(".session").read_text())
|
|
shutil.copy(saved.with_suffix(".session.jsonl"), transcript)
|
|
resumed = ["--resume", transcript.stem]
|
|
if arm == "compact":
|
|
claude("/compact", [*WEAK.flags(), *resumed], clone, work / f"{name}.compact.jsonl")
|
|
if arm == "brief":
|
|
claude(run_prompt(case) + "\n" + (BENCH / "handoff-brief-prompt.md").read_text(), [*STRONG.flags(), "--no-session-persistence"], clone, stream)
|
|
else:
|
|
prompt = (BENCH / "handoff-resume-prompt.md").read_text().format(rung=f"{STRONG.model} at {STRONG.effort} effort")
|
|
claude(prompt, [*STRONG.flags(), *resumed], clone, stream)
|
|
outcome(work, name)
|
|
advisor_bench.save_change(work, name, clone, CASES[case])
|
|
return f"{name}: ran"
|
|
|
|
|
|
def outcome(work, name):
|
|
"""The cost and seconds of an arm's run: its STRONG stream's, plus its compaction's where it made one."""
|
|
streams = [stream for stream in (work / f"{name}.compact.jsonl", work / f"{name}.jsonl") if stream.exists()]
|
|
results = [advisor_bench.read_result(stream.read_text().splitlines()) for stream in streams]
|
|
return {"cost": sum(result.cost for result in results), "seconds": sum(result.seconds for result in results)}
|
|
|
|
|
|
def rows_of(work):
|
|
"""One row per graded run: its arm, verdict, cost and seconds."""
|
|
rows = []
|
|
for verdict_file in sorted(work.glob("*.verdict")):
|
|
name = verdict_file.stem
|
|
rows.append({"arm": advisor_bench.split_name(name)[1], "verdict": json.loads(verdict_file.read_text())["verdict"], **outcome(work, name)})
|
|
return rows
|
|
|
|
|
|
def summary(rows):
|
|
"""A markdown table with one row per arm, in ARMS' order: its runs, passes, partials, mean cost and mean seconds."""
|
|
lines = ["| arm | runs | pass | partial | mean cost $ | mean seconds |", "|---|---|---|---|---|---|"]
|
|
for name in ARMS:
|
|
own = [row for row in rows if row["arm"] == name]
|
|
if own:
|
|
passes, partials = (sum(row["verdict"] == kind for row in own) for kind in ("pass", "partial"))
|
|
cost, seconds = (sum(row[key] for row in own) / len(own) for key in ("cost", "seconds"))
|
|
lines.append(f"| {name} | {len(own)} | {passes} | {partials} | {cost:.2f} | {seconds:.0f} |")
|
|
return "\n".join(lines)
|
|
|
|
|
|
def main(argv):
|
|
work, step, names = pathlib.Path(argv[0]), argv[1], argv[2:]
|
|
if step == "summary":
|
|
print(summary(rows_of(work)))
|
|
return
|
|
steps = {"start": start, "run": run, "grade": lambda work, name: advisor_bench.grade(work, name, CASES)}
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
|
|
for result in pool.map(lambda name: advisor_bench.attempted(steps[step], work, name), names):
|
|
print(result, flush=True)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main(sys.argv[1:])
|