okami.mom/strata

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

Niko1221Merge f-029-par-harness1fb3e9a32

main
10.6 KiB211 linesraw
1#!/usr/bin/env python3
2"""Batching test: the same prompts decoded alone (GEN, the usual path with drafts) and together in the batch
3windows (BGEN), greedy.  Every slot's tokens must equal its solo tokens; prints the aggregate decode rate.
4
5  python3 tools/batch_test.py --exe engine/strata --config strata-<model>.json --batch 4 --n 4 \
6      --extra "--layer-split 12,24,36 --trim-stage-weights --pcie-frac 0 --adapt-every 1000000"
7"""
8import argparse, json, os, subprocess, sys, tempfile, threading, time
9from pathlib import Path
10
11sys.path.insert(0, str(Path(__file__).resolve().parent))
12import strata_tokenizer as ST  # noqa: E402
13
14QUESTIONS = [
15    "Explique en detail le fonctionnement d'un B-tree.",
16    "Write a Python function that merges overlapping intervals, then explain it.",
17    "Compare TCP and QUIC: handshake, congestion control, multiplexing.",
18    "Raconte l'histoire du calcul de pi, d'Archimede a nos jours.",
19    "What are the main causes of the French Revolution?",
20    "Explain how a transformer's attention works, step by step.",
21    "Donne une recette de tarte aux pommes, etape par etape.",
22    "Describe the life cycle of a star like the Sun.",
23    "Erklaere ausfuehrlich, wie ein Dieselmotor funktioniert.",
24    "Write a Rust function that parses a CSV line with quoted fields, then explain it.",
25    "What were the main consequences of the invention of the printing press?",
26    "Explique le theoreme de Pythagore avec trois demonstrations differentes.",
27    "Describe how the immune system responds to a viral infection.",
28    "Explain the difference between processes and threads in an operating system.",
29    "Beschreibe die Geschichte des Roemischen Reiches in Grundzuegen.",
30    "How does public-key cryptography work? Give an example with RSA.",
31]
32# more than 16 slots: the same questions again, asked to answer in German
33QUESTIONS = QUESTIONS + [q + " Answer in German." for q in QUESTIONS]
34
35
36def tokenizer(path):
37    t = Path(path)
38    vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8"))
39    tokens = [None] * len(vocab)
40    for s, i in vocab.items():
41        tokens[i] = s
42    merges = (t / "merges.txt").read_text(encoding="utf-8").split("\n")
43    types = json.loads((t / "token_type.json").read_text())
44    return ST.Tokenizer(tokens, merges, types)
45
46
47class Engine:
48    def __init__(self, exe, cfg, batch, extra_env, extra_args):
49        args = list(cfg["args"])
50        if len(cfg.get("gpu") or []) > 1:
51            args += ["--layer-split", str(cfg.get("layer_split") or "auto")]
52        if batch:
53            args += ["--batch", str(batch)]
54        args += extra_args
55        env = dict(os.environ, **extra_env)
56        env["LD_LIBRARY_PATH"] = ":".join(cfg.get("lib_dirs", []) + [env.get("LD_LIBRARY_PATH", "")])
57        if os.name == "nt":
58            env["PATH"] = os.pathsep.join(cfg.get("lib_dirs", []) + [env.get("PATH", "")])
59        self.log_path = os.environ.get("BATCH_TEST_LOG") or os.path.join(tempfile.gettempdir(), "batch_test_engine.log")
60        self.log = open(self.log_path, "w")
61        self.p = subprocess.Popen([exe, "--serve", *args], cwd=cfg.get("cwd"), stdin=subprocess.PIPE,
62                                  stdout=subprocess.PIPE, stderr=self.log, text=True, bufsize=1, env=env)
63        for line in self.p.stdout:
64            if line.startswith("READY"):
65                return
66        raise SystemExit(f"the engine ended before READY - see {self.log_path}")
67
68    def send(self, line):
69        self.p.stdin.write(line + "\n")
70        self.p.stdin.flush()
71
72    def lines(self):
73        for line in self.p.stdout:
74            yield line.rstrip("\n")
75
76
77def main():
78    ap = argparse.ArgumentParser()
79    ap.add_argument("--exe", required=True)
80    ap.add_argument("--config", required=True)
81    ap.add_argument("--batch", type=int, default=4)
82    ap.add_argument("--n", type=int, default=4, help="prompts (<= --batch)")
83    ap.add_argument("--max-new", type=int, default=64)
84    ap.add_argument("--skip-solo", action="store_true")
85    ap.add_argument("--keys", default="", help='sampling keys for every request, e.g. "temperature=0.7 top_k=20"')
86    ap.add_argument("--extra", default="", help='more engine arguments in one string, e.g. "--adapt-every 1000000"')
87    ap.add_argument("--dump", default="", help="write every slot's tokens (solo and batch) as JSON: an A/B of two engine builds")
88    ap.add_argument("--long-tokens", type=int, default=0,
89                    help="the LAST prompt is read from about this many tokens of filler text first: its chunks run "
90                         "beside the earlier slots' windows (the prompt path lends experts then)")
91    ap.add_argument("--co", action="store_true",
92                    help="PAR-H: before the first BGEN send BCO lines for the other prompts, so the engine reads every prompt "
93                         "in one layer-major pass (the engine needs STRATA_PREFILL_LM_FORCE=1 for prompts this short to be "
94                         "layer-major in the arm without --co)")
95    ap.add_argument("--seq", action="store_true", help="PAR-H: admit the prompts one at a time, each run to its end (no batch composition)")
96    ap.add_argument("--pad", type=int, default=0, help="PAR-H: every prompt gets about this many tokens of its own filler text first")
97    ap.add_argument("--mt-min", default="1", help="STRATA_IQ_MT_MIN for the engine (1: exact; empty: the default)")
98    a = ap.parse_args()
99    cfg = json.loads(Path(a.config).read_text())
100    tok = tokenizer(cfg["tokenizer"])
101    prompts = []
102    for q in QUESTIONS[: a.n]:
103        text = f"<|im_start|>user\n{q}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
104        if a.long_tokens and q is QUESTIONS[a.n - 1]:
105            para = ("The committee reviewed item %d of the long agenda, noting the budget, the schedule and the open "
106                    "risks, and asked the staff to report back next quarter. ")
107            per = max(1, len(tok.encode(para % 100)))
108            filler = "".join(para % i for i in range(a.long_tokens // per + 1))
109            text = f"<|im_start|>user\n{filler}\n\n{q}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
110        if a.pad:
111            para = ("Note %d-%d: the survey team measured the northern ridge, logged the readings of station %d, and sent the "
112                    "figures to the office, where a clerk filed the sheets under reference %d. ")
113            qi = QUESTIONS.index(q)
114            per = max(1, len(tok.encode(para % (qi, 100, 100, 100))))
115            filler = "".join(para % (qi, i, (i * 7 + qi) % 97, i * 13 + qi) for i in range(a.pad // per + 1))
116            text = f"<|im_start|>user\n{filler}\n\n{q}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
117        prompts.append(tok.encode(text, parse_special=True))
118    env = {"STRATA_DECODE_TIMING": "1", **({"STRATA_VERIFY_PROFILE": "1"} if os.environ.get("PROF") else {})}
119    if a.mt_min:
120        env["STRATA_IQ_MT_MIN"] = a.mt_min
121    eng = Engine(a.exe, cfg, a.batch, env, a.extra.split())
122    out = eng.lines()
123
124    solo = []
125    if not a.skip_solo:
126        for i, ids in enumerate(prompts):
127            eng.send(" ".join(x for x in ("GEN", str(a.max_new), a.keys, ",".join(map(str, ids))) if x))
128            got, t0 = [], time.time()
129            for line in out:
130                if line.startswith("T "):
131                    got.append(int(line.split()[1]))
132                elif line.startswith("DONE") or line.startswith("ERR"):
133                    print(f"solo {i}: {len(got)} tokens in {time.time() - t0:.1f}s  {line[:60]}", flush=True)
134                    break
135            solo.append(got)
136
137    # batch: admit every prompt, then the slots decode together
138    got = {i: [] for i in range(len(prompts))}
139    done = {}
140    t_admit = time.time()
141    first_bt = None
142    if a.co:
143        for i, ids in enumerate(prompts):
144            if i >= 1:
145                eng.send(f"BCO {i} " + ",".join(map(str, ids)))
146    for i, ids in enumerate(prompts):
147        eng.send(" ".join(x for x in ("BGEN", str(i), str(a.max_new), a.keys, ",".join(map(str, ids))) if x))
148        for line in out:
149            if line.startswith("T "):
150                got[i].append(int(line.split()[1]))
151            elif line.startswith("BT "):
152                _, s, y = line.split()
153                got[int(s)].append(int(y))
154                first_bt = first_bt or time.time()
155            elif line.startswith("BDONE "):
156                done[int(line.split()[1])] = line
157            elif line.startswith("ERR"):
158                print("batch:", line)
159                return 1
160            elif line.startswith("BADM "):
161                if line.split()[2] == "0":
162                    done[i] = line
163                break
164        if a.seq and i not in done:   # one prompt at a time: this slot runs to its end before the next is admitted
165            for line in out:
166                if line.startswith("BT "):
167                    _, s, y = line.split()
168                    got[int(s)].append(int(y))
169                elif line.startswith("BDONE "):
170                    done[int(line.split()[1])] = line
171                    break
172                elif line.startswith("ERR"):
173                    print("batch:", line)
174                    return 1
175    t_admitted = time.time()
176    for line in (out if len(done) < len(prompts) else []):
177        if line.startswith("BT "):
178            _, s, y = line.split()
179            got[int(s)].append(int(y))
180            first_bt = first_bt or time.time()
181        elif line.startswith("BDONE "):
182            done[int(line.split()[1])] = line
183            if len(done) == len(prompts):
184                break
185        elif line.startswith("ERR"):
186            print("batch:", line)
187            return 1
188    t_end = time.time()
189    total = sum(len(v) for v in got.values())
190    print(f"batch: {len(prompts)} slots, {total} tokens; admissions {t_admitted - t_admit:.1f}s; "
191          f"then {t_end - t_admitted:.1f}s -> aggregate {total / max(t_end - t_admit, 1e-9):.1f} tok/s overall, "
192          f"{sum(len(v) for v in got.values()) / max(t_end - (first_bt or t_admit), 1e-9):.1f} tok/s from the first batch token",
193          flush=True)
194    ok = True
195    for i in range(len(prompts)):
196        b = got[i]
197        if solo:
198            same = b == solo[i]
199            ok &= same
200            first_diff = next((k for k in range(min(len(b), len(solo[i]))) if b[k] != solo[i][k]), None)
201            print(f"slot {i}: {len(b)} tokens, solo {len(solo[i])}: {'IDENTICAL' if same else f'DIFFERS at {first_diff}'}")
202        print("   ", ascii(tok.decode(b)[:160]))
203    if a.dump:
204        Path(a.dump).write_text(json.dumps({"solo": solo, "batch": [got[i] for i in range(len(prompts))]}), encoding="utf-8")
205    eng.send("QUIT")
206    eng.p.wait(timeout=180)   # the next run needs the GPUs back
207    return 0 if ok else 2
208
209
210if __name__ == "__main__":
211    sys.exit(main())