Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
117 lines
5.8 KiB
Python
117 lines
5.8 KiB
Python
#!/usr/bin/env python3
|
||
"""Speed tables of the KAR on / off replay A/B (docs/experiments/kar-off-ab-5090.md). Offline, stdlib only; test tooling.
|
||
|
||
kar_off_speed.py RUN_DIR [--md OUT.md] [--json OUT.json]
|
||
|
||
RUN_DIR holds `<arm>-p<n>/` (arm kar|gguf) with `engine.log` (the engine's own `ev:request` records) and `replay.jsonl` (replay_fwd.py). Per run (one stack start):
|
||
decode tok/s = sum(output tokens) / sum(decode ms) (pooled over the requests, not a mean of per-request rates)
|
||
prefill tok/s = sum(prompt - cached tokens) / sum(prefill ms)
|
||
tokens / round = sum(output tokens) / sum(speculative rounds)
|
||
Per arm: mean and sample sd over the passes; pairs are pass k of kar against pass k of gguf (the arms alternate, so a pair is two stack starts of the same window, not the same minute).
|
||
The recorded replies are not fed back, but each stack produces its own text, so the output tokens (and the speculation they allow) differ between arms; that difference is part of the result and is reported (output tokens per run).
|
||
"""
|
||
import argparse, glob, json, math, os, re, statistics, sys
|
||
|
||
|
||
def requests(path):
|
||
out = []
|
||
for line in open(path, encoding="utf-8", errors="replace"):
|
||
if '"ev":"request"' not in line or '"comp":"engine"' not in line:
|
||
continue
|
||
try:
|
||
out.append(json.loads(line))
|
||
except ValueError:
|
||
pass
|
||
return out
|
||
|
||
|
||
def pooled(rows):
|
||
otok = sum(r["otok"] for r in rows)
|
||
dec = sum(r["dec_ms"] for r in rows)
|
||
unc = sum(r["ptok"] - r["ctok"] for r in rows)
|
||
pf = sum(r["pf_ms"] for r in rows)
|
||
rounds = sum(r["rounds"] for r in rows)
|
||
return {
|
||
"requests": len(rows), "output_tokens": otok, "uncached_prompt_tokens": unc, "decode_s": dec / 1000, "prefill_s": pf / 1000,
|
||
"decode_tps": otok / dec * 1000 if dec else float("nan"),
|
||
"prefill_tps": unc / pf * 1000 if pf else float("nan"),
|
||
"tok_per_round": otok / rounds if rounds else float("nan"),
|
||
"tier_vram_pct": statistics.mean(r.get("tier_vram_pct", float("nan")) for r in rows) if rows else float("nan"),
|
||
}
|
||
|
||
|
||
def load_run(d):
|
||
rows = requests(os.path.join(d, "engine.log"))
|
||
replay = [json.loads(l) for l in open(os.path.join(d, "replay.jsonl"))] if os.path.exists(os.path.join(d, "replay.jsonl")) else []
|
||
errors = [r for r in replay if r.get("error") or r.get("status") != 200]
|
||
res = {"dir": d, "replay_requests": len(replay), "replay_errors": len(errors), "engine_requests": len(rows)}
|
||
res["all"] = pooled(rows)
|
||
if len(rows) == len(replay): # same order: split by recorded cell
|
||
cells = {}
|
||
for r, p in zip(rows, replay):
|
||
cells.setdefault(p["cell"], []).append(r)
|
||
res["cells"] = {c: pooled(v) for c, v in cells.items()}
|
||
return res
|
||
|
||
|
||
def ms(xs):
|
||
xs = [x for x in xs if not math.isnan(x)]
|
||
if not xs:
|
||
return float("nan"), float("nan")
|
||
return statistics.mean(xs), (statistics.stdev(xs) if len(xs) > 1 else float("nan"))
|
||
|
||
|
||
def fmt(m, s, nd=1):
|
||
return "-" if math.isnan(m) else (f"{m:.{nd}f} ± {s:.{nd}f}" if not math.isnan(s) else f"{m:.{nd}f}")
|
||
|
||
|
||
def main():
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("run_dir")
|
||
ap.add_argument("--md")
|
||
ap.add_argument("--json")
|
||
a = ap.parse_args()
|
||
if hasattr(sys.stdout, "reconfigure"):
|
||
sys.stdout.reconfigure(encoding="utf-8")
|
||
runs = {}
|
||
for d in sorted(glob.glob(os.path.join(a.run_dir, "*-p[0-9]*"))):
|
||
m = re.match(r"(kar|gguf)-p(\d+)$", os.path.basename(d))
|
||
if not m or not os.path.exists(os.path.join(d, "engine.log")):
|
||
continue
|
||
order = open(os.path.join(d, "order.txt")).read().strip() if os.path.exists(os.path.join(d, "order.txt")) else "?"
|
||
r = load_run(d)
|
||
r["order"] = order
|
||
runs[(m.group(1), int(m.group(2)))] = r
|
||
lines = ["| run | window order | requests | errors | output tokens | decode tok/s | prefill tok/s | tokens / round |", "| --- | --- | --- | --- | --- | --- | --- | --- |"]
|
||
for (arm, n), r in sorted(runs.items()):
|
||
t = r["all"]
|
||
lines.append(f"| {arm} p{n} | {r['order']} | {r['engine_requests']} | {r['replay_errors']} | {t['output_tokens']} | {t['decode_tps']:.1f} | {t['prefill_tps']:.0f} | {t['tok_per_round']:.3f} |")
|
||
lines.append("")
|
||
summary = {}
|
||
metrics = [("decode_tps", "decode tok/s", 1), ("prefill_tps", "prefill tok/s", 0), ("tok_per_round", "tokens / round", 3), ("output_tokens", "output tokens", 0)]
|
||
lines += ["| scope | metric | KAR mean ± sd (n) | GGUF mean ± sd (n) | GGUF − KAR, mean of pairs ± sd | GGUF / KAR − 1 |", "| --- | --- | --- | --- | --- | --- |"]
|
||
scopes = ["all"] + sorted({c for r in runs.values() for c in r.get("cells", {})})
|
||
for scope in scopes:
|
||
for key, label, nd in metrics:
|
||
def get(r):
|
||
return (r["all"] if scope == "all" else r.get("cells", {}).get(scope, {})).get(key, float("nan"))
|
||
k = {n: get(r) for (arm, n), r in runs.items() if arm == "kar"}
|
||
g = {n: get(r) for (arm, n), r in runs.items() if arm == "gguf"}
|
||
km, ks = ms(list(k.values())); gm, gs = ms(list(g.values()))
|
||
pairs = [g[n] - k[n] for n in sorted(set(k) & set(g))]
|
||
pm, ps = ms(pairs)
|
||
rel = (gm / km - 1) * 100 if km and not math.isnan(km) and not math.isnan(gm) else float("nan")
|
||
lines.append(f"| {scope} | {label} | {fmt(km, ks, nd)} ({len(k)}) | {fmt(gm, gs, nd)} ({len(g)}) | {fmt(pm, ps, nd)} | {'-' if math.isnan(rel) else f'{rel:+.1f} %'} |")
|
||
summary[f"{scope}.{key}"] = {"kar": k, "gguf": g, "pairs": pairs}
|
||
text = "\n".join(lines) + "\n"
|
||
print(text)
|
||
if a.md:
|
||
open(a.md, "w", encoding="utf-8").write(text)
|
||
if a.json:
|
||
json.dump({"runs": {f"{k[0]}-p{k[1]}": v for k, v in runs.items()}, "summary": summary}, open(a.json, "w"), indent=1)
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|