okami.mom/strata

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

Niko1221Merge f-141-fixb: Python, docs and bench fixes and portsef8071303

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