okami.mom/strata

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

Niko1221Merge branch 'f-021-bench' into f-021-intbcf67d177

main
13.6 KiB262 linesraw
1#!/usr/bin/env python3
2"""Build the frozen fixture bundle of the Strata standard benchmark (docs/BENCHMARK_PROTOCOL.md).
3
4    python tools/build_standard_corpus.py --tokenizer PACK/tokenizer [--out bench/prompts/standard-v1]
5
6`strata bench run` reads the bundle this writes and never builds prompts at run time, so every machine sends the same bytes. The
7bundle has one JSON file per scheduled request (the 22 required ones and the 12 of the optional concurrency stage), `build.json`
8(how it was made: the tokenizer and template hashes, the target and actual token counts) and `MANIFEST.sha256` (a `sha256sum`
9listing of every other file). The SHA-256 of that manifest is the protocol's `corpus_sha256`.
10
11The prompts are synthetic. The two record counts (for about 4,096 and 16,384 tokens) are chosen with the pinned tokenizer and the
12chat template Strata ships (serve/chat_template.jinja), rendered the way the server renders a thinking request. Run it again
13and the bytes are identical; a change to anything the protocol freezes needs a new protocol ID.
14"""
15from __future__ import annotations
16
17import argparse
18import hashlib
19import json
20import math
21import sys
22from pathlib import Path
23
24ROOT = Path(__file__).resolve().parents[1]
25sys.path.insert(0, str(ROOT))
26sys.path.insert(0, str(Path(__file__).resolve().parent))
27
28PROTOCOL_ID = "strata-qwen38-thinking-v1-draft.1"
29BUNDLE = "standard-v1"
30
31SHORT_TASK = "Explain how a hash table finds a value, including collisions and one small example."
32RECORD = "record{:06d}: alpha beta gamma delta epsilon zeta eta theta."
33SUMMARY_QUESTION = "Summarize the structure of these records and explain how to look up a record by its ID."
34TARGETS = {"prompt-4k": 4096, "prompt-16k": 16384}
35TOLERANCE = 0.02
36TOOL_DESCRIPTION = "Synthetic benchmark lookup; no external action is performed."
37
38# What the template is rendered with when the runner asks for the protocol's thinking settings.
39TEMPLATE_KWARGS = {"enable_thinking": True, "preserve_thinking": True, "reasoning_effort": "xhigh"}
40
41WARMUP_CAP, PERFORMANCE_CAP, SANITY_CAP, CONCURRENCY_CAP = 128, 512, 2048, 512
42
43INSTRUCTION = {
44    "I1": ("Return only a JSON object with ok set to true and count set to the integer 3. No other keys.",
45           {"kind": "json", "value": {"ok": True, "count": 3}}),
46    "I2": ("Sort these integers in ascending order and remove duplicates: 9, 2, -4, 2, 1. Return only a JSON array.",
47           {"kind": "json", "value": [-4, 1, 2, 9]}),
48    "I3": ("Project: Orion. Build: 17. Return only a JSON object with keys project (string) and build (integer).",
49           {"kind": "json", "value": {"project": "Orion", "build": 17}}),
50    "I4": ("Reply with exactly the word READY in uppercase and nothing else.",
51           {"kind": "text", "value": "READY"}),
52}
53
54# id -> (records, inserts [(fraction, line)], question, expected)
55RETRIEVAL = {
56    "R1": ("prompt-4k", [(0.10, "access_code = ORBIT-731")],
57           "What is access_code? Reply only with its value.", {"kind": "text", "value": "ORBIT-731"}),
58    "R2": ("prompt-4k", [(0.50, "storage_label = CEDAR-284")],
59           "What is storage_label? Reply only with its value.", {"kind": "text", "value": "CEDAR-284"}),
60    "R3": ("prompt-16k", [(0.90, "archive_code = DELTA-906")],
61           "What is archive_code? Reply only with its value.", {"kind": "text", "value": "DELTA-906"}),
62    "R4": ("prompt-16k", [(0.10, "north = N-124"), (0.90, "south = S-875")],
63           "Return only a JSON object containing north and south and their values.",
64           {"kind": "json", "value": {"north": "N-124", "south": "S-875"}}),
65}
66
67# id -> (prompt, function name, {property: type}, expected arguments)
68TOOLS = {
69    "T1": ("Use lookup_record to look up record A-17.", "lookup_record", {"id": "string"}, {"id": "A-17"}),
70    "T2": ("Use get_weather for Zagreb in celsius.", "get_weather", {"city": "string", "unit": "string"},
71           {"city": "Zagreb", "unit": "celsius"}),
72    "T3": ("Use convert_units to convert 3 km to m.", "convert_units",
73           {"value": "number", "from_unit": "string", "to_unit": "string"},
74           {"value": 3, "from_unit": "km", "to_unit": "m"}),
75    "T4": ("Use get_build_status for project Orion, build 17.", "get_build_status",
76           {"project": "string", "build": "integer"}, {"project": "Orion", "build": 17}),
77}
78
79
80def sha256_bytes(data: bytes) -> str:
81    return hashlib.sha256(data).hexdigest()
82
83
84def encoded(obj) -> bytes:
85    """The one serialization of every fixture file: UTF-8, LF, two-space indent, key order as written."""
86    return (json.dumps(obj, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
87
88
89def tool_schema(name: str, properties: dict) -> dict:
90    return {"type": "function", "function": {
91        "name": name, "description": TOOL_DESCRIPTION,
92        "parameters": {"type": "object", "properties": {key: {"type": kind} for key, kind in properties.items()},
93                       "required": list(properties), "additionalProperties": False}}}
94
95
96def user_message(request_id: str, body: str) -> list[dict]:
97    return [{"role": "user", "content": f"[case {request_id}]\n{body}"}]
98
99
100def records_body(count: int, question: str, inserts: list[tuple[float, str]] = ()) -> str:
101    """`count` records, one per line, with each insert placed before record index floor(fraction * count); then the question."""
102    before: dict[int, list[str]] = {}
103    for fraction, line in inserts:
104        before.setdefault(math.floor(fraction * count), []).append(line)
105    lines: list[str] = []
106    for index in range(count):
107        lines.extend(before.get(index, ()))
108        lines.append(RECORD.format(index + 1))
109    return "\n".join(lines) + "\n" + question
110
111
112class Counter:
113    """Token counts of a rendered request, with the tokenizer and the template the server uses."""
114
115    def __init__(self, tokenizer_dir: Path, template_path: Path):
116        import strata_tokenizer as ST
117        from serve.frontend import ChatTemplate
118        vocab = json.loads((tokenizer_dir / "vocab.json").read_text(encoding="utf-8"))
119        tokens = [None] * len(vocab)
120        for token, index in vocab.items():
121            tokens[index] = token
122        merges = (tokenizer_dir / "merges.txt").read_text(encoding="utf-8").split("\n")
123        if merges and merges[-1] == "":
124            merges.pop()
125        types = json.loads((tokenizer_dir / "token_type.json").read_text(encoding="utf-8"))
126        self.tok = ST.Tokenizer(tokens, merges, types)
127        self.template = ChatTemplate(template_path)
128
129    def ids(self, messages: list[dict], tools: list[dict] | None) -> list[int]:
130        functions = [t["function"] for t in tools] if tools else None
131        text = self.template.render(messages, tools=functions, **TEMPLATE_KWARGS)
132        return self.tok.encode(text, parse_special=True)
133
134
135def pick_record_count(counter: Counter, target: int) -> tuple[int, int]:
136    """The number of complete records whose rendered performance request is closest to `target` tokens."""
137    def tokens(count: int) -> int:
138        body = records_body(count, SUMMARY_QUESTION)
139        return len(counter.ids(user_message("performance-prompt-4k-r1", body), None))
140    low, high = 20, 60
141    t_low, t_high = tokens(low), tokens(high)
142    slope = (t_high - t_low) / (high - low)
143    count = max(1, round(low + (target - t_low) / slope))
144    for _ in range(4):
145        current = tokens(count)
146        step = round((target - current) / slope)
147        if step == 0:
148            break
149        count += step
150    best = min(range(max(1, count - 4), count + 5), key=lambda n: (abs(tokens(n) - target), n))
151    return best, tokens(best)
152
153
154def lcp(a: list[int], b: list[int]) -> int:
155    n = 0
156    for x, y in zip(a, b):
157        if x != y:
158            break
159        n += 1
160    return n
161
162
163def build(tokenizer_dir: Path, template_path: Path, out: Path) -> dict:
164    counter = Counter(tokenizer_dir, template_path)
165    counts = {}
166    for case, target in TARGETS.items():
167        count, actual = pick_record_count(counter, target)
168        if abs(actual - target) > TOLERANCE * target:
169            raise SystemExit(f"{case}: {actual} tokens is not within {TOLERANCE:.0%} of {target}")
170        counts[case] = {"records": count, "target_tokens": target}
171        print(f"{case}: {count} records, {actual} tokens (target {target})")
172
173    requests: list[dict] = []
174
175    def add(request_id, phase, case_id, repetition, seed, cap, messages, *, tools=None, expected=None, category=None,
176            round_=None, concurrency=1, target=None):
177        requests.append({
178            "id": request_id, "phase": phase, "case_id": case_id, "repetition": repetition, "round": round_,
179            "seed": seed, "max_output_tokens": cap, "concurrency": concurrency, "category": category,
180            "target_input_tokens": target, "messages": messages, "tools": tools,
181            "tool_choice": "auto" if tools else None, "expected": expected})
182
183    short = lambda request_id: user_message(request_id, SHORT_TASK)          # noqa: E731
184    long_body = lambda case: records_body(counts[case]["records"], SUMMARY_QUESTION)   # noqa: E731
185    add("warmup", "warmup", "warmup", 1, 1, WARMUP_CAP, short("warmup"))
186    for repetition in (1, 2, 3):
187        add(f"performance-short-r{repetition}", "performance", "short", repetition, repetition, PERFORMANCE_CAP,
188            short(f"performance-short-r{repetition}"))
189        for case in ("prompt-4k", "prompt-16k"):
190            request_id = f"performance-{case}-r{repetition}"
191            add(request_id, "performance", case, repetition, repetition, PERFORMANCE_CAP,
192                user_message(request_id, long_body(case)), target=TARGETS[case])
193    for name, (prompt, expected) in INSTRUCTION.items():
194        add(f"sanity-{name}", "sanity", name, 1, 1, SANITY_CAP, user_message(f"sanity-{name}", prompt),
195            expected=expected, category="instruction")
196    for name, (case, inserts, question, expected) in RETRIEVAL.items():
197        body = records_body(counts[case]["records"], question, inserts)
198        add(f"sanity-{name}", "sanity", name, 1, 1, SANITY_CAP, user_message(f"sanity-{name}", body),
199            expected=expected, category="retrieval", target=TARGETS[case])
200    for name, (prompt, function, properties, arguments) in TOOLS.items():
201        add(f"sanity-{name}", "sanity", name, 1, 1, SANITY_CAP, user_message(f"sanity-{name}", prompt),
202            tools=[tool_schema(function, properties)],
203            expected={"kind": "tool_call", "name": function, "arguments": arguments}, category="tool_call")
204    for round_ in (1, 2, 3):
205        for client in (1, 2, 3, 4):
206            request_id = f"concurrency-r{round_}-c{client}"
207            add(request_id, "concurrency", "short-burst", round_, 4 * (round_ - 1) + client, CONCURRENCY_CAP,
208                short(request_id), round_=round_, concurrency=4)
209
210    token_ids = {r["id"]: counter.ids(r["messages"], r["tools"]) for r in requests}
211    for request in requests:
212        ids = token_ids[request["id"]]
213        request["input_tokens_frozen"] = len(ids)
214        request["max_shared_prefix_tokens"] = max(lcp(ids, other) for key, other in token_ids.items()
215                                                  if key != request["id"])
216        if request["target_input_tokens"] is not None:
217            deviation = abs(len(ids) - request["target_input_tokens"]) / request["target_input_tokens"]
218            if deviation > TOLERANCE:
219                raise SystemExit(f"{request['id']}: {len(ids)} tokens is more than {TOLERANCE:.0%} from the target")
220
221    (out / "requests").mkdir(parents=True, exist_ok=True)
222    for stale in (out / "requests").glob("*.json"):
223        stale.unlink()
224    files: dict[str, bytes] = {}
225    for request in requests:
226        files[f"requests/{request['id']}.json"] = encoded(request)
227    tokenizer_files = {name: sha256_bytes((tokenizer_dir / name).read_bytes())
228                       for name in ("vocab.json", "merges.txt", "token_type.json")}
229    files["build.json"] = encoded({
230        "protocol_id": PROTOCOL_ID, "bundle": BUNDLE,
231        "profile": "qwen3.8-flash-next-thinking",
232        "tokenizer_files": tokenizer_files,
233        "template": {"path": "serve/chat_template.jinja", "sha256": sha256_bytes(template_path.read_bytes())},
234        "template_kwargs": TEMPLATE_KWARGS,
235        "record_format": RECORD, "short_task": SHORT_TASK, "summary_question": SUMMARY_QUESTION,
236        "record_counts": counts, "length_tolerance": TOLERANCE,
237        "requests": [{"id": r["id"], "input_tokens": r["input_tokens_frozen"],
238                      "max_shared_prefix_tokens": r["max_shared_prefix_tokens"]} for r in requests],
239        "note": "input_tokens counts the rendered thinking request with the generation prompt. max_shared_prefix_tokens is "
240                "the longest token prefix this request shares with any other request of the bundle: cache reuse above it "
241                "means the user payload was read from the cache."})
242    for name, data in files.items():
243        (out / name).write_bytes(data)
244    manifest = "".join(f"{sha256_bytes(data)}  {name}\n" for name, data in sorted(files.items())).encode("utf-8")
245    (out / "MANIFEST.sha256").write_bytes(manifest)
246    print(f"{len(requests)} requests, corpus_sha256 {sha256_bytes(manifest)}")
247    return {"corpus_sha256": sha256_bytes(manifest), "requests": len(requests)}
248
249
250def main(argv: list[str] | None = None) -> int:
251    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
252    ap.add_argument("--tokenizer", required=True, type=Path,
253                    help="folder with vocab.json, merges.txt and token_type.json (a pack's tokenizer/ folder)")
254    ap.add_argument("--template", type=Path, default=ROOT / "serve" / "chat_template.jinja")
255    ap.add_argument("--out", type=Path, default=ROOT / "bench" / "prompts" / BUNDLE)
256    a = ap.parse_args(argv)
257    build(a.tokenizer, a.template, a.out)
258    return 0
259
260
261if __name__ == "__main__":
262    raise SystemExit(main())