okami.mom/strata

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

Niko1221bench: Strata vs llama.cpp v0.6.0 head-to-head script and results (3060, P100, 5070 one round)e2de691c7

main
13.0 KiB281 linesraw
1#!/usr/bin/env python3
2"""Strata vs llama.cpp head-to-head (stream 1402-h).  Measurement only.
3
4Both engines are driven through their OpenAI-compatible HTTP servers (/v1/chat/completions), with the same prompt
5text, same sampler settings and the same GGUF.  Server-side timings (llama.cpp's names, which Strata's server also
6emits) give prompt tok/s and decode tok/s; time to first token is the server's prompt_ms (non-streaming request,
7so TTFT = prompt processing time).  Peak VRAM comes from nvidia-smi polling (minus the idle baseline), RAM from the
8engine process tree (psutil RSS, which counts mmap'd file pages) and the system's used-memory delta.
9
10    python bench_vs_llama.py prompts  --out DIR --tokenizer DIR --corpus FILE...     # build 4K / 32K prompt files
11    python bench_vs_llama.py run      --machine CFG.json --out DIR --rounds N [--configs a,b] [--cells ...]
12    python bench_vs_llama.py quality  --machine CFG.json --out DIR [--configs a,b]
13    python bench_vs_llama.py summary  --out DIR
14
15CFG.json: {"gguf": ..., "strata_cfg": ..., "llama_server": ..., "configs": [{"name","kind":"llama|strata","args":[...]}]}
16Interleaving: engines cannot be loaded together (12 GB card, 64 GB RAM), so one ROUND runs every config once
17(start, warm-up, cells, stop), and rounds alternate the config order.  Medians are taken over rounds.
18The caller holds the machine's GPU lock.  Processes are stopped by PID only.
19"""
20import argparse, json, os, statistics, subprocess, sys, threading, time, urllib.request
21from pathlib import Path
22
23import psutil
24
25CELLS = [("4k", 4000, 2), ("32k", 32000, 1)]       # (name, prompt tokens, reps per round)
26TEMPS = [0.0, 0.7]
27GEN = 256
28PORT = 8190
29
30
31def http(url, body=None, timeout=3600):
32    req = urllib.request.Request(url, data=json.dumps(body).encode() if body is not None else None,
33                                 headers={"Content-Type": "application/json"})
34    with urllib.request.urlopen(req, timeout=timeout) as r:
35        return json.loads(r.read())
36
37
38def vram_used_mib():
39    try:
40        out = subprocess.run(["nvidia-smi", "--query-gpu=memory.used", "--format=csv,noheader,nounits"],
41                             capture_output=True, text=True, timeout=20).stdout.split()
42        return int(out[0])
43    except Exception:
44        return -1
45
46
47class Sampler(threading.Thread):
48    def __init__(self, pid):
49        super().__init__(daemon=True)
50        self.pid, self.stop, self.vram, self.rss, self.sysused = pid, False, 0, 0, 0
51
52    def run(self):
53        while not self.stop:
54            self.vram = max(self.vram, vram_used_mib())
55            try:
56                p = psutil.Process(self.pid)
57                self.rss = max(self.rss, sum(c.memory_info().rss for c in [p] + p.children(recursive=True)))
58            except psutil.Error:
59                pass
60            self.sysused = max(self.sysused, psutil.virtual_memory().used)
61            time.sleep(1.0)
62
63
64class Engine:
65    def __init__(self, machine, cfg):
66        self.m, self.cfg, self.proc, self.log = machine, cfg, None, None
67
68    def command(self):
69        c = self.cfg
70        if c["kind"] == "llama":
71            return [self.m["llama_server"], "-m", self.m["gguf"], "--port", str(PORT), "--host", "127.0.0.1",
72                    "-np", "1", "--no-webui", "--jinja"] + c["args"]
73        scfg = json.load(open(self.m["strata_cfg"], encoding="utf-8-sig"))
74        scfg["port"] = PORT
75        scfg.pop("vision", None)
76        args = [a for a in scfg["args"]]
77        for k, v in c.get("override", {}).items():          # replace "--flag value" pairs
78            if k in args:
79                args[args.index(k) + 1] = v
80            else:
81                args += [k, v]
82        scfg["args"] = args + c["args"]
83        if self.m.get("strata_exe"):
84            scfg["exe"] = self.m["strata_exe"]
85        p = Path(self.out) / ("strata-cfg-%s.json" % c["name"])
86        p.write_text(json.dumps(scfg, indent=1))
87        return [sys.executable, str(Path(self.m["serve"]) / "server.py"), "--engine", "strata", "--config", str(p),
88                "--port", str(PORT)]
89
90    def start(self, out):
91        self.out = out = str(Path(out).resolve())
92        self.base_vram, self.base_used = vram_used_mib(), psutil.virtual_memory().used
93        cmd = self.command()
94        self.cmdline = " ".join(cmd)
95        self.log = open(Path(out) / ("server-%s-%d.log" % (self.cfg["name"], int(time.time()))), "w", encoding="utf-8")
96        env = dict(os.environ, PYTHONIOENCODING="utf-8")
97        self.proc = subprocess.Popen(cmd, stdout=self.log, stderr=subprocess.STDOUT, env=env,
98                                     cwd=self.m.get("cwd"))
99        self.t0 = time.time()
100        self.sampler = Sampler(self.proc.pid)
101        self.sampler.start()
102        health = "http://127.0.0.1:%d/health" % PORT
103        while time.time() - self.t0 < 1500:
104            if self.proc.poll() is not None:
105                raise RuntimeError("server exited rc=%s (see %s)" % (self.proc.returncode, self.log.name))
106            try:
107                r = http(health, timeout=5)
108                if r.get("status", "ok") == "ok":
109                    break
110            except Exception:
111                pass
112            time.sleep(2)
113        else:
114            raise RuntimeError("server not ready in 1500 s")
115        self.load_s = time.time() - self.t0
116
117    def stop(self):
118        if self.proc:
119            self.sampler.stop = True
120            try:
121                p = psutil.Process(self.proc.pid)
122                kids = p.children(recursive=True)
123                for c in kids + [p]:
124                    try:
125                        c.terminate()
126                    except psutil.Error:
127                        pass
128                psutil.wait_procs(kids + [p], timeout=30)
129                for c in kids + [p]:
130                    try:
131                        if c.is_running():
132                            c.kill()
133                    except psutil.Error:
134                        pass
135            except psutil.Error:
136                pass
137            self.log.close()
138            self.proc = None
139            time.sleep(5)
140
141    def chat(self, prompt, temp, max_tokens=GEN, seed=1):
142        body = {"model": "x", "messages": [{"role": "user", "content": prompt}], "max_tokens": max_tokens,
143                "temperature": temp, "top_k": 20, "top_p": 0.95, "seed": seed, "stream": False,
144                "cache_prompt": False, "chat_template_kwargs": {"enable_thinking": False}}
145        if temp == 0:
146            body.pop("top_p"), body.pop("top_k")
147        t = time.time()
148        r = http("http://127.0.0.1:%d/v1/chat/completions" % PORT, body)
149        wall = time.time() - t
150        tm = r.get("timings") or {}
151        u = r.get("usage") or {}
152        return {"wall_s": round(wall, 2), "prompt_n": tm.get("prompt_n", u.get("prompt_tokens")),
153                "prompt_ms": tm.get("prompt_ms"), "prompt_tps": tm.get("prompt_per_second"),
154                "pred_n": tm.get("predicted_n", u.get("completion_tokens")), "pred_tps": tm.get("predicted_per_second"),
155                "draft_n": tm.get("draft_n"), "draft_acc": tm.get("draft_n_accepted"),
156                "text": (r["choices"][0]["message"].get("content") or "")}
157
158
159def cmd_prompts(a):
160    sys.path.insert(0, str(Path(a.repo) / "tools"))
161    import strata_tokenizer as ST
162    tp = Path(a.tokenizer)
163    vocab = json.loads((tp / "vocab.json").read_text(encoding="utf-8"))
164    toks = [None] * len(vocab)
165    for t, i in vocab.items():
166        toks[i] = t
167    tok = ST.Tokenizer(toks, (tp / "merges.txt").read_text(encoding="utf-8").split("\n"),
168                       json.loads((tp / "token_type.json").read_text()))
169    corpus = "\n\n".join(Path(f).read_text(encoding="utf-8", errors="replace") for f in a.corpus)
170    print("corpus chars", len(corpus))
171    out = Path(a.out)
172    out.mkdir(parents=True, exist_ok=True)
173    allids = tok.encode(corpus)
174    print("corpus tokens", len(allids))
175    for name, n, _ in CELLS:
176        if len(allids) < n:
177            raise SystemExit("corpus too small for %s" % name)
178        (out / ("prompt-%s.txt" % name)).write_text(tok.decode(allids[:n]), encoding="utf-8")
179        print(name, n, "tokens")
180
181
182def load_prompt(out, name):
183    return (Path(out) / ("prompt-%s.txt" % name)).read_text(encoding="utf-8")
184
185
186def cmd_run(a):
187    m = json.load(open(a.machine))
188    out = Path(a.out)
189    (out / "raw").mkdir(parents=True, exist_ok=True)
190    cfgs = [c for c in m["configs"] if not a.configs or c["name"] in a.configs.split(",")]
191    cells = [c for c in CELLS if not a.cells or c[0] in a.cells.split(",")]
192    prompts = {c[0]: load_prompt(out, c[0]) for c in cells}
193    for rnd in range(a.start_round, a.start_round + a.rounds):
194        order = cfgs if rnd % 2 == 0 else cfgs[::-1]
195        for cfg in order:
196            eng = Engine(m, cfg)
197            rec_path = out / "raw" / ("%s.jsonl" % cfg["name"])
198            try:
199                eng.start(str(out))
200                eng.chat("Say hello.", 0.0, 16)                              # warm-up, discarded
201                eng.chat(prompts["4k"][:6000] if "4k" in prompts else "hi", 0.0, 32)
202                for cname, n, reps in cells:
203                    for t in TEMPS:
204                        for k in range(reps):
205                            nonce = "[bench %s r%d %s t%.1f k%d %d]\n" % (cfg["name"], rnd, cname, t, k, time.time())
206                            r = eng.chat(nonce + prompts[cname] + "\n\nSummarize the text above in three sentences.", t)
207                            r.update(config=cfg["name"], round=rnd, cell=cname, temp=t, rep=k,
208                                     vram_peak_mib=eng.sampler.vram, vram_base_mib=eng.base_vram,
209                                     rss_peak_gib=round(eng.sampler.rss / 2**30, 2),
210                                     sys_used_delta_gib=round((eng.sampler.sysused - eng.base_used) / 2**30, 2),
211                                     load_s=round(eng.load_s, 1), cmd=eng.cmdline if (rnd == a.start_round and k == 0) else None)
212                            r["text"] = r["text"][:300]
213                            with open(rec_path, "a", encoding="utf-8") as f:
214                                f.write(json.dumps(r) + "\n")
215                            print(cfg["name"], rnd, cname, t, "pp %s tg %s draft %s/%s ttft %s" % (
216                                r["prompt_tps"], r["pred_tps"], r["draft_acc"], r["draft_n"], r["prompt_ms"]), flush=True)
217            except Exception as e:
218                print("ERROR", cfg["name"], rnd, repr(e), flush=True)
219                with open(out / "raw" / "errors.log", "a") as f:
220                    f.write("%s r%d %r\n" % (cfg["name"], rnd, e))
221            finally:
222                eng.stop()
223
224
225QPROMPT = "Write a short story about a lighthouse keeper."
226
227
228def cmd_quality(a):
229    m = json.load(open(a.machine))
230    out = Path(a.out)
231    (out / "raw").mkdir(parents=True, exist_ok=True)
232    cfgs = [c for c in m["configs"] if not a.configs or c["name"] in a.configs.split(",")]
233    res = {}
234    for cfg in cfgs:
235        eng = Engine(m, cfg)
236        try:
237            eng.start(str(out))
238            eng.chat("Say hello.", 0.0, 16)
239            for q in (QPROMPT, "Write a Python function that parses a CSV file into a list of dicts, with tests."):
240                r = eng.chat(q, 0.0, 200)
241                res.setdefault(cfg["name"], []).append(r["text"])
242        finally:
243            eng.stop()
244    (out / "raw" / "quality.json").write_text(json.dumps(res, indent=1), encoding="utf-8")
245
246
247def cmd_summary(a):
248    out = Path(a.out)
249    rows = {}
250    for f in sorted((out / "raw").glob("*.jsonl")):
251        for line in open(f, encoding="utf-8"):
252            r = json.loads(line)
253            rows.setdefault((r["config"], r["cell"], r["temp"]), []).append(r)
254    med = lambda xs: statistics.median(xs) if xs else float("nan")
255    print("| config | ctx | temp | n | prompt tok/s | decode tok/s | TTFT s | draft acc | VRAM peak MiB (delta) | RSS GiB |")
256    print("|---|---|---|---|---|---|---|---|---|---|")
257    for (c, cell, t), rs in sorted(rows.items()):
258        pp = [r["prompt_tps"] for r in rs if r["prompt_tps"]]
259        tg = [r["pred_tps"] for r in rs if r["pred_tps"]]
260        tt = [r["prompt_ms"] / 1000 for r in rs if r["prompt_ms"]]
261        da = [r["draft_acc"] / r["draft_n"] for r in rs if r.get("draft_n")]
262        print("| %s | %s | %.1f | %d | %.1f | %.2f | %.2f | %s | %d (+%d) | %.1f |" % (
263            c, cell, t, len(rs), med(pp), med(tg), med(tt), ("%.2f" % med(da)) if da else "-",
264            max(r["vram_peak_mib"] for r in rs), max(r["vram_peak_mib"] - r["vram_base_mib"] for r in rs),
265            max(r["rss_peak_gib"] for r in rs)))
266
267
268if __name__ == "__main__":
269    ap = argparse.ArgumentParser()
270    ap.add_argument("mode", choices=["prompts", "run", "quality", "summary"])
271    ap.add_argument("--out", required=True)
272    ap.add_argument("--machine")
273    ap.add_argument("--configs")
274    ap.add_argument("--cells")
275    ap.add_argument("--rounds", type=int, default=1)
276    ap.add_argument("--start-round", type=int, default=0)
277    ap.add_argument("--tokenizer")
278    ap.add_argument("--repo")
279    ap.add_argument("--corpus", nargs="*")
280    a = ap.parse_args()
281    {"prompts": cmd_prompts, "run": cmd_run, "quality": cmd_quality, "summary": cmd_summary}[a.mode](a)