okami.mom/strata

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

zimuhuan-codeCommunity benchmark: 2× RTX 3060 12 GB, Qwen3.8-Flash-Next IQ3_S (three prompt sizes, 3 runs each) (#721)eb4e0c4b4

main
12.4 KiB290 linesraw
1#!/usr/bin/env python3
2"""
3Strata community benchmark runner — 2x RTX 3060, Qwen3.8-Flash-Next IQ3_S.
4
5Protocol follows docs/COMMUNITY_BENCHMARKS.md:
6  * three prompt sizes (~4k / ~32k / ~128k tokens), RUNS measured runs each;
7  * non-streaming requests for the main numbers, because the engine returns exact
8    per-request `timings` (prompt_n / cache_n / prompt_ms / predicted_n / predicted_ms /
9    draft_n) — the streaming path does NOT emit usage or timings on this version;
10  * a separate streaming run per size to measure time-to-first-token, because TTFT can
11    only be observed client-side;
12  * fixed output cap (256 tokens), greedy (temperature 0);
13  * every run carries a distinct leading tag, so a prompt prefix is never reused and
14    `cache_n` stays 0 — freshly processed prompt tokens, as the guide asks.
15
16Environment variables (all optional):
17  STRATA_URL       default http://127.0.0.1:8081
18  STRATA_KEY       default "local"
19  STRATA_MODEL     default qwen3.8-flash-next-iq3_s
20  STRATA_RUNS      default 3
21  STRATA_MAXTOK    default 256
22  STRATA_TARGETS   default 4096,32768,131072
23  STRATA_TTFT      default 1 (also run one streaming TTFT run per size)
24
25Outputs (next to this script):
26  results.json     meta + every run + summary
27  raw/*.json       the complete response of every non-streaming run
28  samples.jsonl    GPU/RAM samples taken every 2 s while the bench runs
29"""
30import json
31import os
32import statistics
33import subprocess
34import sys
35import threading
36import time
37import urllib.error
38import urllib.request
39
40URL = os.environ.get("STRATA_URL", "http://127.0.0.1:8081")
41API_KEY = os.environ.get("STRATA_KEY", "local")
42MODEL = os.environ.get("STRATA_MODEL", "qwen3.8-flash-next-iq3_s")
43OUTDIR = os.path.dirname(os.path.abspath(__file__))
44RAW = os.path.join(OUTDIR, "raw")
45RUNS = int(os.environ.get("STRATA_RUNS", "3"))
46MAXTOK = int(os.environ.get("STRATA_MAXTOK", "256"))
47TARGETS = [int(x) for x in os.environ.get("STRATA_TARGETS", "4096,32768,131072").split(",")]
48DO_TTFT = os.environ.get("STRATA_TTFT", "1") == "1"
49
50# Fixed filler text; the exact prompts are reproducible from this string plus the
51# repetition count recorded in each run (see `filler_repeats` / `prompt_sha256`).
52FILLER = (
53    "A mixture-of-experts layer replaces one large feed-forward network with several smaller "
54    "expert networks plus a routing function. For every token the router selects a small subset "
55    "of experts, so the total parameter count can grow while the compute per token stays roughly "
56    "constant. The trade-off is memory: every expert that might be selected has to be resident "
57    "somewhere, and on a machine whose VRAM is smaller than the model, the experts that are not "
58    "cached are streamed from host memory or from disk. This makes decode throughput sensitive to "
59    "the expert-cache hit rate, the PCIe link, and the layout of the cache itself. "
60)
61TASK = "\n\nTask: summarise the text above in exactly one sentence."
62
63
64def build_prompt(tag, target_tokens):
65    """English filler is ~4 chars/token; aim a little above the target and let the
66    engine report the exact prompt token count."""
67    want = int(target_tokens * 3.9)
68    parts, n = [], 0
69    while n < want:
70        parts.append(FILLER)
71        n += len(FILLER)
72    body = "".join(parts)
73    return f"[run {tag}] " + body + TASK, len(parts)
74
75
76def gpu_mem():
77    try:
78        out = subprocess.run(
79            ["nvidia-smi", "--query-gpu=index,memory.used", "--format=csv,noheader,nounits"],
80            capture_output=True, text=True, timeout=10).stdout
81        return {int(a): int(b) for a, b in (l.split(",") for l in out.strip().splitlines())}
82    except Exception:
83        return {}
84
85
86def ram():
87    info = {}
88    with open("/proc/meminfo") as fh:
89        for line in fh:
90            k, v = line.split(":", 1)
91            info[k] = int(v.split()[0])
92    mib = 1048576.0
93    return {"total_gb": round(info["MemTotal"] / mib, 2),
94            "used_gb": round((info["MemTotal"] - info["MemAvailable"]) / mib, 2),
95            "available_gb": round(info["MemAvailable"] / mib, 2)}
96
97
98_samples = []
99_sampling = threading.Event()
100
101
102def _sampler():
103    while not _sampling.is_set():
104        _samples.append({"t": round(time.time(), 3), "gpu_mib": gpu_mem(), "ram": ram()})
105        _sampling.wait(2.0)
106
107
108def post(path, payload, timeout=3600):
109    req = urllib.request.Request(
110        URL + path, data=json.dumps(payload).encode(),
111        headers={"Content-Type": "application/json", "Authorization": f"Bearer {API_KEY}"},
112        method="POST")
113    return urllib.request.urlopen(req, timeout=timeout)
114
115
116def run_nonstream(tag, target, repeat):
117    prompt, reps = build_prompt(tag, target)
118    payload = {"model": MODEL, "messages": [{"role": "user", "content": prompt}],
119               "max_tokens": MAXTOK, "temperature": 0, "stream": False}
120    t0 = time.perf_counter()
121    with post("/v1/chat/completions", payload) as resp:
122        raw = resp.read().decode("utf-8", "replace")
123    wall = time.perf_counter() - t0
124    obj = json.loads(raw)
125    with open(os.path.join(RAW, f"{tag}.json"), "w") as fh:
126        json.dump({"request": {k: v for k, v in payload.items() if k != "messages"},
127                   "prompt_chars": len(prompt), "filler_repeats": reps,
128                   "response": obj}, fh, indent=1)
129    usage, tim = obj.get("usage") or {}, obj.get("timings") or {}
130    ch = (obj.get("choices") or [{}])[0]
131    msg = ch.get("message") or {}
132    return {
133        "run": tag, "mode": "nonstream", "target_prompt_tokens": target,
134        "filler_repeats": reps, "prompt_chars": len(prompt),
135        "wall_seconds": round(wall, 3),
136        "prompt_tokens_reported": usage.get("prompt_tokens"),
137        "completion_tokens_reported": usage.get("completion_tokens"),
138        "finish_reason": ch.get("finish_reason"),
139        "content_chars": len(msg.get("content") or ""),
140        "reasoning_chars": len(msg.get("reasoning_content") or ""),
141        "timings": tim,
142        "prompt_tok_s": tim.get("prompt_per_second"),
143        "decode_tok_s": tim.get("predicted_per_second"),
144        "cache_n": tim.get("cache_n"),
145        "draft_n": tim.get("draft_n"),
146    }
147
148
149def run_stream(tag, target):
150    prompt, reps = build_prompt(tag, target)
151    payload = {"model": MODEL, "messages": [{"role": "user", "content": prompt}],
152               "max_tokens": MAXTOK, "temperature": 0, "stream": True}
153    t0 = time.perf_counter()
154    ttft = None
155    n_content = n_reason = 0
156    with post("/v1/chat/completions", payload) as resp:
157        for rawline in resp:
158            line = rawline.decode("utf-8", "replace").strip()
159            if not line.startswith("data:"):
160                continue                      # keep-alive comments
161            data = line[5:].strip()
162            if data == "[DONE]":
163                break
164            try:
165                obj = json.loads(data)
166            except Exception:
167                continue
168            delta = ((obj.get("choices") or [{}])[0].get("delta")) or {}
169            if ttft is None and (delta.get("content") or delta.get("reasoning_content")):
170                ttft = time.perf_counter() - t0
171            if delta.get("content"):
172                n_content += 1
173            if delta.get("reasoning_content"):
174                n_reason += 1
175    wall = time.perf_counter() - t0
176    return {"run": tag, "mode": "stream", "target_prompt_tokens": target,
177            "filler_repeats": reps, "prompt_chars": len(prompt),
178            "ttft_seconds": round(ttft, 3) if ttft is not None else None,
179            "wall_seconds": round(wall, 3),
180            "content_chunks": n_content, "reasoning_chunks": n_reason}
181
182
183def meta():
184    def sh(cmd):
185        try:
186            return subprocess.run(cmd, capture_output=True, text=True, timeout=15).stdout.strip()
187        except Exception:
188            return ""
189    gpu = sh(["nvidia-smi", "--query-gpu=index,name,memory.total,driver_version,power.limit,"
190              "power.max_limit,pcie.link.gen.max,pcie.link.width.max,pcie.link.gen.current,"
191              "pcie.link.width.current", "--format=csv,noheader"])
192    return {
193        "captured_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
194        "engine": {"url": URL, "model": MODEL, "health": sh(["curl", "-s", "-m", "5",
195                   "--noproxy", "*", URL + "/health"])},
196        "host": {"uname": sh(["uname", "-a"]),
197                 "os": sh(["bash", "-c", ". /etc/os-release && echo $PRETTY_NAME"]),
198                 "cpu_model": sh(["bash", "-c", "lscpu | grep -m1 'Model name' | cut -d: -f2- | xargs"]),
199                 "cpu_sockets_cores_threads": sh(["bash", "-c",
200                    "lscpu | grep -E '^(Socket|Core|Thread)\\(s\\)' | tr -s ' ' | tr '\\n' ';'"]),
201                 "ram": ram(), "gpu": gpu, "gpu6": gpu_mem()},
202        "protocol": {"targets": TARGETS, "runs_per_target": RUNS, "max_tokens": MAXTOK,
203                     "temperature": 0, "streaming_ttft_runs": DO_TTFT,
204                     "filler_sha256": __import__("hashlib").sha256(FILLER.encode()).hexdigest(),
205                     "filler_chars": len(FILLER)},
206    }
207
208
209def main():
210    os.makedirs(RAW, exist_ok=True)
211    print("== health ==")
212    try:
213        with urllib.request.urlopen(URL + "/health", timeout=10) as r:
214            print(r.read().decode())
215    except Exception as e:
216        print("health failed:", e)
217        return 1
218    m = meta()
219    print(json.dumps(m["host"], indent=1)[:1200])
220
221    t = threading.Thread(target=_sampler, daemon=True)
222    t.start()
223    runs = []
224    for target in TARGETS:
225        for i in range(1, RUNS + 1):
226            tag = f"nonstream-{target}-r{i}"
227            print(f"[{time.strftime('%H:%M:%S')}] {tag} ...", flush=True)
228            try:
229                rec = run_nonstream(tag, target, None)
230            except Exception as e:
231                rec = {"run": tag, "mode": "nonstream", "target_prompt_tokens": target,
232                       "error": f"{type(e).__name__}: {e}"}
233            rec["gpu_mib_after"] = gpu_mem()
234            rec["ram_after"] = ram()
235            runs.append(rec)
236            print("   ->", {k: rec.get(k) for k in
237                            ("prompt_tokens_reported", "completion_tokens_reported",
238                             "prompt_tok_s", "decode_tok_s", "wall_seconds", "cache_n")}, flush=True)
239    if DO_TTFT:
240        for target in TARGETS:
241            tag = f"stream-{target}-r1"
242            print(f"[{time.strftime('%H:%M:%S')}] {tag} (TTFT) ...", flush=True)
243            try:
244                rec = run_stream(tag, target)
245            except Exception as e:
246                rec = {"run": tag, "mode": "stream", "target_prompt_tokens": target,
247                       "error": f"{type(e).__name__}: {e}"}
248            runs.append(rec)
249            print("   -> ttft =", rec.get("ttft_seconds"), "wall =", rec.get("wall_seconds"), flush=True)
250    _sampling.set()
251
252    # summary: median + range per target (non-streaming runs only)
253    summary = {}
254    for target in TARGETS:
255        rs = [r for r in runs if r.get("mode") == "nonstream"
256              and r.get("target_prompt_tokens") == target and "error" not in r]
257        if not rs:
258            continue
259        def med(key):
260            vals = [r[key] for r in rs if isinstance(r.get(key), (int, float))]
261            return {"median": round(statistics.median(vals), 3),
262                    "min": round(min(vals), 3), "max": round(max(vals), 3),
263                    "n": len(vals)} if vals else None
264        summary[str(target)] = {
265            "runs": len(rs),
266            "prompt_tokens": med("prompt_tokens_reported"),
267            "completion_tokens": med("completion_tokens_reported"),
268            "prompt_tok_s": med("prompt_tok_s"),
269            "decode_tok_s": med("decode_tok_s"),
270            "wall_seconds": med("wall_seconds"),
271            "cache_n": med("cache_n"),
272        }
273    out = {"meta": m, "runs": runs, "summary": summary,
274           "gpu_peak_mib": {str(k): max((s["gpu_mib"].get(k, 0) for s in _samples), default=None)
275                            for k in (0, 1)},
276           "ram_peak_used_gb": max((s["ram"]["used_gb"] for s in _samples), default=None)}
277    with open(os.path.join(OUTDIR, "results.json"), "w") as fh:
278        json.dump(out, fh, indent=1)
279    with open(os.path.join(OUTDIR, "samples.jsonl"), "w") as fh:
280        for s in _samples:
281            fh.write(json.dumps(s) + "\n")
282    print("\n== summary ==")
283    print(json.dumps(summary, indent=1))
284    print("gpu_peak_mib:", out["gpu_peak_mib"], "ram_peak_used_gb:", out["ram_peak_used_gb"])
285    print("wrote results.json / samples.jsonl / raw/")
286    return 0
287
288
289if __name__ == "__main__":
290    sys.exit(main())