okami.mom/strata

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

homeofebench: community results, RX 9070 XT 16 GB on Windows 11, ready-made AMD engine 0.1.35, IQ3_S (#499)aebd0f34d

main
7.0 KiB150 linesraw
1#!/usr/bin/env python3
2"""Measure any OpenAI-compatible server the same way: decode speed and prompt (prefill) speed.
3
4Standard library only. Every request starts with a fresh nonce so no server can answer from a prompt cache.
5
6  python3 bench/bench.py --url http://127.0.0.1:8080/v1 --label strata-iq3s --out bench/results/<dir>
7  python3 bench/bench.py --url http://127.0.0.1:8811/v1 --label mimo-stock --extra '{"chat_template_kwargs":{"enable_thinking":false}}'
8
9Tests:
10  decode     short prompt, --decode-tokens tokens out (default 256): tokens/s after the first token
11  prefill-N  a ~N-token code prompt, 1 token out: prompt tokens / time to first token
12"""
13import argparse
14import json
15import os
16import random
17import statistics
18import sys
19import time
20import urllib.request
21
22DECODE_PROMPT = ("Write a Python function that parses an Apache access log line into a dict with ip, time, method, "
23                 "path, status and size. Then explain each regular expression group in two sentences.")
24
25
26def code_corpus(n_tokens, seed=1234):
27    """Deterministic synthetic Python code, roughly n_tokens long (about 3.2 characters per token)."""
28    rng = random.Random(seed)
29    words = ["user", "token", "session", "query", "cache", "request", "payload", "config", "record", "result",
30             "handler", "buffer", "index", "limit", "offset", "account", "secret", "path", "status", "retry"]
31    out, size, target = [], 0, int(n_tokens * 3.2)
32    i = 0
33    while size < target:
34        a, b, c = rng.sample(words, 3)
35        block = (f"def {a}_{b}_{i}({c}, {a}=None):\n"
36                 f"    \"\"\"Return the {b} for {c}.\"\"\"\n"
37                 f"    if {a} is None:\n"
38                 f"        {a} = load_{a}({c})\n"
39                 f"    for k in range({rng.randint(2, 64)}):\n"
40                 f"        {c} = update_{b}({c}, k, {a})\n"
41                 f"    return {{'{b}': {c}, 'n': {rng.randint(0, 9999)}}}\n\n")
42        out.append(block)
43        size += len(block)
44        i += 1
45    return "".join(out)
46
47
48def load_extra(value):
49    if value.startswith("@"):
50        with open(value[1:], encoding="utf-8") as f:
51            return json.load(f)
52    return json.loads(value)
53
54
55def post_stream(url, key, body, timeout):
56    req = urllib.request.Request(url + "/chat/completions", data=json.dumps(body).encode(), method="POST",
57                                 headers={"Content-Type": "application/json", "Authorization": f"Bearer {key}"})
58    t0 = time.perf_counter()
59    t_first, n_chunks, usage = None, 0, None
60    with urllib.request.urlopen(req, timeout=timeout) as r:
61        for raw in r:
62            line = raw.decode("utf-8", "replace").strip()
63            if not line.startswith("data:"):
64                continue
65            data = line[5:].strip()
66            if data == "[DONE]":
67                break
68            d = json.loads(data)
69            if d.get("usage"):
70                usage = d["usage"]
71            for ch in d.get("choices") or []:
72                delta = ch.get("delta") or {}
73                if delta.get("content") or delta.get("reasoning_content"):
74                    if t_first is None:
75                        t_first = time.perf_counter()
76                    n_chunks += 1
77    t_end = time.perf_counter()
78    return t0, t_first, t_end, n_chunks, usage
79
80
81def one(args, model, prompt, max_tokens):
82    nonce = f"[run {time.time_ns()}] "
83    body = {"model": model, "messages": [{"role": "user", "content": nonce + prompt}], "max_tokens": max_tokens,
84            "temperature": 0, "stream": True, "stream_options": {"include_usage": True}}
85    body.update(args.extra)
86    t0, t_first, t_end, n_chunks, usage = post_stream(args.url, args.key, body, args.timeout)
87    if t_first is None:
88        if max_tokens > 1:
89            raise RuntimeError("no tokens came back")
90        # prefill test: the one token may be a template token with no visible text; the request still ends right
91        # after the prompt is read
92        t_first = t_end
93    out_tokens = (usage or {}).get("completion_tokens") or n_chunks
94    prompt_tokens = (usage or {}).get("prompt_tokens")
95    decode_s = t_end - t_first
96    return {"ttft_s": t_first - t0, "total_s": t_end - t0, "prompt_tokens": prompt_tokens,
97            "completion_tokens": out_tokens,
98            "decode_tps": (out_tokens - 1) / decode_s if out_tokens > 1 and decode_s > 0 else None,
99            "prefill_tps": prompt_tokens / (t_first - t0) if prompt_tokens else None}
100
101
102def main():
103    p = argparse.ArgumentParser()
104    p.add_argument("--url", required=True, help="base URL ending in /v1")
105    p.add_argument("--key", default=os.environ.get("BENCH_API_KEY", "none"))
106    p.add_argument("--model", default=None, help="default: first id from /v1/models")
107    p.add_argument("--label", required=True)
108    p.add_argument("--runs", type=int, default=3)
109    p.add_argument("--decode-tokens", type=int, default=256)
110    p.add_argument("--prefill", default="4096,32768", help="prompt sizes in tokens, comma separated; '' for none")
111    p.add_argument("--extra", type=load_extra, default={},
112                   help="JSON merged into every request body, or @file.json (avoids shell quoting, e.g. on Windows)")
113    p.add_argument("--timeout", type=int, default=1800)
114    p.add_argument("--out", default=None, help="directory for <label>.json")
115    p.add_argument("--skip-decode", action="store_true", help="only the prefill tests")
116    args = p.parse_args()
117
118    model = args.model
119    if not model:
120        req = urllib.request.Request(args.url + "/models", headers={"Authorization": f"Bearer {args.key}"})
121        model = json.load(urllib.request.urlopen(req, timeout=60))["data"][0]["id"]
122
123    tests = [] if args.skip_decode else [("decode", DECODE_PROMPT, args.decode_tokens)]
124    tests += [(f"prefill-{n}", "Summarize what this code does.\n\n" + code_corpus(n), 1)
125              for n in (int(x) for x in args.prefill.split(",") if x)]
126
127    print(f"# {args.label}: {model} at {args.url}", file=sys.stderr)
128    one(args, model, "Say hi.", 8)  # warm-up, not counted
129    result = {"label": args.label, "model": model, "url": args.url, "extra": args.extra, "runs": args.runs,
130              "date": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "tests": {}}
131    for name, prompt, max_tokens in tests:
132        rows = []
133        for i in range(args.runs):
134            r = one(args, model, prompt, max_tokens)
135            rows.append(r)
136            print(f"  {name} run {i + 1}: " + ", ".join(f"{k}={v:.2f}" if isinstance(v, float) else f"{k}={v}"
137                                                        for k, v in r.items()), file=sys.stderr)
138        key = "decode_tps" if name == "decode" else "prefill_tps"
139        vals = [r[key] for r in rows if r[key]]
140        result["tests"][name] = {"median_" + key: statistics.median(vals) if vals else None, "runs": rows}
141        print(f"{args.label}\t{name}\t{key}={result['tests'][name]['median_' + key]:.1f}" if vals else
142              f"{args.label}\t{name}\tno value")
143    if args.out:
144        os.makedirs(args.out, exist_ok=True)
145        with open(os.path.join(args.out, f"{args.label}.json"), "w") as f:
146            json.dump(result, f, indent=2)
147
148
149if __name__ == "__main__":
150    main()