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