okami.mom/strata

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

steve8697Add an RTX 5090 + Ryzen 7 9700X IQ3_S benchmark on engine 0.1.39 (#811)75b055490

main
9.1 KiB187 linesraw
1#!/usr/bin/env python3
2"""Serial fresh-prompt benchmark for the installed IQ3_S server.
3
4Same shape as the 2026-10-04 IQ3_XXS community run, plus three prompts that
5fill this host's 262144-token window. The full-window prompt is 261880 tokens
6so a 256-token answer still fits: the server keeps 8 tokens of slack and
7refuses a request that would pass the limit.
8"""
9import argparse
10import hashlib
11import json
12import statistics
13import subprocess
14import sys
15import threading
16import time
17import urllib.request
18from pathlib import Path
19
20
21def get(url):
22    with urllib.request.urlopen(url, timeout=30) as response:
23        return json.load(response)
24
25
26def main():
27    parser = argparse.ArgumentParser(description=__doc__)
28    parser.add_argument("--root", type=Path, default=Path(r"D:\AI\Strata"))
29    parser.add_argument("--pack", type=Path, default=Path(r"D:\AI\Strata-data\packs\iq3_s"))
30    parser.add_argument("--url", default="http://127.0.0.1:5310")
31    parser.add_argument("--out", type=Path, default=Path(r"D:\AI\Strata-data\community-bench-20261005-iq3s"))
32    parser.add_argument("--targets", default="4096,32768,128000,261880")
33    parser.add_argument("--runs", type=int, default=3)
34    parser.add_argument("--model", default="qwen3.8-flash-next-iq3_s")
35    args = parser.parse_args()
36    args.out.mkdir(parents=True, exist_ok=True)
37    sys.path[:0] = [str(args.root), str(args.root / "tools")]
38    from strata_tokenizer import Tokenizer
39    from serve.frontend import ChatTemplate, openai_to_messages
40
41    directory = args.pack / "tokenizer"
42    vocab = json.loads((directory / "vocab.json").read_text(encoding="utf-8"))
43    tokens = [None] * len(vocab)
44    for token, number in vocab.items():
45        tokens[number] = token
46    tokenizer = Tokenizer(tokens, (directory / "merges.txt").read_text(encoding="utf-8").splitlines(),
47                          json.loads((directory / "token_type.json").read_text(encoding="utf-8")))
48    template = ChatTemplate(directory / "chat_template.jinja")
49    initial = get(args.url + "/v1/status")
50    (args.out / "initial-status.json").write_text(json.dumps(initial, indent=2) + "\n", encoding="utf-8")
51    metrics0 = get(args.url + "/metrics")
52    (args.out / "initial-metrics.json").write_text(json.dumps(metrics0, indent=2) + "\n", encoding="utf-8")
53    rows = []
54    stop = threading.Event()
55    tel_path = args.out / "telemetry.csv"
56    progress_path = args.out / "progress.txt"
57
58    def progress(line):
59        print(line, flush=True)
60        with progress_path.open("a", encoding="utf-8") as fh:
61            fh.write(line + "\n")
62
63    def sample():
64        if not tel_path.exists():
65            tel_path.write_text("unix,mem_used_mib,util_gpu,pcie_gen,pcie_width,power_w\n", encoding="utf-8")
66        while not stop.is_set():
67            try:
68                out = subprocess.check_output(
69                    ["nvidia-smi",
70                     "--query-gpu=memory.used,utilization.gpu,pcie.link.gen.current,pcie.link.width.current,power.draw",
71                     "--format=csv,noheader,nounits"],
72                    text=True, timeout=15).strip()
73                with tel_path.open("a", encoding="utf-8") as fh:
74                    fh.write(f"{time.time():.0f},{out}\n")
75            except (OSError, subprocess.SubprocessError):
76                pass
77            stop.wait(5)
78
79    threading.Thread(target=sample, daemon=True).start()
80
81    def request(content, maximum=256):
82        return {"model": args.model,
83                "messages": [{"role": "user", "content": content}],
84                "temperature": 0, "reasoning_effort": "none", "max_tokens": maximum,
85                "stream": True, "stream_options": {"include_usage": True}}
86
87    def count(req):
88        messages, tools, kwargs = openai_to_messages(req)
89        return len(tokenizer.encode(template.render(messages, tools, **kwargs), parse_special=True))
90
91    def perform(label, req, expected=None):
92        body = json.dumps(req).encode()
93        (args.out / (label + "-request.json")).write_bytes(body + b"\n")
94        progress(f"start {label} tokens {expected}")
95        chunks, texts, first, finish = [], [], None, None
96        started = time.perf_counter()
97        wire = urllib.request.Request(args.url + "/v1/chat/completions", data=body,
98                                      headers={"Content-Type": "application/json"})
99        with urllib.request.urlopen(wire, timeout=3600) as response:
100            for line in response:
101                if not line.startswith(b"data: "):
102                    continue
103                payload = line[6:].strip()
104                if payload == b"[DONE]":
105                    break
106                chunk = json.loads(payload)
107                chunks.append(chunk)
108                for choice in chunk.get("choices", []):
109                    delta = choice.get("delta", {})
110                    text = (delta.get("content") or "") + (delta.get("reasoning_content") or "")
111                    if text:
112                        first = first if first is not None else time.perf_counter() - started
113                        texts.append(text)
114                    finish = choice.get("finish_reason") or finish
115        elapsed = time.perf_counter() - started
116        metrics = get(args.url + "/metrics")
117        engine = metrics["requests"][0]
118        usage = next((chunk["usage"] for chunk in reversed(chunks) if "usage" in chunk), {})
119        row = {"label": label, "expected_prompt_tokens": expected,
120               "request_sha256": hashlib.sha256(body).hexdigest(),
121               "client_ttft_s": first, "client_elapsed_s": elapsed, "finish_reason": finish,
122               "usage": usage, "engine": engine, "text": "".join(texts)}
123        if expected is not None and engine.get("prompt_tokens") != expected:
124            raise RuntimeError(f"token count mismatch: {expected} vs {engine.get('prompt_tokens')}")
125        if not texts:
126            raise RuntimeError(f"no text received for {label}")
127        (args.out / (label + "-raw.json")).write_text(
128            json.dumps({"chunks": chunks, "row": row}, indent=2) + "\n", encoding="utf-8")
129        rows.append(row)
130        (args.out / "results.json").write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8")
131        progress("done " + label + " " + json.dumps({
132            "ttft_s": first, "elapsed_s": elapsed,
133            "prompt_tokens": engine.get("prompt_tokens"), "reused": engine.get("reused"),
134            "prompt_ms": engine.get("prompt_ms"), "decode_ms": engine.get("decode_ms"),
135            "engine_generated": engine.get("engine_generated"),
136            "finish": finish}))
137        return row
138
139    try:
140        perform("warmup", request("Reply with exactly the word READY.", 16))
141        filler = "\n".join(
142            f"def task_{i:05d}(value: int) -> int: return (value * {(i % 97) + 1} + {i}) % 100003"
143            for i in range(80000))
144        ending = ("\n\nWrite a detailed explanation of the code above. Discuss deterministic integer transforms, "
145                  "modulo arithmetic, testing, naming, complexity, and maintainability. Write at least 600 words.")
146        for target in map(int, args.targets.split(",")):
147            for run in range(1, args.runs + 1):
148                prefix = f"Benchmark nonce: series-{target}-trial-{run}.\nReview this synthetic Python module:\n"
149                lo, hi = 0, len(filler)
150                while lo < hi:
151                    middle = (lo + hi + 1) // 2
152                    if count(request(prefix + filler[:middle] + ending)) <= target:
153                        lo = middle
154                    else:
155                        hi = middle - 1
156                req = request(prefix + filler[:lo] + ending)
157                actual = count(req)
158                if actual < target - 20 or actual > target:
159                    raise RuntimeError(f"could not construct target {target}: {actual}")
160                perform(f"tokens-{target}-run-{run}", req, actual)
161        measured = [row for row in rows if row["label"] != "warmup"]
162        groups = {}
163        for target in map(int, args.targets.split(",")):
164            subset = [r for r in measured if r["label"].startswith(f"tokens-{target}-")]
165            values = {
166                "prompt_tokens": [r["engine"]["prompt_tokens"] for r in subset],
167                "cached_tokens": [r["engine"].get("reused") or 0 for r in subset],
168                "output_tokens": [r["engine"]["engine_generated"] for r in subset],
169                "client_ttft_s": [r["client_ttft_s"] for r in subset],
170                "client_elapsed_s": [r["client_elapsed_s"] for r in subset],
171                "prefill_tok_s": [
172                    (r["engine"]["prompt_tokens"] - (r["engine"].get("reused") or 0))
173                    / (r["engine"]["prompt_ms"] / 1000) for r in subset],
174                "decode_tok_s": [
175                    r["engine"]["engine_generated"] / (r["engine"]["decode_ms"] / 1000) for r in subset],
176            }
177            groups[str(target)] = {
178                key: {"median": statistics.median(v), "min": min(v), "max": max(v)}
179                for key, v in values.items()}
180        (args.out / "summary.json").write_text(json.dumps(groups, indent=2) + "\n", encoding="utf-8")
181        progress("summary " + json.dumps(groups))
182    finally:
183        stop.set()
184
185
186if __name__ == "__main__":
187    main()