okami.mom/strata

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

Niko1221Merge f-142b-serve into f-1426e1085c1d

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