Files

81 lines
4.9 KiB
Python

#!/usr/bin/env python3
"""Parse a claude/adaptive-spec replay log (run_replay) into a per-arm table.
usage: spec_replay.py LOG [--trace ARM:PASS:REQUEST]
Per arm (the warm-up pass is dropped): weighted decode tok/s per pass (total tokens / total decode time, REPLAY PASS lines),
mean and range over the repetitions, pooled tokens per round, accepted-per-round histogram, mean round ms per window width
(from the `DBG spec-stats` lines), and the policy trace of one request (`DBG spec-trace`, when the job traced).
"""
import re, sys, collections, statistics
def main():
lines = open(sys.argv[1], errors="replace").read().splitlines()
passes = collections.OrderedDict() # (pass_no) -> dict(arm, tok_s, tokens)
arms = collections.OrderedDict()
cur_stats = None; trace = []
req_trace = {} # (arm, pass, request) -> trace lines
for ln in lines:
if ln.startswith("DBG spec-trace"):
trace.append(ln); continue
m = re.match(r"DBG spec-stats arm=(\S+) (.*)", ln)
if m:
cur_stats = (m.group(1), m.group(2)); stats_trace = trace; trace = []; continue
m = re.match(r"REPLAY #(\d+) pass=(\d+) (\S+) arm=(\S+) .*produced=(\d+) rounds=(\d+) .*decode_ms=([\d.]+)", ln)
if m:
n, p, lab, arm = int(m.group(1)), int(m.group(2)), m.group(3), m.group(4)
if cur_stats:
req_trace[(arm, p, n)] = stats_trace
if lab != "warm":
a = arms.setdefault(arm, dict(hist_t=[0]*9, hist_acc=[0]*9, ms=[0.0]*9, rounds=0, tokens=0, expl=0, lookup=0, passes={}))
kv = dict(re.findall(r"(\w+)(?:\[[^\]]*\])?=(\S+)", cur_stats[1]))
a["rounds"] += int(kv["rounds"]); a["tokens"] += int(kv["tokens"])
a["expl"] += int(kv["explored"]); a["lookup"] += int(kv["lookup_rounds"])
th = kv["T_hist"].split(",")
for i, v in enumerate(th): a["hist_t"][i] += int(v)
for i, v in enumerate(kv["acc_hist"].split(",")): a["hist_acc"][i] += int(v)
for i, v in enumerate(kv["ms_by_T"].split(",")):
if v != "-": a["ms"][i] += float(v) * int(th[i])
cur_stats = None
continue
m = re.match(r"REPLAY PASS (\d+) (\S+) arm=(\S+) requests=(\d+) weighted_decode_tok_s=([\d.]+) \(tokens (\d+) / decode ([\d.]+) s\) rounds=(\d+)", ln)
if m:
p, lab, arm = int(m.group(1)), m.group(2), m.group(3)
if lab == "warm": continue
a = arms.setdefault(arm, dict(hist_t=[0]*9, hist_acc=[0]*9, ms=[0.0]*9, rounds=0, tokens=0, expl=0, lookup=0, passes={}))
a["passes"][p] = (float(m.group(5)), int(m.group(6)), float(m.group(7)), int(m.group(8)))
print(f"{'arm':14} {'reps':>4} {'tok/s mean':>10} {'min':>7} {'max':>7} {'tok/round':>9} {'round ms':>8} {'lookup%':>7} {'explored':>8}")
base = None
for name, a in arms.items():
v = [x[0] for x in a["passes"].values()]
if not v: continue
timed = sum(a["hist_t"]); tot = sum(a["ms"])
tot_tok = sum(x[1] for x in a["passes"].values()); tot_s = sum(x[2] for x in a["passes"].values()); tot_r = sum(x[3] for x in a["passes"].values())
w = tot_tok / tot_s
print(f"{name:14} {len(v):4d} {w:10.2f} {min(v):7.2f} {max(v):7.2f} {tot_tok/max(tot_r,1):9.3f} {tot/max(timed,1):8.2f} {100*a['lookup']/max(timed,1):7.1f} {a['expl']:8d}")
print()
for name, a in arms.items():
timed = sum(a["hist_t"])
if not timed: continue
print(f"[{name}] widths (share / mean round ms): " + " ".join(
f"T{t}:{100*a['hist_t'][t]/timed:4.1f}%/{a['ms'][t]/a['hist_t'][t]:5.1f}" for t in range(1, 9) if a["hist_t"][t]))
print(f" accepted per round: " + " ".join(f"{i}:{100*a['hist_acc'][i]/timed:.1f}%" for i in range(9) if a["hist_acc"][i]))
# paired by repetition: each arm's per-pass tok/s relative to the same repetition's fixed4@0.5
ref = next((n for n in arms if n.startswith("fixed4@0.5")), None)
if ref:
print(f"\nper-repetition tok/s relative to {ref} (same repetition = adjacent passes):")
order = sorted({p for a in arms.values() for p in a["passes"]})
nar = len(arms)
for name, a in arms.items():
rel = []
for p, (t, *_r) in sorted(a["passes"].items()):
rep = (p - 1) // nar
lo = 1 + rep * nar
rr = [arms[ref]["passes"][q][0] for q in range(lo, lo + nar) if q in arms[ref]["passes"]]
if rr: rel.append(100 * (t / rr[0] - 1))
print(f" {name:14} " + " ".join(f"{x:+6.1f}%" for x in rel))
if "--trace" in sys.argv:
arm, p, n = sys.argv[sys.argv.index("--trace") + 1].split(":")
print("\n".join(l.replace("DBG spec-trace ", "") for l in req_trace.get((arm, int(p), int(n)), [])))
main()