scripts: baseline-pair LF line endings (CRLF broke the job on Linux), SEQ and PRE_ARM_HOOK options

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-31 21:36:25 +01:00
co-authored by Claude Sonnet 5.5
parent c3e7067afe
commit 63fb009f42
3 changed files with 738 additions and 738 deletions
+332 -332
View File
@@ -1,332 +1,332 @@
#!/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"] == "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 = ["ours", "v1", "v2"]
by = {a: [r for r in runs if r["arm"] == a] for a in arms}
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")):
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"]), ("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)
#!/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"] == "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 = ["ours", "v1", "v2"]
by = {a: [r for r in runs if r["arm"] == a] for a in arms}
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")):
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"]), ("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)
+196 -196
View File
@@ -1,196 +1,196 @@
#!/usr/bin/env bash
# baseline-pair: balanced, interleaved ours-vs-vanilla Strata 0.2.6 A/B on the RTX 5090 at ~245k context, with a machine-state record around every run.
# HOLDER JOB (rnr5090). Install: scripts/e2e/decode/baseline-install.sh (copies the tools to /data/leleka-e2e/baseline-pair/tools, freezes them read-only, writes
# MANIFEST.sha256) ; stub ~/work/gpu-runs/holder2/jobs/<job>.sh = `#!/usr/bin/env bash` / `exec bash /data/leleka-e2e/baseline-pair/tools/baseline-pair-ab.sh` (+ env lines) ;
# one line in jobs/PRIORITY (back PRIORITY up first). gpu.lock per arm; ~5 min an arm.
#
# Arms (one session each: the frozen 245k corpus, 5 turns, --max-output 300, final-turn input >= 200k tokens, the harness of speedtrain3-ab.sh):
# ours dt/bin-footprint3b = code of main e381c3082 (git diff 9e13fc809 e381c3082 outside docs/ and scripts/ is empty), shipped lossless defaults: seed off (the profile
# default), upstream ranked profile, auto expert slots (12,192), budget 31,300 MiB, spec-min-p 0, prefix cache auto. Nothing experimental.
# v1 vanilla Strata 0.2.6 shipped defaults: route tail skip ON (rank 7, lossy), prefill CPU share ON (below 1024-token chunks).
# v2 vanilla with STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0 (lossless-comparable).
# Order: a block runs the three arms once, in one of the 6 permutations (BLOCKS = permutation numbers). Permutations 1..6 are three reversed pairs, so over blocks 1-6 every arm
# is first, second and last twice and every ordered neighbour pair occurs equally often (ABBA generalised to three arms). A block is the unit of pairing: ours - v1 and ours - v2 are
# formed inside the block, never across blocks.
# Warm-up discipline: all arms start from the same procedure (no GPU process, load1 < 0.5, GPU <= 48 C or 150 s, no page-cache drop, nothing pre-touched); the state is RECORDED
# (pre.jsonl before the arm; state.jsonl every 15 s and per-CPU clocks every 2 s during it; startup.txt = the engine's own start lines: arena / THP / PCIe probe / pool). Block 1 is not discarded.
# Per-turn client lines are timestamped (client.ts.log) so decode windows can be joined to the state samples.
#
# BLOCKS="1 2 3 4 5 6" BLOCK_BASE=0 RUN_TAG= bash baseline-pair-ab.sh # job bp-a ; job bp-b: BLOCK_BASE=6
set -uo pipefail
BP=/data/leleka-e2e/baseline-pair
D=/data/leleka-e2e/decode/dt
LOCK=/data/leleka-e2e/gpu.lock
OUTR=${OUTR:-/data/leleka-e2e/runs/baseline-pair}
CORPUS=/data/leleka-e2e/decode/corpus/src/crates
UP=/data/leleka-e2e/decode/assets/expert-profile-upstream.bin
BINDIR=${BINDIR:-bin-footprint3b}
BLOCKS=${BLOCKS:-"1 2 3 4 5 6"}
BLOCK_BASE=${BLOCK_BASE:-0}
RUN_TAG=${RUN_TAG:-}
SESSION_ARGS="--turns 5 --target-tokens 245000 --max-output 300 --min-final-tokens 200000"
perm() { case $1 in 1) echo "ours v1 v2";; 2) echo "v2 v1 ours";; 3) echo "v1 v2 ours";; 4) echo "ours v2 v1";; 5) echo "v2 ours v1";; 6) echo "v1 ours v2";; *) return 1;; esac; }
mkdir -p "$OUTR"
# frozen inputs: refuse to run when one is missing or its digest differs (MANIFEST.sha256 holds tools, the ours binaries, the vanilla launcher and engine, the profile, the harness)
( cd / && sha256sum --quiet -c "$BP/MANIFEST.sha256" ) || { echo "baseline-pair: MANIFEST.sha256 check failed" >&2; exit 3; }
for f in "$UP" "$CORPUS/backend-api/src/lib.rs" "$D/$BINDIR/leleka-inference" "$BP/tools/baseline-sampler.py" "$BP/tools/ts-wrap.sh"; do
[ -r "$f" ] || { echo "missing $f" >&2; exit 3; }
done
settle() { # $1 run dir: same start procedure for every arm; the waits are recorded
local n=0 t l
while [ $n -lt 30 ]; do # <= 150 s for the GPU to cool
t=$(nvidia-smi --query-gpu=temperature.gpu --format=csv,noheader,nounits | head -1)
[ "${t:-99}" -le 48 ] && break
sleep 5; n=$((n + 1))
done
echo "gpu_temp_c=$t cooled_after_s=$((n * 5))" >"$1/settle.txt"
n=0
while [ $n -lt 24 ]; do # <= 120 s for the machine to go quiet (a foreign CPU job is waited out, then recorded)
l=$(cut -d" " -f1 /proc/loadavg)
awk -v l="$l" 'BEGIN{exit !(l < 0.5)}' && break
sleep 5; n=$((n + 1))
done
echo "load1=$l quiet_after_s=$((n * 5))" >>"$1/settle.txt"
python3 -I "$BP/tools/baseline-sampler.py" "$1/pre.jsonl" --once
}
start_sampler() { # $1 run dir -> SAMP
taskset -c 31 python3 -I "$BP/tools/baseline-sampler.py" "$1/state.jsonl" --full-s 15 --fast-s 2 >/dev/null 2>&1 &
SAMP=$!
}
stop_sampler() {
kill -TERM "$SAMP" 2>/dev/null; wait "$SAMP" 2>/dev/null
python3 -I "$BP/tools/baseline-sampler.py" "$1/post.jsonl" --once
}
ours() { # $1 tag, $2 run dir
local tag=$1 R=$2
( export E2E_BIN=$D/$BINDIR E2E_OUT=$R
export LELEKA_BRINGUP_TRACE=1 LELEKA_PREFIX_TRACE=1
export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto E2E_GPU_BUDGET=${GPU_BUDGET:-32819404800}
export E2E_ENGINE_ARGS="--prefix-cache-mib auto --prefix-cache-tail reply --original-prefill-capacity 8192 --prefix-cache-block 8192 --spec-min-p 0"
export E2E_SAMPLE_S=10 LELEKA_CHAIN=all
export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$UP
unset LELEKA_FOOTPRINT_LEGACY LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS LELEKA_SM120_ATTN_DAILY LELEKA_SM120_GU_SWIGLU LELEKA_SM120_SIDE_MIXER LELEKA_SM120_PERF LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB LELEKA_ROUTE_TAIL_SKIP
export LELEKA_ORIGINAL_SERVE_SEED=off
{ echo "arm=ours tag=$tag"; date -u +%FT%TZ; free -g | sed -n 2p; uptime; sha256sum "$UP" "$E2E_BIN"/leleka-inference "$E2E_BIN"/leleka-daemon "$E2E_BIN"/leleka-cli "$E2E_BIN"/strata-next
cat "$E2E_BIN/COMMIT.txt" 2>/dev/null; head -1 /data/leleka-e2e/decode/corpus/MANIFEST.txt
env | grep -E '^(LELEKA_|STRATA_|E2E_)' | sort; } >"$R/env-arm.txt"
export E2E_RUN_CMD="bash $BP/tools/ts-wrap.sh $R/client.ts.log python3 -I $D/tools/long-session.py --src $CORPUS $SESSION_ARGS"
bash "$D/scripts/e2e/run-e2e.sh" 2>&1 | grep -a -E "^\{|expert cache|request outcome|ready after|rc=|refus|error|Error|long_session|client exit" | cut -c1-300
echo "run-e2e done $tag $(date -u +%FT%TZ)" )
}
vanilla() { # $1 tag, $2 run dir, $3 variant (v1|v2)
local tag=$1 R=$2 var=$3
( export XDG_CONFIG_HOME=$R/xdg-config XDG_STATE_HOME=$R/xdg-state
mkdir -p "$XDG_CONFIG_HOME/strata" "$XDG_STATE_HOME"
cp ~/.config/strata/settings.json "$XDG_CONFIG_HOME/strata/"
if [ "$var" = v2 ]; then export STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0; fi
{ echo "arm=$var tag=$tag"; date -u +%FT%TZ; free -g | sed -n 2p; uptime; head -1 /data/leleka-e2e/decode/corpus/MANIFEST.txt; env | grep -E '^(STRATA_|LELEKA_)' | sort; } > "$R/env.txt"
S=$HOME/work/vanilla-strata/control/bin/strata
cd "$HOME/work/vanilla-strata/control"
T0=$(date +%s)
timeout 2400 $S launch --model iq3_s --family qwen --model-path /home/para/work/leleka/models/leleka-gates/assets/model --context 256k --kv int8 --vision off --parallel 1 --tune skip --access local --port 8090 --no-api-key --no-tui --yes > "$R/launch.out" 2>&1
echo "launch_rc=$? ready_wall_s=$(( $(date +%s) - T0 ))" >> "$R/env.txt"
if curl -fs http://127.0.0.1:8090/v1/models > "$R/models.json"; then
MODEL=$(python3 -c "import json;print(json.load(open('$R/models.json'))['data'][0]['id'])")
E2E_BASE_URL=http://127.0.0.1:8090 E2E_MODEL=$MODEL E2E_API_KEY=none E2E_OUT_DIR=$R bash "$BP/tools/ts-wrap.sh" "$R/client.ts.log" python3 -I $D/tools/long-session.py --src $CORPUS $SESSION_ARGS > "$R/client.log" 2>&1
echo "session_rc=$?" >> "$R/env.txt"
cp "$XDG_STATE_HOME/strata/launch/iq3_s-256k.engine.log" "$R/engine.log"
else
echo "not ready" >> "$R/env.txt"
fi
$S launch --stop >> "$R/launch.out" 2>&1
sleep 8
date -u +%FT%TZ >> "$R/env.txt"
cut -c1-300 "$R/client.log" 2>/dev/null )
}
validity() { # $1 run dir, $2 arm
python3 -I - "$1" "$2" <<'PY'
import json, os, re, sys
d, arm = sys.argv[1], sys.argv[2]
f = os.path.join(d, "long-session.json")
verdict = "INVALID: no long-session.json"
if os.path.exists(f):
t = json.load(open(f))
final = (t[-1].get("input_tokens") or 0) if t else 0
if any("error" in r for r in t):
verdict = "INVALID: a turn failed"
elif len(t) < 5 or final < 200000:
verdict = "INVALID: %d turns, final-turn input tokens %d < 200000 (short corpus?)" % (len(t), final)
else:
verdict = "VALID: 5 turns, final-turn input tokens %d" % final
if arm == "ours":
wins, last = [], []
for ln in open(os.path.join(d, "inference.log"), errors="replace"):
if ln.startswith("DBG window "):
last.append(dict((k, float(v)) for k, v in re.findall(r"(\w+)=([-\d.]+)", ln)))
elif "leleka-serve request outcome" in ln:
wins.append(last); last = []
w = wins[-1] if wins else []
ple = sum(x.get("ple", 0) for x in w) / max(len(w), 1)
verdict += "; turn-5 window.ple mean %.2f ms over %d windows" % (ple, len(w))
if not w:
verdict = "INVALID: no turn-5 window lines (trace env missing?)"
elif ple >= 5:
verdict = "INVALID: turn-5 window.ple mean %.2f ms >= 5 ms (PLE scan back?)" % ple
else:
log = open(os.path.join(d, "engine.log"), errors="replace").read() if os.path.exists(os.path.join(d, "engine.log")) else ""
skip_on = "STRATA_ROUTE_TAIL_SKIP=7 is ON" in log
share_on = "the CPU share is ON by default" in log
if arm == "v1" and not (skip_on and share_on):
verdict = "INVALID: v1 but tail skip on=%s cpu share on=%s in the engine log" % (skip_on, share_on)
elif arm == "v2" and (skip_on or share_on):
verdict = "INVALID: v2 but tail skip on=%s cpu share on=%s in the engine log" % (skip_on, share_on)
else:
verdict += "; engine log: tail skip %s, cpu share %s" % ("ON" if skip_on else "off", "ON" if share_on else "off")
open(os.path.join(d, "VALIDITY.txt"), "w").write(verdict + "\n")
print(os.path.basename(d), verdict)
PY
}
# the run list: "block:pos:arm" entries. Default = permutations of BLOCKS. SEQ="v2 v2 ours ..." runs exactly that sequence instead (SEQ_GROUP arms per block, default 3), used by
# the predecessor test of job bp-b (VV O repeated: a vanilla run directly after ours against a vanilla run directly after vanilla, interleaved in time).
LIST=""
if [ -n "${SEQ:-}" ]; then
i=0; for arm in $SEQ; do LIST="$LIST $((BLOCK_BASE + i / ${SEQ_GROUP:-3} + 1)):$((i % ${SEQ_GROUP:-3} + 1)):$arm"; i=$((i + 1)); done
else
for b in $BLOCKS; do pos=0; for arm in $(perm "$b"); do pos=$((pos + 1)); LIST="$LIST $((BLOCK_BASE + b)):$pos:$arm"; done; done
fi
for ent in $LIST; do
bn=${ent%%:*}; rest=${ent#*:}; pos=${rest%%:*}; arm=${rest#*:}
tag=$(printf "b%02dp%d-%s%s" "$bn" "$pos" "$arm" "$RUN_TAG"); R=$OUTR/$tag
[ -e "$BP/STOP" ] && { echo "STOP file present, ending before $tag"; exit 0; }
got=0
for _ in $(seq 1 1080); do
if mkdir "$LOCK" 2>/dev/null; then echo "baseline-pair $tag $(date -u +%FT%TZ)" >"$LOCK/owner"; got=1; break; fi
sleep 5
done
[ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; exit 3; }
echo "=== $tag $(date -u +%FT%TZ)"
if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader)" ]; then
echo "GPU busy, skipping $tag"; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; continue
fi
mkdir -p "$R"; echo "block=$bn pos=$pos arm=$arm" >"$R/ARM.txt"
# optional owner-run hook before the settle (e.g. a root script that compacts memory); default none. Its exit status and stdout go to hook.txt
[ -n "${PRE_ARM_HOOK:-}" ] && { bash "$PRE_ARM_HOOK" "$arm" >"$R/hook.txt" 2>&1; echo "hook_rc=$?" >>"$R/hook.txt"; }
settle "$R"
start_sampler "$R"
case $arm in
ours) ours "$tag" "$R" ;;
v1|v2) vanilla "$tag" "$R" "$arm" ;;
esac
stop_sampler "$R"
# the engine's own start lines (arena / THP / PCIe probe / pool / cache), one small file per run
for lg in "$R/engine.log" "$R/inference.log"; do [ -r "$lg" ] && grep -a -E "arena|MAP_HUGETLB|huge|PCIe probe|pcie_frac|CPU pool|pool workers|expert cache|memory guard|ROUTE_TAIL_SKIP|CPU share|Cpus|pinned|affin" "$lg" | head -60 | cut -c1-300; done >"$R/startup.txt"
validity "$R" "$arm"
echo "arm done $tag $(date -u +%FT%TZ)"
rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null
sleep 15
done
[ -r "$BP/tools/baseline-analyze.py" ] && python3 -I "$BP/tools/baseline-analyze.py" "$OUTR" > "$OUTR/ANALYSIS.$(date -u +%Y%m%dT%H%M%SZ).txt" 2>&1
echo "baseline-pair job done $(date -u +%FT%TZ)"
#!/usr/bin/env bash
# baseline-pair: balanced, interleaved ours-vs-vanilla Strata 0.2.6 A/B on the RTX 5090 at ~245k context, with a machine-state record around every run.
# HOLDER JOB (rnr5090). Install: scripts/e2e/decode/baseline-install.sh (copies the tools to /data/leleka-e2e/baseline-pair/tools, freezes them read-only, writes
# MANIFEST.sha256) ; stub ~/work/gpu-runs/holder2/jobs/<job>.sh = `#!/usr/bin/env bash` / `exec bash /data/leleka-e2e/baseline-pair/tools/baseline-pair-ab.sh` (+ env lines) ;
# one line in jobs/PRIORITY (back PRIORITY up first). gpu.lock per arm; ~5 min an arm.
#
# Arms (one session each: the frozen 245k corpus, 5 turns, --max-output 300, final-turn input >= 200k tokens, the harness of speedtrain3-ab.sh):
# ours dt/bin-footprint3b = code of main e381c3082 (git diff 9e13fc809 e381c3082 outside docs/ and scripts/ is empty), shipped lossless defaults: seed off (the profile
# default), upstream ranked profile, auto expert slots (12,192), budget 31,300 MiB, spec-min-p 0, prefix cache auto. Nothing experimental.
# v1 vanilla Strata 0.2.6 shipped defaults: route tail skip ON (rank 7, lossy), prefill CPU share ON (below 1024-token chunks).
# v2 vanilla with STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0 (lossless-comparable).
# Order: a block runs the three arms once, in one of the 6 permutations (BLOCKS = permutation numbers). Permutations 1..6 are three reversed pairs, so over blocks 1-6 every arm
# is first, second and last twice and every ordered neighbour pair occurs equally often (ABBA generalised to three arms). A block is the unit of pairing: ours - v1 and ours - v2 are
# formed inside the block, never across blocks.
# Warm-up discipline: all arms start from the same procedure (no GPU process, load1 < 0.5, GPU <= 48 C or 150 s, no page-cache drop, nothing pre-touched); the state is RECORDED
# (pre.jsonl before the arm; state.jsonl every 15 s and per-CPU clocks every 2 s during it; startup.txt = the engine's own start lines: arena / THP / PCIe probe / pool). Block 1 is not discarded.
# Per-turn client lines are timestamped (client.ts.log) so decode windows can be joined to the state samples.
#
# BLOCKS="1 2 3 4 5 6" BLOCK_BASE=0 RUN_TAG= bash baseline-pair-ab.sh # job bp-a ; job bp-b: BLOCK_BASE=6
set -uo pipefail
BP=/data/leleka-e2e/baseline-pair
D=/data/leleka-e2e/decode/dt
LOCK=/data/leleka-e2e/gpu.lock
OUTR=${OUTR:-/data/leleka-e2e/runs/baseline-pair}
CORPUS=/data/leleka-e2e/decode/corpus/src/crates
UP=/data/leleka-e2e/decode/assets/expert-profile-upstream.bin
BINDIR=${BINDIR:-bin-footprint3b}
BLOCKS=${BLOCKS:-"1 2 3 4 5 6"}
BLOCK_BASE=${BLOCK_BASE:-0}
RUN_TAG=${RUN_TAG:-}
SESSION_ARGS="--turns 5 --target-tokens 245000 --max-output 300 --min-final-tokens 200000"
perm() { case $1 in 1) echo "ours v1 v2";; 2) echo "v2 v1 ours";; 3) echo "v1 v2 ours";; 4) echo "ours v2 v1";; 5) echo "v2 ours v1";; 6) echo "v1 ours v2";; *) return 1;; esac; }
mkdir -p "$OUTR"
# frozen inputs: refuse to run when one is missing or its digest differs (MANIFEST.sha256 holds tools, the ours binaries, the vanilla launcher and engine, the profile, the harness)
( cd / && sha256sum --quiet -c "$BP/MANIFEST.sha256" ) || { echo "baseline-pair: MANIFEST.sha256 check failed" >&2; exit 3; }
for f in "$UP" "$CORPUS/backend-api/src/lib.rs" "$D/$BINDIR/leleka-inference" "$BP/tools/baseline-sampler.py" "$BP/tools/ts-wrap.sh"; do
[ -r "$f" ] || { echo "missing $f" >&2; exit 3; }
done
settle() { # $1 run dir: same start procedure for every arm; the waits are recorded
local n=0 t l
while [ $n -lt 30 ]; do # <= 150 s for the GPU to cool
t=$(nvidia-smi --query-gpu=temperature.gpu --format=csv,noheader,nounits | head -1)
[ "${t:-99}" -le 48 ] && break
sleep 5; n=$((n + 1))
done
echo "gpu_temp_c=$t cooled_after_s=$((n * 5))" >"$1/settle.txt"
n=0
while [ $n -lt 24 ]; do # <= 120 s for the machine to go quiet (a foreign CPU job is waited out, then recorded)
l=$(cut -d" " -f1 /proc/loadavg)
awk -v l="$l" 'BEGIN{exit !(l < 0.5)}' && break
sleep 5; n=$((n + 1))
done
echo "load1=$l quiet_after_s=$((n * 5))" >>"$1/settle.txt"
python3 -I "$BP/tools/baseline-sampler.py" "$1/pre.jsonl" --once
}
start_sampler() { # $1 run dir -> SAMP
taskset -c 31 python3 -I "$BP/tools/baseline-sampler.py" "$1/state.jsonl" --full-s 15 --fast-s 2 >/dev/null 2>&1 &
SAMP=$!
}
stop_sampler() {
kill -TERM "$SAMP" 2>/dev/null; wait "$SAMP" 2>/dev/null
python3 -I "$BP/tools/baseline-sampler.py" "$1/post.jsonl" --once
}
ours() { # $1 tag, $2 run dir
local tag=$1 R=$2
( export E2E_BIN=$D/$BINDIR E2E_OUT=$R
export LELEKA_BRINGUP_TRACE=1 LELEKA_PREFIX_TRACE=1
export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto E2E_GPU_BUDGET=${GPU_BUDGET:-32819404800}
export E2E_ENGINE_ARGS="--prefix-cache-mib auto --prefix-cache-tail reply --original-prefill-capacity 8192 --prefix-cache-block 8192 --spec-min-p 0"
export E2E_SAMPLE_S=10 LELEKA_CHAIN=all
export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$UP
unset LELEKA_FOOTPRINT_LEGACY LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS LELEKA_SM120_ATTN_DAILY LELEKA_SM120_GU_SWIGLU LELEKA_SM120_SIDE_MIXER LELEKA_SM120_PERF LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB LELEKA_ROUTE_TAIL_SKIP
export LELEKA_ORIGINAL_SERVE_SEED=off
{ echo "arm=ours tag=$tag"; date -u +%FT%TZ; free -g | sed -n 2p; uptime; sha256sum "$UP" "$E2E_BIN"/leleka-inference "$E2E_BIN"/leleka-daemon "$E2E_BIN"/leleka-cli "$E2E_BIN"/strata-next
cat "$E2E_BIN/COMMIT.txt" 2>/dev/null; head -1 /data/leleka-e2e/decode/corpus/MANIFEST.txt
env | grep -E '^(LELEKA_|STRATA_|E2E_)' | sort; } >"$R/env-arm.txt"
export E2E_RUN_CMD="bash $BP/tools/ts-wrap.sh $R/client.ts.log python3 -I $D/tools/long-session.py --src $CORPUS $SESSION_ARGS"
bash "$D/scripts/e2e/run-e2e.sh" 2>&1 | grep -a -E "^\{|expert cache|request outcome|ready after|rc=|refus|error|Error|long_session|client exit" | cut -c1-300
echo "run-e2e done $tag $(date -u +%FT%TZ)" )
}
vanilla() { # $1 tag, $2 run dir, $3 variant (v1|v2)
local tag=$1 R=$2 var=$3
( export XDG_CONFIG_HOME=$R/xdg-config XDG_STATE_HOME=$R/xdg-state
mkdir -p "$XDG_CONFIG_HOME/strata" "$XDG_STATE_HOME"
cp ~/.config/strata/settings.json "$XDG_CONFIG_HOME/strata/"
if [ "$var" = v2 ]; then export STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0; fi
{ echo "arm=$var tag=$tag"; date -u +%FT%TZ; free -g | sed -n 2p; uptime; head -1 /data/leleka-e2e/decode/corpus/MANIFEST.txt; env | grep -E '^(STRATA_|LELEKA_)' | sort; } > "$R/env.txt"
S=$HOME/work/vanilla-strata/control/bin/strata
cd "$HOME/work/vanilla-strata/control"
T0=$(date +%s)
timeout 2400 $S launch --model iq3_s --family qwen --model-path /home/para/work/leleka/models/leleka-gates/assets/model --context 256k --kv int8 --vision off --parallel 1 --tune skip --access local --port 8090 --no-api-key --no-tui --yes > "$R/launch.out" 2>&1
echo "launch_rc=$? ready_wall_s=$(( $(date +%s) - T0 ))" >> "$R/env.txt"
if curl -fs http://127.0.0.1:8090/v1/models > "$R/models.json"; then
MODEL=$(python3 -c "import json;print(json.load(open('$R/models.json'))['data'][0]['id'])")
E2E_BASE_URL=http://127.0.0.1:8090 E2E_MODEL=$MODEL E2E_API_KEY=none E2E_OUT_DIR=$R bash "$BP/tools/ts-wrap.sh" "$R/client.ts.log" python3 -I $D/tools/long-session.py --src $CORPUS $SESSION_ARGS > "$R/client.log" 2>&1
echo "session_rc=$?" >> "$R/env.txt"
cp "$XDG_STATE_HOME/strata/launch/iq3_s-256k.engine.log" "$R/engine.log"
else
echo "not ready" >> "$R/env.txt"
fi
$S launch --stop >> "$R/launch.out" 2>&1
sleep 8
date -u +%FT%TZ >> "$R/env.txt"
cut -c1-300 "$R/client.log" 2>/dev/null )
}
validity() { # $1 run dir, $2 arm
python3 -I - "$1" "$2" <<'PY'
import json, os, re, sys
d, arm = sys.argv[1], sys.argv[2]
f = os.path.join(d, "long-session.json")
verdict = "INVALID: no long-session.json"
if os.path.exists(f):
t = json.load(open(f))
final = (t[-1].get("input_tokens") or 0) if t else 0
if any("error" in r for r in t):
verdict = "INVALID: a turn failed"
elif len(t) < 5 or final < 200000:
verdict = "INVALID: %d turns, final-turn input tokens %d < 200000 (short corpus?)" % (len(t), final)
else:
verdict = "VALID: 5 turns, final-turn input tokens %d" % final
if arm == "ours":
wins, last = [], []
for ln in open(os.path.join(d, "inference.log"), errors="replace"):
if ln.startswith("DBG window "):
last.append(dict((k, float(v)) for k, v in re.findall(r"(\w+)=([-\d.]+)", ln)))
elif "leleka-serve request outcome" in ln:
wins.append(last); last = []
w = wins[-1] if wins else []
ple = sum(x.get("ple", 0) for x in w) / max(len(w), 1)
verdict += "; turn-5 window.ple mean %.2f ms over %d windows" % (ple, len(w))
if not w:
verdict = "INVALID: no turn-5 window lines (trace env missing?)"
elif ple >= 5:
verdict = "INVALID: turn-5 window.ple mean %.2f ms >= 5 ms (PLE scan back?)" % ple
else:
log = open(os.path.join(d, "engine.log"), errors="replace").read() if os.path.exists(os.path.join(d, "engine.log")) else ""
skip_on = "STRATA_ROUTE_TAIL_SKIP=7 is ON" in log
share_on = "the CPU share is ON by default" in log
if arm == "v1" and not (skip_on and share_on):
verdict = "INVALID: v1 but tail skip on=%s cpu share on=%s in the engine log" % (skip_on, share_on)
elif arm == "v2" and (skip_on or share_on):
verdict = "INVALID: v2 but tail skip on=%s cpu share on=%s in the engine log" % (skip_on, share_on)
else:
verdict += "; engine log: tail skip %s, cpu share %s" % ("ON" if skip_on else "off", "ON" if share_on else "off")
open(os.path.join(d, "VALIDITY.txt"), "w").write(verdict + "\n")
print(os.path.basename(d), verdict)
PY
}
# the run list: "block:pos:arm" entries. Default = permutations of BLOCKS. SEQ="v2 v2 ours ..." runs exactly that sequence instead (SEQ_GROUP arms per block, default 3), used by
# the predecessor test of job bp-b (VV O repeated: a vanilla run directly after ours against a vanilla run directly after vanilla, interleaved in time).
LIST=""
if [ -n "${SEQ:-}" ]; then
i=0; for arm in $SEQ; do LIST="$LIST $((BLOCK_BASE + i / ${SEQ_GROUP:-3} + 1)):$((i % ${SEQ_GROUP:-3} + 1)):$arm"; i=$((i + 1)); done
else
for b in $BLOCKS; do pos=0; for arm in $(perm "$b"); do pos=$((pos + 1)); LIST="$LIST $((BLOCK_BASE + b)):$pos:$arm"; done; done
fi
for ent in $LIST; do
bn=${ent%%:*}; rest=${ent#*:}; pos=${rest%%:*}; arm=${rest#*:}
tag=$(printf "b%02dp%d-%s%s" "$bn" "$pos" "$arm" "$RUN_TAG"); R=$OUTR/$tag
[ -e "$BP/STOP" ] && { echo "STOP file present, ending before $tag"; exit 0; }
got=0
for _ in $(seq 1 1080); do
if mkdir "$LOCK" 2>/dev/null; then echo "baseline-pair $tag $(date -u +%FT%TZ)" >"$LOCK/owner"; got=1; break; fi
sleep 5
done
[ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; exit 3; }
echo "=== $tag $(date -u +%FT%TZ)"
if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader)" ]; then
echo "GPU busy, skipping $tag"; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; continue
fi
mkdir -p "$R"; echo "block=$bn pos=$pos arm=$arm" >"$R/ARM.txt"
# optional owner-run hook before the settle (e.g. a root script that compacts memory); default none. Its exit status and stdout go to hook.txt
[ -n "${PRE_ARM_HOOK:-}" ] && { bash "$PRE_ARM_HOOK" "$arm" >"$R/hook.txt" 2>&1; echo "hook_rc=$?" >>"$R/hook.txt"; }
settle "$R"
start_sampler "$R"
case $arm in
ours) ours "$tag" "$R" ;;
v1|v2) vanilla "$tag" "$R" "$arm" ;;
esac
stop_sampler "$R"
# the engine's own start lines (arena / THP / PCIe probe / pool / cache), one small file per run
for lg in "$R/engine.log" "$R/inference.log"; do [ -r "$lg" ] && grep -a -E "arena|MAP_HUGETLB|huge|PCIe probe|pcie_frac|CPU pool|pool workers|expert cache|memory guard|ROUTE_TAIL_SKIP|CPU share|Cpus|pinned|affin" "$lg" | head -60 | cut -c1-300; done >"$R/startup.txt"
validity "$R" "$arm"
echo "arm done $tag $(date -u +%FT%TZ)"
rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null
sleep 15
done
[ -r "$BP/tools/baseline-analyze.py" ] && python3 -I "$BP/tools/baseline-analyze.py" "$OUTR" > "$OUTR/ANALYSIS.$(date -u +%Y%m%dT%H%M%SZ).txt" 2>&1
echo "baseline-pair job done $(date -u +%FT%TZ)"
+210 -210
View File
@@ -1,210 +1,210 @@
#!/usr/bin/env python3
"""State sampler for the baseline-pair A/B (ours against vanilla Strata). Stdlib only, read-only: it never writes to /proc or /sys.
python3 -I baseline-sampler.py OUT.jsonl [--full-s 15] [--fast-s 2] [--once]
One JSON object per line, two kinds:
kind=full every --full-s seconds (and at start): uptime, loadavg, PSI, per-CPU scaling_cur_freq (kHz) and utilisation, cpufreq governor / driver / EPP / boost,
/proc/meminfo (AnonHugePages, HugePages_*, MemAvailable, Cached, Shmem ...), THP enabled / defrag / khugepaged knobs, /proc/vmstat THP + compaction +
allocstall counters, /proc/buddyinfo (raw), nvidia-smi (SM / mem clocks, temperature, power, pstate, throttle reasons, utilisation, memory),
for every process that uses the GPU: Cpus_allowed_list, smaps_rollup (Rss, Pss, AnonHugePages, ...), every thread (tid, comm, last cpu, cpu ticks,
allowed list), and the top 5 other CPU consumers of the interval (so a foreign CPU job is visible).
kind=fast every --fast-s seconds: per-CPU scaling_cur_freq and utilisation only (cheap, to see the clocks of the cores in use during a decode window).
--once writes a single full sample and exits (the pre-run state record). SIGTERM / SIGINT stop it cleanly.
"""
import json, os, signal, subprocess, sys, time
OUT = sys.argv[1]
ARGS = sys.argv[2:]
def opt(name, default):
return float(ARGS[ARGS.index(name) + 1]) if name in ARGS else default
FULL_S, FAST_S, ONCE = opt("--full-s", 15.0), opt("--fast-s", 2.0), "--once" in ARGS
CPUS = sorted(int(d[3:]) for d in os.listdir("/sys/devices/system/cpu") if d.startswith("cpu") and d[3:].isdigit())
MEM_KEYS = {"MemTotal", "MemFree", "MemAvailable", "Cached", "Buffers", "Active(file)", "Inactive(file)", "Shmem", "ShmemHugePages", "AnonPages", "AnonHugePages",
"FileHugePages", "FilePmdMapped", "Mlocked", "Unevictable", "Dirty", "SwapFree", "HugePages_Total", "HugePages_Free", "HugePages_Rsvd", "HugePages_Surp"}
VM_PREFIX = ("thp_", "compact_", "allocstall", "pgmajfault", "pgfault", "pswpin", "pswpout", "pgscan_direct", "pgscan_kswapd", "pgsteal_direct", "pgsteal_kswapd", "numa_", "kswapd_low_wmark")
STOP = False
def _stop(*_):
global STOP
STOP = True
signal.signal(signal.SIGTERM, _stop)
signal.signal(signal.SIGINT, _stop)
def rd(path, default=None):
try:
with open(path) as f:
return f.read().strip()
except Exception:
return default
def read_stat():
cpu, total = {}, {}
try:
for ln in open("/proc/stat"):
if ln.startswith("cpu") and ln[3:4].isdigit():
p = ln.split()
v = [int(x) for x in p[1:9]]
idle = v[3] + v[4]
cpu[int(p[0][3:])] = (sum(v), idle)
except Exception:
pass
return cpu
def freqs():
out = []
for c in CPUS:
v = rd("/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq" % c)
out.append(int(v) if v and v.isdigit() else None)
return out
def util(prev, cur):
if prev is None:
return None
out = []
for c in CPUS:
if c in prev and c in cur:
dt, di = cur[c][0] - prev[c][0], cur[c][1] - prev[c][1]
out.append(round(100.0 * (dt - di) / dt, 1) if dt > 0 else None)
else:
out.append(None)
return out
def kv_file(path, keys=None, prefix=None):
d = {}
try:
for ln in open(path):
p = ln.replace(":", " ").split()
if len(p) < 2:
continue
k = p[0]
if (keys and k in keys) or (prefix and k.startswith(prefix)):
d[k] = int(p[1])
except Exception:
pass
return d
def nvsmi():
q = "temperature.gpu,clocks.sm,clocks.mem,power.draw,power.limit,utilization.gpu,memory.used,pstate,%s"
names = "temp_c sm_mhz mem_mhz power_w power_limit_w util_pct mem_used_mib pstate throttle".split()
for reasons in ("clocks_event_reasons.active", "clocks_throttle_reasons.active"):
try:
r = subprocess.run(["nvidia-smi", "--query-gpu=" + q % reasons, "--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=8)
if r.returncode == 0 and r.stdout.strip():
return dict(zip(names, [x.strip() for x in r.stdout.strip().splitlines()[0].split(",")]))
except Exception:
pass
return {}
def gpu_pids():
try:
r = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,used_memory", "--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=8)
return [int(l.split(",")[0]) for l in r.stdout.strip().splitlines() if l.strip()]
except Exception:
return []
def proc_info(pid):
d = {"pid": pid, "exe": os.path.basename(os.readlink("/proc/%d/exe" % pid)) if os.path.exists("/proc/%d/exe" % pid) else None}
st = rd("/proc/%d/status" % pid, "")
for ln in st.splitlines():
if ln.startswith("Cpus_allowed_list:"):
d["allowed"] = ln.split(":", 1)[1].strip()
elif ln.startswith("Threads:"):
d["threads"] = int(ln.split(":", 1)[1])
d["smaps_rollup_kb"] = kv_file("/proc/%d/smaps_rollup" % pid, keys={"Rss", "Pss", "Pss_Anon", "Pss_File", "Pss_Shmem", "Shared_Clean", "Shared_Dirty", "Private_Clean", "Private_Dirty",
"Anonymous", "AnonHugePages", "ShmemPmdMapped", "FilePmdMapped", "Shared_Hugetlb", "Private_Hugetlb", "Swap", "Locked"})
ths = []
try:
for t in os.listdir("/proc/%d/task" % pid):
s = rd("/proc/%d/task/%s/stat" % (pid, t))
if not s:
continue
comm = s[s.index("(") + 1:s.rindex(")")]
f = s[s.rindex(")") + 2:].split()
# f[0]=state, utime=f[11], stime=f[12], processor=f[36]
allowed = None
for ln in (rd("/proc/%d/task/%s/status" % (pid, t), "") or "").splitlines():
if ln.startswith("Cpus_allowed_list:"):
allowed = ln.split(":", 1)[1].strip()
break
ths.append([int(t), comm, int(f[36]), int(f[11]) + int(f[12]), allowed])
except Exception:
pass
d["thr"] = ths
return d
def all_proc_ticks():
out = {}
for p in os.listdir("/proc"):
if p.isdigit():
s = rd("/proc/%s/stat" % p)
if s:
try:
comm = s[s.index("(") + 1:s.rindex(")")]
f = s[s.rindex(")") + 2:].split()
out[int(p)] = (comm, int(f[11]) + int(f[12]))
except Exception:
pass
return out
def full(prev_stat, prev_ticks, gpids_hint):
now = read_stat()
ticks = all_proc_ticks()
s = {"kind": "full", "t": round(time.time(), 3), "uptime_s": float(rd("/proc/uptime", "0 0").split()[0]), "loadavg": rd("/proc/loadavg", "").split()[:3]}
s["cpu_khz"], s["cpu_util"] = freqs(), util(prev_stat, now)
s["cpufreq"] = {"governor": rd("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor"), "driver": rd("/sys/devices/system/cpu/cpu0/cpufreq/scaling_driver"),
"epp": rd("/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference"), "boost": rd("/sys/devices/system/cpu/cpufreq/boost"),
"max_khz": rd("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq"), "min_khz": rd("/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq"),
"pstate_status": rd("/sys/devices/system/cpu/amd_pstate/status")}
s["meminfo_kb"] = kv_file("/proc/meminfo", keys=MEM_KEYS)
thp = "/sys/kernel/mm/transparent_hugepage/"
s["thp"] = {"enabled": rd(thp + "enabled"), "defrag": rd(thp + "defrag"), "shmem_enabled": rd(thp + "shmem_enabled"), "khugepaged_defrag": rd(thp + "khugepaged/defrag"),
"khugepaged_pages_collapsed": rd(thp + "khugepaged/pages_collapsed"), "nr_hugepages": rd("/proc/sys/vm/nr_hugepages")}
s["vmstat"] = {}
try:
for ln in open("/proc/vmstat"):
k, v = ln.split()
if k.startswith(VM_PREFIX):
s["vmstat"][k] = int(v)
except Exception:
pass
s["buddy"] = rd("/proc/buddyinfo")
s["psi"] = {n: (rd("/proc/pressure/" + n, "").splitlines() or [None])[0] for n in ("cpu", "memory", "io")}
s["gpu"] = nvsmi()
pids = gpu_pids()
s["gpu_pids"] = pids
s["procs"] = [proc_info(p) for p in pids if os.path.exists("/proc/%d" % p)]
if prev_ticks is not None:
d = []
for p, (comm, t) in ticks.items():
if p in pids or p == os.getpid():
continue
pt = prev_ticks.get(p)
if pt and t - pt[1] > 0:
d.append((t - pt[1], p, comm))
d.sort(reverse=True)
s["others_top"] = [[p, c, tk] for tk, p, c in d[:5]]
return s, now, ticks
def main():
prev_stat, prev_ticks = read_stat(), None
out = open(OUT, "a", buffering=1)
nxt_full, nxt_fast = 0.0, 0.0
while not STOP:
t = time.time()
if t >= nxt_full:
s, prev_stat, prev_ticks = full(prev_stat, prev_ticks, None)
out.write(json.dumps(s, separators=(",", ":")) + "\n")
nxt_full = t + FULL_S
nxt_fast = t + FAST_S
if ONCE:
break
elif t >= nxt_fast:
now = read_stat()
out.write(json.dumps({"kind": "fast", "t": round(t, 3), "cpu_khz": freqs(), "cpu_util": util(prev_stat, now)}, separators=(",", ":")) + "\n")
prev_stat = now
nxt_fast = t + FAST_S
time.sleep(max(0.05, min(nxt_full, nxt_fast) - time.time()))
out.close()
main()
#!/usr/bin/env python3
"""State sampler for the baseline-pair A/B (ours against vanilla Strata). Stdlib only, read-only: it never writes to /proc or /sys.
python3 -I baseline-sampler.py OUT.jsonl [--full-s 15] [--fast-s 2] [--once]
One JSON object per line, two kinds:
kind=full every --full-s seconds (and at start): uptime, loadavg, PSI, per-CPU scaling_cur_freq (kHz) and utilisation, cpufreq governor / driver / EPP / boost,
/proc/meminfo (AnonHugePages, HugePages_*, MemAvailable, Cached, Shmem ...), THP enabled / defrag / khugepaged knobs, /proc/vmstat THP + compaction +
allocstall counters, /proc/buddyinfo (raw), nvidia-smi (SM / mem clocks, temperature, power, pstate, throttle reasons, utilisation, memory),
for every process that uses the GPU: Cpus_allowed_list, smaps_rollup (Rss, Pss, AnonHugePages, ...), every thread (tid, comm, last cpu, cpu ticks,
allowed list), and the top 5 other CPU consumers of the interval (so a foreign CPU job is visible).
kind=fast every --fast-s seconds: per-CPU scaling_cur_freq and utilisation only (cheap, to see the clocks of the cores in use during a decode window).
--once writes a single full sample and exits (the pre-run state record). SIGTERM / SIGINT stop it cleanly.
"""
import json, os, signal, subprocess, sys, time
OUT = sys.argv[1]
ARGS = sys.argv[2:]
def opt(name, default):
return float(ARGS[ARGS.index(name) + 1]) if name in ARGS else default
FULL_S, FAST_S, ONCE = opt("--full-s", 15.0), opt("--fast-s", 2.0), "--once" in ARGS
CPUS = sorted(int(d[3:]) for d in os.listdir("/sys/devices/system/cpu") if d.startswith("cpu") and d[3:].isdigit())
MEM_KEYS = {"MemTotal", "MemFree", "MemAvailable", "Cached", "Buffers", "Active(file)", "Inactive(file)", "Shmem", "ShmemHugePages", "AnonPages", "AnonHugePages",
"FileHugePages", "FilePmdMapped", "Mlocked", "Unevictable", "Dirty", "SwapFree", "HugePages_Total", "HugePages_Free", "HugePages_Rsvd", "HugePages_Surp"}
VM_PREFIX = ("thp_", "compact_", "allocstall", "pgmajfault", "pgfault", "pswpin", "pswpout", "pgscan_direct", "pgscan_kswapd", "pgsteal_direct", "pgsteal_kswapd", "numa_", "kswapd_low_wmark")
STOP = False
def _stop(*_):
global STOP
STOP = True
signal.signal(signal.SIGTERM, _stop)
signal.signal(signal.SIGINT, _stop)
def rd(path, default=None):
try:
with open(path) as f:
return f.read().strip()
except Exception:
return default
def read_stat():
cpu, total = {}, {}
try:
for ln in open("/proc/stat"):
if ln.startswith("cpu") and ln[3:4].isdigit():
p = ln.split()
v = [int(x) for x in p[1:9]]
idle = v[3] + v[4]
cpu[int(p[0][3:])] = (sum(v), idle)
except Exception:
pass
return cpu
def freqs():
out = []
for c in CPUS:
v = rd("/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq" % c)
out.append(int(v) if v and v.isdigit() else None)
return out
def util(prev, cur):
if prev is None:
return None
out = []
for c in CPUS:
if c in prev and c in cur:
dt, di = cur[c][0] - prev[c][0], cur[c][1] - prev[c][1]
out.append(round(100.0 * (dt - di) / dt, 1) if dt > 0 else None)
else:
out.append(None)
return out
def kv_file(path, keys=None, prefix=None):
d = {}
try:
for ln in open(path):
p = ln.replace(":", " ").split()
if len(p) < 2:
continue
k = p[0]
if (keys and k in keys) or (prefix and k.startswith(prefix)):
d[k] = int(p[1])
except Exception:
pass
return d
def nvsmi():
q = "temperature.gpu,clocks.sm,clocks.mem,power.draw,power.limit,utilization.gpu,memory.used,pstate,%s"
names = "temp_c sm_mhz mem_mhz power_w power_limit_w util_pct mem_used_mib pstate throttle".split()
for reasons in ("clocks_event_reasons.active", "clocks_throttle_reasons.active"):
try:
r = subprocess.run(["nvidia-smi", "--query-gpu=" + q % reasons, "--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=8)
if r.returncode == 0 and r.stdout.strip():
return dict(zip(names, [x.strip() for x in r.stdout.strip().splitlines()[0].split(",")]))
except Exception:
pass
return {}
def gpu_pids():
try:
r = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,used_memory", "--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=8)
return [int(l.split(",")[0]) for l in r.stdout.strip().splitlines() if l.strip()]
except Exception:
return []
def proc_info(pid):
d = {"pid": pid, "exe": os.path.basename(os.readlink("/proc/%d/exe" % pid)) if os.path.exists("/proc/%d/exe" % pid) else None}
st = rd("/proc/%d/status" % pid, "")
for ln in st.splitlines():
if ln.startswith("Cpus_allowed_list:"):
d["allowed"] = ln.split(":", 1)[1].strip()
elif ln.startswith("Threads:"):
d["threads"] = int(ln.split(":", 1)[1])
d["smaps_rollup_kb"] = kv_file("/proc/%d/smaps_rollup" % pid, keys={"Rss", "Pss", "Pss_Anon", "Pss_File", "Pss_Shmem", "Shared_Clean", "Shared_Dirty", "Private_Clean", "Private_Dirty",
"Anonymous", "AnonHugePages", "ShmemPmdMapped", "FilePmdMapped", "Shared_Hugetlb", "Private_Hugetlb", "Swap", "Locked"})
ths = []
try:
for t in os.listdir("/proc/%d/task" % pid):
s = rd("/proc/%d/task/%s/stat" % (pid, t))
if not s:
continue
comm = s[s.index("(") + 1:s.rindex(")")]
f = s[s.rindex(")") + 2:].split()
# f[0]=state, utime=f[11], stime=f[12], processor=f[36]
allowed = None
for ln in (rd("/proc/%d/task/%s/status" % (pid, t), "") or "").splitlines():
if ln.startswith("Cpus_allowed_list:"):
allowed = ln.split(":", 1)[1].strip()
break
ths.append([int(t), comm, int(f[36]), int(f[11]) + int(f[12]), allowed])
except Exception:
pass
d["thr"] = ths
return d
def all_proc_ticks():
out = {}
for p in os.listdir("/proc"):
if p.isdigit():
s = rd("/proc/%s/stat" % p)
if s:
try:
comm = s[s.index("(") + 1:s.rindex(")")]
f = s[s.rindex(")") + 2:].split()
out[int(p)] = (comm, int(f[11]) + int(f[12]))
except Exception:
pass
return out
def full(prev_stat, prev_ticks, gpids_hint):
now = read_stat()
ticks = all_proc_ticks()
s = {"kind": "full", "t": round(time.time(), 3), "uptime_s": float(rd("/proc/uptime", "0 0").split()[0]), "loadavg": rd("/proc/loadavg", "").split()[:3]}
s["cpu_khz"], s["cpu_util"] = freqs(), util(prev_stat, now)
s["cpufreq"] = {"governor": rd("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor"), "driver": rd("/sys/devices/system/cpu/cpu0/cpufreq/scaling_driver"),
"epp": rd("/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference"), "boost": rd("/sys/devices/system/cpu/cpufreq/boost"),
"max_khz": rd("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq"), "min_khz": rd("/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq"),
"pstate_status": rd("/sys/devices/system/cpu/amd_pstate/status")}
s["meminfo_kb"] = kv_file("/proc/meminfo", keys=MEM_KEYS)
thp = "/sys/kernel/mm/transparent_hugepage/"
s["thp"] = {"enabled": rd(thp + "enabled"), "defrag": rd(thp + "defrag"), "shmem_enabled": rd(thp + "shmem_enabled"), "khugepaged_defrag": rd(thp + "khugepaged/defrag"),
"khugepaged_pages_collapsed": rd(thp + "khugepaged/pages_collapsed"), "nr_hugepages": rd("/proc/sys/vm/nr_hugepages")}
s["vmstat"] = {}
try:
for ln in open("/proc/vmstat"):
k, v = ln.split()
if k.startswith(VM_PREFIX):
s["vmstat"][k] = int(v)
except Exception:
pass
s["buddy"] = rd("/proc/buddyinfo")
s["psi"] = {n: (rd("/proc/pressure/" + n, "").splitlines() or [None])[0] for n in ("cpu", "memory", "io")}
s["gpu"] = nvsmi()
pids = gpu_pids()
s["gpu_pids"] = pids
s["procs"] = [proc_info(p) for p in pids if os.path.exists("/proc/%d" % p)]
if prev_ticks is not None:
d = []
for p, (comm, t) in ticks.items():
if p in pids or p == os.getpid():
continue
pt = prev_ticks.get(p)
if pt and t - pt[1] > 0:
d.append((t - pt[1], p, comm))
d.sort(reverse=True)
s["others_top"] = [[p, c, tk] for tk, p, c in d[:5]]
return s, now, ticks
def main():
prev_stat, prev_ticks = read_stat(), None
out = open(OUT, "a", buffering=1)
nxt_full, nxt_fast = 0.0, 0.0
while not STOP:
t = time.time()
if t >= nxt_full:
s, prev_stat, prev_ticks = full(prev_stat, prev_ticks, None)
out.write(json.dumps(s, separators=(",", ":")) + "\n")
nxt_full = t + FULL_S
nxt_fast = t + FAST_S
if ONCE:
break
elif t >= nxt_fast:
now = read_stat()
out.write(json.dumps({"kind": "fast", "t": round(t, 3), "cpu_khz": freqs(), "cpu_util": util(prev_stat, now)}, separators=(",", ":")) + "\n")
prev_stat = now
nxt_fast = t + FAST_S
time.sleep(max(0.05, min(nxt_full, nxt_fast) - time.time()))
out.close()
main()