okami.mom/strata

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

homeofebench: community results, RTX 2080 Ti 11 GB + Threadripper 3960X, IQ3_S at 262K with KV streaming (#469)707fd49eb

main
10.7 KiB207 linesraw
1#!/usr/bin/env python3
2"""Fresh-prompt read + decode speed, and follow-up turns on a long conversation, through a running Strata server.
3
4Every measured prompt starts with its own nonce, so no earlier prompt's prefix can be reused: each fresh run reads its
5whole prompt (the engine log's "N reused" confirms it). The prompt text is the repository's own files (the haystack
6of tools/needle_bench.py: docs, sources), cut to an exact token count with the pack's tokenizer and the chat
7template, followed by a request for ~600 words of plain prose; the output cap is 400 tokens, greedy, reasoning
8off (reasoning_effort "none"). Prompts of 100K tokens or more carry a code word at 40 % depth; with --followup, the
9last run of such a size is followed by a second user turn on the same conversation (the long prefix reused) that
10asks for the code word and ~400 more words.
11
12Before every request the script waits until GET /status says busy=false, queued=0 for 3 s. After it, the run is
13discarded and repeated if GET /metrics counted more than one finished request or the engine log shows more than one
14prompt line (someone else's request overlapped). Run with the install's Python (it needs `regex` for the tokenizer):
15
16    STRATA_API_KEY=... python bench_server.py --targets 4096,32768,128000 --runs 3 --followup
17    python bench_server.py --key-config <server config.json> --targets 250000 --runs 1 --followup
18"""
19from __future__ import annotations
20
21import argparse
22import hashlib
23import json
24import random
25import sys
26import time
27import urllib.request
28from pathlib import Path
29
30from common import LogTail, Server, api_key, parse_engine, scrub_lines
31
32HERE = Path(__file__).resolve().parent
33ROOT = HERE.parents[2]
34sys.path[:0] = [str(ROOT), str(ROOT / "tools")]
35
36from strata_tokenizer import Tokenizer  # noqa: E402
37from serve.frontend import ChatTemplate, openai_to_messages  # noqa: E402
38from needle_bench import haystack  # noqa: E402
39
40ENDING = ("\n\nWrite a plain-prose overview of the material above in about 600 words, as continuous paragraphs "
41          "without lists, headings or code.")
42FOLLOWUP = ("What is the secret code word mentioned in the text above? Write the code word first, on its own line. "
43            "Then, in about 400 words of plain prose, explain how the server described in these files handles a "
44            "long prompt.")
45WORDS = ["amber", "falcon", "quartz", "willow", "copper", "harbor", "saffron", "glacier", "orchid", "lantern"]
46
47
48def load_tokenizer(directory: Path):
49    vocab = json.loads((directory / "vocab.json").read_text())
50    tokens = [None] * len(vocab)
51    for token, number in vocab.items():
52        tokens[number] = token
53    tok = Tokenizer(tokens, (directory / "merges.txt").read_text().splitlines(),
54                    json.loads((directory / "token_type.json").read_text()))
55    return tok, ChatTemplate(directory / "chat_template.jinja")
56
57
58def body(messages, max_tokens):
59    return {"model": "strata", "messages": messages, "temperature": 0, "reasoning_effort": "none",
60            "max_tokens": max_tokens, "stream": True, "stream_options": {"include_usage": True}}
61
62
63def stream(server: Server, req: dict, timeout: float = 3600) -> dict:
64    data = json.dumps(req).encode()
65    first = finish = usage = timings = None
66    texts, keepalives = [], 0
67    t0 = time.perf_counter()
68    wire = urllib.request.Request(server.url + "/v1/chat/completions", data=data, headers=server.headers())
69    with urllib.request.urlopen(wire, timeout=timeout) as resp:
70        for raw in resp:
71            line = raw.decode("utf-8", errors="replace").strip()
72            if line.startswith(":"):
73                keepalives += 1
74                continue
75            if not line.startswith("data: "):
76                continue
77            payload = line[6:]
78            if payload == "[DONE]":
79                break
80            chunk = json.loads(payload)
81            usage = chunk.get("usage") or usage
82            timings = chunk.get("timings") or timings
83            for choice in chunk.get("choices", []):
84                delta = choice.get("delta") or {}
85                text = (delta.get("content") or "") + (delta.get("reasoning_content") or "")
86                if text:
87                    if first is None:
88                        first = time.perf_counter() - t0
89                    texts.append(text)
90                finish = choice.get("finish_reason") or finish
91    return {"request_sha256": hashlib.sha256(data).hexdigest(), "client_ttft_s": first,
92            "client_total_s": time.perf_counter() - t0, "finish_reason": finish, "usage": usage, "timings": timings,
93            "keepalives": keepalives, "text": "".join(texts)}
94
95
96def main():
97    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
98    ap.add_argument("--url", default="http://127.0.0.1:8080")
99    ap.add_argument("--key-config", help="server config JSON to read api_key from (else STRATA_API_KEY)")
100    ap.add_argument("--tokenizer", required=True, help="the pack's tokenizer directory")
101    ap.add_argument("--engine-log", required=True)
102    ap.add_argument("--server-log", required=True)
103    ap.add_argument("--out", type=Path, default=HERE / "data")
104    ap.add_argument("--targets", default="4096,32768,128000")
105    ap.add_argument("--runs", type=int, default=3)
106    ap.add_argument("--max-tokens", type=int, default=400)
107    ap.add_argument("--followup", action="store_true", help="a follow-up turn after the last run of sizes >= 100K")
108    ap.add_argument("--warmup", action="store_true", help="one short unmeasured request first")
109    ap.add_argument("--seed", type=int, default=2026)
110    a = ap.parse_args()
111    a.out.mkdir(parents=True, exist_ok=True)
112    server = Server(a.url, api_key(a.key_config))
113    tok, tpl = load_tokenizer(Path(a.tokenizer))
114    elog, slog = LogTail(a.engine_log), LogTail(a.server_log)
115    rnd = random.Random(a.seed)
116    hay = haystack(1_100_000)
117
118    def count(messages):
119        m, tools, kw = openai_to_messages(body(messages, 1))
120        return len(tok.encode(tpl.render(m, tools, **kw), parse_special=True))
121
122    def measured(label, messages, meta):
123        for attempt in range(1, 4):
124            status = server.wait_idle()
125            if not server.loaded():
126                print("  the model is unloaded: this request would include loading; aborting", flush=True)
127                raise SystemExit(2)
128            before = server.totals()
129            elog.mark(), slog.mark()
130            t_start = time.time()
131            print(f"start {label} (attempt {attempt}) {meta.get('expected_prompt_tokens')} tokens", flush=True)
132            res = stream(server, body(messages, a.max_tokens))
133            t_end = time.time()
134            time.sleep(1.5)                                   # the engine prints its timing lines after DONE
135            after = server.totals()
136            elines, slines = elog.since(), slog.since()
137            parsed = parse_engine(elines)
138            metrics = server.get("/metrics")["requests"][0]
139            foreign = (after - before != 1) or len(parsed) != 1
140            row = {"label": label, "attempt": attempt, "epoch_start": t_start, "epoch_end": t_end, **meta, **res,
141                   "status_before": status, "totals_before": before, "totals_after": after, "foreign_overlap": foreign,
142                   "engine": parsed[0] if parsed else None, "metrics_record": metrics,
143                   "engine_log": scrub_lines(elines), "server_log": scrub_lines(slines)}
144            name = f"{label}" + ("" if not foreign else f"-discarded-{attempt}")
145            (a.out / f"{name}.json").write_text(json.dumps(row, indent=1, ensure_ascii=False) + "\n")
146            e = parsed[0] if parsed else {}
147            print(f"done  {label}: {e.get('line', '(no engine line)')}  ttft {res['client_ttft_s']:.2f} s "
148                  f"total {res['client_total_s']:.1f} s foreign={foreign}", flush=True)
149            if not foreign:
150                return row
151            print("  foreign traffic overlapped this run: discarded, repeating", flush=True)
152        raise SystemExit(f"{label}: three attempts overlapped with other requests")
153
154    if a.warmup:
155        server.wait_idle()
156        r = stream(server, body([{"role": "user", "content": "Reply with exactly the word READY."}], 8))
157        print("warm-up:", r["text"].strip(), flush=True)
158
159    for target in map(int, a.targets.split(",")):
160        for run in range(1, a.runs + 1):
161            label = f"fresh-{target}-run{run}"
162            nonce = f"Benchmark nonce {label}-{rnd.getrandbits(48):012x}.\n"
163            head = nonce + "The text below is a collection of files from a software repository.\n"
164            word = None
165            if target >= 100_000:
166                word = f"{rnd.choice(WORDS)}-{rnd.choice(WORDS)}-{rnd.randint(100, 999)}"
167
168            def build(n):
169                text = hay[:n]
170                if word:
171                    cut = text.rfind("\n", 0, int(n * 0.40)) + 1
172                    text = text[:cut] + f"\nThe secret code word for this text is: {word}. Remember it.\n" + text[cut:]
173                return [{"role": "user", "content": head + text + ENDING}]
174
175            guess = int(target * 3.3)
176            lo, hi = max(0, int(guess * 0.8)), min(len(hay), int(guess * 1.25))
177            if count(build(lo)) > target:
178                lo = 0
179            if count(build(hi)) <= target:
180                raise SystemExit(f"the haystack is too short for {target} tokens")
181            while lo < hi:                                     # largest cut whose prompt fits in `target` tokens
182                mid = (lo + hi + 1) // 2
183                if count(build(mid)) <= target:
184                    lo = mid
185                else:
186                    hi = mid - 1
187            messages = build(lo)
188            n = count(messages)
189            meta = {"kind": "fresh", "target": target, "run": run, "expected_prompt_tokens": n, "needle": word,
190                    "needle_depth_pct": 40 if word else None, "max_tokens": a.max_tokens}
191            row = measured(label, messages, meta)
192            if word:
193                row["needle_found_in_first_answer"] = word in row["text"]
194            if a.followup and word and run == a.runs:
195                follow = messages + [{"role": "assistant", "content": row["text"]},
196                                     {"role": "user", "content": FOLLOWUP}]
197                fmeta = {"kind": "followup", "target": target, "run": 1, "expected_prompt_tokens": count(follow),
198                         "needle": word, "needle_depth_pct": 40, "max_tokens": a.max_tokens,
199                         "follows": label}
200                frow = measured(f"followup-{target}", follow, fmeta)
201                frow["needle_found"] = word in frow["text"][:200]
202                (a.out / f"followup-{target}.json").write_text(json.dumps(frow, indent=1, ensure_ascii=False) + "\n")
203                print(f"  code word {word}: {'FOUND' if frow['needle_found'] else 'missed'}", flush=True)
204
205
206if __name__ == "__main__":
207    main()