okami.mom/strata

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

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

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