"""VRAM hit share of the routed experts, ours against vanilla (docs/experiments/vram-hit-share-gap.md). Read-only, stdlib only, no GPU; run on the server with `nice python3 -I - SUBCOMMAND ... < hit_share_gap.py`. arms hit share per experiment and arm: token-weighted, unweighted, time-weighted, tok/round pairs EXP A B N paired A/B (blocks A.1..A.N against B.1..B.N): decode tok/s, ms/round, hit share requests per request of the 30-request replay: pooled A arms against the two vanilla replays windows hit share by window index since the request start and by window rows T (Q.1 trace) swaps adaptive swaps per round: ours (P run, DBG tier) against vanilla (VANLP timing lines) Definitions: the hit share is VRAM entries / all routed entries (every row of every window counts, rejected draft rows too), the same quantity as vanilla's "hits / all routed". Weights: otok = generated tokens of the request. """ import collections import glob import json import math import os import re import statistics as st import sys R = "/data/leleka-e2e/spd-gap/runs" T95 = {2: 4.303, 3: 3.182, 4: 2.776, 9: 2.262} def lel(path): """Per-request rows of an engine.log of ours (the engine's one structured line per request).""" rows = [] for line in open(path + "/engine.log", errors="replace"): if line.startswith("{") and '"ev":"request"' in line and '"comp":"engine"' in line: j = json.loads(line) if "tier_vram_pct" in j: rows.append(dict(ptok=j["ptok"], otok=j["otok"], rounds=j["rounds"], tpr=j.get("tok_per_round"), dec_ms=j["dec_ms"], v=j["tier_vram_pct"], p=j["tier_pcie_pct"], c=j["tier_cpu_pct"])) return rows def van(path): """Per-request rows of a vanilla engine.log: the `prompt ...` line, then its `hit rate` line.""" rows, cur = [], {} pat_p = r"strata serve: prompt (\d+) tokens = (\d+) reused \+ (\d+) read in .*?(\d+) generated in ([\d.]+) ms" pat_h = r"hit rate: [\d.]+% \((\d+) hits / (\d+) lookups\); (\d+) more.*?of all (\d+) routed" for line in open(path + "/engine.log", errors="replace"): m = re.search(pat_p, line) if m: cur = dict(ptok=int(m[1]), otok=int(m[4]), dec_ms=float(m[5])) m = re.search(pat_h, line) if m and cur: routed = int(m[4]) cur.update(v=100 * int(m[1]) / routed, p=100 * int(m[3]) / routed, c=100 * (int(m[2]) - int(m[1])) / routed, routed=routed) rows.append(cur) cur = {} return rows def wavg(rows, key="v", weight="otok"): return sum(r[key] * r[weight] for r in rows) / sum(r[weight] for r in rows) def metrics(path, n=30): rows = lel(path)[:n] ot, ms, rd = (sum(r[k] for r in rows) for k in ("otok", "dec_ms", "rounds")) return dict(tps=1000 * ot / ms, msr=ms / rd, tpr=ot / rd, v=wavg(rows), vu=st.mean(r["v"] for r in rows)) def replay_dirs(): """Experiment dirs whose replay starts with the 10,187-token request of nestng-crm-r2 and has >= 30 requests.""" for d in sorted(glob.glob(R + "/*/*")): if os.path.isfile(d + "/engine.log") and "contaminated" not in d: rows = lel(d) if len(rows) >= 30 and rows[0]["ptok"] == 10187: yield d, rows def cmd_arms(): agg = collections.defaultdict(list) for d, rows in replay_dirs(): exp, arm = d[len(R) + 1:].split("/") agg[(exp, arm.split(".")[0])].append((wavg(rows[:30]), st.mean(r["v"] for r in rows[:30]), wavg(rows[:30], weight="dec_ms"), st.mean(r["tpr"] for r in rows[:30]))) for key, v in sorted(agg.items()): print("%-52s n=%2d token-w %.2f (sd %.2f) | unweighted %.2f | time-w %.2f | tok/round %.2f" % ( key, len(v), st.mean(x[0] for x in v), st.pstdev(x[0] for x in v), st.mean(x[1] for x in v), st.mean(x[2] for x in v), st.mean(x[3] for x in v))) for name in ("VANL-noprof", "VANLP"): rows = van(R + "/main/" + name)[1:31] print("%-52s token-w %.2f | unweighted %.2f | time-w %.2f | entry-w %.2f" % ( name, wavg(rows), st.mean(r["v"] for r in rows), wavg(rows, weight="dec_ms"), wavg(rows, weight="routed"))) def cmd_pairs(exp, a, b, n): pairs = [] for k in range(1, int(n) + 1): pa, pb = "%s/%s/%s.%d" % (R, exp, a, k), "%s/%s/%s.%d" % (R, exp, b, k) if os.path.isfile(pa + "/engine.log") and os.path.isfile(pb + "/engine.log"): pairs.append((metrics(pa), metrics(pb))) print("%s: %s against %s, %d pairs" % (exp, b, a, len(pairs))) for key, label, rel in (("tps", "decode tok/s %", 1), ("msr", "ms/round %", 1), ("tpr", "tok/round %", 1), ("v", "hit share points (token-w)", 0), ("vu", "hit share points (unweighted)", 0)): d = [(q[key] / p[key] - 1) * 100 if rel else q[key] - p[key] for p, q in pairs] m, sd = st.mean(d), (st.stdev(d) if len(d) > 1 else 0.0) ci = T95.get(len(d) - 1, 2.3) * sd / math.sqrt(len(d)) print(" %-32s %+.2f (CI %+.2f..%+.2f)" % (label, m, m - ci, m + ci)) def cmd_requests(): pool = collections.defaultdict(list) for d, rows in replay_dirs(): if re.search(r"/A(\.\d+)?$", d): for i, r in enumerate(rows[:30]): pool[i].append(r) vs = [van(R + "/main/" + n)[1:31] for n in ("VANL-noprof", "VANLP")] print("idx ptok(V) otok(V) otok(A) | hit V hit A (pooled, sd) | A-V | cpu V/A pcie V/A") out = [] for i in range(30): a, v = pool[i], [x[i] for x in vs] out.append((st.mean(x["otok"] for x in v), st.mean(r["otok"] for r in a), st.mean(x["v"] for x in v), st.mean(r["v"] for r in a))) print("%2d %6d %6d %6.0f | %.1f %.1f (%.2f) | %+.1f | %.1f/%.1f %.1f/%.1f" % ( i + 1, v[0]["ptok"], out[-1][0], out[-1][1], out[-1][2], out[-1][3], st.pstdev([r["v"] for r in a]), out[-1][3] - out[-1][2], st.mean(x["c"] for x in v), st.mean(r["c"] for r in a), st.mean(x["p"] for x in v), st.mean(r["p"] for r in a))) for name, lo, hi in (("< 600 tokens", 0, 600), ("600-2000", 600, 2000), (">= 2000", 2000, 10 ** 9)): sel = [o for o in out if lo <= o[0] < hi] print("%-14s n=%2d token-w V %.2f A %.2f | unweighted V %.2f A %.2f" % ( name, len(sel), sum(o[0] * o[2] for o in sel) / sum(o[0] for o in sel), sum(o[1] * o[3] for o in sel) / sum(o[1] for o in sel), st.mean(o[2] for o in sel), st.mean(o[3] for o in sel))) def windows_of(path): """Per request: the `DBG window` rows (rows, cpu entries, pcie experts) in file order, split at the request line.""" reqs, cur = [], [] for line in open(path, errors="replace"): if line.startswith("DBG window"): m = dict(re.findall(r"(\w+)=([\d.]+)", line)) cur.append((int(m["rows"]), float(m["entries"]), float(m["pcie_experts"]))) elif line.startswith("{") and '"ev":"request"' in line and '"comp":"engine"' in line: if "tier_vram_pct" in json.loads(line): reqs.append(cur) cur = [] return reqs def cmd_windows(): reqs = windows_of(R + "/prof-l5/Q.1/engine.log") edges = [0, 4, 8, 16, 32, 64, 128, 256, 512, 10 ** 6] acc = collections.defaultdict(lambda: [0, 0.0]) for w in reqs[2:]: for i, (rows, cpu, pcie) in enumerate(w): b = max(k for k in range(len(edges) - 1) if edges[k] <= i) acc[b][0] += rows * 480 acc[b][1] += cpu + pcie print("hit share by window index since the request start (requests 3..30 of Q.1, row-weighted)") for b in sorted(acc): print(" windows %4d-%-6d rows %6d hit %.2f%% misses %.1f%% of all" % ( edges[b], edges[b + 1] - 1, acc[b][0] / 480, 100 * (1 - acc[b][1] / acc[b][0]), 100 * acc[b][1] / sum(a[1] for a in acc.values()))) by_t = collections.defaultdict(lambda: [0, 0.0]) for w in reqs[2:]: for i, (rows, cpu, pcie) in enumerate(w): if i >= 64: by_t[rows][0] += rows * 480 by_t[rows][1] += cpu + pcie print("hit share by window rows T (windows >= 64 of requests 3..30)") for t in sorted(by_t): print(" T=%d rows share %.1f%% hit %.2f%%" % (t, 100 * by_t[t][0] / sum(a[0] for a in by_t.values()), 100 * (1 - by_t[t][1] / by_t[t][0]))) def cmd_swaps(): tiers = [] for line in open(R + "/main/P/engine.log", errors="replace"): m = re.search(r"DBG tier request: .*adaptations (\d+) swaps (\d+)", line) if m: tiers.append((int(m[1]), int(m[2]))) rounds = sum(r["rounds"] for r in lel(R + "/main/P")[:30]) print("ours: %d swaps in %d rounds = %.2f per round, %.1f per adaptation (cap 96)" % ( sum(t[1] for t in tiers[:30]), rounds, sum(t[1] for t in tiers[:30]) / rounds, sum(t[1] for t in tiers[:30]) / sum(t[0] for t in tiers[:30]))) vt = [] for line in open(R + "/main/VANLP/engine.log", errors="replace"): m = re.search(r"decode timing: (\d+) windows, avg T ([\d.]+).*?([\d.]+) swaps/window", line) if m: vt.append((int(m[1]), float(m[2]), float(m[3]))) w = sum(x[0] for x in vt) print("vanilla: %.2f swaps per window, avg T %.2f" % (sum(x[0] * x[2] for x in vt) / w, sum(x[0] * x[1] for x in vt) / w)) if __name__ == "__main__": cmds = dict(arms=cmd_arms, pairs=cmd_pairs, requests=cmd_requests, windows=cmd_windows, swaps=cmd_swaps) cmds[sys.argv[1]](*sys.argv[2:])