okami.mom/strata

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

waveringanaedge0-strata: add the engine for Edge0 145B and Edge0 120Bfd19246dc

main
59.6 KiB1143 linesraw
1#!/usr/bin/env python3
2"""One command that measures this Strata install the way it is used, and writes a report you can share.
3
4    BENCH.bat                      (Windows)        ./bench.sh        (Linux)        python tools/strata_bench.py
5
6It starts the server with your existing settings (the newest strata-*.json of this folder, or --config FILE), or uses
7the one already running (it checks the config's port, or --url http://host:port), and sends a fixed suite through the
8real HTTP API, three runs each, medians reported:
9
10  1. chat       three short questions (about 100 tokens out): decode tok/s and time to first token
11  2. 4K prompt  a prompt of about 4,096 tokens: prompt tok/s and time to first token (fresh every run: no cache help)
12  3. 16K prompt the same at about 16,384 tokens (skipped when the context is smaller)
13  4. agent      a coding-agent style session: system prompt + four tools, then five turns, each adding about 1,500 words
14                of a file to the conversation and continuing from the model's own earlier replies - how many prompt
15                tokens the conversation cache reused, how many had to be read again, time to first token per turn
16  5. --clients N   N requests at once (the server needs --batch for them to run together): total tok/s, p50/p95 latency
17  6. --long 32K    the same prompt test at about 32,768 tokens
18
19Speeds are the engine's own timings (the `timings` of the answer: prompt_per_second, predicted_per_second); time to first
20token and latency are measured by this client.  Thinking is off for the suite (--think turns it on), so the answers are
21short and the runs comparable.  The default run takes about 3-10 minutes after the model has loaded (the slower the card, the longer).
22
23The result goes to bench/results/<date>-community-<gpu>-<model>/ : README.md in the format of
24docs/COMMUNITY_BENCHMARKS.md, results.json (every request) and an engine log excerpt.  Home folders, user and host names,
25IP addresses and API keys are replaced by placeholders before anything is written; read it once before you share it.
26`--compare <older results folder>` prints the two side by side.  Standard library only.
27This is the quick speed check, not the standard benchmark: `strata bench run` follows docs/BENCHMARK_PROTOCOL.md (fixed prompts, thinking on,
28the model card sampling, twelve sanity checks) and writes results other people can compare with.
29"""
30from __future__ import annotations
31
32import argparse
33import datetime
34import getpass
35import json
36import os
37import platform
38import re
39import socket
40import statistics
41import subprocess
42import sys
43import tempfile
44import threading
45import time
46import urllib.error
47import urllib.request
48from pathlib import Path
49
50ROOT = Path(__file__).resolve().parents[1]
51sys.path.insert(0, str(Path(__file__).resolve().parent))
52from ab_engine import PROMPTS, long_prompt          # noqa: E402  the same three short questions and word list
53from agent_turns_bench import SYSTEM, TOOLS         # noqa: E402  the same agent system prompt and tool list
54import serve_load                                   # noqa: E402  the burst client for --clients
55
56SCHEMA = 1
57CHAT_MAX_TOKENS = 100
58LONG_MAX_TOKENS = 24
59AGENT_MAX_TOKENS = 64
60AGENT_TURNS = 5
61AGENT_WORDS = 1500
62AGENT_MIN_CONTEXT = 10240      # the last turn of the session holds about 10K tokens
63BURST_MAX_TOKENS = 128
64
65
66# --------------------------------------------------------------------------------------------------------- redaction
67def usable_key(value) -> str:
68    """An API key as a client may send it: "" for nothing, blanks, or "none" in any case (the server's word for no key, #4483)."""
69    if isinstance(value, (list, tuple)):                # a config may list several keys: the first one is the client's
70        value = value[0] if value else None
71    text = "" if value is None else str(value).strip()
72    return "" if text.lower() == "none" else text
73
74
75def redactor(extra: list[str] = (), key: str = ""):
76    """-> f(text) -> text with this machine's home folders, user and host names, the Strata folder, IP addresses and the
77    API key replaced.  Applied to everything that is written or printed from the server's or the machine's own text."""
78    subs: list[tuple[re.Pattern, str, int]] = []
79
80    def add(value, label, word=False, exact=False):
81        if value and len(str(value)) >= 4:
82            v = str(value)
83            for form in sorted({v, v.replace("\\", "/"), v.replace("/", "\\")}, key=len, reverse=True):
84                pat = re.escape(form)
85                subs.append((re.compile(r"(?<![\w-])" + pat + r"(?![\w-])" if word else pat, 0 if exact else re.I), label, len(form)))
86
87    add(ROOT, "<strata>")
88    add(Path.home(), "<home>")
89    add(tempfile.gettempdir(), "<tmp>")
90    try:
91        add(getpass.getuser(), "<user>", True)
92    except Exception:                                   # noqa: BLE001
93        pass
94    add(socket.gethostname(), "<host>", True)
95    add(platform.node(), "<host>", True)
96    for x in extra:
97        add(x, "<private>", True)
98    add(usable_key(key), "<key>", word=True, exact=True)
99    subs.sort(key=lambda s: -s[2])      # by the text that is replaced: the word wrappers would make a short user name outrank the folder holding it
100    path_user = re.compile(r"(?i)([A-Za-z]:)?([\\/])(Users|home)([\\/])(?!<)[^\\/\s\"':;,]+")
101    ip4 = re.compile(r"\b(?:192\.168|10\.\d{1,3}|172\.(?:1[6-9]|2\d|3[01])|100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])|169\.254)\.\d{1,3}\.\d{1,3}\b")
102    bearer = re.compile(r"(?i)(bearer\s+)[A-Za-z0-9._~+/=-]{8,}")
103
104    def f(text):
105        if not isinstance(text, str):
106            return text
107        for pat, label, _ in subs:
108            text = pat.sub(label, text)
109        text = path_user.sub(lambda m: f"{m.group(1) or ''}{m.group(2)}{m.group(3)}{m.group(4)}<user>", text)
110        text = bearer.sub(r"\1<key>", text)
111        return ip4.sub("<ip>", text)
112    return f
113
114
115def redact_obj(obj, red):
116    if isinstance(obj, dict):
117        return {red(k) if isinstance(k, str) else k: redact_obj(v, red) for k, v in obj.items()}
118    if isinstance(obj, list):
119        return [redact_obj(v, red) for v in obj]
120    return red(obj) if isinstance(obj, str) else obj
121
122
123# ---------------------------------------------------------------------------------------------------------- HTTP
124def http_json(base: str, path: str, key: str = "", timeout: float = 20):
125    req = urllib.request.Request(base + path, headers={"Authorization": "Bearer " + key} if key else {})
126    with urllib.request.urlopen(req, timeout=timeout) as r:
127        return json.loads(r.read())
128
129
130def try_json(base, path, key="", timeout=20):
131    try:
132        return http_json(base, path, key, timeout)
133    except Exception:                                   # noqa: BLE001
134        return None
135
136
137def chat(base: str, key: str, messages: list, max_tokens: int, think: bool = False, tools=None, timeout: float = 3600) -> dict:
138    """One streamed chat request -> {first, total, text, usage, timings, err}.  `first` is the seconds to the first
139    non-empty content or reasoning piece (keep-alives and empty deltas ignored)."""
140    body = {"model": "strata", "stream": True, "max_tokens": max_tokens, "temperature": 0, "messages": messages}
141    if tools:
142        body["tools"] = tools
143    if not think:
144        body["reasoning_effort"] = "none"
145        body["chat_template_kwargs"] = {"enable_thinking": False}
146    req = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps(body).encode(),
147                                 headers={"Content-Type": "application/json",
148                                          **({"Authorization": "Bearer " + key} if key else {})})
149    t0 = time.perf_counter()
150    first, text, usage, timings, err, pieces = None, [], None, None, None, 0
151    try:
152        with urllib.request.urlopen(req, timeout=timeout) as r:
153            for raw in r:
154                line = raw.decode("utf-8", "replace").strip()
155                if not line.startswith("data:"):
156                    continue
157                d = line[5:].strip()
158                if d == "[DONE]":
159                    break
160                try:
161                    j = json.loads(d)
162                except ValueError:
163                    continue
164                if j.get("error"):
165                    err = str(j["error"])[:300]
166                for ch in j.get("choices") or []:
167                    dl = ch.get("delta") or {}
168                    piece = (dl.get("content") or "") + (dl.get("reasoning_content") or "")
169                    if piece:
170                        if first is None:
171                            first = time.perf_counter() - t0
172                        pieces += 1
173                        text.append(dl.get("content") or "")
174                if j.get("usage"):
175                    usage = j["usage"]
176                if j.get("timings"):
177                    timings = j["timings"]
178    except urllib.error.HTTPError as e:
179        err = f"HTTP {e.code}: {e.read()[:200]!r}"
180    except Exception as e:                              # noqa: BLE001
181        err = repr(e)[:300]
182    total = time.perf_counter() - t0
183    if os.environ.get("STRATA_BENCH_ANSWERS"):
184        try:
185            with open(os.environ["STRATA_BENCH_ANSWERS"], "a", encoding="utf-8") as _f:
186                _f.write(json.dumps({"messages": messages[-1:], "text": "".join(text), "usage": usage,
187                                     "err": err}) + "\n")
188        except Exception:                               # noqa: BLE001
189            pass
190    return {"first": first, "total": total, "text": "".join(text), "usage": usage, "timings": timings, "err": err,
191            "pieces": pieces}
192
193
194def digest(r: dict) -> dict:
195    """The numbers of one request, the engine's own where it reported them."""
196    u, t = r.get("usage") or {}, r.get("timings") or {}
197    gen = u.get("completion_tokens") or r.get("pieces") or 0
198    prompt_tokens = u.get("prompt_tokens")
199    cached = (u.get("prompt_tokens_details") or {}).get("cached_tokens")
200    if cached is None:
201        cached = t.get("cache_n")
202    read = t.get("prompt_n")
203    if read is None and prompt_tokens is not None and cached is not None:
204        read = prompt_tokens - cached
205    dec, dsrc = t.get("predicted_per_second"), "engine"
206    if dec is None and r.get("first") is not None and gen > 1 and r["total"] > r["first"]:
207        dec, dsrc = round((gen - 1) / (r["total"] - r["first"]), 1), "client"
208    pp, psrc = t.get("prompt_per_second"), "engine"
209    if pp is None:
210        pp, psrc = None, None
211    return {"ok": r.get("err") is None and r.get("first") is not None,
212            "err": r.get("err"), "ttft_s": None if r.get("first") is None else round(r["first"], 3),
213            "total_s": round(r["total"], 3), "prompt_tokens": prompt_tokens, "reused_tokens": cached,
214            "read_tokens": read, "generated_tokens": gen, "prompt_tps": pp, "prompt_tps_source": psrc,
215            "decode_tps": dec, "decode_tps_source": dsrc if dec is not None else None,
216            "prompt_ms": t.get("prompt_ms"), "decode_ms": t.get("predicted_ms"),
217            "drafts_offered": t.get("draft_n"), "drafts_accepted": t.get("draft_n_accepted")}
218
219
220# ----------------------------------------------------------------------------------------------------- statistics
221def stat(values) -> dict | None:
222    v = [x for x in values if isinstance(x, (int, float))]
223    if not v:
224        return None
225    return {"median": round(statistics.median(v), 3), "min": round(min(v), 3), "max": round(max(v), 3), "n": len(v)}
226
227
228def fmt(s, digits=1, unit="") -> str:
229    if not s:
230        return "not measured"
231    d = digits
232    return f"{s['median']:.{d}f}{unit} ({s['min']:.{d}f}-{s['max']:.{d}f})"
233
234
235def pctl(values, p):
236    return serve_load.pct(values, p)
237
238
239# ---------------------------------------------------------------------------------------------------- the suite
240class Suite:
241    def __init__(self, base, key, ctx, runs, think, log=print, want_clients=0, want_long=False, quick=False):
242        self.base, self.key, self.ctx, self.runs, self.think, self.log = base, key, ctx, runs, think, log
243        self.clients, self.want_long = want_clients, want_long
244        self.quick = quick
245        self.nonce = str(int(time.time()))
246        self.tokens_per_word, self.overhead = 1.1, 40
247        self.out: dict = {"chat": {}, "prompts": {}, "agent": {}, "clients": {}, "skipped": {}, "failures": []}
248
249    def tag(self, *parts) -> str:
250        return "-".join([*map(str, parts), self.nonce])
251
252    def fail(self, where, d):
253        self.out["failures"].append({"where": where, "error": d.get("err") or "no token came back"})
254        self.log(f"    FAILED: {d.get('err') or 'no token came back'}")
255
256    def calibrate(self):
257        """Words that make a prompt of a wanted size: two tiny requests (200 and 800 words) give the tokens per word as a
258        slope, so the template's fixed part does not skew it."""
259        pts = []
260        for words in (200, 800):
261            r = digest(chat(self.base, self.key, [{"role": "user", "content": f"[{self.tag('cal', words)}]\n" + long_prompt(words)}], 1))
262            pts.append(r.get("prompt_tokens"))
263        slope = (pts[1] - pts[0]) / 600 if all(pts) and pts[1] > pts[0] else None
264        self.tokens_per_word = slope or 1.1
265        self.overhead = max(0, (pts[0] or 0) - 200 * self.tokens_per_word) if slope else 40
266        self.log(f"  calibrated: about {self.tokens_per_word:.2f} tokens per word")
267
268    def prompt_for(self, tokens: int, run: int) -> list:
269        words = max(50, int((tokens - self.overhead) / self.tokens_per_word))
270        return [{"role": "user", "content": f"[bench {self.tag(run, tokens, 'p')}]\n" + long_prompt(words)}]
271
272    def warm_up(self):
273        self.log("warming up (not measured) ...")
274        chat(self.base, self.key, [{"role": "user", "content": PROMPTS[0]}], 24, self.think)
275        self.calibrate()
276        chat(self.base, self.key, self.prompt_for(1024, -1), 8, self.think)
277
278    def run_chat(self):
279        self.log(f"chat: {len(PROMPTS)} short questions x {self.runs} runs, up to {CHAT_MAX_TOKENS} new tokens")
280        rows = []
281        for run in range(self.runs):
282            for i, p in enumerate(PROMPTS):
283                d = digest(chat(self.base, self.key, [{"role": "user", "content": f"[{self.tag(run, i, 'c')}] {p}"}],
284                                CHAT_MAX_TOKENS, self.think))
285                d.update(run=run, prompt=i)
286                rows.append(d)
287                if not d["ok"]:
288                    self.fail("chat", d)
289                else:
290                    self.log(f"  run {run + 1} q{i + 1}: decode {d['decode_tps']} tok/s, first token {d['ttft_s']} s, "
291                             f"{d['generated_tokens']} tokens")
292        good = [r for r in rows if r["ok"]]
293        self.out["chat"] = {"requests": rows, "decode_tps": stat(r["decode_tps"] for r in good),
294                            "ttft_s": stat(r["ttft_s"] for r in good), "generated_tokens": stat(r["generated_tokens"] for r in good),
295                            "prompt_tokens": stat(r["prompt_tokens"] for r in good)}
296
297    def run_prompt(self, tokens: int, label: str):
298        if self.ctx and tokens + LONG_MAX_TOKENS + 256 > self.ctx:
299            self.out["skipped"][label] = f"the context is {self.ctx} tokens"
300            self.log(f"{label} prompt: skipped (the context is {self.ctx} tokens)")
301            return
302        self.log(f"{label} prompt: {self.runs} fresh prompts of about {tokens} tokens, {LONG_MAX_TOKENS} new tokens")
303        rows = []
304        for run in range(self.runs):
305            d = digest(chat(self.base, self.key, self.prompt_for(tokens, run), LONG_MAX_TOKENS, self.think))
306            d["run"] = run
307            rows.append(d)
308            if not d["ok"]:
309                self.fail(label, d)
310            else:
311                self.log(f"  run {run + 1}: {d['prompt_tokens']} tokens, prompt {d['prompt_tps']} tok/s "
312                         f"({d['reused_tokens'] or 0} reused), first token {d['ttft_s']} s")
313        good = [r for r in rows if r["ok"]]
314        self.out["prompts"][label] = {"target_tokens": tokens, "requests": rows,
315                                      "prompt_tps": stat(r["prompt_tps"] for r in good),
316                                      "ttft_s": stat(r["ttft_s"] for r in good),
317                                      "prompt_tokens": stat(r["prompt_tokens"] for r in good),
318                                      "reused_tokens": stat(r["reused_tokens"] or 0 for r in good)}
319
320    def agent_files(self) -> list[tuple[str, str]]:
321        """Five pieces of text a coding agent would read: this folder's own documents when they exist (nothing personal),
322        else generated filler of the same size."""
323        names = []
324        for rel in ("README.md", "docs/HOW_IT_WORKS.md", "docs/DETAILS.md", "docs/INSTALL.md", "docs/MODELS.md", "docs/COMMUNITY_BENCHMARKS.md"):
325            p = ROOT / rel
326            if p.is_file():
327                words = p.read_text(encoding="utf-8", errors="replace").split()
328                if len(words) >= AGENT_WORDS // 2:
329                    names.append((rel, " ".join(words[:AGENT_WORDS])))
330        i = 0
331        while len(names) < AGENT_TURNS:
332            names.append((f"generated/part{i}.txt", long_prompt(AGENT_WORDS)))
333            i += 1
334        return names[:AGENT_TURNS]
335
336    def agent_session(self, run: int) -> list[dict]:
337        files = self.agent_files()
338        msgs = [{"role": "system", "content": f"{SYSTEM}\n(session {self.tag(run, 'a')})"},
339                {"role": "user", "content": "I will show you files from a project one at a time. After each file, answer in "
340                                            "one or two sentences what it is for. Do not call tools."}]
341        turns = []
342        for t in range(AGENT_TURNS + 1):
343            if t > 0:
344                rel, body = files[t - 1]
345                msgs.append({"role": "user", "content": f"File {rel}:\n{body}\n\nWhat is this file for? Two sentences."})
346            r = chat(self.base, self.key, msgs, AGENT_MAX_TOKENS, self.think, tools=TOOLS)
347            d = digest(r)
348            d.update(run=run, turn=t)
349            turns.append(d)
350            if not d["ok"]:
351                self.fail("agent", d)
352                break
353            msgs.append({"role": "assistant", "content": r["text"] or "Understood."})
354        return turns
355
356    def run_agent(self):
357        if self.ctx and self.ctx < AGENT_MIN_CONTEXT:
358            self.out["skipped"]["agent"] = f"context {self.ctx} is below ~10K"
359            self.log(f"agent: skipped: context {self.ctx} is below ~10K")
360            return
361        self.log(f"agent: a session of {AGENT_TURNS + 1} turns with four tools, x {self.runs} runs")
362        sessions = []
363        for run in range(self.runs):
364            turns = self.agent_session(run)
365            sessions.append(turns)
366            for d in turns:
367                if d["ok"]:
368                    self.log(f"  run {run + 1} turn {d['turn']}: prompt {d['prompt_tokens']}, reused {d['reused_tokens']}, "
369                             f"read {d['read_tokens']}, first token {d['ttft_s']} s")
370        follow = [[d for d in s if d["ok"] and d["turn"] > 0] for s in sessions]
371        hit = [sum(d["reused_tokens"] or 0 for d in s) / max(1, sum(d["prompt_tokens"] or 0 for d in s)) * 100
372               for s in follow if s]
373        # earlier conversation read again: what the previous turn held (prompt + its reply) minus what this turn reused
374        reread, fresh = [], []
375        for s in sessions:
376            s = [d for d in s if d["ok"]]
377            reread.append(sum(max(0, (p["prompt_tokens"] or 0) + (p["generated_tokens"] or 0) - (d["reused_tokens"] or 0))
378                              for p, d in zip(s, s[1:])))
379            fresh.append(sum(d["read_tokens"] or 0 for d in s[1:]) - reread[-1])
380        self.out["agent"] = {"sessions": sessions, "hit_pct": stat(hit), "reread_tokens": stat(reread), "new_tokens": stat(fresh),
381                             "turn_ttft_s": stat(d["ttft_s"] for s in follow for d in s),
382                             "last_turn_prompt_tokens": stat(s[-1]["prompt_tokens"] for s in follow if s),
383                             "turn_decode_tps": stat(d["decode_tps"] for s in follow for d in s),
384                             "first_turn_ttft_s": stat(s[0]["ttft_s"] for s in sessions if s and s[0]["ok"])}
385
386    def run_clients(self, n: int):
387        self.log(f"concurrency: {n} requests at once x {self.runs} rounds, {BURST_MAX_TOKENS} new tokens each")
388        rows = []
389        for rd in range(self.runs):
390            res: dict = {}
391            th = []
392            t0 = time.perf_counter()
393            for i in range(n):
394                t = threading.Thread(target=serve_load.one, args=(self.base, self.key, "strata", i, 400, BURST_MAX_TOKENS, res, {},
395                                                                 self.think, f" {self.tag('b', n, rd)}"))
396                t.start()
397                th.append(t)
398            for t in th:
399                t.join()
400            wall = time.perf_counter() - t0
401            toks = sum(r["tokens"] for r in res.values())
402            errs = [r["err"] for r in res.values() if r["err"]]
403            rows.append({"round": rd, "wall_s": round(wall, 2), "tokens": toks, "total_tps": round(toks / wall, 2),
404                         "first_s": [r["first"] for r in res.values() if r["first"] is not None],
405                         "latency_s": [r["total"] for r in res.values()], "errors": errs[:3], "error_count": len(errs)})
406            self.log(f"  round {rd + 1}: {toks} tokens in {wall:.1f} s = {toks / wall:.1f} tok/s total"
407                     + (f"  ERRORS {errs[:1]}" if errs else ""))
408        firsts = [x for r in rows for x in r["first_s"]]
409        lats = [x for r in rows for x in r["latency_s"]]
410        self.out["clients"] = {"clients": n, "rounds": rows, "total_tps": stat(r["total_tps"] for r in rows),
411                               "ttft_p50_s": round(pctl(firsts, .5), 3) if firsts else None,
412                               "ttft_p95_s": round(pctl(firsts, .95), 3) if firsts else None,
413                               "latency_p50_s": round(pctl(lats, .5), 3) if lats else None,
414                               "latency_p95_s": round(pctl(lats, .95), 3) if lats else None,
415                               "errors": sum(r["error_count"] for r in rows)}
416
417    def run(self):
418        self.warm_up()
419        self.run_chat()
420        self.run_prompt(4096, "4K")
421        self.run_prompt(16384, "16K")
422        self.run_agent()
423        if self.clients:
424            self.run_clients(self.clients)
425        if self.want_long:
426            self.run_prompt(32768, "32K")
427        return self.out
428
429
430def summary_metrics(out: dict) -> dict:
431    """The flat {name: stat} the --compare table and the README table read."""
432    m = {"chat decode tok/s": out["chat"].get("decode_tps"), "chat first token (s)": out["chat"].get("ttft_s")}
433    for k, v in out["prompts"].items():
434        m[f"{k} prompt tok/s"] = v.get("prompt_tps")
435        m[f"{k} first token (s)"] = v.get("ttft_s")
436    a = out["agent"]
437    if a:
438        m["agent cache hit %"] = a.get("hit_pct")
439        m["agent re-read tokens/session"] = a.get("reread_tokens")
440        m["agent turn first token (s)"] = a.get("turn_ttft_s")
441        m["agent decode tok/s"] = a.get("turn_decode_tps")
442    c = out["clients"]
443    if c:
444        m[f"{c['clients']} clients total tok/s"] = c.get("total_tps")
445    return m
446
447
448# -------------------------------------------------------------------------------------------------- the machine
449def run_cmd(cmd, timeout=15) -> str:
450    try:
451        r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, encoding="utf-8", errors="replace")
452        return r.stdout if r.returncode == 0 else ""
453    except (OSError, subprocess.SubprocessError):
454        return ""
455
456
457def total_ram_gib() -> float | None:
458    try:
459        import psutil
460        return round(psutil.virtual_memory().total / 2 ** 30, 1)
461    except Exception:                                   # noqa: BLE001
462        pass
463    try:
464        for line in Path("/proc/meminfo").read_text().splitlines():
465            if line.startswith("MemTotal:"):
466                return round(int(line.split()[1]) / 2 ** 20, 1)
467    except OSError:
468        pass
469    if os.name == "nt":
470        try:
471            import ctypes
472
473            class MS(ctypes.Structure):
474                _fields_ = [("l", ctypes.c_ulong), ("load", ctypes.c_ulong), ("total", ctypes.c_ulonglong)] + [
475                    (n, ctypes.c_ulonglong) for n in ("a", "b", "c", "d", "e")]
476            ms = MS()
477            ms.l = ctypes.sizeof(MS)
478            ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(ms))
479            return round(ms.total / 2 ** 30, 1)
480        except Exception:                               # noqa: BLE001
481            pass
482    return None
483
484
485def cpu_name() -> str | None:
486    try:
487        for line in Path("/proc/cpuinfo").read_text().splitlines():
488            if line.lower().startswith("model name"):
489                return line.split(":", 1)[1].strip()
490    except OSError:
491        pass
492    if os.name == "nt":
493        out = run_cmd(["powershell", "-NoProfile", "-Command", "(Get-CimInstance Win32_Processor | Select-Object -First 1).Name"])
494        if out.strip():
495            return out.strip()
496    return platform.processor() or None
497
498
499def gpu_info_local() -> dict:
500    out = run_cmd(["nvidia-smi", "--query-gpu=name,memory.total,driver_version,power.limit,power.draw,pcie.link.gen.current,pcie.link.width.current,pstate,temperature.gpu",
501                   "--format=csv,noheader,nounits"])
502    gpus = []
503    for line in out.splitlines():
504        p = [x.strip() for x in line.split(",")]
505        if len(p) >= 3:
506            g = {"name": p[0], "vram_mib": int(float(p[1])) if p[1].replace(".", "").isdigit() else None, "driver": p[2]}
507            if len(p) >= 9:
508                g.update({"power_limit_w": p[3], "power_draw_w": p[4], "pcie": f"gen{p[5]} x{p[6]}",
509                          "pstate": p[7], "temp_c": p[8]})
510            gpus.append(g)
511    if not gpus:
512        out = run_cmd(["nvidia-smi", "--query-gpu=name,memory.total,driver_version", "--format=csv,noheader,nounits"])
513        for line in out.splitlines():
514            p = [x.strip() for x in line.split(",")]
515            if len(p) >= 3:
516                gpus.append({"name": p[0], "vram_mib": int(float(p[1])) if p[1].replace(".", "").isdigit() else None, "driver": p[2]})
517    info = {"gpus": gpus}
518    head = run_cmd(["nvidia-smi"])
519    m = re.search(r"CUDA(?: UMD)? Version:\s*([\d.]+)", head)
520    if m:
521        info["cuda"] = m.group(1)
522    if not gpus:
523        rocm = run_cmd(["rocm-smi", "--showproductname"])
524        names = re.findall(r"Card [Ss]eries:\s*(.+)", rocm) or re.findall(r"Card [Mm]odel:\s*(.+)", rocm)
525        info["gpus"] = [{"name": n.strip(), "vram_mib": None, "driver": None} for n in names]
526        v = run_cmd(["rocm-smi", "--showdriverversion"])
527        m2 = re.search(r"Driver version:\s*(\S+)", v)
528        if m2:
529            info["rocm_driver"] = m2.group(1)
530    if not info["gpus"] and os.name != "nt":
531        # ROCm 7 and newer ship `amd-smi` and no `rocm-smi`, so a Radeon wrote the server's vendor stub ("AMD
532        # Radeon", `...-community-unknown-...`) and `GPU driver: not read`. `static --asic` gives the marketing
533        # name, `static --driver` the kernel driver's version, the PCI address only comes from `amd-smi list` and
534        # the VRAM size is the amdgpu driver's sysfs file for that address (same probe as strata_cli/bench_facts.py).
535        def amd_json(args):
536            try:
537                return json.loads(run_cmd(["amd-smi", "static"] + args + ["--json"]).strip() or "{}").get("gpu_data") or []
538            except ValueError:                               # noqa: BLE001 - a report without the card's name is a report
539                return []
540        try:
541            bdf = {e.get("gpu"): (e.get("bdf") or "") for e in json.loads(run_cmd(["amd-smi", "list", "--json"]).strip() or "[]")}
542        except ValueError:
543            bdf = {}
544        drv = {e.get("gpu"): ((e.get("driver") or {}).get("version") or "") for e in amd_json(["--driver"])}
545        cards = []
546        for e in amd_json(["--asic"]):
547            name = ((e.get("asic") or {}).get("market_name") or "").strip()
548            if not name:
549                continue
550            d = drv.get(e.get("gpu"), "")
551            d = d if d.upper() not in ("", "N/A") else None
552            if d:
553                info["rocm_driver"] = info.get("rocm_driver") or d
554            vram = None
555            for dev in Path("/sys/class/drm").glob("card[0-9]*/device"):
556                try:
557                    if bdf.get(e.get("gpu")) and os.path.basename(os.path.realpath(dev)).lower() == bdf[e["gpu"]].lower():
558                        vram = int((dev / "mem_info_vram_total").read_text(encoding="utf-8").strip()) >> 20
559                except (OSError, ValueError):
560                    pass
561            cards.append({"name": name, "vram_mib": vram, "driver": d})
562        info["gpus"] = cards
563    if not info["gpus"] and os.name == "nt":
564        # #1587: Windows with only an AMD card has neither nvidia-smi nor rocm-smi; the display class in the registry
565        # names the card, its VRAM and its driver (the run was labelled "CPU only" before)
566        try:
567            if str(ROOT) not in sys.path:
568                sys.path.insert(0, str(ROOT))
569            from serve.telemetry import windows_amd_cards
570            info["gpus"] = [{"name": c["name"], "vram_mib": (c["vram_bytes"] >> 20) if c["vram_bytes"] else None,
571                             "driver": c["driver"]} for c in windows_amd_cards()]
572        except Exception:   # noqa: BLE001 - a report without the card's name is still a report
573            pass
574    return info
575
576
577def storage_info() -> str | None:
578    if os.name == "nt":
579        out = run_cmd(["powershell", "-NoProfile", "-Command",
580                       "Get-PhysicalDisk | Select-Object -First 4 FriendlyName,MediaType,BusType | "
581                       "ForEach-Object { $_.FriendlyName + ' ' + $_.MediaType + '/' + $_.BusType }"])
582        names = [x.strip() for x in out.splitlines() if x.strip() and "FriendlyName" not in x]
583        return "; ".join(names) or None
584    if sys.platform == "darwin":
585        out = run_cmd(["system_profiler", "SPNVMeDataType", "SPSerialATADataType"])
586        names = re.findall(r"Model:\s*(.+)", out)
587        if names:
588            return "; ".join(n.strip() for n in names)
589        return None
590    out = run_cmd(["lsblk", "-d", "-o", "NAME,MODEL,TRAN", "-n", "-e", "7"])   # -e 7: skip loop devices (snap mounts)
591    if out.strip():
592        return "; ".join(x.strip() for x in out.splitlines() if x.strip()) or None
593    return None
594
595
596def engine_build(cfg: dict | None) -> dict | None:
597    """BUILD.json next to the engine exe: the toolkit/archs it was compiled with, unlike nvidia-smi's driver ceiling."""
598    exe = (cfg or {}).get("exe")
599    if not exe:
600        return None
601    try:
602        b = json.loads((Path(exe).parent / "BUILD.json").read_text(encoding="utf-8"))
603    except (OSError, ValueError):
604        return None
605    return {k: b[k] for k in ("version", "source", "cuda", "rocm", "archs", "ptx", "portable") if b.get(k) is not None} or None
606
607
608QUANT = re.compile(r"(?i)(?:^|[-_.])((?:UD-)?(?:IQ\d_[A-Z]+|Q\d_[A-Z0-9_]+|Q\d_K(?:_[A-Z]+)?|IQ\d_?[A-Z]*|BF16|F16|Q\d))(?=[-_.]|$)")
609SECRET_KEY = re.compile(r"(?i)key|token|secret|password|auth")
610
611
612def base_if_path(v):
613    if isinstance(v, str) and (("/" in v or "\\" in v) or re.search(r"\.(gguf|bin|json|pack|txt|jinja|so|dll|exe)$", v, re.I)):
614        return re.split(r"[\\/]", v.rstrip("\\/"))[-1]
615    return v
616
617
618def config_view(cfg: dict) -> dict:
619    """The settings worth reporting, with paths cut to file names and secrets dropped."""
620    out = {}
621    for k, v in cfg.items():
622        if SECRET_KEY.search(k) or k in ("log", "cwd", "env"):
623            continue
624        if k == "exe":
625            out[k] = base_if_path(v)
626        elif k == "args" and isinstance(v, list):
627            out[k] = [base_if_path(x) if isinstance(x, str) else x for x in v]
628        elif isinstance(v, (str, int, float, bool)) or v is None:
629            out[k] = base_if_path(v)
630        elif isinstance(v, (list, dict)):
631            out[k] = json.loads(json.dumps(v))
632    env = cfg.get("env")
633    if isinstance(env, dict):
634        out["env"] = {k: base_if_path(str(v)) for k, v in env.items() if k.startswith(("STRATA_", "HIP_", "CUDA_", "ROCR_", "ONEAPI_", "SYCL_")) and not SECRET_KEY.search(k)}
635    return out
636
637
638def launch_line(view: dict) -> str:
639    args = " ".join(f'"{a}"' if " " in str(a) else str(a) for a in view.get("args", []))
640    return f"{view.get('exe', 'strata')} {args}".strip()
641
642
643def detect_quant(view: dict) -> str | None:
644    names = [a for a in view.get("args", []) if isinstance(a, str) and re.search(r"\.(gguf|pack)$|^[\w.-]+$", a)]
645    names += [str(view.get("model_name") or "")]
646    for n in names:
647        m = QUANT.search(n)
648        if m:
649            return m.group(1).upper()
650    return None
651
652
653def project_version() -> str | None:
654    try:
655        # UTF-8 as setup.py reads it, whatever the locale's code page (#2792)
656        m = re.search(r"project\(strata VERSION ([\d.]+)", (ROOT / "CMakeLists.txt").read_text(encoding="utf-8"))
657        return m.group(1) if m else None
658    except OSError:
659        return None
660
661
662def git_commit() -> str | None:
663    if not (ROOT / ".git").exists():
664        return None
665    out = run_cmd(["git", "-C", str(ROOT), "rev-parse", "--short=8", "HEAD"]).strip()
666    return out or None
667
668
669def gpu_selection(cfg: dict | None, gpu_arg: str | None = None) -> list[int]:
670    """#1985: the GPU numbers (as nvidia-smi numbers them) the engine is told to use: the bench's --gpu when it starts
671    the server, else the config's "gpu" (one card, a list or "0,2"), else a "--gpu" in the config's args.  [] when
672    nothing says."""
673    def parse(v):
674        if v is None or v == "":
675            return []
676        items = v if isinstance(v, (list, tuple)) else str(v).split(",")
677        out = []
678        for x in items:
679            x = str(x).strip()
680            if x.isdigit():
681                out.append(int(x))
682        return out
683    sel = parse(gpu_arg) or parse((cfg or {}).get("gpu"))
684    if not sel:
685        args = [str(x) for x in ((cfg or {}).get("args") or [])]
686        if "--gpu" in args and args.index("--gpu") + 1 < len(args):
687            sel = parse(args[args.index("--gpu") + 1])
688    return sel
689
690
691def collect_machine(base: str, key: str, cfg: dict | None, gpu_arg: str | None = None) -> dict:
692    status = try_json(base, "/v1/status", key) or {}
693    metrics = try_json(base, "/metrics", key, 30) or {}
694    props = try_json(base, "/props", key) or {}
695    models = try_json(base, "/v1/models", key) or {}
696    static = metrics.get("hardware_static") or {}
697    eng = metrics.get("engine") or {}
698    local = gpu_info_local()
699    view = config_view(cfg) if cfg else {}
700    # #1985: only the GPUs the engine uses - the config's / --gpu selection; with none given the engine runs on one card
701    # (the one the server reports), not on every card the PC has
702    used = local["gpus"]
703    sel = gpu_selection(cfg, gpu_arg)
704    if sel:
705        used = [local["gpus"][i] for i in sel if 0 <= i < len(local["gpus"])] or used
706    elif len(used) > 1 and static.get("gpu_name"):
707        named = [g for g in used if g["name"] == static["gpu_name"]]
708        used = named[:1] or used[:1]
709    gpu_names = [g["name"] for g in used] or ([static["gpu_name"]] if static.get("gpu_name") else [])
710    m = status.get("machine") or {}
711    vram_mib = (m.get("gpu") or {}).get("total_mib") or None
712    # #2001: the server names the cards it reads (" + " between them).  A name nvidia-smi does not list means the
713    # engine runs on another vendor's card (an Intel Arc beside a GeForce): the server's names are the right ones, and
714    # so is its VRAM total - the PC's NVIDIA cards were not used.
715    served = [n for n in (static.get("gpu_name") or "").split(" + ") if n and n != "?"]
716    # the engine's own stub when the driver names no card is the vendor alone ("AMD Radeon"), not a card name:
717    # taking it as one would throw away the real name amd-smi read (same guard as strata_cli/bench_facts.py)
718    served = [n for n in served if not re.fullmatch(r"(?i)\s*(nvidia|amd|intel|advanced micro devices)"
719                                                    r"([ -](geforce|radeon|graphics|arc))?\s*", n)]
720    if served and not all(n in {g["name"] for g in local["gpus"]} for n in served):
721        gpu_names, used = served, []
722        local = {**local, "cuda": None}            # the PC's CUDA belongs to cards the engine did not use
723    elif used and used[0].get("vram_mib"):
724        vram_mib = sum(g.get("vram_mib") or 0 for g in used)
725    n_ctx = None
726    for d in models.get("data") or []:
727        n_ctx = (d.get("meta") or {}).get("n_ctx") or n_ctx
728    n_ctx = n_ctx or (props.get("default_generation_settings") or {}).get("n_ctx")
729    return {
730        "gpu": gpu_names, "gpu_vram_mib": vram_mib, "gpu_driver": (used[0].get("driver") if used else local.get("rocm_driver")),
731        "gpu_detail": [{k: v for k, v in g.items() if k not in ("name", "vram_mib", "driver")} for g in used] or None,
732        "cuda": local.get("cuda"), "engine_build": engine_build(cfg),
733        "cpu": static.get("cpu_name") or cpu_name(), "cpu_cores": static.get("cores"),
734        "storage": storage_info(),
735        "cpu_threads": static.get("threads") or os.cpu_count(), "ram_gib": total_ram_gib(),
736        "os": f"{platform.system()} {'11' if int(platform.version().split('.')[-1] or 0) >= 22000 else platform.release()} ({platform.version()})" if os.name == "nt" else f"{platform.system()} {platform.release()}",
737        "python": platform.python_version(),
738        "strata_version": project_version(), "strata_commit": git_commit(),
739        "engine_version": (eng.get("version") or status.get("engine") or str(props.get("build_info", "")).replace("Strata ", "") or None),
740        "model": view.get("model_name") or status.get("model") or props.get("model_alias"),
741        "quant": detect_quant(view) if view else None,
742        "context": n_ctx or eng.get("max_context"), "parallel_slots": props.get("total_slots"),
743        "config": view, "launch": launch_line(view) if view else None,
744        "engine_info": {k: v for k, v in eng.items() if isinstance(v, (str, int, float, bool, dict)) and k not in ("model_path",)},
745        "vram_after": (status.get("vram") or {}),
746    }
747
748
749# --------------------------------------------------------------------------------------------------- the server
750def find_configs(folder: Path = ROOT) -> list[Path]:
751    out = []
752    for p in folder.glob("strata-*.json"):
753        if p.name.endswith(".shared-settings.json"):
754            continue
755        try:
756            c = json.loads(p.read_text(encoding="utf-8-sig"))
757        except (OSError, ValueError):
758            continue
759        if isinstance(c, dict) and c.get("exe") and isinstance(c.get("args"), list):
760            out.append(p)
761    return sorted(out, key=lambda p: p.stat().st_mtime, reverse=True)
762
763
764def is_strata(base: str, key: str) -> bool:
765    h = try_json(base, "/health", key, 5)
766    return bool(h and h.get("service") == "strata")
767
768
769def without_profile_save(cfg: dict) -> tuple[dict, bool]:
770    """#2088: the config without `--expert-profile-save FILE` (and its value) - the engine writes that profile when the
771    server quits, and a benchmark's short prompts must not replace the user's calibrated one.  -> (config, removed)."""
772    args = list(cfg.get("args") or [])
773    out, i, removed = [], 0, False
774    while i < len(args):
775        if args[i] == "--expert-profile-save":
776            i, removed = i + 2, True
777        elif isinstance(args[i], str) and args[i].startswith("--expert-profile-save="):
778            i, removed = i + 1, True
779        else:
780            out.append(args[i])
781            i += 1
782    return ({**cfg, "args": out} if removed else cfg), removed
783
784
785def start_server(cfg_path: Path, port: int, gpu: str | None, log_path: Path):
786    try:
787        cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig"))
788    except (OSError, ValueError):
789        cfg = None
790    if isinstance(cfg, dict):
791        safe, removed = without_profile_save(cfg)
792        if removed:                       # a copy beside the log: the user's config file is not touched
793            print("Note: the bench starts this model without --expert-profile-save, so its short prompts do not "
794                  "overwrite your saved expert profile.", file=sys.stderr)
795            tmp = log_path.with_suffix(".config.json")
796            tmp.write_text(json.dumps(safe), encoding="utf-8")
797            cfg_path = tmp
798    cmd = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), "--port", str(port)]
799    if gpu:
800        cmd += ["--gpu", gpu]
801    logf = open(log_path, "w", encoding="utf-8", errors="replace")
802    return subprocess.Popen(cmd, cwd=str(ROOT), stdout=logf, stderr=subprocess.STDOUT)
803
804
805def wait_ready(base: str, key: str, proc, timeout: float, log=print) -> bool:
806    t0, last = time.time(), 0
807    while time.time() - t0 < timeout:
808        if proc is not None and proc.poll() is not None:
809            return False
810        h = try_json(base, "/health", key, 5)
811        if h and h.get("service") == "strata" and h.get("loaded"):
812            return True
813        if time.time() - last > 30:
814            log(f"  still loading ({int(time.time() - t0)} s) ...")
815            last = time.time()
816        time.sleep(3)
817    return False
818
819
820def stop_server(proc):
821    if proc is None or proc.poll() is not None:
822        return
823    proc.terminate()
824    try:
825        proc.wait(90)
826    except subprocess.TimeoutExpired:
827        proc.kill()
828
829
830def log_excerpt(path: Path, limit: int = 80) -> list[str]:
831    try:
832        lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
833    except OSError:
834        return []
835    keep = re.compile(r"(?i)expert cache|slots|vram|ready|resident|kv |context|backend|gpu|prefill|mtp|spec|batch|version|hit")
836    out = [x for x in lines if keep.search(x) and "[strata] done:" not in x]
837    return out[:limit]
838
839
840# --------------------------------------------------------------------------------------------------- the report
841def slug(text: str, limit: int = 40) -> str:
842    s = re.sub(r"[^a-z0-9]+", "-", (text or "").lower()).strip("-")
843    return s[:limit].strip("-") or "unknown"
844
845
846def gpu_slug(machine: dict) -> str:
847    names = machine.get("gpu") or []
848    if not names:
849        return "cpu"
850    # #2062: the cards one by one when they differ (rtx-5070-ti-plus-rtx-a4000), "2x-" only for identical ones
851    groups: list[list] = []                              # [name, count], in the order the cards are listed
852    for name in names:
853        same = next((g for g in groups if g[0] == name), None)
854        if same:
855            same[1] += 1
856        else:
857            groups.append([name, 1])
858    parts = []
859    for name, count in groups:
860        n = re.sub(r"(?i)\b(nvidia|geforce|amd|radeon|intel|graphics|corporation)\b", " ", name)
861        parts.append(slug(n, 30) if count == 1 else f"{count}x-{slug(n, 30)}")
862    return "-plus-".join(parts)[:80].strip("-")
863
864
865def model_label(machine: dict) -> str:
866    model, q = machine.get("model") or "model", machine.get("quant")
867    return model if not q or slug(q) in slug(model, 200) else f"{model}-{q}"
868
869
870def results_dir_name(machine: dict, date: str) -> str:
871    return f"{date}-community-{gpu_slug(machine)}-{slug(model_label(machine), 40)}"
872
873
874def unique_dir(parent: Path, name: str) -> Path:
875    p, n = parent / name, 2
876    while p.exists():
877        p = parent / f"{name}-{n}"
878        n += 1
879    return p
880
881
882def row(label, prompt_tokens, reused, gen, runs, pp, dec, ttft):
883    return f"| {label} | {prompt_tokens} | {reused} | {gen} | {runs} | {pp} | {dec} | {ttft} |"
884
885
886def results_table(out: dict) -> list[str]:
887    lines = ["| Configuration | Actual prompt tokens | Reused tokens | Generated tokens | Runs | Prompt tok/s median and range | "
888             "Decode tok/s median and range | TTFT seconds median and range |",
889             "| --- | ---: | ---: | ---: | ---: | --- | --- | --- |"]
890    c = out["chat"]
891    if c:
892        lines.append(row("short chat", fmt(c.get("prompt_tokens"), 0), "0", fmt(c.get("generated_tokens"), 0),
893                         (c.get("ttft_s") or {}).get("n", 0), "not measured", fmt(c.get("decode_tps")), fmt(c.get("ttft_s"), 2)))
894    for k, v in out["prompts"].items():
895        lines.append(row(f"{k} prompt, fresh", fmt(v.get("prompt_tokens"), 0), fmt(v.get("reused_tokens"), 0), str(LONG_MAX_TOKENS) + " cap",
896                         (v.get("ttft_s") or {}).get("n", 0), fmt(v.get("prompt_tps")), "not measured", fmt(v.get("ttft_s"), 2)))
897    a = out["agent"]
898    if a:
899        n = len([s for s in a["sessions"] if len(s) > 1])
900        lines.append(row("agent session, follow-up turns", fmt(a.get("last_turn_prompt_tokens"), 0) + " at the last turn",
901                         "see below", f"up to {AGENT_MAX_TOKENS}", n, "see below", fmt(a.get("turn_decode_tps")),
902                         fmt(a.get("turn_ttft_s"), 2)))
903    return lines
904
905
906def render_readme(res: dict) -> str:
907    mc, out, p = res["machine"], res["results"], res["params"]
908    gpu = " + ".join(mc.get("gpu") or []) or "CPU only"
909    vram = f"{mc['gpu_vram_mib'] / 1024:.0f} GiB VRAM" if mc.get("gpu_vram_mib") else "VRAM not read"
910    model = (model_label(mc) if mc.get("model") else mc.get("quant")) or "model not read"
911    L = [f"# Community benchmark on {gpu}", "",
912         f"Measured on {res['date']} with `tools/strata_bench.py` (suite {SCHEMA}, {p['runs']} runs per test, medians with ranges). "
913         f"Speeds are the engine's own timings; first-token times are measured by the client over HTTP. Speed only: no "
914         f"correctness check was run.", "",
915         "## Hardware and software", "",
916         f"- GPU and VRAM: {gpu}, {vram}",
917         f"- CPU: {mc.get('cpu') or 'not read'} ({mc.get('cpu_cores') or '?'} cores, {mc.get('cpu_threads') or '?'} threads); "
918         f"installed RAM: {mc.get('ram_gib') or '?'} GiB; storage: {mc.get('storage') or 'not read'}",
919         f"- OS: {mc.get('os')}; GPU driver: {mc.get('gpu_driver') or 'not read'}; "
920         f"CUDA (driver supports up to): {mc.get('cuda') or 'not read'}"
921         + (f"; engine built for CUDA {(mc.get('engine_build') or {}).get('cuda')}" if (mc.get('engine_build') or {}).get('cuda') else ""),
922         f"- Strata: project {mc.get('strata_version') or '?'}, commit {mc.get('strata_commit') or 'not a git checkout'}; "
923         f"engine {mc.get('engine_version') or 'not read'}"]
924    for g in (mc.get("gpu_detail") or []):
925        if g:
926            L.append("- GPU detail (after the run, near idle): " + ", ".join(f"{k}={v}" for k, v in g.items() if v is not None))
927    L += ["- Background workloads: not recorded (GPU power limit/draw read above)", "",
928         "## Model and configuration", "",
929         f"- Model and quantization: {model}",
930         f"- Context: {mc.get('context') or 'not read'} tokens; parallel slots: {mc.get('parallel_slots') or 1}",
931         f"- Settings: the install's own configuration, unchanged{' (' + mc['config']['backend'] + ' backend)' if mc.get('config', {}).get('backend') else ''}; thinking "
932         f"{'on' if p['think'] else 'off'} for the suite; temperature 0", ""]
933    if mc.get("launch"):
934        L += ["```text", mc["launch"], "```", ""]
935    env = (mc.get("config") or {}).get("env")
936    if env:
937        L += ["Environment of the config: " + ", ".join(f"`{k}={v}`" for k, v in env.items()), ""]
938    L += ["## Method", "",
939          f"Run by `{p['command']}` against the HTTP API of a Strata server "
940          f"({'started by the benchmark from the install configuration' if p['started_server'] else 'already running'}); model loading is not "
941          f"timed. One warm-up chat and a 1K prompt are discarded first. Every prompt starts with a unique tag, so the conversation "
942          f"cache cannot help the fresh-prompt tests.", "",
943          f"- short chat: the three questions of `tools/ab_engine.py`, up to {CHAT_MAX_TOKENS} new tokens, {p['runs']} runs",
944          f"- 4K / 16K{' / 32K' if 'prompt' in res['results'] and '32K' in res['results']['prompts'] else ''} prompts: generated word lists sized by a calibration request, "
945          f"{LONG_MAX_TOKENS} new tokens, {p['runs']} fresh prompts each",
946          f"- agent session: system prompt and four tools, then {AGENT_TURNS} turns that each add about {AGENT_WORDS} words of a project file "
947          f"and continue from the model's own earlier answers (the way agent clients resend a conversation), {AGENT_MAX_TOKENS} new tokens per turn, "
948          f"{p['runs']} sessions; the cache numbers come from the answer's usage (`cached_tokens`) and timings (`prompt_n`)",
949          "- concurrency (when run): N requests sent at the same moment, total tokens over the wall time of the burst, "
950          "latency over all requests", "",
951          "## Results", ""]
952    L += results_table(out)
953    L += ["", "Ranges are the lowest and highest of the runs; `Runs` counts requests that returned a token."]
954    ag = out["agent"]
955    if ag and ag.get("sessions"):
956        L += ["", "### Agent session (conversation cache)", "",
957              f"Cache hit over the follow-up turns: {fmt(ag.get('hit_pct'), 1, ' %')}; earlier-turn tokens read again per session: "
958              f"{fmt(ag.get('reread_tokens'), 0)} (earlier turns that the cache did not hold; the {fmt(ag.get('new_tokens'), 0)} new tokens of the files are read once); first turn (nothing cached) first token: {fmt(ag.get('first_turn_ttft_s'), 2, ' s')}.", "",
959              "| Turn (run 1) | Prompt tokens | Reused | Read | Prompt tok/s | First token (s) | Decode tok/s |", "| ---: | ---: | ---: | ---: | ---: | ---: | ---: |"]
960        for d in ag["sessions"][0]:
961            if d["ok"]:
962                L.append(f"| {d['turn']} | {d['prompt_tokens']} | {d['reused_tokens']} | {d['read_tokens']} | {d['prompt_tps'] or '-'} | {d['ttft_s']} | {d['decode_tps'] or '-'} |")
963    cl = out["clients"]
964    if cl:
965        L += ["", f"### Concurrency: {cl['clients']} clients", "",
966              f"Total {fmt(cl.get('total_tps'), 1, ' tok/s')}; first token p50 {cl.get('ttft_p50_s')} s, p95 {cl.get('ttft_p95_s')} s; "
967              f"request latency p50 {cl.get('latency_p50_s')} s, p95 {cl.get('latency_p95_s')} s; errors {cl.get('errors')}. "
968              f"Server parallel slots: {mc.get('parallel_slots') or 1} (requests beyond that wait their turn)."]
969    if out["skipped"] or out["failures"]:
970        L += ["", "### Skipped and failed", ""]
971        L += [f"- skipped {k}: {v}" for k, v in out["skipped"].items()]
972        L += [f"- failed {f['where']}: {f['error']}" for f in out["failures"]]
973    L += ["", "Per-request data: `results.json`. Engine log lines from the start: `engine-log-excerpt.txt` (when this run started the server).", "",
974          "## Correctness and limitations", "",
975          "Not measured: this is a speed suite. The conversation uses the model's own replies, so token counts differ a little between runs. "
976          "Machine details come from the server, `nvidia-smi`/`rocm-smi` and the OS; background load is not recorded. "
977          f"Total time of the suite: {res['elapsed_s']:.0f} s.", ""]
978    return "\n".join(L)
979
980
981def compare_table(old: dict, new: dict) -> str:
982    a, b = summary_metrics(old["results"]), summary_metrics(new["results"])
983    rows = [f"{'':32s} {'old':>12s} {'new':>12s} {'change':>9s}"]
984    for k in dict.fromkeys([*a, *b]):
985        x, y = (a.get(k) or {}).get("median"), (b.get(k) or {}).get("median")
986        if x is None and y is None:
987            continue
988        ch = f"{(y - x) / x * 100:+.1f}%" if x and y is not None else ""
989        rows.append(f"{k:32s} {('-' if x is None else format(x, '.2f')):>12s} {('-' if y is None else format(y, '.2f')):>12s} {ch:>9s}")
990    ho, hn = old["machine"], new["machine"]
991    notes = [f"  {n}: {ho.get(f)} -> {hn.get(f)}" for n, f in (("GPU", "gpu"), ("engine", "engine_version"), ("model", "model"), ("quant", "quant"),
992                                                              ("context", "context")) if ho.get(f) != hn.get(f)]
993    return "\n".join(rows + (["", "differences:"] + notes if notes else []))
994
995
996def load_results(path: Path) -> dict:
997    p = Path(path)
998    if p.is_dir():
999        p = p / "results.json"
1000    return json.loads(p.read_text(encoding="utf-8"))
1001
1002
1003def short_table(res: dict) -> str:
1004    m = summary_metrics(res["results"])
1005    lines = []
1006    for k, v in m.items():
1007        if v:
1008            lines.append(f"  {k:32s} {v['median']:>10.2f}   ({v['min']:.2f} - {v['max']:.2f}, n={v['n']})")
1009    return "\n".join(lines)
1010
1011
1012def write_results(res: dict, parent: Path, red, log_lines: list[str]) -> Path:
1013    d = unique_dir(parent, results_dir_name(res["machine"], res["date"]))
1014    d.mkdir(parents=True)
1015    clean = redact_obj(res, red)
1016    (d / "results.json").write_text(json.dumps(clean, indent=1, ensure_ascii=False), encoding="utf-8")
1017    (d / "README.md").write_text(red(render_readme(res)), encoding="utf-8")
1018    if log_lines:
1019        (d / "engine-log-excerpt.txt").write_text(red("\n".join(log_lines)) + "\n", encoding="utf-8")
1020    return d
1021
1022
1023# --------------------------------------------------------------------------------------------------------- main
1024def server_base(host, port) -> str:
1025    """The address to talk to for a locally started server. The config's `host` is the interface the server
1026    binds - a specific IP, or a wildcard that is not connectable as written - so it cannot be polled as-is.
1027    An explicit `--url` bypasses this; there the caller knows the address."""
1028    host = host or "127.0.0.1"
1029    host = {"0.0.0.0": "127.0.0.1", "::": "::1"}.get(host, host)     # wildcard binds accept loopback
1030    authority = f"[{host}]" if ":" in host and not host.startswith("[") else host
1031    return f"http://{authority}:{port}"
1032
1033
1034def main(argv=None) -> int:
1035    ap = argparse.ArgumentParser(description="Measure this Strata install and write a shareable report (see the top of this file).")
1036    ap.add_argument("--config", help="the model config to run (default: the newest strata-*.json of this folder)")
1037    ap.add_argument("--url", help="use the server already running at this address (http://127.0.0.1:8080) instead of starting one")
1038    ap.add_argument("--port", type=int, help="the port to start the server on (default: the config's)")
1039    ap.add_argument("--gpu", help="start the server on this GPU only (as the server's --gpu)")
1040    ap.add_argument("--api-key", default=os.environ.get("STRATA_KEY", ""), help="the server's API key, if it has one (or STRATA_KEY)")
1041    ap.add_argument("--runs", type=int, default=3, help="runs per test (default 3)")
1042    ap.add_argument("--clients", type=int, default=0, metavar="N", help="also send N requests at once")
1043    ap.add_argument("--long", action="store_true", help="also a prompt of about 32,768 tokens")
1044    ap.add_argument("--think", action="store_true", help="leave thinking on (the default suite turns it off)")
1045    ap.add_argument("--out", help="where to write the results folder (default: bench/results)")
1046    ap.add_argument("--compare", metavar="DIR", help="a results folder (or its results.json) to put beside this run")
1047    ap.add_argument("--compare-only", metavar="NEW", help="print --compare of two existing results folders and stop")
1048    ap.add_argument("--ready-timeout", type=float, default=1800, help="seconds to wait for the model to load")
1049    ap.add_argument("--quiet", action="store_true")
1050    a = ap.parse_args(argv)
1051    say = (lambda *x, **k: None) if a.quiet else (lambda *x, **k: print(*x, **k, flush=True))
1052
1053    if a.compare_only:
1054        if not a.compare:
1055            ap.error("--compare-only NEW needs --compare OLD")
1056        print(compare_table(load_results(Path(a.compare)), load_results(Path(a.compare_only))))
1057        return 0
1058
1059    cfg_path, cfg, proc, log_path = None, None, None, None
1060    if a.config or not a.url:
1061        if a.config:
1062            cfg_path = Path(a.config)
1063            if not cfg_path.is_absolute() and not cfg_path.exists():
1064                cfg_path = ROOT / a.config
1065        else:
1066            found = find_configs()
1067            if found:
1068                cfg_path = found[0]
1069                if len(found) > 1:
1070                    say(f"Several models are installed; using {cfg_path.name} (the one used last). Pick another with --config FILE.")
1071        if cfg_path is None or not cfg_path.is_file():
1072            print("No Strata model is set up in this folder: run START-HERE.bat (Windows) or ./setup.sh (Linux) first, "
1073                  "or give --url of a running server.", file=sys.stderr)
1074            return 2
1075        cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig"))
1076    key = usable_key(a.api_key) or usable_key((cfg or {}).get("api_key"))
1077    if a.url:
1078        base = a.url.rstrip("/")
1079    else:
1080        port = a.port or int(cfg.get("port", 8080))
1081        base = server_base(cfg.get("host"), port)
1082    red = redactor(key=key)
1083    started = False
1084    try:
1085        if is_strata(base, key):
1086            say(f"Using the Strata server already running at {base}.")
1087        elif a.url:
1088            print(f"No Strata server answers at {base}.", file=sys.stderr)
1089            return 2
1090        else:
1091            if try_json(base, "/health", key, 3) is not None:
1092                print(f"Port {port} is used by something that is not Strata: pass --port N.", file=sys.stderr)
1093                return 2
1094            log_path = Path(tempfile.gettempdir()) / f"strata-bench-{os.getpid()}.log"
1095            say(f"Starting {cfg_path.name} on port {port} (loading takes 1-3 minutes; the PC may be slow meanwhile) ...")
1096            proc = start_server(cfg_path, port, a.gpu, log_path)
1097            started = True
1098            if not wait_ready(base, key, proc, a.ready_timeout, say):
1099                tail = log_path.read_text(encoding="utf-8", errors="replace").splitlines()[-15:] if log_path.exists() else []
1100                print("The server did not become ready. Last log lines:\n" + red("\n".join(tail)), file=sys.stderr)
1101                return 1
1102        t0 = time.time()
1103        pre = collect_machine(base, key, cfg, a.gpu)
1104        suite = Suite(base, key, pre.get("context"), max(1, a.runs), a.think, log=say, want_clients=a.clients, want_long=a.long)
1105        slots = pre.get("parallel_slots") or 1
1106        if a.clients and a.clients > slots:
1107            say(f"Note: the server runs {slots} request(s) at a time (--batch), so {a.clients} clients will partly wait their turn.")
1108        say("Running the suite (about 3-10 minutes) ...")
1109        out = suite.run()
1110        machine = collect_machine(base, key, cfg, a.gpu)      # again: VRAM and the cache after the work
1111        if not machine.get("gpu"):
1112            machine["gpu"] = pre.get("gpu")
1113        res = {"schema": SCHEMA, "tool": "tools/strata_bench.py", "date": datetime.date.today().isoformat(),
1114               "params": {"runs": suite.runs, "think": a.think, "clients": a.clients, "long": a.long, "started_server": started,
1115                          "command": "python tools/strata_bench.py" + "".join(
1116                              f" {x}" for x in (f"--clients {a.clients}" if a.clients else "", "--long" if a.long else "",
1117                                                "--think" if a.think else "", f"--runs {a.runs}" if a.runs != 3 else "") if x)},
1118               "elapsed_s": time.time() - t0, "machine": machine, "results": out}
1119        parent = Path(a.out) if a.out else ROOT / "bench" / "results"
1120        d = write_results(res, parent, red, log_excerpt(log_path) if log_path else [])
1121        say("\nResults (median, range over the runs):")
1122        say(red(short_table(res)))
1123        if out["failures"] or out["skipped"]:
1124            say(f"  ({len(out['failures'])} failed request(s), {len(out['skipped'])} skipped test(s): see the report)")
1125        if a.compare:
1126            say("\nCompared with " + a.compare + ":")
1127            say(red(compare_table(load_results(Path(a.compare)), redact_obj(res, lambda s: s))))
1128        try:
1129            shown = d.relative_to(ROOT)
1130        except ValueError:
1131            shown = d
1132        say(f"\nReport: {shown / 'README.md'}\nShare it: open a pull request that adds the folder {shown} (see docs/COMMUNITY_BENCHMARKS.md), "
1133            f"or paste README.md into a GitHub issue. Home folders, user and host names and IP addresses are already replaced; "
1134            f"read it once before you share it.")
1135        say("For results other people can compare with, run the standard benchmark: strata bench run (docs/BENCHMARK_PROTOCOL.md).")
1136        return 1 if out["failures"] and not any(out[k] for k in ("chat", "prompts", "agent")) else 0
1137    finally:
1138        if started:
1139            stop_server(proc)
1140
1141
1142if __name__ == "__main__":
1143    sys.exit(main())