okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-clean-3 (321794636): docs and history (cleanup step 3, items 3.0-3.10); release manifest and capability table with checks, history/ with pointers, link check, tools/ split, bench index; owner OK'd the wording 11-082b36e8a02

main
14.8 KiB376 linesraw
1"""2507-0: how idle are the GPUs, and does an existing switch close the gap? Interleaved A/B of whole engine runs
2(fresh engine per arm run, rotating arm order), with a per-card utilisation sampler (nvidia-smi, 5 samples/s) over every
3decode, prompt and batch window. Derived from the 0.2.1 split A/B harness; measurement only, no engine change.
4
5  python split_ab.py single CONFIG OUTDIR --arm name=EXE!ARGS!K=V,K=V ... [--pairs 6] [--new 300] [--warm 2] [--pps 4096,20480] [--extra "..."]
6      per run: WARM x 64-token requests, then story/code/facts greedy requests of --new tokens, then one prompt read per --pps length
7  python split_ab.py batch CONFIG OUTDIR --batch N --arm ... [--pairs 5] [--new 200]
8      per run: engine with --batch N, one warm batch (48 tokens), then --passes batch passes of N prompts (BGEN), aggregate tok/s
9  python split_ab.py --summary OUTDIR [--base name]
10
11Results: OUTDIR/results.jsonl, one line per arm run.
12"""
13import hashlib
14import json
15import os
16import re
17import statistics
18import subprocess
19import sys
20import threading
21import time
22
23
24class Sampler:
25    """nvidia-smi utilisation/power per card, time stamped on arrival; window(t0, t1) -> per-card means."""
26
27    def __init__(self):
28        self.rows = []
29        self.proc = subprocess.Popen(["nvidia-smi", "--query-gpu=index,utilization.gpu,power.draw", "--format=csv,noheader,nounits",
30                                      "-lms", "200"], stdout=subprocess.PIPE, text=True)
31        threading.Thread(target=self._read, daemon=True).start()
32
33    def _read(self):
34        for line in self.proc.stdout:
35            try:
36                i, u, w = [x.strip() for x in line.split(",")]
37                self.rows.append((time.time(), int(i), float(u), float(w)))
38            except ValueError:
39                pass
40
41    def window(self, t0, t1):
42        out = {}
43        for t, i, u, w in list(self.rows):
44            if t0 <= t <= t1:
45                d = out.setdefault(i, [[], []])
46                d[0].append(u)
47                d[1].append(w)
48        return {str(i): {"util": round(sum(d[0]) / len(d[0]), 1), "power_w": round(sum(d[1]) / len(d[1]), 1), "n": len(d[0])}
49                for i, d in sorted(out.items())}
50
51    def stop(self):
52        self.proc.kill()
53
54
55SMP = None
56from pathlib import Path
57
58
59def args_of(name):
60    return [sys.argv[i + 1] for i, a in enumerate(sys.argv) if a == name]
61
62
63def arg(name, default):
64    return sys.argv[sys.argv.index(name) + 1] if name in sys.argv else default
65
66
67def med(xs):
68    xs = [x for x in xs if x is not None]
69    return statistics.median(xs) if xs else float("nan")
70
71
72def summary(out, base=None):
73    R = [json.loads(l) for l in open(out / "results.jsonl")]
74    names = []
75    for r in R:
76        if r["arm"] not in names:
77            names.append(r["arm"])
78    base = base or names[0]
79    keys = []
80    for r in R:
81        for x in r["rows"]:
82            k = (x["kind"], "tok_s" if x.get("tok_s") is not None else "pp_tok_s")
83            if k not in keys and x["kind"] != "batch":
84                keys.append(k)
85    if any(x["kind"] == "batch" for r in R for x in r["rows"]):
86        keys += [("batch", "tok_s"), ("batch", "steady"), ("batch", "ttft")]
87
88    def per_round(arm, kind, key):
89        d = {}
90        for r in R:
91            if r["arm"] == arm:
92                v = [x.get(key) for x in r["rows"] if x["kind"] == kind]
93                d[r["round"]] = med(v)
94        return d
95
96    print("arm | metric | median | vs base | pairs faster (higher) | rounds")
97    for kind, key in keys:
98        for nm in names:
99            a, b = per_round(base, kind, key), per_round(nm, kind, key)
100            rounds = [i for i in sorted(set(a) & set(b)) if a[i] == a[i] and b[i] == b[i]]
101            if not rounds:
102                continue
103            ma, mb = med([a[i] for i in rounds]), med([b[i] for i in rounds])
104            fb = sum(1 for i in rounds if (b[i] < a[i] if key == "ttft" else b[i] > a[i]))
105            print(f"{nm} | {kind}:{key} | {mb:.2f} | {mb / ma:.3f} | {fb}/{len(rounds)} | {len(rounds)}")
106    print("\narm | window | mean util per card % (median over runs) | mean power W per card | idle% (mean over cards)")
107    kinds = []
108    for r in R:
109        for x in r["rows"]:
110            if x["kind"] not in kinds:
111                kinds.append(x["kind"])
112    for nm in names:
113        for kind in kinds:
114            us, ws = {}, {}
115            for r in R:
116                if r["arm"] != nm:
117                    continue
118                for x in r["rows"]:
119                    if x["kind"] == kind:
120                        for gi, g in (x.get("gpu") or {}).items():
121                            us.setdefault(gi, []).append(g["util"])
122                            ws.setdefault(gi, []).append(g["power_w"])
123            if us:
124                mu = {gi: med(v) for gi, v in us.items()}
125                print(f"{nm} | {kind} | {', '.join(f'gpu{gi} {v:.0f}' for gi, v in sorted(mu.items()))} | "
126                      f"{', '.join(f'{med(v):.0f}' for gi, v in sorted(ws.items()))} | {100 - sum(mu.values()) / len(mu):.0f}")
127    print("\nanswer hashes per window kind (distinct values over all runs of all arms; 1 = byte-identical)")
128    for kind in kinds:
129        hs = {}
130        for r in R:
131            for x in r["rows"]:
132                if x["kind"] == kind and x.get("sha"):
133                    hs.setdefault(x["sha"], set()).add(r["arm"])
134        print(f"{kind}: {len(hs)} distinct" + ("" if len(hs) == 1 else " -> " + "; ".join(f"{h}:{','.join(sorted(a))}" for h, a in hs.items())))
135    for nm in names:
136        sl = sorted({r.get("slots") for r in R if r["arm"] == nm}, key=str)
137        print(f"{nm}: expert-cache slots {sl}")
138
139
140if "--summary" in sys.argv:
141    summary(Path(arg("--summary", ".")), arg("--base", None))
142    sys.exit(0)
143
144MODE = sys.argv[1]
145REPO = Path(os.environ["STRATA_REPO"])
146sys.path.insert(0, str(REPO / "tools"))
147sys.path.insert(0, str(REPO))
148import strata_tokenizer as ST  # noqa: E402
149from serve.server import child_env  # noqa: E402
150
151SMP = Sampler()
152CFG, OUT = sys.argv[2], Path(sys.argv[3])
153PAIRS = int(arg("--pairs", "5"))
154NEW = int(arg("--new", "300" if MODE == "single" else "200"))
155WARM = int(arg("--warm", "2"))
156PPS = [int(x) for x in arg("--pps", "0").split(",") if int(x)]
157BATCH = int(arg("--batch", "2"))
158PASSES = int(arg("--passes", "2"))
159extra = arg("--extra", "").split()
160ARMS = []
161for a in args_of("--arm"):
162    nm, rest = a.split("=", 1)
163    exe, xargs, envs = (rest.split("!") + ["", ""])[:3]
164    ARMS.append((nm, exe, xargs.split(), dict(kv.split("=", 1) for kv in envs.split(",") if kv)))
165OUT.mkdir(parents=True, exist_ok=True)
166cfg = json.load(open(CFG, encoding="utf-8-sig"))
167tp = Path(cfg["tokenizer"])
168vocab = json.loads((tp / "vocab.json").read_text(encoding="utf-8"))
169toks = [None] * len(vocab)
170for t, i in vocab.items():
171    toks[i] = t
172tok = ST.Tokenizer(toks, (tp / "merges.txt").read_text(encoding="utf-8").split("\n"),
173                   json.loads((tp / "token_type.json").read_text()))
174HEAD = tok.encode("<|im_start|>user\n", parse_special=True)
175TAIL = tok.encode("<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n", parse_special=True)
176KINDS = ["story", "code", "facts"]
177ASK = {
178    "story": "Write a long story about a lighthouse keeper who finds a message in a bottle. Make it detailed.",
179    "code": "Write a Python program that implements an LRU cache class with get and put, plus unit tests. Explain each part.",
180    "facts": "Give me twenty well-known facts about the planets of the solar system, one per line, with the key numbers for each.",
181}
182QUESTIONS = [
183    "Explain in detail how a B-tree works.",
184    "Write a Python function that merges overlapping intervals, then explain it.",
185    "Compare TCP and QUIC: handshake, congestion control, multiplexing.",
186    "Tell the history of the calculation of pi, from Archimedes to today.",
187]
188_DOC = []
189
190
191def doc_ids(n, start=30000):
192    if not _DOC:
193        txt = ""
194        for f in sorted((REPO / "docs").glob("*.md")):
195            txt += f.read_text(encoding="utf-8", errors="replace") + "\n"
196        txt = txt * 8
197        _DOC.extend(tok.encode(txt[start:], parse_special=False))
198    return _DOC[:n]
199
200
201def ids_for(name, n=0):
202    if name == "pp":
203        return HEAD + tok.encode("Summarise:\n\n", parse_special=False) + doc_ids(n, 5000) + tok.encode("\n\nOne line.", parse_special=False) + TAIL
204    if name.startswith("q"):
205        return HEAD + tok.encode(QUESTIONS[int(name[1:])], parse_special=False) + TAIL
206    return HEAD + tok.encode(ASK[name], parse_special=False) + TAIL
207
208
209def clean_env(env_extra):
210    env = child_env(cfg)
211    for k in list(env):
212        if k.startswith("STRATA_"):
213            env.pop(k, None)
214    env["STRATA_DECODE_TIMING"] = "1"
215    env.update(env_extra)
216    return env
217
218
219def finish(p, log):
220    try:
221        p.stdin.close()
222    except Exception:
223        pass
224    try:
225        p.wait(120)
226    except Exception:
227        p.kill()
228    txt = open(log, errors="replace").read()
229    slots = re.findall(r"expert cache (\d+) slots", txt)
230    notes = [l for l in txt.splitlines() if re.search(r"batch_groups|pipeline.windows|SPLIT_OVERLAP|handoff", l, re.I)][:4]
231    return (slots[0] if slots else None), notes
232
233
234def start(exe, args, env, log):
235    lf = open(log, "w")
236    p = subprocess.Popen([exe, "--serve", *args], cwd=cfg.get("cwd"), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
237                         stderr=lf, text=True, bufsize=1, env=env)
238    for line in p.stdout:
239        if line.startswith("READY"):
240            return p
241    raise SystemExit(f"engine ended before READY: {log}")
242
243
244def gen(p, ids, n):
245    p.stdin.write(f"GEN {n} {','.join(map(str, ids))}\n")
246    p.stdin.flush()
247    got, info = [], ""
248    for line in p.stdout:
249        line = line.rstrip("\n")
250        if line.startswith("T "):
251            got.append(int(line.split()[1]))
252        elif line.startswith("DONE") or line.startswith("ERR"):
253            info = line
254            break
255    return got, info
256
257
258def kv_of(info):
259    f = info.split()
260    if len(f) < 5 or f[0] != "DONE":
261        return {}
262    return {"generated": f[1], "prompt_tokens": f[2], "prompt_ms": f[3], "decode_ms": f[4]}
263
264
265def run_single(label, exe, xargs, env_extra):
266    log = OUT / f"{label}.log"
267    p = start(exe, list(cfg["args"]) + extra + xargs, clean_env(env_extra), str(log))
268    for i in range(WARM):
269        gen(p, ids_for(KINDS[i % len(KINDS)]), 64)
270    rows = []
271    for name in KINDS:
272        t0 = time.time()
273        out, info = gen(p, ids_for(name), NEW)
274        t1 = time.time()
275        d = kv_of(info)
276        g, dms = d.get("generated"), d.get("decode_ms")
277        rows.append({"kind": name, "gen": len(out), "tok_s": (len(out) / float(dms) * 1000.0) if dms else None, "ids": out, "info": info,
278                     "sha": hashlib.sha256(",".join(map(str, out)).encode()).hexdigest()[:16], "gpu": SMP.window(t0, t1)})
279    for n in PPS:
280        ids = ids_for("pp", n)
281        t0 = time.time()
282        out, info = gen(p, ids, 8)
283        t1 = time.time()
284        d = kv_of(info)
285        pms = d.get("prompt_ms")
286        rows.append({"kind": f"pp{n // 1024}k", "pp_tokens": len(ids), "pp_tok_s": (len(ids) / float(pms) * 1000.0) if pms else None,
287                     "ids": out, "info": info, "tok_s": None, "gpu": SMP.window(t0, t1),
288                     "sha": hashlib.sha256(",".join(map(str, out)).encode()).hexdigest()[:16]})
289    slots, notes = finish(p, log)
290    return rows, slots, notes
291
292
293def batch_pass(p, n_new, n):
294    prompts = [ids_for(f"q{i % len(QUESTIONS)}") for i in range(n)]
295    got = {i: [] for i in range(n)}
296    first = {}
297    sent = {}
298    done = {}
299    stamp = []
300    t0 = time.time()
301    for i, ids in enumerate(prompts):
302        sent[i] = time.time()
303        p.stdin.write(f"BGEN {i} {n_new} {','.join(map(str, ids))}\n")
304        p.stdin.flush()
305        for line in p.stdout:
306            if line.startswith("T "):
307                got[i].append(int(line.split()[1]))
308                first.setdefault(i, time.time())
309                stamp.append(time.time())
310            elif line.startswith("BT "):
311                _, s, y = line.split()
312                got[int(s)].append(int(y))
313                first.setdefault(int(s), time.time())
314                stamp.append(time.time())
315            elif line.startswith("BDONE "):
316                done[int(line.split()[1])] = line
317            elif line.startswith("ERR"):
318                raise SystemExit("batch ERR: " + line)
319            elif line.startswith("BADM "):
320                if line.split()[2] == "0":
321                    done[i] = line
322                break
323    t_adm = time.time()
324    while len(done) < n:
325        line = p.stdout.readline()
326        if not line:
327            raise SystemExit("engine ended in batch")
328        if line.startswith("BT "):
329            _, s, y = line.split()
330            got[int(s)].append(int(y))
331            first.setdefault(int(s), time.time())
332            stamp.append(time.time())
333        elif line.startswith("BDONE "):
334            done[int(line.split()[1])] = line
335        elif line.startswith("ERR"):
336            raise SystemExit("batch ERR: " + line)
337    t_end = time.time()
338    total = sum(len(v) for v in got.values())
339    late = sum(1 for s in stamp if s > t_adm)
340    return {"kind": "batch", "tokens": total, "tok_s": total / (t_end - t0), "steady": late / max(t_end - t_adm, 1e-9),
341            "gpu": SMP.window(t_adm, t_end), "sha": hashlib.sha256(json.dumps([got[i] for i in range(n)]).encode()).hexdigest()[:16],
342            "ttft": med([first[i] - sent[i] for i in first]), "ids": [got[i] for i in range(n)], "secs": t_end - t0}
343
344
345def run_batch(label, exe, xargs, env_extra):
346    log = OUT / f"{label}.log"
347    p = start(exe, list(cfg["args"]) + ["--batch", str(BATCH)] + extra + xargs, clean_env(env_extra), str(log))
348    batch_pass(p, 48, BATCH)
349    rows = [batch_pass(p, NEW, BATCH) for _ in range(PASSES)]
350    for r in rows:
351        r["pass"] = rows.index(r)
352    p.stdin.write("QUIT\n")
353    p.stdin.flush()
354    slots, notes = finish(p, log)
355    return rows, slots, notes
356
357
358res = OUT / "results.jsonl"
359ROUND0 = int(arg("--round0", "0"))
360only = arg("--only", None)
361for rnd in range(ROUND0, ROUND0 + (1 if only else PAIRS)):
362    order = ARMS[rnd % len(ARMS):] + ARMS[:rnd % len(ARMS)]
363    for nm, exe, xargs, e in order:
364        if only and nm not in only.split(","):
365            continue
366        fn = run_single if MODE == "single" else run_batch
367        rows, slots, notes = fn(f"{nm}_{rnd}", exe, xargs, e)
368        with open(res, "a") as f:
369            f.write(json.dumps({"round": rnd, "arm": nm, "slots": slots, "notes": notes, "rows": rows}) + "\n")
370        if MODE == "single":
371            m = med([r["tok_s"] for r in rows if r.get("tok_s")])
372            pp = [round(r.get("pp_tok_s") or 0) for r in rows if r.get("pp_tok_s")]
373            print(f"round {rnd} {nm}: decode median {m:.2f} tok/s, pp {pp} slots {slots} {notes[:1]}", flush=True)
374        else:
375            print(f"round {rnd} {nm}: agg {[round(r['tok_s'], 1) for r in rows]} steady {[round(r['steady'], 1) for r in rows]} "
376                  f"ttft {[round(r['ttft'], 2) for r in rows]} slots {slots} {notes[:2]}", flush=True)