okami.mom/strata

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

HarukiOtakubench: Windows 11 + Radeon AI PRO R9700 (gfx1201), IQ2_XS, 4K to 248K prompt tokens (#618)34ee68774

main
19.6 KiB447 linesraw
1#!/usr/bin/env python3
2"""
3Strata community benchmark harness — standard library only.
4
5Measures prompt processing (prefill) and decode through the local Strata server,
6mirroring the method used in bench/results/2026-09-30-community-rtx-5090:
7
8  * synthetic Python-like filler of a requested size,
9  * a unique nonce near the start of every request (defeats conversation-prefix
10    reuse so every run processes its whole prompt),
11  * greedy decoding, fixed output cap,
12  * actual token counts taken from the engine's own log line,
13  * client-side time-to-first-token and total latency,
14  * optional needle-in-a-haystack recall checks.
15
16Outputs bench-output.json, bench-output.md and bench-output.txt next to this file.
17
18Usage (run from the folder that has this file):
19  .venv\\Scripts\\python.exe benchmark.py --url http://127.0.0.1:8080/v1/chat/completions \
20      --log D:\\AI\\Strata\\Strata-main\\Strata-main\\strata-iq2_xs.log \
21      --lengths 4096,32768,128000 --reps 3 --needle-lengths 32768,128000 --needle-depths 10,50,90
22"""
23
24from __future__ import annotations
25
26import argparse
27import json
28import os
29import re
30import statistics
31import sys
32import time
33import urllib.error
34import urllib.request
35from pathlib import Path
36
37HERE = Path(__file__).resolve().parent
38NEEDLE = "7-BLUE-MAGNET-4417"
39PROMPT_LINE = re.compile(
40    r"prompt (\d+) tokens = (\d+) reused \+ (\d+) read in (\d+) ms \(([\d.]+) tok/s\), "
41    r"(\d+) generated in (\d+) ms \(([\d.]+) tok/s\)"
42)
43
44
45# ----------------------------------------------------------------------------- prompts
46def code_filler(chars: int, seed: int) -> str:
47    """Deterministic Python-like filler of roughly `chars` characters."""
48    out = []
49    n = 0
50    size = 0
51    while size < chars:
52        n += 1
53        k = (seed + n) % 97 + 3
54        block = (
55            f"def transform_{seed:04d}_{n:05d}(value: int, scale: int = {k}) -> int:\n"
56            f'    """Scale a value by {k} and fold it into the working range."""\n'
57            f"    folded = (value * scale + {n} * 17) % {1000003 + n}\n"
58            f"    if folded % {k} == 0:\n"
59            f"        return folded // {k} + {n}\n"
60            f"    return folded - {n} * scale\n"
61            f"\n"
62        )
63        out.append(block)
64        size += len(block)
65    return "".join(out)[:chars]
66
67
68def build_prompt(target_tokens: int, seed: int, chars_per_token: float, needle_depth: int | None) -> str:
69    """Assemble one benchmark request: instruction + nonce + filler (+ needle)."""
70    filler_chars = max(2000, int(target_tokens * chars_per_token))
71    body = code_filler(filler_chars, seed)
72    nonce = f"{seed:04d}-{int(time.time() * 1000) % 100000:05d}"
73    head = (
74        f"You are reviewing a Python file. The file starts with the marker NONCE {nonce}.\n"
75        f"Explain in three short paragraphs what the functions in this file do.\n\n"
76        f"# NONCE {nonce}\n"
77    )
78    if needle_depth is not None:
79        cut = int(len(body) * needle_depth / 100.0)
80        # move the cut to the next newline so the file stays syntactically plausible
81        cut = body.find("\n", cut)
82        cut = len(body) if cut < 0 else cut
83        body = body[:cut] + f'\nVAULT_CODE = "{NEEDLE}"  # keep this exact value\n' + body[cut:]
84        head = (
85            f"You are reviewing a Python file. The file starts with the marker NONCE {nonce}.\n"
86            f"Answer the question about the file at the end, using only what the file says.\n\n"
87            f"# NONCE {nonce}\n"
88        )
89        tail = "\n\nQuestion: what is the exact value assigned to VAULT_CODE in this file? " \
90               "Answer with the value only, nothing else.\n"
91    else:
92        tail = "\n\nAnswer in English, three short paragraphs.\n"
93    return head + body + tail
94
95
96# ----------------------------------------------------------------------------- engine log
97class EngineLog:
98    def __init__(self, path: Path | None):
99        self.path = path
100        self.offset = 0
101        if path and path.exists():
102            self.offset = path.stat().st_size
103
104    def new_lines(self) -> list[str]:
105        if not self.path or not self.path.exists():
106            return []
107        try:
108            with self.path.open("r", encoding="utf-8", errors="replace") as fh:
109                fh.seek(self.offset)
110                data = fh.read()
111                self.offset = fh.tell()
112        except OSError:
113            return []
114        return [ln.strip() for ln in data.replace("\r", "\n").split("\n") if ln.strip()]
115
116    def last_request_stats(self) -> dict | None:
117        for line in reversed(self.new_lines()):
118            m = PROMPT_LINE.search(line)
119            if m:
120                return {
121                    "engine_prompt_tokens": int(m.group(1)),
122                    "reused_tokens": int(m.group(2)),
123                    "new_prompt_tokens": int(m.group(3)),
124                    "read_ms": int(m.group(4)),
125                    "read_tok_s": float(m.group(5)),
126                    "generated_tokens": int(m.group(6)),
127                    "gen_ms": int(m.group(7)),
128                    "decode_tok_s": float(m.group(8)),
129                }
130        return None
131
132
133# ----------------------------------------------------------------------------- HTTP
134def post_chat(url: str, payload: dict, timeout: int):
135    """POST /v1/chat/completions. Returns (ttft_s, total_s, text, reasoning, usage, finish_reason)."""
136    body = json.dumps(payload).encode()
137    req = urllib.request.Request(url, data=body, headers={"Content-Type": "application/json"})
138    started = time.time()
139    ttft = None
140    text_parts: list[str] = []
141    reasoning_parts: list[str] = []
142    usage = None
143    finish = None
144    with urllib.request.urlopen(req, timeout=timeout) as resp:
145        ctype = resp.headers.get("Content-Type", "")
146        if "text/event-stream" in ctype:
147            for raw in resp:
148                line = raw.decode("utf-8", "replace").strip()
149                if not line.startswith("data:"):
150                    continue
151                chunk = line[5:].strip()
152                if chunk in ("", "[DONE]"):
153                    continue
154                try:
155                    obj = json.loads(chunk)
156                except json.JSONDecodeError:
157                    continue
158                if obj.get("usage"):
159                    usage = obj["usage"]
160                for choice in obj.get("choices", []):
161                    if choice.get("finish_reason"):
162                        finish = choice["finish_reason"]
163                    delta = choice.get("delta") or {}
164                    piece = delta.get("content") or ""
165                    think = delta.get("reasoning_content") or delta.get("reasoning") or ""
166                    if think:
167                        reasoning_parts.append(think)
168                    if piece:
169                        if ttft is None:
170                            ttft = time.time() - started
171                        text_parts.append(piece)
172        else:
173            obj = json.loads(resp.read().decode("utf-8", "replace"))
174            usage = obj.get("usage")
175            for choice in obj.get("choices", []):
176                finish = choice.get("finish_reason") or finish
177                msg = choice.get("message") or {}
178                content = msg.get("content") or ""
179                if msg.get("reasoning_content"):
180                    reasoning_parts.append(msg["reasoning_content"])
181                if content and ttft is None:
182                    ttft = time.time() - started
183                text_parts.append(content)
184    total = time.time() - started
185    return ttft, total, "".join(text_parts), "".join(reasoning_parts), usage, finish
186
187
188def detect_model(url: str) -> str:
189    base = url.split("/v1/")[0]
190    try:
191        with urllib.request.urlopen(base + "/v1/models", timeout=15) as resp:
192            data = json.loads(resp.read().decode())
193        items = data.get("data") or data.get("models") or []
194        if items:
195            return items[0].get("id") or items[0].get("name") or "strata"
196    except Exception:
197        pass
198    return "strata"
199
200
201# ----------------------------------------------------------------------------- measurement
202def one_request(url: str, model: str, prompt: str, cap: int, log: EngineLog, timeout: int) -> dict:
203    base = {
204        "model": model,
205        "messages": [{"role": "user", "content": prompt}],
206        "temperature": 0,
207        "max_tokens": cap,
208    }
209    # "reasoning_effort": "none" -> the engine renders the prompt without thinking
210    # (serve/frontend.py EFFORT map).  Without it the model spends the whole output cap
211    # on reasoning_content and message.content stays empty.
212    no_think = dict(base, reasoning_effort="none")
213    variants = [
214        dict(no_think, stream=True, stream_options={"include_usage": True}),
215        dict(no_think, stream=True),
216        dict(no_think, stream=False),
217        dict(base, stream=True, stream_options={"include_usage": True}),
218        dict(base, stream=False),
219    ]
220    row: dict = {"ok": False}
221    last_error = None
222    for idx, payload in enumerate(variants):
223        try:
224            ttft, total, text, reasoning, usage, finish = post_chat(url, payload, timeout)
225            row.update(
226                ok=True,
227                payload_variant=idx,
228                thinking_off="reasoning_effort" in payload,
229                ttft_s=round(ttft, 3) if ttft is not None else None,
230                total_s=round(total, 3),
231                text=text,
232                answer_len=len(text),
233                reasoning_len=len(reasoning),
234                reasoning_text=reasoning[:2000],
235                finish_reason=finish,
236            )
237            if usage:
238                row["usage"] = usage
239            last_error = None
240            break
241        except urllib.error.HTTPError as exc:
242            body = exc.read()[:400].decode("utf-8", "replace")
243            last_error = f"HTTP {exc.code}: {body}"
244            if exc.code not in (400, 404, 415, 422):
245                break
246        except Exception as exc:  # noqa: BLE001
247            last_error = f"{type(exc).__name__}: {exc}"
248            break
249    if last_error:
250        row["error"] = last_error
251    stats = log.last_request_stats()
252    if stats:
253        row.update(stats)
254        # Bind the log line to this request: the server reports the same prompt token
255        # count in the response usage. A mismatch means the line belongs to another
256        # request (or none) and the row must not be trusted.
257        server_tokens = (row.get("usage") or {}).get("prompt_tokens")
258        if server_tokens is None:
259            row["pairing_ok"] = None
260        else:
261            row["pairing_ok"] = abs(int(server_tokens) - int(stats["engine_prompt_tokens"])) <= 1
262            if not row["pairing_ok"]:
263                row["pairing_note"] = (f"server reported {server_tokens} prompt tokens, the engine log line "
264                                       f"has {stats['engine_prompt_tokens']} - the log line may belong to another request")
265    return row
266
267
268def summarise(rows: list[dict]) -> str:
269    cols = ["target", "actual prompt tok", "reused", "new read", "prefill tok/s", "read s",
270            "gen tok", "decode tok/s", "thinking off", "answer len", "finish", "TTFT s", "total s"]
271    lines = ["| " + " | ".join(cols) + " |", "|" + "---|" * len(cols)]
272    for r in rows:
273        if not r.get("ok"):
274            lines.append("| " + " | ".join([str(r.get("target"))] +
275                                           [f"FAILED: {str(r.get('error'))[:60]}"] +
276                                           [""] * (len(cols) - 2)) + " |")
277            continue
278        vals = [
279            r.get("target"), r.get("engine_prompt_tokens", "?"), r.get("reused_tokens", "?"),
280            r.get("new_prompt_tokens", "?"), r.get("read_tok_s", "?"),
281            f"{(r.get('read_ms') or 0) / 1000:.1f}",
282            r.get("generated_tokens", "?"), r.get("decode_tok_s", "?"),
283            r.get("thinking_off"), r.get("answer_len"), r.get("finish_reason"),
284            r.get("ttft_s"), r.get("total_s"),
285        ]
286        lines.append("| " + " | ".join(str(v) for v in vals) + " |")
287    groups: dict[int, list[float]] = {}
288    for r in rows:
289        if r.get("ok") and r.get("read_tok_s"):
290            groups.setdefault(r.get("target"), []).append(r["read_tok_s"])
291    lines.append("")
292    for target, vals in sorted(groups.items()):
293        dec = [r["decode_tok_s"] for r in rows if r.get("ok") and r.get("target") == target and r.get("decode_tok_s")]
294        lines.append(
295            f"* {target} prompt tokens: prefill median {statistics.median(vals):.1f} tok/s "
296            f"(range {min(vals):.1f}-{max(vals):.1f}, n={len(vals)})"
297            + (f"; decode median {statistics.median(dec):.1f} tok/s "
298               f"(range {min(dec):.1f}-{max(dec):.1f})" if dec else "")
299        )
300    return "\n".join(lines)
301
302
303def main() -> int:
304    ap = argparse.ArgumentParser()
305    ap.add_argument("--url", default="http://127.0.0.1:8080/v1/chat/completions")
306    ap.add_argument("--log", default=r"D:\AI\Strata\Strata-main\Strata-main\strata-iq2_xs.log")
307    ap.add_argument("--lengths", default="4096,32768,128000")
308    ap.add_argument("--reps", type=int, default=3)
309    ap.add_argument("--needle-lengths", default="32768,128000")
310    ap.add_argument("--needle-depths", default="10,50,90")
311    ap.add_argument("--cap", type=int, default=256)
312    ap.add_argument("--timeout", type=int, default=1800)
313    ap.add_argument("--wait-ready", type=int, default=0,
314                    help="poll /v1/models until the engine answers, up to this many seconds")
315    ap.add_argument("--tag", default="", help="suffix for the output files (bench-output-<tag>.json)")
316    ap.add_argument("--skip-needles", action="store_true")
317    ap.add_argument("--model", default=None)
318    args = ap.parse_args()
319
320    log = EngineLog(Path(args.log) if args.log else None)
321    model = args.model or detect_model(args.url)
322    print(f"server   : {args.url}")
323    print(f"model id : {model}")
324    print(f"engine   : {args.log}")
325    if args.tag:
326        print(f"tag      : {args.tag}")
327
328    if args.wait_ready:
329        base = args.url.split("/v1/")[0]
330        ready = False
331        deadline = time.time() + args.wait_ready
332        while time.time() < deadline:
333            try:
334                with urllib.request.urlopen(base + "/v1/models", timeout=10) as resp:
335                    if resp.status == 200:
336                        ready = True
337                        break
338            except Exception:
339                pass
340            print("  waiting for the engine to come up ...", flush=True)
341            time.sleep(5)
342        if not ready:
343            print(f"the engine did not answer within {args.wait_ready} s - stopping.")
344            return 2
345        print("engine is up\n", flush=True)
346
347    results: dict = {
348        "started": time.strftime("%Y-%m-%d %H:%M:%S"),
349        "url": args.url,
350        "model": model,
351        "engine_log": args.log,
352        "cap_tokens": args.cap,
353        "reps": args.reps,
354        "speed": [],
355        "needles": [],
356        "notes": [],
357    }
358
359    # --- calibration: one small request to learn characters-per-token -----------
360    print("\n[calibration] 8,000-char request ...", flush=True)
361    cal_prompt = ("You are reviewing a Python file.\n\n# NONCE 0001\n"
362                  + code_filler(8000, 1) + "\n\nAnswer in one short paragraph.\n")
363    cal = one_request(args.url, model, cal_prompt, 64, log, args.timeout)
364    chars = 8000
365    if cal.get("ok") and cal.get("engine_prompt_tokens"):
366        # prompt tokens includes the instruction wrapper (~40 tok)
367        ratio = (cal["engine_prompt_tokens"] - 40) / chars   # tokens per character
368        ratio = min(1.5, max(0.15, ratio))                   # sane bounds
369        chars_per_token = 1.0 / ratio
370        print(f"[calibration] {cal['engine_prompt_tokens']} prompt tokens for {chars} chars "
371              f"-> {chars_per_token:.3f} chars/token", flush=True)
372    else:
373        chars_per_token = 4.0
374        results["notes"].append("calibration failed; assumed 4.0 chars/token")
375        print(f"[calibration] FAILED ({cal.get('error')}); assuming 4.0 chars/token", flush=True)
376    results["calibration"] = {k: v for k, v in cal.items() if k != "text"}
377    results["chars_per_token"] = chars_per_token
378    print("warming up (one 2,000-token request) ...", flush=True)
379    warm = one_request(args.url, model, build_prompt(2000, 7, chars_per_token, None), 32, log, args.timeout)
380    results["warmup"] = {k: v for k, v in warm.items() if k != "text"}
381
382    # --- speed runs ------------------------------------------------------------
383    seed = 100
384    for target in [int(x) for x in args.lengths.split(",") if x.strip()]:
385        for rep in range(1, args.reps + 1):
386            seed += 1
387            prompt = build_prompt(target, seed, chars_per_token, None)
388            print(f"[speed] target {target} rep {rep}/{args.reps} "
389                  f"({len(prompt):,} chars) ...", flush=True)
390            row = one_request(args.url, model, prompt, args.cap, log, args.timeout)
391            row.update(target=target, rep=rep, chars=len(prompt))
392            row.pop("text", None)
393            results["speed"].append(row)
394            if row.get("ok"):
395                print(f"        -> prompt {row.get('engine_prompt_tokens')} tok, "
396                      f"reused {row.get('reused_tokens')}, prefill {row.get('read_tok_s')} tok/s, "
397                      f"decode {row.get('decode_tok_s')} tok/s, TTFT {row.get('ttft_s')} s", flush=True)
398            else:
399                print(f"        -> FAILED: {row.get('error')}", flush=True)
400
401    # --- needle checks ---------------------------------------------------------
402    if not args.skip_needles:
403        for target in [int(x) for x in args.needle_lengths.split(",") if x.strip()]:
404            for depth in [int(x) for x in args.needle_depths.split(",") if x.strip()]:
405                seed += 1
406                prompt = build_prompt(target, seed, chars_per_token, depth)
407                print(f"[needle] target {target} depth {depth}% ...", flush=True)
408                row = one_request(args.url, model, prompt, 32, log, args.timeout)
409                found = NEEDLE in ((row.get("text") or "") + (row.get("reasoning_text") or ""))
410                row.update(target=target, depth=depth, needle_found=found, chars=len(prompt))
411                results["needles"].append(row)
412                print(f"        -> needle {'FOUND' if found else 'MISSED'}; "
413                      f"prompt {row.get('engine_prompt_tokens')} tok, "
414                      f"prefill {row.get('read_tok_s')} tok/s", flush=True)
415
416    results["finished"] = time.strftime("%Y-%m-%d %H:%M:%S")
417    results["tag"] = args.tag
418    suffix = f"-{args.tag}" if args.tag else ""
419    out_json = HERE / f"bench-output{suffix}.json"
420    out_json.write_text(json.dumps(results, indent=2), encoding="utf-8")
421
422    table = summarise(results["speed"])
423    needle_lines = ["", "Needle checks (exact string recall):"]
424    for r in results["needles"]:
425        needle_lines.append(
426            f"* {r.get('target')} tokens, depth {r.get('depth')}%: "
427            f"{'FOUND' if r.get('needle_found') else 'MISSED'} "
428            f"(prompt {r.get('engine_prompt_tokens')} tok, prefill {r.get('read_tok_s')} tok/s)"
429        )
430    report = (
431        f"# Strata benchmark output\n\n"
432        f"started {results['started']}, finished {results['finished']}\n"
433        f"server {args.url}, model id `{model}`, output cap {args.cap} tokens, "
434        f"{args.reps} reps per length\n\n## Speed\n\n{table}\n"
435        + ("\n".join(needle_lines) if results["needles"] else "") + "\n"
436    )
437    (HERE / f"bench-output{suffix}.md").write_text(report, encoding="utf-8")
438    (HERE / f"bench-output{suffix}.txt").write_text(report, encoding="utf-8")
439    print("\n" + report)
440    print(f"saved: {out_json}")
441    print(f"saved: {HERE / f'bench-output{suffix}.md'}")
442    print("\nDONE - tell Hermes the run is finished.")
443    return 0
444
445
446if __name__ == "__main__":
447    sys.exit(main())