Files
leleka/scripts/e2e/decode/hugepages-analyze.py
T
Pavlo RatushnyiandClaude Opus 5.5 a8171b2cc0 scripts: hugepages A/B, identity gate, analyser, installer; owner script for shmem THP (not run)
hugepages-ab.sh: one binary, hpoff vs hpon (LELEKA_HUGEPAGES=on), 8 ABBA-balanced pairs of the 5-turn
~245k session at the product PCIe share 0.45, baseline-sampler state record (buddyinfo, AnonHugePages,
process smaps_rollup) per run. hugepages-id.sh: bitwise replay identity at 8,000 static slots.
hugepages-analyze.py: pairs, predecessor split, exit fragmentation. owner-shmem-thp.sh: root-only
shmem_enabled toggle, not needed by the decode path. huge_pages.rs: mapped_len test-only (dead-code warning).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 00:16:35 +01:00

137 lines
8.5 KiB
Python

#!/usr/bin/env python3
"""Analyse a hugepages-ab.sh output directory (claude/hugepages). Stdlib only.
python3 -I hugepages-analyze.py /data/leleka-e2e/runs/hugepages-ab [--csv out.csv]
Per VALID run: arm, pair, predecessor arm, decode tok/s per turn and all-turn mean, tokens/round, ms/round, the engine's huge-page coverage line, the GPU process
AnonHugePages (max of the state samples), bank-load and total load seconds, free GiB in blocks of order >= 9 (>= 2 MiB, Normal + DMA32) before the run (pre.jsonl)
and after the engine exited (post.jsonl), and the whole-run thp_fault_alloc / thp_fault_fallback / compact_stall deltas.
Then: per-arm means and spread, the pair differences (hpon - hpoff inside each pair), the split by predecessor (after hpoff / after hpon), and exit fragmentation by arm.
"""
import json, os, re, statistics, sys
def jl(path):
out = []
if os.path.exists(path):
for ln in open(path, errors="replace"):
try:
out.append(json.loads(ln))
except Exception:
pass
return out
def buddy_hi_gib(txt):
if not txt:
return None
tot = 0.0
for ln in txt.splitlines():
if "Normal" in ln or "DMA32" in ln:
c = [int(x) for x in ln.split("zone")[1].split()[1:]]
tot += sum(c[o] * (4096 << o) for o in range(9, len(c)))
return tot / 2**30
def parse(d):
r = {"name": os.path.basename(d)}
a = open(os.path.join(d, "ARM.txt")).read() if os.path.exists(os.path.join(d, "ARM.txt")) else ""
kv = dict(re.findall(r"(\w+)=(\S+)", a))
r["arm"], r["pair"], r["seq"] = kv.get("arm"), int(kv.get("pair", 0)), int(kv.get("seq_index", 0))
v = open(os.path.join(d, "VALIDITY.txt")).read().strip() if os.path.exists(os.path.join(d, "VALIDITY.txt")) else "no VALIDITY.txt"
r["valid"] = v.startswith("VALID")
r["validity"] = v
if not r["valid"]:
return r
sess = json.load(open(os.path.join(d, "long-session.json")))
log = open(os.path.join(d, "inference.log"), errors="replace").read()
outs = [tuple(int(x) for x in m) for m in re.findall(r"leleka-serve request outcome.*?produced=(\d+) rounds=(\d+)", log)]
r["tps"] = [t.get("decode_tok_s") or 0.0 for t in sess]
r["mean"] = statistics.mean(r["tps"])
r["final_in"] = sess[-1].get("input_tokens")
tr, mr = [], []
for i, t in enumerate(sess):
if i < len(outs) and outs[i][1]:
p, n = outs[i]
tr.append(p / n)
out = t.get("output_tokens") or p
mr.append(1000.0 * out / t["decode_tok_s"] / n if t.get("decode_tok_s") else float("nan"))
r["tok_round"] = statistics.mean(tr) if tr else float("nan")
r["ms_round"] = statistics.mean(mr) if mr else float("nan")
hp = re.findall(r"leleka-hugepages: (after \w+): .*?huge ([\d.]+) GiB \(([\d.]+) %", log)
r["cov_fill"] = next((float(p) for k, g, p in hp if k == "after fill"), None)
r["cov_final"] = float(hp[-1][2]) if hp else None
m = re.search(r"MADV_COLLAPSE ([\d.]+) s", log)
r["collapse_s"] = float(m.group(1)) if m else None
m = re.search(r"phase=expert_bank_admission seconds=([\d.]+)", log)
r["bank_load_s"] = float(m.group(1)) if m else None
tots = re.findall(r"leleka-load-time phase=\S+ seconds=[\d.]+ total=([\d.]+)", log)
r["load_total_s"] = float(tots[-1]) if tots else None
pre, post, st = jl(os.path.join(d, "pre.jsonl")), jl(os.path.join(d, "post.jsonl")), [s for s in jl(os.path.join(d, "state.jsonl")) if s.get("kind") == "full"]
r["pre_buddy9"] = buddy_hi_gib(pre[0].get("buddy")) if pre else None
r["post_buddy9"] = buddy_hi_gib(post[0].get("buddy")) if post else None
r["pre_memfree"] = pre[0]["meminfo_kb"]["MemFree"] / 2**20 if pre else None
ah = [max(p["smaps_rollup_kb"].get("AnonHugePages", 0) for p in s.get("procs", []) if p.get("smaps_rollup_kb")) / 2**20
for s in st if any(p.get("smaps_rollup_kb") for p in s.get("procs", []))]
r["proc_anonhuge"] = max(ah) if ah else 0.0
if pre and post:
a0, a1 = pre[0].get("vmstat", {}), post[0].get("vmstat", {})
for k in ("thp_fault_alloc", "thp_fault_fallback", "compact_stall", "thp_collapse_alloc"):
if k in a0 and k in a1:
r["d_" + k] = int(a1[k]) - int(a0[k])
return r
def f(v, p=1):
return "-" if v is None else ("%.*f" % (p, v))
def main():
root = sys.argv[1]
runs = [parse(os.path.join(root, n)) for n in sorted(os.listdir(root)) if os.path.isdir(os.path.join(root, n)) and os.path.exists(os.path.join(root, n, "ARM.txt"))]
runs.sort(key=lambda r: r["seq"])
prev = None
for r in runs:
r["pred"] = prev["arm"] if prev else "none"
prev = r
print("run pred tok/s T1..T5 mean tok/rd ms/rd cov fill/final % procAHP GiB bank/total load s collapse s pre/post buddy>=2M GiB thp alloc/fallback cstall")
for r in runs:
if not r["valid"]:
print("%-14s NOT USED: %s" % (r["name"], r["validity"]))
continue
print("%-14s %-6s %-32s %6.1f %5.2f %6.2f %5s/%-5s %10s %6s/%-6s %8s %8s/%-8s %7s/%-7s %6s" % (
r["name"], r["pred"], " ".join("%.1f" % x for x in r["tps"]), r["mean"], r["tok_round"], r["ms_round"], f(r["cov_fill"]), f(r["cov_final"]), f(r["proc_anonhuge"], 2),
f(r["bank_load_s"]), f(r["load_total_s"]), f(r["collapse_s"], 2), f(r["pre_buddy9"]), f(r["post_buddy9"]), r.get("d_thp_fault_alloc", "-"), r.get("d_thp_fault_fallback", "-"), r.get("d_compact_stall", "-")))
ok = [r for r in runs if r["valid"]]
print()
for arm in ("hpoff", "hpon"):
xs = [r for r in ok if r["arm"] == arm]
if not xs:
continue
m = [r["mean"] for r in xs]
sd = statistics.stdev(m) if len(m) > 1 else 0.0
print("ARM %-5s n=%d all-turn tok/s %.1f (sd %.2f = %.2f %%, %.1f..%.1f) | tok/round %.3f | ms/round %.2f (sd %.3f) | bank load %.1f s, total load %.1f s | post buddy>=2M %.1f GiB" % (
arm, len(xs), statistics.mean(m), sd, 100 * sd / statistics.mean(m), min(m), max(m), statistics.mean(r["tok_round"] for r in xs), statistics.mean(r["ms_round"] for r in xs),
statistics.stdev([r["ms_round"] for r in xs]) if len(xs) > 1 else 0.0, statistics.mean(r["bank_load_s"] or 0 for r in xs), statistics.mean(r["load_total_s"] or 0 for r in xs),
statistics.mean(r["post_buddy9"] or 0 for r in xs)))
for pred in ("hpoff", "hpon"):
ys = [r for r in xs if r["pred"] == pred]
if ys:
print(" after %-5s n=%d tok/s %.1f ms/round %.2f pre buddy>=2M %.1f GiB cov_final %s" % (pred, len(ys), statistics.mean(r["mean"] for r in ys), statistics.mean(r["ms_round"] for r in ys),
statistics.mean(r["pre_buddy9"] or 0 for r in ys), f(statistics.mean(r["cov_final"] for r in ys) if all(r["cov_final"] is not None for r in ys) else None)))
diffs, msd, trd = [], [], []
for p in sorted({r["pair"] for r in ok}):
a = [r for r in ok if r["pair"] == p and r["arm"] == "hpoff"]
b = [r for r in ok if r["pair"] == p and r["arm"] == "hpon"]
if len(a) == 1 and len(b) == 1:
diffs.append(100 * (b[0]["mean"] / a[0]["mean"] - 1)); msd.append(b[0]["ms_round"] - a[0]["ms_round"]); trd.append(b[0]["tok_round"] - a[0]["tok_round"])
print("pair %d (%s first): hpon %.1f vs hpoff %.1f tok/s (%+.2f %%), ms/round %+.3f, tok/round %+.3f" % (p, "hpoff" if a[0]["seq"] < b[0]["seq"] else "hpon", b[0]["mean"], a[0]["mean"], diffs[-1], msd[-1], trd[-1]))
if diffs:
se = statistics.stdev(diffs) / len(diffs) ** 0.5 if len(diffs) > 1 else float("nan")
print("hpon - hpoff over %d pairs: tok/s %+.2f %% (se %.2f, min %+.2f max %+.2f, %d/%d positive); ms/round %+.3f (min %+.3f max %+.3f, %d/%d lower); tok/round %+.3f" % (
len(diffs), statistics.mean(diffs), se, min(diffs), max(diffs), sum(d > 0 for d in diffs), len(diffs), statistics.mean(msd), min(msd), max(msd), sum(d < 0 for d in msd), len(msd), statistics.mean(trd)))
if "--csv" in sys.argv:
cols = ["name", "seq", "pair", "arm", "pred", "mean", "tok_round", "ms_round", "cov_fill", "cov_final", "proc_anonhuge", "bank_load_s", "load_total_s", "collapse_s", "pre_buddy9", "post_buddy9",
"pre_memfree", "d_thp_fault_alloc", "d_thp_fault_fallback", "d_compact_stall"]
with open(sys.argv[sys.argv.index("--csv") + 1], "w") as out:
out.write(",".join(cols) + "\n")
for r in ok:
out.write(",".join(str(r.get(c, "")) for c in cols) + "\n")
main()