okami.mom/strata

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

CYoung83Bench: RTX 5090 / 9950X3D (IQ3_S, three-pass A/B) + RTX 2080 Ti / 9900KF (IQ3_XXS, Turing) (#698)f546be7e3

main
14.9 KiB332 linesraw
1#!/usr/bin/env python3
2"""Strata benchmark harness (contribution plan, PR 1 step 1.2).
3
4Follows the upstream method (bench/results/2026-09-28-speed-0114): one code-agent prompt per
5length, greedy, 256 generated tokens, MTP as configured by setup. Every run gets a unique
6prefix, so conversation checkpoints cannot skip the prompt. Numbers come from the engine log
7lines the owner asks for in issue #74. /metrics and API timing are stored as cross-checks.
8
9Stdlib only. Examples:
10    ./strata-bench.py --label IQ3_XXS-1x3090 --log ./strata-iq3_xxs.log
11  ./strata-bench.py --label Coder-2x3090-auto --contexts 16k,28k --mode needle
12  ./strata-bench.py --url http://127.0.0.1:9292 --model flash-next-strata --label via-llama-swap
13"""
14
15import argparse
16import json
17import os
18import re
19import statistics
20import sys
21import time
22import urllib.error
23import urllib.request
24import uuid
25from datetime import datetime
26from pathlib import Path
27
28NOMINAL = {"1k": 1024, "2.7k": 2765, "4k": 4096, "8k": 8192, "16k": 16384, "28k": 28672,
29           "32k": 32768, "64k": 65536, "128k": 131072, "262k": 262144}
30CODE_EXT = {".py", ".cpp", ".cc", ".h", ".hpp", ".cu", ".cuh", ".js", ".md", ".txt", ".cmake"}
31SKIP_DIRS = {".git", ".venv", "build", "engine", "third_party", "node_modules", "models",
32             "packs", "mtp", "bench", "data", "__pycache__", "Strata-data"}
33LOG_PATTERNS = [
34    re.compile(r"decode expert cache hit rate", re.I),
35    re.compile(r"\bPCIe\b"),
36    re.compile(r"prompt .*tok/s.*generated .*tok/s", re.I),
37    re.compile(r"reus|checkpoint", re.I),
38    re.compile(r"layer split", re.I),
39]
40TOKS_PER_S = re.compile(r"([\d][\d,]*(?:\.\d+)?)\s*tok(?:ens)?/s", re.I)
41
42
43def load_corpus(dirs):
44    parts = []
45    for d in dirs:
46        root = Path(d)
47        for p in sorted(root.rglob("*")):
48            if p.suffix.lower() not in CODE_EXT or not p.is_file():
49                continue
50            if any(s in SKIP_DIRS for s in p.relative_to(root).parts[:-1]):
51                continue
52            text = p.read_text(encoding="utf-8", errors="ignore")
53            if text.strip():
54                parts.append(f"### {p.relative_to(root).as_posix()}\n```\n{text}\n```\n")
55    if not parts:
56        sys.exit(f"no source files found in {dirs}")
57    return parts
58
59
60def build_text(parts, n_chars):
61    out, size, i, repeated = [], 0, 0, False
62    while size < n_chars:
63        if i and i % len(parts) == 0:
64            repeated = True
65        chunk = parts[i % len(parts)]
66        out.append(chunk)
67        size += len(chunk)
68        i += 1
69    return "".join(out)[:n_chars], repeated
70
71
72def post_stream(url, payload, api_key, timeout):
73    req = urllib.request.Request(
74        f"{url}/v1/chat/completions", data=json.dumps(payload).encode(),
75        headers={"Content-Type": "application/json", "Authorization": f"Bearer {api_key or 'none'}"})
76    t0 = time.perf_counter()
77    t_first, text, reasoning, usage, chunks = None, [], [], {}, 0
78    with urllib.request.urlopen(req, timeout=timeout) as resp:
79        for raw in resp:
80            line = raw.decode("utf-8", errors="ignore").strip()
81            if not line.startswith("data:"):
82                continue
83            data = line[5:].strip()
84            if data == "[DONE]":
85                break
86            try:
87                chunk = json.loads(data)
88            except json.JSONDecodeError:
89                continue
90            if chunk.get("usage"):
91                usage = chunk["usage"]
92            for ch in chunk.get("choices") or []:
93                delta = ch.get("delta") or {}
94                piece = delta.get("content") or ""
95                rpiece = delta.get("reasoning_content") or ""
96                if (piece or rpiece) and t_first is None:
97                    t_first = time.perf_counter()
98                if piece or rpiece:
99                    chunks += 1
100                text.append(piece)
101                reasoning.append(rpiece)
102    t_end = time.perf_counter()
103    return {"t_start": t0, "t_first": t_first or t_end, "t_end": t_end, "text": "".join(text),
104            "reasoning": "".join(reasoning), "usage": usage, "chunks": chunks}
105
106
107def get_json(url, path, api_key, timeout=10):
108    try:
109        req = urllib.request.Request(f"{url}{path}", headers={"Authorization": f"Bearer {api_key or 'none'}"})
110        with urllib.request.urlopen(req, timeout=timeout) as r:
111            body = r.read().decode("utf-8", errors="ignore")
112        try:
113            return json.loads(body)
114        except json.JSONDecodeError:
115            return body
116    except (urllib.error.URLError, TimeoutError) as e:
117        return {"error": str(e)}
118
119
120def wait_healthy(url, api_key, timeout):
121    deadline = time.time() + timeout
122    while time.time() < deadline:
123        h = get_json(url, "/health", api_key, timeout=5)
124        if not (isinstance(h, dict) and "error" in h):
125            return True
126        time.sleep(5)
127    return False
128
129
130def log_offset(log):
131    return log.stat().st_size if log and log.exists() else 0
132
133
134def log_lines_since(log, offset):
135    if not log or not log.exists():
136        return []
137    time.sleep(0.5)
138    with log.open("r", encoding="utf-8", errors="ignore") as f:
139        f.seek(offset)
140        new = f.read().splitlines()
141    return [ln for ln in new if any(p.search(ln) for p in LOG_PATTERNS)]
142
143
144def engine_numbers(lines):
145    """Best effort: the last 'prompt ... tok/s ... generated ... tok/s' line -> (prompt, decode)."""
146    for ln in reversed(lines):
147        if LOG_PATTERNS[2].search(ln):
148            vals = [float(v.replace(",", "")) for v in TOKS_PER_S.findall(ln)]
149            if len(vals) >= 2:
150                return vals[0], vals[1]
151    return None, None
152
153
154def target_tokens(key, max_tokens):
155    n = NOMINAL[key]
156    # leave room for the answer, like upstream's 259,943-token "262K" prompt.
157    # NAT-local fix: at >=128k the tokenizer drifts over the cap (129,792 target
158    # -> HTTP 400 on a 131,072-context server), so keep a 2048-token margin.
159    margin = 2048 if n >= 131072 else 1024
160    return n - max_tokens - margin if n >= 32768 else n
161
162
163def make_messages(mode, parts, n_chars, run_id):
164    body, repeated = build_text(parts, n_chars)
165    system = f"[bench run {run_id}] You are a coding agent working in the repository shown below."
166    if mode == "needle":
167        word = uuid.uuid4().hex[:8].upper()
168        mid = len(body) // 2
169        body = f"{body[:mid]}\n# NOTE: the secret code word is {word}.\n{body[mid:]}"
170        task = "What is the secret code word mentioned in the files above? Answer with the word only."
171    else:
172        word = None
173        task = ("Task: explain what the last file above does, then propose one concrete improvement "
174                "as a unified diff.")
175    msgs = [{"role": "system", "content": system},
176            {"role": "user", "content": f"Repository files:\n\n{body}\n\n{task}"}]
177    return msgs, word, repeated
178
179
180def run_once(a, parts, key, run, cpt):
181    tgt = target_tokens(key, a.max_tokens)
182    run_id = uuid.uuid4().hex[:12]
183    msgs, word, repeated = make_messages(a.mode, parts, int(tgt * cpt), run_id)
184    payload = {"model": a.model, "messages": msgs, "max_tokens": a.max_tokens, "stream": True,
185               "stream_options": {"include_usage": True}, "temperature": 0,
186               "reasoning_effort": a.reasoning_effort}
187    off = log_offset(a.log)
188    rec = {"label": a.label, "mode": a.mode, "ctx": key, "target_tokens": tgt, "run": run,
189           "run_id": run_id, "corpus_repeated": repeated, "time": datetime.now().isoformat(timespec="seconds")}
190    for attempt in range(2):
191        try:
192            r = post_stream(a.url, payload, a.api_key, a.timeout)
193            break
194        except urllib.error.HTTPError as e:
195            # The server reports the exact prompt token count in the 400 body;
196            # rescale the char budget once and retry (tokenizer drift per slice).
197            body = ""
198            try:
199                body = e.read().decode("utf-8", errors="ignore")
200            except Exception:
201                pass
202            mtok = re.search(r"prompt \((\d+) tokens\)", body)
203            if e.code == 400 and mtok and attempt == 0:
204                allowed = a.max_context - a.max_tokens - 64
205                scale = allowed / int(mtok.group(1))
206                if scale >= 1:
207                    rec["error"] = f"HTTP 400: prompt {mtok.group(1)} tokens, scale {scale:.2f} >= 1"
208                    return rec, cpt
209                # rebuild messages with the scaled char budget
210                scaled_chars = int(len(msgs[1]["content"]) * scale)
211                msgs, word, repeated = make_messages(a.mode, parts, scaled_chars, run_id)
212                payload["messages"] = msgs
213                continue
214            rec["error"] = f"HTTP {e.code}: {body[:200]}"
215            return rec, cpt
216        except Exception as e:  # noqa: BLE001 - record and continue with the next cell
217            rec["error"] = str(e)[:300]
218            return rec, cpt
219    pt = r["usage"].get("prompt_tokens")
220    ct = r["usage"].get("completion_tokens") or r["chunks"]
221    ttft = r["t_first"] - r["t_start"]
222    dec_t = r["t_end"] - r["t_first"]
223    lines = log_lines_since(a.log, off)
224    e_prompt, e_decode = engine_numbers(lines)
225    rec.update({
226        "prompt_tokens": pt, "completion_tokens": ct,
227        "ttft_s": round(ttft, 3), "e2e_s": round(r["t_end"] - r["t_start"], 3),
228        "api_prompt_tps": round(pt / ttft, 1) if pt and ttft > 0 else None,
229        "api_decode_tps": round((ct - 1) / dec_t, 1) if ct and ct > 1 and dec_t > 0 else None,
230        "engine_prompt_tps": e_prompt, "engine_decode_tps": e_decode,
231        "log_lines": lines, "answer_head": r["text"][:300],
232    })
233    if word:
234        rec["needle_found"] = word in r["text"].upper() or word in r["reasoning"].upper()
235    if a.mode == "two-turn":
236        follow = msgs + [{"role": "assistant", "content": r["text"]},
237                         {"role": "user", "content": "Summarize your answer in one sentence."}]
238        off2 = log_offset(a.log)
239        r2 = post_stream(a.url, {**payload, "messages": follow, "max_tokens": 64}, a.api_key, a.timeout)
240        rec["turn2_ttft_s"] = round(r2["t_first"] - r2["t_start"], 3)
241        rec["turn2_prompt_tokens"] = r2["usage"].get("prompt_tokens")
242        rec["turn2_log_lines"] = log_lines_since(a.log, off2)
243    if pt:
244        cpt = (int(tgt * cpt) + 400) / pt  # refine chars per token for the next cells
245    return rec, cpt
246
247
248def write_md(path, recs, label):
249    def med(vals):
250        vals = [v for v in vals if v is not None]
251        return round(statistics.median(vals), 1) if vals else None
252
253    rows = ["| ctx | prompt tokens | runs | TTFT s (med) | prompt tok/s engine / API (med) "
254            "| decode tok/s engine / API (run 1) | decode tok/s engine / API (med) | needle |",
255            "|---|---|---|---|---|---|---|---|"]
256    for key in dict.fromkeys(r["ctx"] for r in recs):
257        rs = [r for r in recs if r["ctx"] == key and "error" not in r]
258        errs = sum(1 for r in recs if r["ctx"] == key and "error" in r)
259        if not rs:
260            rows.append(f"| {key} | - | 0 ({errs} errors) | | | | | |")
261            continue
262        first = rs[0]
263        needle = "" if rs[0].get("needle_found") is None else f"{sum(r['needle_found'] for r in rs)}/{len(rs)}"
264        rows.append(
265            f"| {key} | {rs[0]['prompt_tokens']} | {len(rs)}{f' ({errs} err)' if errs else ''} "
266            f"| {med(r['ttft_s'] for r in rs)} "
267            f"| {med(r['engine_prompt_tps'] for r in rs)} / {med(r['api_prompt_tps'] for r in rs)} "
268            f"| {first['engine_decode_tps']} / {first['api_decode_tps']} "
269            f"| {med(r['engine_decode_tps'] for r in rs)} / {med(r['api_decode_tps'] for r in rs)} | {needle} |")
270    path.write_text(f"# {label}\n\n" + "\n".join(rows) + "\n", encoding="utf-8")
271
272
273def main():
274    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
275    ap.add_argument("--url", default="http://127.0.0.1:8090")
276    ap.add_argument("--model", default="strata", help="model name sent (llama-swap: the model id)")
277    ap.add_argument("--api-key", default=os.environ.get("STRATA_API_KEY", ""))
278    ap.add_argument("--label", required=True, help="e.g. IQ3_XXS-1x3090-calibrated")
279    ap.add_argument("--contexts", default="1k,4k,32k,128k", help=f"comma list of {','.join(NOMINAL)}")
280    ap.add_argument("--repeats", type=int, default=3)
281    ap.add_argument("--max-tokens", type=int, default=256)
282    ap.add_argument("--reasoning-effort", default="none")
283    ap.add_argument("--mode", choices=["speed", "needle", "two-turn"], default="speed")
284    ap.add_argument("--source-dir", action="append", default=None,
285                    help="code corpus for the prompts (default: current directory, the Strata repo)")
286    ap.add_argument("--log", type=Path, default=None,
287                    help="engine log, e.g. ./strata-iq3_xxs.log")
288    ap.add_argument("--out", type=Path, default=Path(f"./benchmark-output/{datetime.now():%Y-%m-%d}"))
289    ap.add_argument("--timeout", type=float, default=1800, help="per request, seconds (262K prefill takes minutes)")
290    ap.add_argument("--chars-per-token", type=float, default=3.4, help="start value, refined after each run")
291    ap.add_argument("--max-context", type=int, default=131072, help="server context cap for the 400-rescale retry")
292    a = ap.parse_args()
293
294    keys = [k.strip().lower() for k in a.contexts.split(",") if k.strip()]
295    bad = [k for k in keys if k not in NOMINAL]
296    if bad:
297        sys.exit(f"unknown context(s): {bad}")
298    parts = load_corpus(a.source_dir or ["."])
299    if a.log and not a.log.exists():
300        print(f"warning: log {a.log} not found; engine numbers will be empty", file=sys.stderr)
301    if not wait_healthy(a.url, a.api_key, 900):
302        sys.exit(f"{a.url}/health not reachable")
303
304    out = a.out / a.label
305    (out / "data").mkdir(parents=True, exist_ok=True)
306    recs, cpt = [], a.chars_per_token
307    for key in keys:
308        for run in range(1, a.repeats + 1):
309            rec, cpt = run_once(a, parts, key, run, cpt)
310            rec["metrics_after"] = get_json(a.url, "/metrics", a.api_key)
311            recs.append(rec)
312            (out / "data" / f"{a.mode}-{key}-{run}.json").write_text(json.dumps(rec, indent=1), encoding="utf-8")
313            status = rec.get("error") or (f"prompt {rec['prompt_tokens']} tok, TTFT {rec['ttft_s']} s, "
314                                          f"decode engine {rec['engine_decode_tps']} / API {rec['api_decode_tps']} tok/s")
315            print(f"[{a.label}] {a.mode} {key} run {run}: {status}", flush=True)
316
317    matrix_path = out / "matrix.json"
318    merged = {}
319    if matrix_path.exists():
320        for record in json.loads(matrix_path.read_text(encoding="utf-8")):
321            merged[(record["mode"], record["ctx"], record["run"])] = record
322    for record in recs:
323        key = (record["mode"], record["ctx"], record["run"])
324        merged[key] = {k: v for k, v in record.items() if k != "metrics_after"}
325    combined = list(merged.values())
326    matrix_path.write_text(json.dumps(combined, indent=1), encoding="utf-8")
327    write_md(out / "matrix.md", combined, f"{a.label} ({a.mode})")
328    print(f"written: {out}/matrix.md, matrix.json, data/")
329
330
331if __name__ == "__main__":
332    main()