okami.mom/strata

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

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
14.4 KiB319 linesraw
1#!/usr/bin/env python3
2"""Split serving (serve/split.py): the exactness check and the speed comparison, run on a test box with the real engine.
3
4  python3 tools/split_serve_check.py exact CONFIG.json OUT.json [--tokens N]
5  python3 tools/split_serve_check.py bench CONFIG.json OUT.json --arm layer|single|split [--reps 3]
6
7Run it from the repository root (it imports serve.server and serve.split).  CONFIG.json:
8
9  {"exe": "/path/strata", "cwd": "/path/repo", "args": ["--serve", "--pack", ..., "--max-context", "40960", ...],
10   "env": {...}, "prompts": "/path/prompts", "dir": "/path/work",
11   "prefill_gpu": 0, "decode_gpu": 1, "arena": "/path/arena.bin" (optional), "min_prompt_tokens": 2048}
12
13`args` holds no --layer-split, --shared-expert-arena or card choice: the tool adds them for each arm.
14The prompts folder has pp_<N>.txt files of comma-separated token ids (the bench harness's).
15
16exact: a fresh engine reads a prompt and answers (the reference, twice, to show the engine's own run-to-run noise);
17then the prefill engine reads the same prompt, saves the session, a fresh decode engine restores it and answers.  Compared:
18the state fingerprint (STRATA_STATE_HASH) of the prefill engine and of the decode engine right after the restore, then the
19answer's token ids and the fingerprint after the answer.
20
21bench: one arm per call (run it in its own job so the engines start fresh):
22  layer  one engine over both cards (--layer-split auto), the normal two-card setup
23  single one engine on the decode card
24  split  prefill engine on one card, decode engine on the other, through SplitEngine (the production path)
25Workloads: 8K and 32K prompt + 256 tokens, a 3-turn chat with short follow-ups, a 3-turn chat with long follow-ups.
26"""
27import argparse
28import copy
29import json
30import os
31import re
32import sys
33import threading
34import time
35
36sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
37from serve import server as srv          # noqa: E402
38from serve import split as split_mod     # noqa: E402
39
40
41def read_ids(path):
42    return [int(x) for x in open(path).read().replace("\n", ",").split(",") if x.strip()]
43
44
45def session_dir(cfg):
46    """Where the session files go: cfg["session_dir"], else /dev/shm when it has room (as the server chooses), else cfg["dir"]."""
47    d = cfg.get("session_dir")
48    if not d and os.path.isdir("/dev/shm"):
49        import shutil
50        if shutil.disk_usage("/dev/shm").free > (6 << 30):
51            d = "/dev/shm/strata-split-check"
52    d = d or cfg["dir"]
53    os.makedirs(d, exist_ok=True)
54    return d
55
56
57def mem_available_gib():
58    for line in open("/proc/meminfo"):
59        if line.startswith("MemAvailable"):
60            return int(line.split()[1]) / 1048576.0
61    return 0.0
62
63
64def make_engine(cfg, gpus, tag, extra_args=(), arena=None, min_free_gib=8.0, state_hash=False):
65    free = mem_available_gib()
66    if free < min_free_gib:
67        raise SystemExit(f"only {free:.1f} GiB of RAM available (< {min_free_gib}): not starting an engine")
68    c = copy.deepcopy(cfg)
69    c["gpu"] = gpus
70    c["args"] = list(c["args"]) + list(extra_args) + (["--shared-expert-arena", arena] if arena else [])
71    c["log"] = os.path.join(cfg["dir"], f"engine-{tag}.log")
72    open(c["log"], "w").close()
73    env = srv.child_env(c)
74    if state_hash:                  # the fingerprint after every request costs time proportional to the prompt: exact mode only
75        env["STRATA_STATE_HASH"] = "1"
76    for k, v in (cfg.get("env") or {}).items():
77        env[str(k)] = str(v)
78    t0 = time.time()
79    e = srv.StrataEngine(c["exe"], srv.engine_args(c), cwd=c.get("cwd"), log=c["log"], env=env)
80    e.silence_s = 0
81    e.tag, e.load_s = tag, time.time() - t0
82    return e
83
84
85def log_tail(e, start):
86    try:
87        with open(e.log_path, "rb") as f:
88            f.seek(start)
89            return f.read().decode("utf-8", "replace")
90    except OSError:
91        return ""
92
93
94def log_size(e):
95    try:
96        return os.path.getsize(e.log_path)
97    except OSError:
98        return 0
99
100
101def state_hashes(text):
102    """The STATE_HASH lines of an engine log excerpt, as dicts."""
103    out = []
104    for m in re.finditer(r"STATE_HASH L=(\d+) (.*)", text):
105        d = {"L": int(m.group(1))}
106        d.update(dict(kv.split("=", 1) for kv in m.group(2).split() if "=" in kv))
107        out.append(d)
108    return out
109
110
111def run_gen(engine, ids, max_new):
112    """One request through engine.generate (a StrataEngine or a SplitEngine).  -> dict of tokens and times."""
113    cancel = threading.Event()
114    toks, t_first = [], None
115    t0 = time.perf_counter()
116    for t in engine.generate(ids, max_new, {}, cancel):
117        if t is None:
118            continue
119        if t_first is None:
120            t_first = time.perf_counter()
121        toks.append(t)
122    t_end = time.perf_counter()
123    last = dict(engine.last or {})
124    dec = (len(toks) - 1) / (t_end - t_first) if t_first and len(toks) > 1 and t_end > t_first else None
125    return {"tokens": toks, "ttft_s": (t_first - t0) if t_first else None, "wall_s": t_end - t0,
126            "dec_tok_s": dec, "last": last}
127
128
129def close_all(*engines):
130    for e in engines:
131        try:
132            e.close()
133        except Exception as x:       # noqa: BLE001
134            print("close:", x, flush=True)
135
136
137def cmd_exact(a, cfg):
138    ids = read_ids(os.path.join(cfg["prompts"], f"pp_{a.prompt}.txt"))[:a.prompt]
139    arena = cfg.get("arena")
140    P, Dg = cfg["prefill_gpu"], cfg["decode_gpu"]
141    res = {"prompt_tokens": len(ids), "new_tokens": a.tokens, "runs": {}}
142    # 1. the reference twice: a fresh engine on the decode card each time
143    for k in (1, 2):
144        e = make_engine(cfg, Dg, f"ref{k}", arena=arena, state_hash=True)
145        pos = log_size(e)
146        r = run_gen(e, ids, a.tokens)
147        h = state_hashes(log_tail(e, pos))
148        res["runs"][f"ref{k}"] = {"tokens": r["tokens"], "hash_end": h[-1] if h else None, "last": r["last"],
149                                  "wall_s": r["wall_s"]}
150        print(f"ref{k}: {len(r['tokens'])} tokens, wall {r['wall_s']:.1f} s", flush=True)
151        close_all(e)
152    # 2. the split: prefill engine, save, fresh decode engine, restore, answer
153    pe = make_engine(cfg, P, "prefill", arena=arena, state_hash=True)
154    pos = log_size(pe)
155    cancel = threading.Event()
156    for _ in pe.generate(ids, 0, {}, cancel, prefill_only=True):
157        pass
158    hp = state_hashes(log_tail(pe, pos))
159    path = os.path.join(session_dir(cfg), "exact.session")
160    saved = pe.session_file("save", path)
161    print(f"prefill engine: held {saved['tokens']} tokens, saved {saved['bytes'] / 2**20:.0f} MiB in {saved['ms']:.0f} ms",
162          flush=True)
163    de = make_engine(cfg, Dg, "decode", arena=arena, state_hash=True)
164    restored = de.session_file("restore", path)
165    print(f"decode engine: restored {restored['tokens']} tokens in {restored['ms']:.0f} ms", flush=True)
166    pos = log_size(de)
167    for _ in de.generate(ids, 0, {}, cancel, prefill_only=True):    # nothing to read: only the state fingerprint
168        pass
169    hd = state_hashes(log_tail(de, pos))
170    pos = log_size(de)
171    r = run_gen(de, ids, a.tokens)
172    h = state_hashes(log_tail(de, pos))
173    res["runs"]["split"] = {"tokens": r["tokens"], "hash_end": h[-1] if h else None, "last": r["last"],
174                            "wall_s": r["wall_s"], "hash_prefill_engine": hp[-1] if hp else None,
175                            "hash_decode_after_restore": hd[-1] if hd else None, "saved": saved, "restored": restored}
176    print(f"split: {len(r['tokens'])} tokens, wall {r['wall_s']:.1f} s", flush=True)
177    close_all(pe, de)
178    try:
179        os.unlink(path)
180    except OSError:
181        pass
182    # verdicts
183    ref1, ref2, sp = (res["runs"][k] for k in ("ref1", "ref2", "split"))
184
185    def first_diff(x, y):
186        for i, (p, q) in enumerate(zip(x, y)):
187            if p != q:
188                return i
189        return None if len(x) == len(y) else min(len(x), len(y))
190    v = {
191        "restore_round_trip_state_equal": sp["hash_prefill_engine"] == sp["hash_decode_after_restore"] and
192                                          sp["hash_prefill_engine"] is not None,
193        "ref1_vs_ref2_first_diff": first_diff(ref1["tokens"], ref2["tokens"]),
194        "ref1_vs_split_first_diff": first_diff(ref1["tokens"], sp["tokens"]),
195        "ref2_vs_split_first_diff": first_diff(ref2["tokens"], sp["tokens"]),
196        "end_state_ref1_eq_ref2": ref1["hash_end"] == ref2["hash_end"],
197        "end_state_ref1_eq_split": ref1["hash_end"] == sp["hash_end"],
198    }
199    res["verdict"] = v
200    json.dump(res, open(a.out, "w"), indent=1)
201    print(json.dumps(v, indent=1), flush=True)
202    # the check passes when the split run equals the reference wherever the reference equals itself
203    same_ref = v["ref1_vs_ref2_first_diff"] is None
204    ok = v["restore_round_trip_state_equal"] and (
205        (v["ref1_vs_split_first_diff"] is None and v["end_state_ref1_eq_split"]) if same_ref
206        else v["ref1_vs_split_first_diff"] is None or v["ref2_vs_split_first_diff"] is None)
207    print("EXACT: PASS" if ok else "EXACT: FAIL", flush=True)
208    return 0 if ok else 1
209
210
211WORKLOADS = [
212    ("p8k", {"prompt": 8192, "gen": 256}),
213    ("p32k", {"prompt": 32768, "gen": 256}),
214    ("chat_short", {"prompt": 4096, "gen": 128, "turns": 3, "follow": 200}),
215    ("chat_long", {"prompt": 8192, "gen": 128, "turns": 3, "follow": 6000}),
216]
217
218
219def follow_ids(cfg, n, turn):
220    """n token ids for a follow-up message: a slice of the 16K prompt (different for each turn)."""
221    pool = read_ids(os.path.join(cfg["prompts"], "pp_16384.txt"))
222    start = 1000 + turn * 7000
223    return pool[start:start + n]
224
225
226def cmd_bench(a, cfg):
227    arm = a.arm
228    P, Dg = cfg["prefill_gpu"], cfg["decode_gpu"]
229    arena = cfg.get("arena")
230    t_load = time.time()
231    if arm == "layer":
232        eng = make_engine(cfg, [min(P, Dg), max(P, Dg)], "layer")
233        closers = [eng]
234    elif arm == "single":
235        eng = make_engine(cfg, Dg, "single")
236        closers = [eng]
237    elif arm == "single_shared":                 # one card, the arena in the shared file: what the split's engines read from
238        eng = make_engine(cfg, Dg, "single_shared", arena=arena)
239        closers = [eng]
240    elif arm == "split":
241        spec = split_mod.split_spec({"split_serve": {"prefill_gpu": P, "decode_gpu": Dg,
242                                                    "min_prompt_tokens": cfg.get("min_prompt_tokens", 2048)}})
243        pe = make_engine(cfg, P, "prefill", extra_args=cfg.get("prefill_args", []), arena=arena)
244        de = make_engine(cfg, Dg, "decode", extra_args=cfg.get("decode_args", []), arena=arena)
245        eng = split_mod.SplitEngine(pe, de, min_tokens=spec["min_prompt_tokens"], work_dir=session_dir(cfg), say=print)
246        closers = [pe, de]
247    else:
248        raise SystemExit("--arm layer|single|split")
249    load_s = time.time() - t_load
250    print(f"[{arm}] loaded in {load_s:.0f} s", flush=True)
251    rows = []
252    try:
253        warm = read_ids(os.path.join(cfg["prompts"], "dec_story.txt"))
254        for _ in range(3):                                       # warm-up: graphs, the adaptive tier (discarded)
255            run_gen(eng, warm, 100)
256        if arm == "split":
257            wp = read_ids(os.path.join(cfg["prompts"], "pp_4096.txt"))
258            wp[0] = 2999                                     # its own prompt: no workload below finds it in a cache
259            run_gen(eng, wp, 16)                             # one hand-over: warms the file path
260        for rep in range(a.reps):
261            for widx, (name, w) in enumerate(WORKLOADS):
262                if a.only and name not in a.only:
263                    continue
264                ids = read_ids(os.path.join(cfg["prompts"], f"pp_{w['prompt']}.txt"))[:w["prompt"]]
265                ids[0] = 3000 + rep * 16 + widx              # a prompt of its own: a cold start in every arm, every rep
266                if "turns" not in w:
267                    # a fresh conversation each time: a tiny unrelated request first, so no session is continued
268                    run_gen(eng, warm[:40], 1)
269                    r = run_gen(eng, ids, w["gen"])
270                    turns = [r]
271                else:
272                    run_gen(eng, warm[:40], 1)
273                    turns, conv = [], list(ids)
274                    for t in range(w["turns"]):
275                        r = run_gen(eng, conv, w["gen"])
276                        turns.append(r)
277                        conv = conv + r["tokens"] + follow_ids(cfg, w["follow"], t)
278                row = {"arm": arm, "rep": rep, "workload": name, "load_s": round(load_s, 1), "turns": []}
279                for r in turns:
280                    last = r["last"]
281                    row["turns"].append({
282                        "prompt": last.get("prompt_tokens"), "generated": len(r["tokens"]),
283                        "ttft_s": round(r["ttft_s"], 3) if r["ttft_s"] else None, "wall_s": round(r["wall_s"], 3),
284                        "dec_tok_s": round(r["dec_tok_s"], 2) if r["dec_tok_s"] else None,
285                        "reused": last.get("reused"), "prompt_ms": last.get("prompt_ms"),
286                        "split": {k: last[k] for k in last if k.startswith("split_")} or None,
287                        "finish": last.get("finish"), "tokens": r["tokens"][:8]})
288                row["total_wall_s"] = round(sum(r["wall_s"] for r in turns), 3)
289                rows.append(row)
290                print(json.dumps({k: row[k] for k in ("arm", "rep", "workload", "total_wall_s")}), flush=True)
291                for t in row["turns"]:
292                    print("   ", json.dumps({k: t[k] for k in ("prompt", "generated", "ttft_s", "wall_s", "dec_tok_s",
293                                                             "reused", "split")}), flush=True)
294    finally:
295        out = {"arm": arm, "rows": rows, "cfg": {k: v for k, v in cfg.items() if k != "env"},
296               "split_view": eng.split_view() if hasattr(eng, "split_view") else None}
297        json.dump(out, open(a.out, "w"), indent=1)
298        close_all(*closers)
299    return 0
300
301
302def main():
303    ap = argparse.ArgumentParser()
304    ap.add_argument("mode", choices=["exact", "bench"])
305    ap.add_argument("config")
306    ap.add_argument("out")
307    ap.add_argument("--tokens", type=int, default=64)
308    ap.add_argument("--prompt", type=int, default=4096)
309    ap.add_argument("--arm", default="split", choices=["layer", "single", "single_shared", "split"])
310    ap.add_argument("--reps", type=int, default=2)
311    ap.add_argument("--only", nargs="*", default=None)
312    a = ap.parse_args()
313    cfg = json.load(open(a.config))
314    os.makedirs(cfg["dir"], exist_ok=True)
315    return cmd_exact(a, cfg) if a.mode == "exact" else cmd_bench(a, cfg)
316
317
318if __name__ == "__main__":
319    sys.exit(main())