okami.mom/strata

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

Yasei-no-otokobench: report Coder IQ1_M on Threadripper 3990X and RX 6900 XT (#628)cc86ad90d

main
15.7 KiB318 linesraw
1#!/usr/bin/env python3
2"""Measure Strata streaming latency and engine throughput using only Python's stdlib.
3
4Run against an already-started local server. This script does not install or start
5Strata, clear server state, or contact any host other than the configured URL.
6"""
7import argparse
8import hashlib
9import json
10import re
11import statistics
12import time
13import urllib.error
14import urllib.request
15from pathlib import Path
16
17
18DEFAULT_URL = "http://127.0.0.1:8080"
19DEFAULT_CASES = "short,4k,32k"
20ENGINE_LINE = re.compile(
21    r"prompt (?P<prompt>\d+) tokens = (?P<reused>\d+) reused \+ (?P<read>\d+)(?: of \d+)? read in "
22    r"(?P<read_ms>[\d.]+) ms \((?P<prefill>[\d.]+) tok/s\), (?P<generated>\d+) generated in "
23    r"(?P<decode_ms>[\d.]+) ms \((?P<decode>[\d.]+) tok/s\)"
24)
25
26
27def json_request(url, payload=None, headers=None, timeout=30):
28    data = None if payload is None else json.dumps(payload, ensure_ascii=False).encode("utf-8")
29    request = urllib.request.Request(url, data=data, headers=headers or {})
30    with urllib.request.urlopen(request, timeout=timeout) as response:
31        return json.loads(response.read().decode("utf-8"))
32
33
34def auth_headers(api_key, content_type=False):
35    headers = {"Content-Type": "application/json"} if content_type else {}
36    if api_key:
37        headers["Authorization"] = "Bearer " + api_key
38    return headers
39
40
41def read_log_from(path, offset):
42    if path is None:
43        return ""
44    try:
45        with path.open("rb") as stream:
46            stream.seek(0, 2)
47            end = stream.tell()
48            stream.seek(min(offset, end))
49            return stream.read().decode("utf-8", "replace")
50    except OSError as exc:
51        return f"[log read error: {exc}]"
52
53
54def request_body(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
60def short_prompt(run_id):
61    return (f"Benchmark nonce: {run_id}. Write a complete Python module for a robust in-memory task queue. "
62            "Include typed dataclasses, validation, stable priority ordering, enqueue/dequeue/peek/remove operations, "
63            "clear exceptions, and a detailed unittest suite with edge cases. Explain behavior in docstrings and "
64            "comments. Output the complete code only; make it production-quality and detailed.")
65
66
67def sized_prompt(target_tokens, run_id, count_tokens):
68    """Build a deterministic code-review prompt at the target rendered length."""
69    prefix = (f"Benchmark nonce: {run_id}. Treat this as an independent request.\n"
70              "Review this synthetic Python module and explain its behavior, edge cases, tests, and complexity.\n")
71    suffix = "\n\nGive a concise code review with concrete observations.\n"
72    def build(lines):
73        filler = "".join(
74            f"def transform_{i:05d}(value: int, offset: int = {i}) -> int:\n"
75            f"    return (value * {(i % 97) + 1} + offset + {i}) % 100003\n\n"
76            for i in range(lines)
77        )
78        return prefix + filler + suffix
79
80    # The count endpoint renders and tokenizes the prompt without running the
81    # model. Binary search the generated lines; the actual OpenAI request usage
82    # is retained too because the server reports that authoritative count.
83    lo, hi = 0, max(8, int(target_tokens / 12))
84    while count_tokens(build(hi)) < target_tokens:
85        hi *= 2
86    while lo < hi:
87        middle = (lo + hi + 1) // 2
88        if count_tokens(build(middle)) <= target_tokens:
89            lo = middle
90        else:
91            hi = middle - 1
92    return build(lo)
93
94
95def history_record(metrics, started_wall):
96    for record in metrics.get("requests", []):
97        if record.get("time", 0) >= started_wall - 0.1:
98            return record
99    return None
100
101
102def summarize(values):
103    vals = [v for v in values if isinstance(v, (int, float))]
104    if not vals:
105        return {"median": None, "min": None, "max": None}
106    return {"median": statistics.median(vals), "min": min(vals), "max": max(vals)}
107
108
109def main():
110    parser = argparse.ArgumentParser(description=__doc__)
111    parser.add_argument("--url", default=DEFAULT_URL, help="Strata base URL (default: %(default)s)")
112    parser.add_argument("--cases", default=DEFAULT_CASES, help="comma-separated subset of short,4k,32k")
113    parser.add_argument("--runs", type=int, default=3, help="measured runs per case (default: %(default)s)")
114    parser.add_argument("--out", type=Path, default=Path(__file__).resolve().parent,
115                        help="directory for raw.jsonl, summary.json, and log snippets")
116    parser.add_argument("--log", type=Path, help="optional Strata engine log to capture per-run appended lines")
117    parser.add_argument("--api-key", default="", help="API key, if the local server requires one")
118    args = parser.parse_args()
119    if args.runs < 1:
120        parser.error("--runs must be at least 1")
121    cases = [name.strip().lower() for name in args.cases.split(",") if name.strip()]
122    unknown = sorted(set(cases) - {"short", "4k", "32k"})
123    if not cases or unknown:
124        parser.error("--cases must be a non-empty comma-separated subset of short,4k,32k")
125    args.out.mkdir(parents=True, exist_ok=True)
126    base = args.url.rstrip("/")
127    headers = auth_headers(args.api_key, content_type=True)
128    get_headers = auth_headers(args.api_key)
129
130    initial = json_request(base + "/health", headers=get_headers)
131    (args.out / "initial-health.json").write_text(json.dumps(initial, indent=2) + "\n", encoding="utf-8")
132    records = []
133    warmup_records = []
134    raw_path = args.out / "raw.jsonl"
135    # Reset this harness's output for a new invocation; server/model state stays intact.
136    raw_path.write_text("", encoding="utf-8")
137
138    def perform(label, content, maximum=256, warmup=False, expected_prompt_tokens=None):
139        payload = request_body(content, maximum)
140        wire = json.dumps(payload, ensure_ascii=False).encode("utf-8")
141        try:
142            metrics_before = json_request(base + "/metrics", headers=get_headers)
143        except (urllib.error.URLError, TimeoutError, OSError, ValueError) as exc:
144            metrics_before = {"error": str(exc)}
145        started_wall = time.time()
146        log_offset = 0
147        if args.log:
148            try:
149                log_offset = args.log.stat().st_size
150            except OSError:
151                pass
152        started = time.perf_counter()
153        first_text_at = None
154        chunks, text_parts, reasoning_parts = [], [], []
155        finish_reason = None
156        stream_error = None
157        usage = None
158        request = urllib.request.Request(base + "/v1/chat/completions", data=wire, headers=headers)
159        try:
160            with urllib.request.urlopen(request, timeout=1800) as response:
161                for line in response:
162                    if not line.startswith(b"data: "):
163                        continue
164                    data = line[6:].strip()
165                    if data == b"[DONE]":
166                        break
167                    try:
168                        chunk = json.loads(data.decode("utf-8"))
169                    except (UnicodeDecodeError, json.JSONDecodeError):
170                        continue
171                    chunks.append(chunk)
172                    if chunk.get("error"):
173                        stream_error = chunk["error"]
174                    if "usage" in chunk:
175                        usage = chunk["usage"]
176                    for choice in chunk.get("choices", []):
177                        delta = choice.get("delta") or {}
178                        text = delta.get("content") or ""
179                        reasoning = delta.get("reasoning_content") or ""
180                        if text or reasoning:
181                            if first_text_at is None:
182                                first_text_at = time.perf_counter() - started
183                            text_parts.append(text)
184                            reasoning_parts.append(reasoning)
185                        finish_reason = choice.get("finish_reason") or finish_reason
186        except (urllib.error.URLError, TimeoutError, OSError) as exc:
187            stream_error = {"message": str(exc), "type": "client_error"}
188        elapsed = time.perf_counter() - started
189        metrics, metric_error = {}, None
190        try:
191            metrics = json_request(base + "/metrics", headers=get_headers)
192        except (urllib.error.URLError, TimeoutError, OSError, ValueError) as exc:
193            metric_error = str(exc)
194        engine = history_record(metrics, started_wall)
195        log_text = read_log_from(args.log, log_offset)
196        log_lines = [line.rstrip() for line in log_text.splitlines() if line.strip()]
197        parsed_log = []
198        for line in log_lines:
199            match = ENGINE_LINE.search(line)
200            if match:
201                parsed_log.append({key: (float(value) if "." in value else int(value))
202                                   for key, value in match.groupdict().items()})
203        stream_timings = next((chunk["timings"] for chunk in reversed(chunks) if chunk.get("timings")), None)
204        if engine:
205            fresh = max(0, (engine.get("prompt_tokens") or 0) - (engine.get("reused") or 0))
206            engine_timings = {
207                "prompt_tokens": engine.get("prompt_tokens"), "fresh_prompt_tokens": fresh,
208                "reused_tokens": engine.get("reused"), "prompt_ms": engine.get("prompt_ms"),
209                "prefill_tok_s": (fresh / (engine["prompt_ms"] / 1000)
210                                  if engine.get("prompt_ms") else None),
211                "generated_tokens": engine.get("engine_generated"), "decode_ms": engine.get("decode_ms"),
212                "decode_tok_s": engine.get("decode_tok_s"),
213                "drafts_offered": engine.get("drafts_offered"),
214                "drafts_accepted": engine.get("drafts_accepted"),
215            }
216        else:
217            engine_timings = None
218        row = {
219            "label": label, "warmup": warmup, "target_prompt_tokens": expected_prompt_tokens,
220            "request_sha256": hashlib.sha256(wire).hexdigest(),
221            "request_body": payload,
222            "client_ttft_s": first_text_at, "client_total_latency_s": elapsed,
223            "finish_reason": finish_reason, "usage": usage, "engine": engine,
224            "metrics_before": metrics_before, "metrics_after": metrics,
225            "engine_timings": stream_timings or engine_timings,
226            "prefix_reused_tokens": (engine or {}).get("reused"),
227            "api_cached_tokens": ((usage or {}).get("prompt_tokens_details") or {}).get("cached_tokens"),
228            "output_text": "".join(text_parts), "reasoning_text": "".join(reasoning_parts),
229            "raw_stream_chunks": chunks, "stream_error": stream_error,
230            "metrics_error": metric_error, "engine_log_lines": log_lines[-30:],
231            "parsed_engine_log_timings": parsed_log,
232        }
233        if warmup:
234            warmup_records.append(row)
235            (args.out / "warmup.json").write_text(
236                json.dumps(warmup_records, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
237        else:
238            records.append(row)
239            with raw_path.open("a", encoding="utf-8") as stream:
240                stream.write(json.dumps(row, ensure_ascii=False) + "\n")
241            if args.log:
242                safe_label = re.sub(r"[^A-Za-z0-9_.-]", "_", label)
243                (args.out / f"{safe_label}.log-snippet.txt").write_text(
244                    "\n".join(log_lines) + ("\n" if log_lines else ""), encoding="utf-8")
245        print(json.dumps({"run": label, "ttft_s": first_text_at, "total_s": elapsed,
246                          "prompt_tokens": (engine or {}).get("prompt_tokens"),
247                          "reused": (engine or {}).get("reused"), "engine_timings": row["engine_timings"],
248                          "error": stream_error}, ensure_ascii=False), flush=True)
249        if stream_error:
250            raise RuntimeError(f"{label} failed: {stream_error}")
251        if not text_parts:
252            raise RuntimeError(f"{label} produced no nonempty content delta")
253        return row
254
255    # Separate warm-up from the measured sample set.
256    perform("warmup", "Benchmark warm-up: explain in detail how a Python heap maintains priority order.",
257            maximum=256, warmup=True)
258    (args.out / "warmup.json").write_text(json.dumps(warmup_records, indent=2, ensure_ascii=False) + "\n",
259                                            encoding="utf-8")
260    for case in cases:
261        for run in range(1, args.runs + 1):
262            nonce = f"rx6900xt-coder-{case}-trial-{run}"
263            if case == "short":
264                content, maximum = short_prompt(nonce), 256
265                label = f"short-run-{run}"
266            else:
267                target = 4096 if case == "4k" else 32768
268                def count_tokens(text):
269                    result = json_request(base + "/v1/messages/count_tokens",
270                                          {"model": "strata", "messages": [{"role": "user", "content": text}]},
271                                          headers=headers, timeout=180)
272                    return int(result["input_tokens"])
273                content, maximum = sized_prompt(target, nonce, count_tokens), 256
274                expected_tokens = count_tokens(content)
275                label = f"{case}-run-{run}"
276            if case == "short":
277                expected_tokens = None
278            perform(label, content, maximum=maximum, expected_prompt_tokens=expected_tokens)
279
280    grouped = {}
281    for case in cases:
282        subset = [row for row in records if row["label"].startswith(case + "-")]
283        def metric(row, key):
284            engine = row.get("engine") or {}
285            if key == "prompt_tok_s":
286                n = engine.get("prompt_tokens", 0) - (engine.get("reused") or 0)
287                ms = engine.get("prompt_ms")
288                return n / (ms / 1000) if ms else None
289            if key == "decode_tok_s":
290                n = engine.get("engine_generated") or 0
291                ms = engine.get("decode_ms")
292                return n / (ms / 1000) if ms else None
293            return row.get(key)
294        grouped[case] = {
295            "runs": len(subset),
296            "prompt_tokens": summarize([(r.get("engine") or {}).get("prompt_tokens") for r in subset]),
297            "prefix_reused_tokens": summarize([r.get("prefix_reused_tokens") for r in subset]),
298            "completion_tokens": summarize([(r.get("usage") or {}).get("completion_tokens") for r in subset]),
299            "client_ttft_s": summarize([metric(r, "client_ttft_s") for r in subset]),
300            "client_total_latency_s": summarize([metric(r, "client_total_latency_s") for r in subset]),
301            "prompt_tok_s": summarize([metric(r, "prompt_tok_s") for r in subset]),
302            "decode_tok_s": summarize([metric(r, "decode_tok_s") for r in subset]),
303            "finish_reasons": [r.get("finish_reason") for r in subset],
304        }
305    summary = {"url": base, "cases": cases, "runs_per_case": args.runs,
306               "request_settings": {"max_tokens": 256, "temperature": 0, "reasoning_effort": "none",
307                                    "stream": True, "warmup_excluded": True},
308               "cache_note": "No server cache-clear API is used. Every measured prompt starts with a unique nonce; "
309                             "actual prefix reuse is taken from before/after engine history and API usage. The target "
310                             "size uses /v1/messages/count_tokens; completion usage is also retained for the actual "
311                             "OpenAI request.",
312               "case_results": grouped, "raw_jsonl": str(raw_path)}
313    (args.out / "summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
314    print(json.dumps(summary, indent=2, ensure_ascii=False))
315
316
317if __name__ == "__main__":
318    main()