#!/usr/bin/env python3 """Parse a claude/adaptive-spec holder log (run_arms) into per-arm tables. usage: spec_analyze.py LOG [--trace ARM:PROMPT:PASS] Per arm: weighted decode tok/s = sum(tokens) / sum(serve ms) (decode.serve span of the profile line, i.e. the verify loop alone) and with the phase wall (DBG timing, includes the per-request verifier assembly), tokens per round, accepted-per-round histogram, mean round ms and round count per window width. Also: greedy token equality of every arm against fixed4, per prompt. """ import re, sys, collections, statistics def main(): path = sys.argv[1] lines = open(path, errors="replace").read().splitlines() stats = None; prof = None reqs = [] # dict per corpus request outputs = {} # (prompt, pass) -> (arm, ids) trace = collections.defaultdict(list) # request index -> trace lines cur_trace = [] for ln in lines: if ln.startswith("DBG spec-trace"): cur_trace.append(ln) elif ln.startswith("DBG spec-stats"): stats = ln; stats_trace = cur_trace; cur_trace = [] elif ln.startswith("DBG profile request"): prof = ln else: m = re.match(r"DBG corpus (\d+) output pass=(\d+) arm=(\S+) \((\d+) tokens, rounds (\d+)\): (.*)", ln) if m: outputs[(int(m.group(1)), int(m.group(2)))] = (m.group(3), m.group(6).split()) continue m = re.match(r"DBG corpus (\d+) timing pass=(\d+) arm=(\S+) prompt=(\d+) produced=(\d+) rounds=(\d+) ttft_ms=([\d.]+) total_ms=([\d.]+)", ln) if m: r = dict(prompt=int(m.group(1)), pass_=int(m.group(2)), arm=m.group(3), plen=int(m.group(4)), produced=int(m.group(5)), rounds=int(m.group(6)), ttft=float(m.group(7))) r["stats"] = stats; r["trace"] = stats_trace if stats else [] r["serve_ms"] = None if prof: mm = re.search(r"decode\.serve=([\d.]+)/", prof) if mm: r["serve_ms"] = float(mm.group(1)) reqs.append(r); stats = None; prof = None continue m = re.match(r"DBG timing corpus (\d+) pass (\d+): prompt ([\d.]+) ms, decode ([\d.]+) ms, produced (\d+)", ln) if m and reqs and reqs[-1]["prompt"] == int(m.group(1)) and reqs[-1]["pass_"] == int(m.group(2)): reqs[-1]["phase_ms"] = float(m.group(4)) arms = collections.OrderedDict() for r in reqs: st = r["stats"] or "" kv = dict(re.findall(r"(\w+)=(\S+)", st)) a = arms.setdefault(r["arm"], dict(tok=0, serve=0.0, phase=0.0, rounds=0, n=0, tpr=[], hist_t=[0]*9, hist_acc=[0]*9, ms_by_t=[0.0]*9, expl=0, lookup=0, per_prompt=collections.defaultdict(list))) a["n"] += 1; a["tok"] += r["produced"]; a["rounds"] += r["rounds"] if r.get("serve_ms"): a["serve"] += r["serve_ms"] if r.get("phase_ms"): a["phase"] += r["phase_ms"] a["expl"] += int(kv.get("explored", 0)); a["lookup"] += int(kv.get("lookup_rounds", 0)) if "T_hist[0..=8]" in kv: for i, v in enumerate(kv["T_hist[0..=8]"].split(",")): a["hist_t"][i] += int(v) for i, v in enumerate(kv["acc_hist"].split(",")): a["hist_acc"][i] += int(v) ms = kv["ms_by_T"].split(",") th = kv["T_hist[0..=8]"].split(",") for i, v in enumerate(ms): if v != "-": a["ms_by_t"][i] += float(v) * int(th[i]) if r.get("serve_ms"): a["per_prompt"][r["prompt"]].append(r["produced"] * 1e3 / r["serve_ms"]) print(f"{'arm':10} {'reqs':>4} {'tok':>6} {'serve tok/s':>11} {'phase tok/s':>11} {'tok/round':>9} {'round ms':>8} {'lookup%':>7} {'expl':>5}") for name, a in arms.items(): timed = sum(a["hist_t"]) tot_ms = sum(a["ms_by_t"]) print(f"{name:10} {a['n']:4d} {a['tok']:6d} {a['tok']*1e3/max(a['serve'],1e-9):11.2f} {a['tok']*1e3/max(a['phase'],1e-9):11.2f} " f"{a['tok']/max(a['rounds'],1):9.3f} {tot_ms/max(timed,1):8.2f} {100*a['lookup']/max(timed,1):7.1f} {a['expl']:5d}") print() for name, a in arms.items(): timed = sum(a["hist_t"]) print(f"[{name}] window width histogram (rows: share%, mean round ms):") print(" " + " ".join(f"T{t}:{100*a['hist_t'][t]/max(timed,1):4.1f}%/{(a['ms_by_t'][t]/a['hist_t'][t] if a['hist_t'][t] else 0):5.1f}ms" for t in range(1, 9) if a["hist_t"][t])) acc = a["hist_acc"] print(" accepted per round: " + " ".join(f"{i}:{100*acc[i]/max(timed,1):.1f}%" for i in range(9) if acc[i])) # greedy equality against fixed4 (or the first arm) ref = "fixed4" if "fixed4" in arms else next(iter(arms)) by = collections.defaultdict(dict) for (p, q), (arm, ids) in outputs.items(): by[p].setdefault(arm, []).append(ids) print(f"\ngreedy token ids against {ref} (same prompt, any pass): identical / first-diff index") for arm in arms: if arm == ref: continue same = tot = 0; diffs = [] for p, d in sorted(by.items()): if arm in d and ref in d: for ids in d[arm]: tot += 1 r0 = d[ref][0] n = min(len(ids), len(r0)) k = next((i for i in range(n) if ids[i] != r0[i]), None) if k is None and len(ids) == len(r0): same += 1 else: diffs.append((p, k if k is not None else n)) print(f" {arm}: {same}/{tot} identical; differing (prompt, first diff token): {diffs}") # fixed4 self-consistency (repeats of the reference arm) selfsame = selftot = 0 for p, d in by.items(): if ref in d and len(d[ref]) > 1: for ids in d[ref][1:]: selftot += 1; selfsame += ids == d[ref][0] print(f" {ref} against itself (repeat passes): {selfsame}/{selftot} identical") # per prompt serve tok/s per arm print("\nper-prompt serve tok/s (mean over passes):") ps = sorted({p for a in arms.values() for p in a["per_prompt"]}) print("prompt " + " ".join(f"{n:>9}" for n in arms)) for p in ps: print(f"{p:6d} " + " ".join(f"{statistics.mean(a['per_prompt'][p]) if a['per_prompt'].get(p) else 0:9.2f}" for a in arms.values())) if "--trace" in sys.argv: spec = sys.argv[sys.argv.index("--trace") + 1].split(":") arm, prompt, pas = spec[0], int(spec[1]), int(spec[2]) for r in reqs: if r["arm"] == arm and r["prompt"] == prompt and r["pass_"] == pas: print("\n".join(l.replace("DBG spec-trace ", "") for l in r["trace"])) main()