okami.mom/strata

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

Niko1221Merge branch 'f-1402-w' into f-140253623e56f

main
10.0 KiB198 linesraw
1#!/usr/bin/env python3
2"""Serial, fresh-prompt Strata benchmark (Windows-capable).
3
4Derived from bench/results/2026-09-30-community-rtx-5090/benchmark.py: same synthetic prompts, nonces,
5token targets, greedy decoding, reasoning off and 256-token output cap, so the numbers are comparable.
6Changes: runs with Strata's own Windows venv; a failed or cancelled run is recorded with its error and
7excluded from the statistics instead of stopping the suite; peak host RAM and GPU memory are sampled
8every 0.5 s during each request.
9
10    .venv\\Scripts\\python.exe benchmark.py --root . --pack <data-dir>\\packs\\q2_0 --url http://127.0.0.1:18096 --out results
11"""
12import argparse
13import hashlib
14import json
15import statistics
16import subprocess
17import sys
18import threading
19import time
20import urllib.request
21from pathlib import Path
22
23import psutil
24
25
26def get(url):
27    with urllib.request.urlopen(url, timeout=30) as response:
28        return json.load(response)
29
30
31class Peak:
32    """Samples system-wide host RAM in use (total - available) and GPU memory used while a request runs."""
33
34    def __init__(self, interval=0.5):
35        self.interval, self.ram, self.vram, self._stop = interval, 0, 0, threading.Event()
36
37    def _gpu_mib(self):
38        try:
39            out = subprocess.check_output(["nvidia-smi", "--query-gpu=memory.used", "--format=csv,noheader,nounits"],
40                                          text=True, timeout=5)
41            return int(out.strip().splitlines()[0])
42        except Exception:
43            return 0
44
45    def _run(self):
46        while not self._stop.is_set():
47            vm = psutil.virtual_memory()
48            self.ram = max(self.ram, vm.total - vm.available)
49            self.vram = max(self.vram, self._gpu_mib())
50            self._stop.wait(self.interval)
51
52    def __enter__(self):
53        self._thread = threading.Thread(target=self._run, daemon=True)
54        self._thread.start()
55        return self
56
57    def __exit__(self, *exc):
58        self._stop.set()
59        self._thread.join()
60
61    def as_dict(self):
62        return {"peak_host_ram_used_gib": round(self.ram / 2**30, 2), "peak_gpu_memory_used_mib": self.vram}
63
64
65def main():
66    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
67    parser.add_argument("--root", type=Path, default=Path("."))
68    parser.add_argument("--pack", type=Path, required=True)
69    parser.add_argument("--url", default="http://127.0.0.1:18096")
70    parser.add_argument("--out", type=Path, default=Path("results"))
71    parser.add_argument("--targets", default="4096,32768,128000")
72    parser.add_argument("--runs", type=int, default=3)
73    args = parser.parse_args()
74    args.out.mkdir(parents=True, exist_ok=True)
75    sys.path[:0] = [str(args.root), str(args.root / "tools")]
76    from strata_tokenizer import Tokenizer
77    from serve.frontend import ChatTemplate, openai_to_messages
78    directory = args.pack / "tokenizer"
79    vocab = json.loads((directory / "vocab.json").read_text(encoding="utf-8"))
80    tokens = [None] * len(vocab)
81    for token, number in vocab.items():
82        tokens[number] = token
83    tokenizer = Tokenizer(tokens, (directory / "merges.txt").read_text(encoding="utf-8").splitlines(),
84                          json.loads((directory / "token_type.json").read_text(encoding="utf-8")))
85    template = ChatTemplate(directory / "chat_template.jinja")
86    initial = get(args.url + "/v1/status")
87    (args.out / "initial-status.json").write_text(json.dumps(initial, indent=2) + "\n", encoding="utf-8")
88    rows = []
89
90    def request(content, maximum=256):
91        return {"model": "strata", "messages": [{"role": "user", "content": content}],
92                "temperature": 0, "reasoning_effort": "none", "max_tokens": maximum,
93                "stream": True, "stream_options": {"include_usage": True}}
94
95    def count(req):
96        messages, tools, kwargs = openai_to_messages(req)
97        return len(tokenizer.encode(template.render(messages, tools, **kwargs), parse_special=True))
98
99    def save():
100        (args.out / "results.json").write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8")
101
102    def perform(label, req, expected=None):
103        body = json.dumps(req).encode()
104        (args.out / (label + "-request.json")).write_bytes(body + b"\n")
105        print("start", label, "tokens", expected, flush=True)
106        chunks, texts, first, finish = [], [], None, None
107        started = time.perf_counter()
108        try:
109            with Peak() as peak:
110                wire = urllib.request.Request(args.url + "/v1/chat/completions", data=body,
111                                              headers={"Content-Type": "application/json"})
112                with urllib.request.urlopen(wire, timeout=1800) as response:
113                    for line in response:
114                        if not line.startswith(b"data: "):
115                            continue
116                        payload = line[6:].strip()
117                        if payload == b"[DONE]":
118                            break
119                        chunk = json.loads(payload)
120                        chunks.append(chunk)
121                        for choice in chunk.get("choices", []):
122                            delta = choice.get("delta", {})
123                            text = (delta.get("content") or "") + (delta.get("reasoning_content") or "")
124                            if text:
125                                first = first if first is not None else time.perf_counter() - started
126                                texts.append(text)
127                            finish = choice.get("finish_reason") or finish
128            elapsed = time.perf_counter() - started
129            engine = get(args.url + "/metrics")["requests"][0]
130            usage = next((chunk["usage"] for chunk in reversed(chunks) if "usage" in chunk), {})
131            row = {"label": label, "status": "ok", "expected_prompt_tokens": expected,
132                   "request_sha256": hashlib.sha256(body).hexdigest(),
133                   "client_ttft_s": first, "client_elapsed_s": elapsed, "finish_reason": finish,
134                   "usage": usage, "engine": engine, "memory": peak.as_dict(), "text": "".join(texts)}
135            if expected is not None and engine["prompt_tokens"] != expected:
136                raise RuntimeError(f"token count mismatch: {expected} vs {engine['prompt_tokens']}")
137            if not texts:
138                raise RuntimeError(f"no text received for {label}")
139        except Exception as error:  # recorded, excluded from the statistics
140            row = {"label": label, "status": "failed", "error": repr(error), "expected_prompt_tokens": expected,
141                   "request_sha256": hashlib.sha256(body).hexdigest(),
142                   "client_elapsed_s": time.perf_counter() - started, "text": "".join(texts)}
143        (args.out / (label + "-raw.json")).write_text(json.dumps({"chunks": chunks, "row": row}, indent=2) + "\n",
144                                                      encoding="utf-8")
145        rows.append(row)
146        save()
147        print("done", label, row["status"], json.dumps({k: row.get(k) for k in ("client_ttft_s", "client_elapsed_s", "memory")}),
148              flush=True)
149        return row
150
151    perform("warmup", request("Reply with exactly the word READY.", 16))
152    # Each nonce occurs before the filler so previous long prompts cannot be reused.
153    filler = "\n".join(f"def task_{i:05d}(value: int) -> int: return (value * {(i % 97) + 1} + {i}) % 100003"
154                       for i in range(12000))
155    ending = ("\n\nWrite a detailed explanation of the code above. Discuss deterministic integer transforms, "
156              "modulo arithmetic, testing, naming, complexity, and maintainability. Write at least 600 words.")
157    for target in map(int, args.targets.split(",")):
158        for run in range(1, args.runs + 1):
159            prefix = f"Benchmark nonce: series-{target}-trial-{run}.\nReview this synthetic Python module:\n"
160            lo, hi = 0, len(filler)
161            while lo < hi:
162                middle = (lo + hi + 1) // 2
163                if count(request(prefix + filler[:middle] + ending)) <= target:
164                    lo = middle
165                else:
166                    hi = middle - 1
167            req = request(prefix + filler[:lo] + ending)
168            actual = count(req)
169            if actual < target - 20 or actual > target:
170                raise RuntimeError(f"could not construct target {target}: {actual}")
171            perform(f"tokens-{target}-run-{run}", req, actual)
172    measured = [row for row in rows if row["label"] != "warmup" and row["status"] == "ok"]
173    groups = {}
174    for target in map(int, args.targets.split(",")):
175        subset = [r for r in measured if r["label"].startswith(f"tokens-{target}-")]
176        failed = [r["label"] for r in rows if r["label"].startswith(f"tokens-{target}-") and r["status"] != "ok"]
177        if not subset:
178            groups[str(target)] = {"runs_ok": 0, "failed": failed}
179            continue
180        values = {
181            "prompt_tokens": [r["engine"]["prompt_tokens"] for r in subset],
182            "cached_tokens": [r["engine"].get("reused", 0) for r in subset],
183            "output_tokens": [r["engine"]["engine_generated"] for r in subset],
184            "client_ttft_s": [r["client_ttft_s"] for r in subset],
185            "client_elapsed_s": [r["client_elapsed_s"] for r in subset],
186            "prefill_tok_s": [(r["engine"]["prompt_tokens"] - (r["engine"].get("reused") or 0)) / (r["engine"]["prompt_ms"] / 1000) for r in subset],
187            "decode_tok_s": [r["engine"]["engine_generated"] / (r["engine"]["decode_ms"] / 1000) for r in subset],
188            "peak_host_ram_used_gib": [r["memory"]["peak_host_ram_used_gib"] for r in subset],
189            "peak_gpu_memory_used_mib": [r["memory"]["peak_gpu_memory_used_mib"] for r in subset],
190        }
191        groups[str(target)] = {"runs_ok": len(subset), "failed": failed,
192                               **{key: {"median": statistics.median(v), "min": min(v), "max": max(v)} for key, v in values.items()}}
193    (args.out / "summary.json").write_text(json.dumps(groups, indent=2) + "\n", encoding="utf-8")
194    print("summary", json.dumps(groups), flush=True)
195
196
197if __name__ == "__main__":
198    main()