okami.mom/strata

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

steve8697Add an RTX 5090 + Ryzen 7 9700X IQ3_XXS benchmark on engine 0.1.39 (#777)c9fc15774

main
12.5 KiB286 linesraw
1#!/usr/bin/env python3
2"""One full-window prompt, then two waves of two overlapping 128000-token prompts.
3
4The installed config is unchanged. Prompt tok/s is fresh tokens / prompt_ms.
5Decode tok/s is engine_generated / decode_ms. A wave records /metrics slot
6samples so overlap is counted from the server, not assumed.
7"""
8import hashlib
9import json
10import threading
11import time
12import urllib.error
13import urllib.request
14from pathlib import Path
15
16ROOT = Path(r"D:\AI\Strata")
17PACK = Path(r"D:\AI\Strata-data\packs\iq3_xxs")
18OUT = Path(r"D:\AI\Strata-data\community-bench-20261004-long")
19URL = "http://127.0.0.1:5310"
20# 262144 context, 8-token slack, 256-token answer.
21FULL = 262144 - 8 - 256
22LONG = 128000
23MODEL = "qwen3.8-flash-next-iq3_xxs"
24
25
26def get(path):
27    with urllib.request.urlopen(URL + path, timeout=30) as response:
28        return json.load(response)
29
30
31def post(body):
32    wire = urllib.request.Request(
33        URL + "/v1/chat/completions", data=body,
34        headers={"Content-Type": "application/json"})
35    chunks, texts, first, finish = [], [], None, None
36    started = time.perf_counter()
37    wall = time.time()
38    try:
39        response = urllib.request.urlopen(wire, timeout=1800)
40    except urllib.error.HTTPError as error:
41        detail = error.read().decode("utf-8", "replace")[:800]
42        raise RuntimeError(f"HTTP {error.code}: {detail}") from error
43    with response:
44        for line in response:
45            if not line.startswith(b"data: "):
46                continue
47            payload = line[6:].strip()
48            if payload == b"[DONE]":
49                break
50            chunk = json.loads(payload)
51            chunks.append(chunk)
52            for choice in chunk.get("choices", []):
53                delta = choice.get("delta", {})
54                text = (delta.get("content") or "") + (delta.get("reasoning_content") or "")
55                if text:
56                    first = first if first is not None else time.perf_counter() - started
57                    texts.append(text)
58                finish = choice.get("finish_reason") or finish
59    elapsed = time.perf_counter() - started
60    usage = next((chunk["usage"] for chunk in reversed(chunks) if "usage" in chunk), {})
61    return {"client_ttft_s": first, "client_elapsed_s": elapsed, "client_start": wall,
62            "finish_reason": finish, "usage": usage, "text": "".join(texts), "chunks": len(chunks)}
63
64
65def request(content, maximum=256):
66    return {"model": MODEL, "messages": [{"role": "user", "content": content}],
67            "temperature": 0, "reasoning_effort": "none", "max_tokens": maximum,
68            "stream": True, "stream_options": {"include_usage": True}}
69
70
71def progress(text):
72    print(text, flush=True)
73    path = OUT / "progress.txt"
74    previous = path.read_text(encoding="utf-8") if path.exists() else ""
75    path.write_text(previous + time.strftime("%H:%M:%S ") + text + "\n", encoding="utf-8")
76
77
78def rates(engine):
79    reused = engine.get("reused") or 0
80    prompt_ms = engine.get("prompt_ms") or 0
81    decode_ms = engine.get("decode_ms") or 0
82    generated = engine.get("engine_generated") or 0
83    fresh = (engine.get("prompt_tokens") or 0) - reused
84    return {
85        "prefill_tok_s": (fresh / (prompt_ms / 1000)) if prompt_ms else None,
86        "decode_tok_s": (generated / (decode_ms / 1000)) if decode_ms and generated else None,
87    }
88
89
90def assign_engines(pairs):
91    """pairs: (name, client_start, prompt_tokens). One history row each."""
92    history = list(get("/metrics?requests=all")["requests"])
93    assigned = {}
94    for name, start, tokens in sorted(pairs, key=lambda item: item[1]):
95        candidates = [row for row in history
96                      if row.get("prompt_tokens") == tokens and abs((row.get("time") or 0) - start) <= 180]
97        if not candidates:
98            assigned[name] = None
99            continue
100        best = min(candidates, key=lambda row: abs((row.get("time") or 0) - start))
101        history.remove(best)
102        assigned[name] = best
103    return assigned
104
105
106def main():
107    import sys
108    OUT.mkdir(parents=True, exist_ok=True)
109    sys.path[:0] = [str(ROOT), str(ROOT / "tools")]
110    from strata_tokenizer import Tokenizer
111    from serve.frontend import ChatTemplate, openai_to_messages
112
113    directory = PACK / "tokenizer"
114    vocab = json.loads((directory / "vocab.json").read_text(encoding="utf-8"))
115    tokens = [None] * len(vocab)
116    for token, number in vocab.items():
117        tokens[number] = token
118    tokenizer = Tokenizer(
119        tokens, (directory / "merges.txt").read_text(encoding="utf-8").splitlines(),
120        json.loads((directory / "token_type.json").read_text(encoding="utf-8")))
121    template = ChatTemplate(directory / "chat_template.jinja")
122
123    def count(req):
124        messages, tools, kwargs = openai_to_messages(req)
125        return len(tokenizer.encode(template.render(messages, tools, **kwargs), parse_special=True))
126
127    (OUT / "initial-status.json").write_text(
128        json.dumps(get("/v1/status"), indent=2) + "\n", encoding="utf-8")
129    (OUT / "initial-metrics.json").write_text(
130        json.dumps(get("/metrics"), indent=2) + "\n", encoding="utf-8")
131
132    ending = ("\n\nWrite a detailed explanation of the code above. Discuss deterministic integer transforms, "
133              "modulo arithmetic, testing, naming, complexity, and maintainability. Write at least 600 words.")
134
135    def build(label, target):
136        prefix = f"Benchmark nonce: {label}.\nReview this synthetic Python module:\n"
137        lines = 8000
138        filler = ""
139        while True:
140            filler = "\n".join(
141                f"def task_{i:05d}(value: int) -> int: return (value * {(i % 97) + 1} + {i}) % 100003"
142                for i in range(lines))
143            total = count(request(prefix + filler + ending))
144            progress(f"size {label} lines={lines} tokens={total} target={target}")
145            if total >= target or lines >= 40000:
146                break
147            lines += 4000
148        lo, hi = 0, len(filler)
149        while lo < hi:
150            middle = (lo + hi + 1) // 2
151            if count(request(prefix + filler[:middle] + ending)) <= target:
152                lo = middle
153            else:
154                hi = middle - 1
155        req = request(prefix + filler[:lo] + ending)
156        actual = count(req)
157        if actual < target - 20 or actual > target:
158            raise RuntimeError(f"could not construct {label} target {target}: got {actual}")
159        return req, actual
160
161    def perform(label, req, expected):
162        body = json.dumps(req).encode()
163        (OUT / f"{label}-request.json").write_bytes(body + b"\n")
164        progress(f"start {label} tokens {expected} bytes {len(body)}")
165        client = post(body)
166        if not client["text"]:
167            raise RuntimeError(f"no text received for {label}")
168        engine = assign_engines([(label, client["client_start"], expected)])[label]
169        if engine is None:
170            raise RuntimeError(f"no /metrics row for {label}")
171        if engine.get("prompt_tokens") != expected:
172            raise RuntimeError(f"token count mismatch for {label}: {expected} vs {engine.get('prompt_tokens')}")
173        row = {"label": label, "expected_prompt_tokens": expected,
174               "request_sha256": hashlib.sha256(body).hexdigest(),
175               **{k: v for k, v in client.items() if k != "chunks"},
176               "stream_chunks": client["chunks"], "engine": engine, **rates(engine)}
177        (OUT / f"{label}-row.json").write_text(json.dumps(row, indent=2) + "\n", encoding="utf-8")
178        progress("done " + label + " " + json.dumps({
179            "ttft_s": row["client_ttft_s"], "elapsed_s": row["client_elapsed_s"],
180            "prefill_tok_s": row["prefill_tok_s"], "decode_tok_s": row["decode_tok_s"],
181            "reused": engine.get("reused"), "finish": row["finish_reason"],
182            "drafts": [engine.get("drafts_accepted"), engine.get("drafts_offered")],
183            "hit_rate": engine.get("hit_rate"), "pcie_share": engine.get("pcie_share")}))
184        return row
185
186    rows = []
187    progress("warmup")
188    warm = perform("warmup", request("Reply with exactly the word READY.", 16), None) if False else None
189    # Warmup has no expected token count. Run it without the equality check.
190    body = json.dumps(request("Reply with exactly the word READY.", 16)).encode()
191    client = post(body)
192    progress(f"warmup ttft {client['client_ttft_s']} finish {client['finish_reason']}")
193    (OUT / "warmup-row.json").write_text(json.dumps(client, indent=2) + "\n", encoding="utf-8")
194
195    for run in (1, 2):
196        req, actual = build(f"full-window-run-{run}", FULL)
197        rows.append(perform(f"full-window-run-{run}", req, actual))
198        (OUT / "results.json").write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8")
199
200    def wave(number):
201        left_req, left_n = build(f"wave-{number}-a", LONG)
202        right_req, right_n = build(f"wave-{number}-b", LONG)
203        jobs = (("a", left_req, left_n), ("b", right_req, right_n))
204        bodies = {}
205        for name, req, _expected in jobs:
206            bodies[name] = json.dumps(req).encode()
207            (OUT / f"wave-{number}-{name}-request.json").write_bytes(bodies[name] + b"\n")
208        samples = []
209        stop = threading.Event()
210
211        def sample():
212            while not stop.is_set():
213                try:
214                    live = get("/metrics")["live"]
215                    samples.append({"t": time.time(), "state": live.get("state"),
216                                     "running": live.get("running"), "outside_slots": live.get("outside_slots"),
217                                     "waiting": live.get("waiting"), "slots": live.get("slots")})
218                except (OSError, ValueError, urllib.error.URLError):
219                    pass
220                stop.wait(2)
221
222        sampler = threading.Thread(target=sample, daemon=True)
223        barrier = threading.Barrier(2)
224        found = {}
225        errors = {}
226
227        def worker(name, expected):
228            try:
229                barrier.wait(timeout=120)
230                progress(f"start wave-{number}-{name} tokens {expected}")
231                client = post(bodies[name])
232                found[name] = (expected, client)
233            except Exception as error:
234                errors[name] = f"{type(error).__name__}: {error}"
235
236        sampler.start()
237        threads = [threading.Thread(target=worker, args=(name, expected)) for name, _req, expected in jobs]
238        for thread in threads:
239            thread.start()
240        for thread in threads:
241            thread.join()
242        stop.set()
243        sampler.join(timeout=5)
244        (OUT / f"wave-{number}-slots.json").write_text(
245            json.dumps(samples, indent=2) + "\n", encoding="utf-8")
246        if errors:
247            raise RuntimeError(f"wave {number} failed: {errors}")
248        active = 0
249        for sample_row in samples:
250            busy = [slot for slot in (sample_row.get("slots") or []) if slot.get("state") != "idle"]
251            active = max(active, len(busy))
252        paired = assign_engines([
253            (name, found[name][1]["client_start"], found[name][0]) for name, _req, _expected in jobs])
254        for name, _req, expected in jobs:
255            got, client = found[name]
256            if not client["text"]:
257                raise RuntimeError(f"wave {number} {name} returned no text")
258            engine = paired[name]
259            if engine is None:
260                raise RuntimeError(f"wave {number} {name} has no /metrics row")
261            row = {"label": f"wave-{number}-{name}", "expected_prompt_tokens": got,
262                   "request_sha256": hashlib.sha256(bodies[name]).hexdigest(),
263                   "overlap_samples": len(samples), "max_busy_slots_seen": active,
264                   **{k: v for k, v in client.items() if k != "chunks"},
265                   "stream_chunks": client["chunks"], "engine": engine, **rates(engine)}
266            rows.append(row)
267            progress("done " + row["label"] + " " + json.dumps({
268                "ttft_s": row["client_ttft_s"], "elapsed_s": row["client_elapsed_s"],
269                "prefill_tok_s": row["prefill_tok_s"], "decode_tok_s": row["decode_tok_s"],
270                "reused": engine.get("reused"), "finish": row["finish_reason"],
271                "drafts": [engine.get("drafts_accepted"), engine.get("drafts_offered")],
272                "hit_rate": engine.get("hit_rate"), "max_busy_slots_seen": active}))
273        (OUT / "results.json").write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8")
274
275    wave(1)
276    wave(2)
277    (OUT / "summary.json").write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8")
278    progress("complete")
279
280
281if __name__ == "__main__":
282    try:
283        main()
284    except Exception as error:
285        progress(f"ERROR {type(error).__name__}: {error}")
286        raise