okami.mom/strata

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

Niko1221Merge f-141-cuda: foresight, GDN chunked, per-arch tables, stage pin, CUDA bug fixesc27998f5a

main
6.3 KiB139 linesraw
1"""A/B two engine builds or environments on one config: restart the server per arm, alternate arms over rounds.
2
3    python tools/ab_engine.py strata-q2_0.json A:exe=/path/a B:exe=/path/b,STRATA_EXP_MODE=0 [--rounds 3]
4
5An arm is NAME:key=value,...; `exe` replaces the config's engine, `xargs` appends ';'-separated engine arguments,
6every other key is set in the engine's environment.  Each round starts the server once per arm (the arms' order alternates), warms it up with one short
7answer, then sends the same requests: greedy, fixed prompts, a short chat set and one long prompt.  Prints the
8server's own timings (llama.cpp's `timings`: decode and prompt tokens per second) per request and the per-arm
9medians.  Decode numbers move run to run (the adaptive expert tier, the OS), so compare medians over rounds.
10"""
11from __future__ import annotations
12
13import argparse
14import json
15import os
16import random
17import statistics
18import subprocess
19import sys
20import tempfile
21import time
22import urllib.request
23from pathlib import Path
24
25ROOT = Path(__file__).resolve().parents[1]
26PROMPTS = (
27    "Write a Python function that merges two sorted lists into one sorted list, with a docstring and two tests.",
28    "Explain in two paragraphs how a refrigerator moves heat from inside to outside.",
29    "List ten practical tips for learning a new language as an adult, one sentence each.",
30)
31
32
33def long_prompt(words: int) -> str:
34    rng = random.Random(7)
35    vocab = ("river stone market lantern copper winter garden signal harbor needle orbit velvet canyon ember "
36             "ledger quartz meadow anchor violet thunder").split()
37    body = " ".join(rng.choice(vocab) for _ in range(words))
38    return f"Here is a list of words:\n{body}\n\nSummarize what kinds of words appear in the list, in five sentences."
39
40
41def post(port: int, prompt: str, max_tokens: int) -> dict:
42    req = urllib.request.Request(
43        f"http://127.0.0.1:{port}/v1/chat/completions",
44        data=json.dumps({"messages": [{"role": "user", "content": prompt}], "max_tokens": max_tokens,
45                         "temperature": 0, "chat_template_kwargs": {"enable_thinking": False}}).encode(),
46        headers={"Content-Type": "application/json"})
47    with urllib.request.urlopen(req, timeout=1800) as r:
48        return json.loads(r.read())
49
50
51def wait_ready(port: int, proc: subprocess.Popen, timeout: float = 1800) -> None:
52    t0 = time.time()
53    while time.time() - t0 < timeout:
54        if proc.poll() is not None:
55            raise RuntimeError(f"server exited with {proc.returncode}")
56        try:
57            with urllib.request.urlopen(f"http://127.0.0.1:{port}/v1/models", timeout=5) as r:
58                if r.status == 200:
59                    post(port, "Say hi.", 8)
60                    return
61        except Exception:
62            pass
63        time.sleep(3)
64    raise TimeoutError("server not ready")
65
66
67def main() -> int:
68    ap = argparse.ArgumentParser()
69    ap.add_argument("config")
70    ap.add_argument("arms", nargs="+")
71    ap.add_argument("--rounds", type=int, default=3)
72    ap.add_argument("--port", type=int, default=8090)
73    ap.add_argument("--max-new", type=int, default=256)
74    ap.add_argument("--long-words", type=int, default=6000)
75    ap.add_argument("--log", default="ab_engine.jsonl")
76    a = ap.parse_args()
77    base = json.loads(Path(a.config).read_text())
78    arms = []
79    for s in a.arms:
80        name, _, kv = s.partition(":")
81        env = dict(x.split("=", 1) for x in kv.split(",") if x)
82        arms.append((name, env))
83    reqs = [(f"chat{i}", p) for i, p in enumerate(PROMPTS)] + [("long", long_prompt(a.long_words))]
84    out = open(a.log, "a")
85    res: dict = {n: {} for n, _ in arms}
86    for rnd in range(a.rounds):
87        order = arms if rnd % 2 == 0 else arms[::-1]
88        for name, env in order:
89            cfg = dict(base)
90            e = dict(env)
91            if "exe" in e:
92                cfg["exe"] = e.pop("exe")
93            if "xargs" in e:                       # extra engine arguments, ';'-separated
94                cfg["args"] = list(base["args"]) + e.pop("xargs").split(";")
95            cfg["port"] = a.port
96            cfg["log"] = str(Path(tempfile.gettempdir()) / f"ab_{name}_r{rnd}.log")
97            cpath = Path(tempfile.gettempdir()) / f"ab_{name}.json"
98            cpath.write_text(json.dumps(cfg, indent=1))
99            penv = dict(os.environ, **e)
100            proc = subprocess.Popen([sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config",
101                                     str(cpath), "--port", str(a.port)], cwd=str(ROOT), env=penv,
102                                    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
103            try:
104                t0 = time.time()
105                wait_ready(a.port, proc)
106                print(f"round {rnd} {name}: ready in {time.time() - t0:.0f} s", flush=True)
107                for tag, p in reqs:
108                    r = post(a.port, p, a.max_new)
109                    t = r.get("timings", {})
110                    row = {"round": rnd, "arm": name, "req": tag, "decode": t.get("predicted_per_second"),
111                           "prompt": t.get("prompt_per_second"), "prompt_n": t.get("prompt_n"),
112                           "n": r.get("usage", {}).get("completion_tokens"),
113                           "text": r["choices"][0]["message"].get("content", "")[:80]}
114                    out.write(json.dumps(row) + "\n")
115                    out.flush()
116                    res[name].setdefault(tag, []).append(row)
117                    print(f"  {tag:6s} decode {row['decode']} tok/s  prompt {row['prompt']} tok/s ({row['prompt_n']})  "
118                          f"n {row['n']}", flush=True)
119            finally:
120                proc.terminate()
121                try:
122                    proc.wait(60)
123                except subprocess.TimeoutExpired:
124                    proc.kill()
125                time.sleep(5)
126    print("\nmedians over rounds:")
127    for tag, _ in reqs:
128        cells = []
129        for name, _ in arms:
130            rows = res[name].get(tag, [])
131            d = statistics.median([x["decode"] for x in rows if x["decode"]]) if rows else float("nan")
132            pr = statistics.median([x["prompt"] for x in rows if x["prompt"]]) if rows else float("nan")
133            cells.append(f"{name}: decode {d:6.1f}  prompt {pr:7.1f}")
134        print(f"  {tag:6s} | " + " | ".join(cells))
135    return 0
136
137
138if __name__ == "__main__":
139    sys.exit(main())