okami.mom/strata

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

avarakinBench: RTX 5060 Ti 16 GB on Ryzen 9 7945HX, IQ3_S (#1016)60982e6ad

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