Files
leleka/scripts/e2e/decode/baseline-analyze.py
T

333 lines
19 KiB
Python

#!/usr/bin/env python3
"""Analysis of the baseline-pair runs (stdlib only; run on the server): python3 -I baseline-analyze.py RUNROOT [--csv OUT.csv]
Per run (b<block>p<pos>-<arm>): VALID runs only.
speed client decode tok/s per turn and the all-turn mean; vanilla ms/round and tokens/round derived from the engine line
"300 generated in X ms, drafts accepted A of N" (rounds = generated - A, tokens/round = generated / rounds, ms/round = X / rounds), ours from the
"leleka-serve request outcome ... rounds=R" line and the client decode time (300 / decode_tok_s)
state from state.jsonl, restricted to the decode window of each turn (client.ts.log: the turn line time T, decode seconds = output_tokens / decode_tok_s):
mean scaling_cur_freq of the cores that are busy (util > 40 % in the fast sample), AnonHugePages of the GPU process (smaps_rollup), system AnonHugePages,
MemAvailable, free blocks of order >= 9 (buddyinfo, GiB), GPU SM clock / temperature / power; whole-run THP counters delta (thp_fault_alloc / fallback,
compact_stall / fail, allocstall); the arm's uptime at start; the start lines of the engine (arena THP, PCIe probe)
Then: arm table, block-paired deltas (ours - v1, ours - v2, v1 - v2 inside each block) with per-arm spread, order effects (position 1/2/3), and correlations of the all-turn
tok/s of each arm with uptime, order, AnonHugePages of the process, busy-core frequency, MemAvailable, order-9+ free GiB, GPU SM clock, temperature.
"""
import glob, json, math, os, re, statistics as st, sys
ROOT = sys.argv[1]
CSV = sys.argv[sys.argv.index("--csv") + 1] if "--csv" in sys.argv else None
def pearson(x, y):
n = len(x)
if n < 4:
return None
mx, my = st.mean(x), st.mean(y)
sx = math.sqrt(sum((a - mx) ** 2 for a in x)); sy = math.sqrt(sum((b - my) ** 2 for b in y))
return None if sx == 0 or sy == 0 else sum((a - mx) * (b - my) for a, b in zip(x, y)) / (sx * sy)
def ranks(v):
o = sorted(range(len(v)), key=lambda i: v[i]); r = [0.0] * len(v); i = 0
while i < len(o):
j = i
while j + 1 < len(o) and v[o[j + 1]] == v[o[i]]:
j += 1
for k in range(i, j + 1):
r[o[k]] = (i + j) / 2 + 1
i = j + 1
return r
def spearman(x, y):
return pearson(ranks(x), ranks(y)) if len(x) >= 4 else None
def fmt(v, p=1):
return "-" if v is None else ("%." + str(p) + "f") % v
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):
"""GiB of free memory in blocks of order >= 9 (>= 2 MiB), Normal zone."""
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:]]
for o in range(9, len(c)):
tot += c[o] * (4096 << o)
return tot / 2**30
def parse_run(d):
name = os.path.basename(d)
m = re.match(r"b(\d+)p(\d+)-(\w+)$", name)
if not m or not os.path.exists(os.path.join(d, "VALIDITY.txt")) or not open(os.path.join(d, "VALIDITY.txt")).read().startswith("VALID"):
return None
r = {"name": name, "block": int(m.group(1)), "pos": int(m.group(2)), "arm": m.group(3)}
turns = json.load(open(os.path.join(d, "long-session.json")))
r["tok_s"] = [t.get("decode_tok_s") or 0.0 for t in turns]
r["mean"] = st.mean(r["tok_s"])
out_tok = [t.get("output_tokens") or 300 for t in turns]
# rounds per turn
rounds, ms_round, tok_round = [], [], []
if r["arm"].startswith("ours"):
for ln in open(os.path.join(d, "inference.log"), errors="replace"):
mm = re.search(r"leleka-serve request outcome=completed produced=(\d+) rounds=(\d+)", ln)
if mm:
rounds.append((int(mm.group(1)), int(mm.group(2))))
rounds = rounds[-5:]
for (prod, rd), t, o in zip(rounds, turns, out_tok):
if rd:
tok_round.append(prod / rd)
ms_round.append(1000.0 * (o / (t.get("decode_tok_s") or 1)) / rd)
else:
lines = [l for l in open(os.path.join(d, "engine.log"), errors="replace") if "strata serve: prompt" in l and "generated in" in l]
lines = lines[-5:] if len(lines) >= 5 else lines
for ln in lines:
mm = re.search(r"(\d+) generated in (\d+) ms.*drafts accepted (\d+) of (\d+)", ln)
if mm:
gen, ms, acc = int(mm.group(1)), int(mm.group(2)), int(mm.group(3))
rd = gen - acc
if rd > 0 and gen > 1:
tok_round.append(gen / rd); ms_round.append(ms / rd)
r["tok_round"], r["ms_round"] = tok_round, ms_round
# decode windows from the timestamped client lines
win = []
ts = os.path.join(d, "client.ts.log")
if os.path.exists(ts):
k = 0
for ln in open(ts, errors="replace"):
try:
t_s, rest = ln.split(" ", 1)
if rest.startswith("{") and '"decode_tok_s"' in rest and k < len(turns):
T = float(t_s); dur = out_tok[k] / (turns[k].get("decode_tok_s") or 1); win.append((T - dur, T)); k += 1
except Exception:
pass
r["win"] = win
S = jl(os.path.join(d, "state.jsonl"))
full = [s for s in S if s.get("kind") == "full"]
fast = [s for s in S if s.get("kind") == "fast"] + full
pre = jl(os.path.join(d, "pre.jsonl")); post = jl(os.path.join(d, "post.jsonl"))
pre = pre[0] if pre else (full[0] if full else None); post = post[0] if post else (full[-1] if full else None)
r["uptime_h"] = pre["uptime_s"] / 3600.0 if pre else None
r["t0"] = pre["t"] if pre else None
def inwin(s):
return any(a <= s["t"] <= b for a, b in win)
busy = []
for s in fast:
if s.get("cpu_util") and inwin(s):
f = [k for k, u, kh in zip(range(len(s["cpu_util"])), s["cpu_util"], s["cpu_khz"]) if u is not None and u > 40 and kh]
if f:
busy.append(st.mean(s["cpu_khz"][c] for c in f) / 1000.0)
r["busy_mhz"] = st.mean(busy) if busy else None
r["busy_mhz_n"] = len(busy)
# all-run busy freq (any time util > 40): the load phase is included, used when the decode windows hold no sample
allb = []
for s in fast:
if s.get("cpu_util"):
f = [c for c, u in enumerate(s["cpu_util"]) if u is not None and u > 40 and s["cpu_khz"][c]]
if len(f) >= 4:
allb.append(st.mean(s["cpu_khz"][c] for c in f) / 1000.0)
r["busy_mhz_all"] = st.mean(allb) if allb else None
ah, ahs, ma, buddy, gsm, gtemp, gpow = [], [], [], [], [], [], []
for s in full:
if not inwin(s) and win:
continue
pr = [p for p in s.get("procs", []) if p.get("smaps_rollup_kb")]
if pr:
ah.append(max(p["smaps_rollup_kb"].get("AnonHugePages", 0) for p in pr) / 2**20)
ahs.append(max(p["smaps_rollup_kb"].get("Rss", 0) for p in pr) / 2**20)
mi = s.get("meminfo_kb", {})
ma.append(mi.get("MemAvailable", 0) / 2**20)
b = buddy_hi_gib(s.get("buddy"))
if b is not None:
buddy.append(b)
g = s.get("gpu", {})
for lst, key in ((gsm, "sm_mhz"), (gtemp, "temp_c"), (gpow, "power_w")):
try:
lst.append(float(g[key]))
except Exception:
pass
# fall back to every full sample when no full sample landed inside a decode window
if not ah:
for s in full:
pr = [p for p in s.get("procs", []) if p.get("smaps_rollup_kb")]
if pr:
ah.append(max(p["smaps_rollup_kb"].get("AnonHugePages", 0) for p in pr) / 2**20)
ahs.append(max(p["smaps_rollup_kb"].get("Rss", 0) for p in pr) / 2**20)
r["state_scope"] = "run"
else:
r["state_scope"] = "decode windows"
mx = lambda v: max(v) if v else None
mean = lambda v: st.mean(v) if v else None
r["proc_anonhuge_gib"], r["proc_rss_gib"], r["memavail_gib"], r["buddy9_gib"] = mx(ah), mx(ahs), mean(ma), mean(buddy)
r["gpu_sm_mhz"], r["gpu_temp"], r["gpu_power"] = mean(gsm), mean(gtemp), mean(gpow)
# pre-run state
if pre:
mi = pre.get("meminfo_kb", {})
r["pre_memavail_gib"] = mi.get("MemAvailable", 0) / 2**20
r["pre_buddy9_gib"] = buddy_hi_gib(pre.get("buddy"))
r["pre_cached_gib"] = mi.get("Cached", 0) / 2**20
r["pre_load1"] = float(pre["loadavg"][0])
if pre and post:
v0, v1 = pre.get("vmstat", {}), post.get("vmstat", {})
for k in ("thp_fault_alloc", "thp_fault_fallback", "compact_stall", "compact_fail", "allocstall_normal", "pgmajfault"):
r["d_" + k] = v1.get(k, 0) - v0.get(k, 0)
# other CPU consumers inside the run (ticks per interval; 100 ticks = 1 s of one CPU)
oth, who = 0, ""
own = ("leleka", "strata", "python", "nvidia", "bash", "ssh", "curl", "sleep", "grep", "cut", "tee", "date", "cat", "awk", "sed", "timeout", "taskset", "kworker", "ksoftirq", "rcu_", "migration")
for s in full:
for p, c, tk in s.get("others_top", []):
if not any(c.startswith(o) or o in c for o in own) and tk > oth:
oth, who = tk, c
r["other_cpu_max_ticks"], r["other_cpu_who"] = oth, who
# engine start lines
sf = os.path.join(d, "startup.txt")
txt = open(sf, errors="replace").read() if os.path.exists(sf) else ""
mm = re.search(r"PCIe probe: ([\d.]+) GB/s", txt); r["pcie_gbs"] = float(mm.group(1)) if mm else None
mm = re.search(r"needed (\d+) 2 MiB pages", txt); r["arena_pages"] = int(mm.group(1)) if mm else None
ep = os.path.join(d, "engine.log")
if os.path.exists(ep):
etxt = open(ep, errors="replace").read()
pf = re.findall(r"the CPU pool takes (\d+) us per missed expert .*?the link ([\d.]+) GB/s -> pcie_frac ([\d.]+)", etxt)
r["cpu_us_per_expert"] = float(pf[-1][0]) if pf else None
r["pcie_frac_final"] = float(pf[-1][2]) if pf else None
hr = re.findall(r"decode expert cache hit rate: ([\d.]+)% \((\d+) hits / (\d+) lookups\); (\d+) more read", etxt)
r["hit_pct"] = st.mean(float(h[0]) for h in hr[-5:]) if hr else None
r["pcie_read_pct"] = st.mean(100.0 * int(h[3]) / max(int(h[2]), 1) for h in hr[-5:]) if hr else None
for lg in ("inference.log", "engine.log"):
lp = os.path.join(d, lg)
if os.path.exists(lp):
with open(lp, errors="replace") as f:
head = f.read(400000)
mm = re.search(r"expert cache (\d+) slots", head)
if mm:
r["slots"] = int(mm.group(1)); break
return r
runs = []
for d in sorted(glob.glob(os.path.join(ROOT, "b*p*-*"))):
if os.path.isdir(d):
x = parse_run(d)
if x:
runs.append(x)
else:
v = os.path.join(d, "VALIDITY.txt")
print(os.path.basename(d), "not used:", open(v).read().strip() if os.path.exists(v) else "no VALIDITY.txt")
runs.sort(key=lambda r: (r["block"], r["pos"]))
if not runs:
print("no valid runs"); sys.exit(0)
print("== per run (tok/s T1..T5, all-turn mean; tokens/round, ms/round = mean of the 5 turns) ==")
print("run up_h tok/s T1..T5 mean tok/rd ms/rd busyMHz AnonHuge/Rss GiB MemAvail buddy>=2M GPU sm MHz/C/W d_thp_fb d_cstall pcie GB/s")
for r in runs:
print("%-12s %5s %s %6.1f %6s %6s %7s %5s/%-5s %8s %8s %6s/%s/%s %8s %8s %6s" % (
r["name"], fmt(r["uptime_h"]), " ".join("%5.1f" % x for x in r["tok_s"]), r["mean"], fmt(st.mean(r["tok_round"]) if r["tok_round"] else None, 2),
fmt(st.mean(r["ms_round"]) if r["ms_round"] else None, 2), fmt(r["busy_mhz"] or r["busy_mhz_all"], 0), fmt(r["proc_anonhuge_gib"]), fmt(r["proc_rss_gib"]),
fmt(r["memavail_gib"]), fmt(r["buddy9_gib"]), fmt(r["gpu_sm_mhz"], 0), fmt(r["gpu_temp"], 0), fmt(r["gpu_power"], 0), r.get("d_thp_fault_fallback", "-"), r.get("d_compact_stall", "-"),
fmt(r["pcie_gbs"])))
arms = [a for a in ["ours", "ours45", "v1", "v2"] if any(r["arm"] == a for r in runs)]
by = {a: [r for r in runs if r["arm"] == a] for a in ["ours", "ours45", "v1", "v2"]}
print("\n== arm summary (n runs; all-turn mean tok/s: mean, sd, min, max; per-turn means; tokens/round; ms/round) ==")
for a in arms:
rs = by[a]
if not rs:
continue
m = [r["mean"] for r in rs]
pt = [st.mean(c) for c in zip(*[r["tok_s"] for r in rs])]
tr = [st.mean(r["tok_round"]) for r in rs if r["tok_round"]]
mr = [st.mean(r["ms_round"]) for r in rs if r["ms_round"]]
print("%-5s n=%d mean %.1f sd %.1f min %.1f max %.1f | per-turn %s | tok/round %s | ms/round %s (sd %s)" % (
a, len(rs), st.mean(m), st.stdev(m) if len(m) > 1 else 0, min(m), max(m), " ".join("%.1f" % x for x in pt), fmt(st.mean(tr) if tr else None, 2),
fmt(st.mean(mr) if mr else None, 2), fmt(st.stdev(mr) if len(mr) > 1 else None, 2)))
def block_pairs(a, b):
out = []
blocks = sorted(set(r["block"] for r in runs))
for bl in blocks:
ra = [r for r in by[a] if r["block"] == bl]; rb = [r for r in by[b] if r["block"] == bl]
if ra and rb:
out.append((bl, ra[0], rb[0]))
return out
print("\n== block-paired deltas (a - b inside the same block; % = a / b - 1 on the all-turn mean) ==")
for a, b in (("ours", "v1"), ("ours", "v2"), ("v1", "v2"), ("ours45", "v1"), ("ours45", "v2"), ("ours", "ours45")):
ps = block_pairs(a, b)
if not ps:
continue
dl = [pa["mean"] - pb["mean"] for _, pa, pb in ps]
pc = [100 * (pa["mean"] / pb["mean"] - 1) for _, pa, pb in ps]
rr = [(pa["ms_round"] and pb["ms_round"]) and (st.mean(pa["ms_round"]) - st.mean(pb["ms_round"])) for _, pa, pb in ps]
tt = [(pa["tok_round"] and pb["tok_round"]) and (st.mean(pa["tok_round"]) - st.mean(pb["tok_round"])) for _, pa, pb in ps]
n = len(dl); mdl = st.mean(dl); sd = st.stdev(dl) if n > 1 else 0; se = sd / math.sqrt(n) if n > 1 else 0
print("%s - %s: n=%d pairs" % (a, b, n))
print(" block : " + " ".join("%7d" % bl for bl, _, _ in ps))
print(" tok/s : " + " ".join("%+7.1f" % x for x in dl) + " mean %+.1f sd %.1f se %.1f (95%% CI about %+.1f..%+.1f, t-approx, n small)" % (mdl, sd, se, mdl - 2.57 * se if n == 6 else mdl - 2 * se, mdl + 2.57 * se if n == 6 else mdl + 2 * se))
print(" percent : " + " ".join("%+7.1f" % x for x in pc) + " mean %+.1f %% (pairs where a is faster: %d of %d)" % (st.mean(pc), sum(1 for x in dl if x > 0), n))
if all(isinstance(x, float) for x in rr) and rr:
print(" ms/round: " + " ".join("%+7.2f" % x for x in rr) + " mean %+.2f" % st.mean(rr))
if all(isinstance(x, float) for x in tt) and tt:
print(" tok/rd : " + " ".join("%+7.2f" % x for x in tt) + " mean %+.2f" % st.mean(tt))
print("\n== order effect: all-turn mean tok/s by position in the block (1 = first after the previous block's last arm) ==")
for a in arms:
row = []
for p in (1, 2, 3):
v = [r["mean"] for r in by[a] if r["pos"] == p]
row.append("pos%d n=%d %s" % (p, len(v), fmt(st.mean(v) if v else None)))
print("%-5s %s" % (a, " | ".join(row)))
print("by predecessor arm (what ran just before):")
seq = sorted(runs, key=lambda r: (r["block"], r["pos"]))
for a in arms:
row = []
for prev in arms + ["(block start)"]:
v = []
for i, r in enumerate(seq):
if r["arm"] != a:
continue
pa = seq[i - 1]["arm"] if (i > 0 and seq[i - 1]["block"] == r["block"]) else "(block start)"
if pa == prev:
v.append(r["mean"])
row.append("after %s n=%d %s" % (prev, len(v), fmt(st.mean(v) if v else None)))
print("%-5s %s" % (a, " | ".join(row)))
print("\n== drift: correlation (Pearson / Spearman) of a run's all-turn mean tok/s and mean ms/round with the state variable; vanilla = v1 + v2 pooled ==")
VARS = [("uptime_h", "uptime at start (h)"), ("t0", "wall time of the run"), ("pos", "position in block"), ("proc_anonhuge_gib", "GPU process AnonHugePages (GiB)"), ("proc_rss_gib", "process Rss"),
("busy_mhz", "busy-core MHz (decode windows)"), ("busy_mhz_all", "busy-core MHz (whole run)"), ("memavail_gib", "MemAvailable"), ("buddy9_gib", "free GiB in order>=9 blocks"),
("pre_buddy9_gib", "free GiB order>=9 before the run"), ("pre_memavail_gib", "MemAvailable before the run"), ("gpu_sm_mhz", "GPU SM MHz"), ("gpu_temp", "GPU temp"), ("pcie_gbs", "PCIe probe GB/s (vanilla)"), ("pcie_frac_final", "vanilla final pcie_frac"), ("cpu_us_per_expert", "vanilla CPU pool us/expert"), ("hit_pct", "vanilla decode VRAM hit %"), ("pcie_read_pct", "vanilla PCIe-read %"),
("d_thp_fault_fallback", "thp_fault_fallback delta"), ("d_compact_stall", "compact_stall delta"), ("other_cpu_max_ticks", "foreign (non-arm) process CPU ticks, max per sample interval")]
for a, rs in (("ours", by["ours"]), ("ours45", by["ours45"]), ("v1", by["v1"]), ("v2", by["v2"]), ("vanilla (v1+v2)", by["v1"] + by["v2"])):
print("%s (n=%d)" % (a, len(rs)))
for k, label in VARS:
pts = [(r[k], r["mean"], st.mean(r["ms_round"])) for r in rs if r.get(k) is not None and r["ms_round"]]
if len(pts) < 4:
continue
x, y, z = [p[0] for p in pts], [p[1] for p in pts], [p[2] for p in pts]
if len(set(x)) < 2:
continue
print(" %-44s n=%2d tok/s: r=%s rho=%s | ms/round: r=%s rho=%s | x %s..%s" % (label[:44], len(pts), fmt(pearson(x, y), 2), fmt(spearman(x, y), 2), fmt(pearson(x, z), 2), fmt(spearman(x, z), 2), fmt(min(x), 1), fmt(max(x), 1)))
vs = by["v1"] + by["v2"]
part = [r for r in vs if r.get("proc_anonhuge_gib") is not None and r["proc_anonhuge_gib"] < 45.5]
full_ = [r for r in vs if r.get("proc_anonhuge_gib") is not None and r["proc_anonhuge_gib"] >= 45.5]
if part and full_:
print("\nvanilla runs by THP coverage of the process (AnonHugePages < 45.5 GiB of a 46.8 GiB arena = partial): partial n=%d tok/s %.1f ms/round %.2f | full n=%d tok/s %.1f ms/round %.2f" % (
len(part), st.mean(r["mean"] for r in part), st.mean(st.mean(r["ms_round"]) for r in part), len(full_), st.mean(r["mean"] for r in full_), st.mean(st.mean(r["ms_round"]) for r in full_)))
if CSV:
cols = ["name", "block", "pos", "arm", "mean", "uptime_h", "t0", "busy_mhz", "busy_mhz_all", "proc_anonhuge_gib", "proc_rss_gib", "memavail_gib", "buddy9_gib", "pre_buddy9_gib", "gpu_sm_mhz", "gpu_temp",
"pcie_gbs", "pcie_frac_final", "cpu_us_per_expert", "hit_pct", "pcie_read_pct", "slots", "d_thp_fault_alloc", "d_thp_fault_fallback", "d_compact_stall", "d_compact_fail", "d_allocstall_normal", "other_cpu_max_ticks"]
with open(CSV, "w") as f:
f.write(",".join(cols + ["t1", "t2", "t3", "t4", "t5", "tok_round", "ms_round"]) + "\n")
for r in runs:
f.write(",".join("" if r.get(c) is None else str(r.get(c)) for c in cols) + "," + ",".join("%.2f" % x for x in r["tok_s"]) + ",%s,%s\n" % (
"%.3f" % st.mean(r["tok_round"]) if r["tok_round"] else "", "%.3f" % st.mean(r["ms_round"]) if r["ms_round"] else ""))
print("\ncsv:", CSV)