okami.mom/strata

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

xxDomanbench: community MI50 (gfx906) — Strata 0.1.38 speed and recall (#758)c97ad41eb

main
7.3 KiB144 linesraw
1#!/usr/bin/env python3
2"""Serial, fresh-prompt Strata benchmark — adapted for the MI50 (gfx906) container.
3
4Based on bench/results/2026-09-30-community-rtx-5090/benchmark.py. Runs INSIDE the
5strata container (imports strata_tokenizer and serve.frontend from /opt/strata).
6Added: --api-key (Strata's server requires an Authorization header).
7"""
8import argparse
9import hashlib
10import json
11import statistics
12import sys
13import time
14import urllib.request
15from pathlib import Path
16
17
18def main():
19    parser = argparse.ArgumentParser(description=__doc__)
20    parser.add_argument("--root", type=Path, default=Path("/opt/strata"))
21    parser.add_argument("--pack", type=Path, default=Path("/data/packs/iq2_xs"))
22    parser.add_argument("--url", default="http://127.0.0.1:8085")
23    parser.add_argument("--api-key", default="")
24    parser.add_argument("--out", type=Path, default=Path("/work/bench/results"))
25    parser.add_argument("--targets", default="4096,32768")
26    parser.add_argument("--runs", type=int, default=3)
27    args = parser.parse_args()
28    args.out.mkdir(parents=True, exist_ok=True)
29    sys.path[:0] = [str(args.root), str(args.root / "tools")]
30    from strata_tokenizer import Tokenizer
31    from serve.frontend import ChatTemplate, openai_to_messages
32
33    auth = {"Content-Type": "application/json"}
34    if args.api_key:
35        auth["Authorization"] = "Bearer " + args.api_key
36
37    def get(url):
38        request = urllib.request.Request(url, headers=auth)
39        with urllib.request.urlopen(request, timeout=30) as response:
40            return json.load(response)
41
42    directory = args.pack / "tokenizer"
43    vocab = json.loads((directory / "vocab.json").read_text())
44    tokens = [None] * len(vocab)
45    for token, number in vocab.items():
46        tokens[number] = token
47    tokenizer = Tokenizer(tokens, (directory / "merges.txt").read_text().splitlines(),
48                          json.loads((directory / "token_type.json").read_text()))
49    template = ChatTemplate(directory / "chat_template.jinja")
50    initial = get(args.url + "/v1/status")
51    (args.out / "initial-status.json").write_text(json.dumps(initial, indent=2) + "\n")
52    rows = []
53
54    def request(content, maximum=256):
55        return {"model": "strata", "messages": [{"role": "user", "content": content}],
56                "temperature": 0, "reasoning_effort": "none", "max_tokens": maximum,
57                "stream": True, "stream_options": {"include_usage": True}}
58
59    def count(req):
60        messages, tools, kwargs = openai_to_messages(req)
61        return len(tokenizer.encode(template.render(messages, tools, **kwargs), parse_special=True))
62
63    def perform(label, req, expected=None):
64        body = json.dumps(req).encode()
65        (args.out / (label + "-request.json")).write_bytes(body + b"\n")
66        print("start", label, "tokens", expected, flush=True)
67        chunks, texts, first, finish = [], [], None, None
68        started = time.perf_counter()
69        wire = urllib.request.Request(args.url + "/v1/chat/completions", data=body, headers=auth)
70        with urllib.request.urlopen(wire, timeout=1800) as response:
71            for line in response:
72                if not line.startswith(b"data: "):
73                    continue
74                payload = line[6:].strip()
75                if payload == b"[DONE]":
76                    break
77                chunk = json.loads(payload)
78                chunks.append(chunk)
79                for choice in chunk.get("choices", []):
80                    delta = choice.get("delta", {})
81                    text = (delta.get("content") or "") + (delta.get("reasoning_content") or "")
82                    if text:
83                        first = first if first is not None else time.perf_counter() - started
84                        texts.append(text)
85                    finish = choice.get("finish_reason") or finish
86        elapsed = time.perf_counter() - started
87        metrics = get(args.url + "/metrics")
88        engine = metrics["requests"][0]
89        usage = next((chunk["usage"] for chunk in reversed(chunks) if "usage" in chunk), {})
90        row = {"label": label, "expected_prompt_tokens": expected,
91               "request_sha256": hashlib.sha256(body).hexdigest(),
92               "client_ttft_s": first, "client_elapsed_s": elapsed, "finish_reason": finish,
93               "usage": usage, "engine": engine, "text": "".join(texts)}
94        if expected is not None and engine["prompt_tokens"] != expected:
95            raise RuntimeError(f"token count mismatch: {expected} vs {engine['prompt_tokens']}")
96        if not texts:
97            raise RuntimeError(f"no text received for {label}")
98        (args.out / (label + "-raw.json")).write_text(json.dumps({"chunks": chunks, "row": row}, indent=2) + "\n")
99        rows.append(row)
100        (args.out / "results.json").write_text(json.dumps(rows, indent=2) + "\n")
101        print("done", label, json.dumps({"ttft_s": first, "elapsed_s": elapsed, "engine": engine}), flush=True)
102        return row
103
104    perform("warmup", request("Reply with exactly the word READY.", 16))
105    filler = "\n".join(f"def task_{i:05d}(value: int) -> int: return (value * {(i % 97) + 1} + {i}) % 100003"
106                       for i in range(12000))
107    ending = ("\n\nWrite a detailed explanation of the code above. Discuss deterministic integer transforms, "
108              "modulo arithmetic, testing, naming, complexity, and maintainability. Write at least 600 words.")
109    for target in map(int, args.targets.split(",")):
110        for run in range(1, args.runs + 1):
111            prefix = f"Benchmark nonce: series-{target}-trial-{run}.\nReview this synthetic Python module:\n"
112            lo, hi = 0, len(filler)
113            while lo < hi:
114                middle = (lo + hi + 1) // 2
115                if count(request(prefix + filler[:middle] + ending)) <= target:
116                    lo = middle
117                else:
118                    hi = middle - 1
119            req = request(prefix + filler[:lo] + ending)
120            actual = count(req)
121            if actual < target - 20 or actual > target:
122                raise RuntimeError(f"could not construct target {target}: {actual}")
123            perform(f"tokens-{target}-run-{run}", req, actual)
124    measured = [row for row in rows if row["label"] != "warmup"]
125    groups = {}
126    for target in map(int, args.targets.split(",")):
127        subset = [r for r in measured if r["label"].startswith(f"tokens-{target}-")]
128        values = {
129            "prompt_tokens": [r["engine"]["prompt_tokens"] for r in subset],
130            "cached_tokens": [r["engine"].get("reused", 0) for r in subset],
131            "output_tokens": [r["engine"]["engine_generated"] for r in subset],
132            "client_ttft_s": [r["client_ttft_s"] for r in subset],
133            "client_elapsed_s": [r["client_elapsed_s"] for r in subset],
134            "prefill_tok_s": [(r["engine"]["prompt_tokens"] - (r["engine"].get("reused") or 0)) / (r["engine"]["prompt_ms"] / 1000) for r in subset],
135            "decode_tok_s": [r["engine"]["engine_generated"] / (r["engine"]["decode_ms"] / 1000) for r in subset],
136        }
137        groups[str(target)] = {key: {"median": statistics.median(v), "min": min(v), "max": max(v)}
138                              for key, v in values.items()}
139    (args.out / "summary.json").write_text(json.dumps(groups, indent=2) + "\n")
140    print("summary", json.dumps(groups), flush=True)
141
142
143if __name__ == "__main__":
144    main()