okami.mom/strata

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

Niko1221Merge f-142c-small into f-142407ea8192

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