okami.mom/strata

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

Amboliobench: community report, RTX 5090 + Ryzen 9 9950X3D, IQ3_S at the full 262K window; prefill auto:32768 A/B; conversation-cache 32 GiB demo (#440)263c99b96

main
6.9 KiB159 linesraw
1"""Speed sweep against the live :8080, in the docs/COMMUNITY_BENCHMARKS.md format.
2
3Prompts are built from this repository's text the way tools/needle_bench.py does, with a fresh
4slice per run so no prompt is reused (cache_n must stay 0; a run that shows reuse is reported).
5Greedy, thinking off, 256 output tokens, 1 warm-up + 3 measured runs per cell. Throughput comes
6from the engine's own clock (the response's `timings`, llama.cpp names); TTFT is measured at the
7client on one streaming run per cell (the server is a FIFO, so TTFT can include queue time).
8Decode runs under 75% of the cell median are flagged as possible WDDM stalls (PR #279).
9
10    python bench/results/2026-10-02-community-rtx-5090-iq3s/bench.py
11"""
12from __future__ import annotations
13
14import json
15import re
16import statistics
17import subprocess
18import sys
19import threading
20import time
21import urllib.request
22from pathlib import Path
23
24ROOT = Path(__file__).resolve().parents[3]          # the Strata runtime folder
25sys.path.insert(0, str(ROOT / "tools"))
26from needle_bench import haystack, CHARS_PER_TOKEN  # noqa: E402
27
28URL = "http://127.0.0.1:8080/v1/chat/completions"
29MODEL = "qwen3.8-flash-next-iq3_s"
30LOG = ROOT / "strata-iq3_s.log"
31LENGTHS = [1024, 4096, 32768, 131072]
32MAX_NEW = 256
33OUT = Path(__file__).with_name("runs.json")
34
35TAIL = re.compile(r"(decode expert cache hit rate: [\d.]+%[^\n]*|KV streaming: [\d.]+%[^\n]*)")
36
37
38def post(payload: dict, timeout: float = 1800.0) -> dict:
39    req = urllib.request.Request(URL, data=json.dumps(payload).encode(),
40                                 headers={"Content-Type": "application/json"})
41    with urllib.request.urlopen(req, timeout=timeout) as r:
42        return json.load(r)
43
44
45def make_prompt(n_tokens: int, off: int) -> str:
46    n_chars = int(n_tokens * CHARS_PER_TOKEN)
47    text = haystack(n_chars + off + 4096)[off:off + n_chars]
48    return (text + "\n\nQuestion: In at least 150 words, summarize what kinds of files the text "
49                    "above is made of and what they are for. Name three of them.\n")
50
51
52def log_tails(n_lines: int = 400) -> dict:
53    try:
54        lines = LOG.read_text(encoding="utf-8", errors="replace").splitlines()[-n_lines:]
55    except OSError:
56        return {}
57    hits = [m for l in lines for m in TAIL.findall(l)]
58    out = {}
59    for h in hits[::-1]:
60        if h.startswith("decode") and "hit" not in out:
61            out["hit"] = h
62        if h.startswith("KV") and "kv" not in out:
63            out["kv"] = h
64        if len(out) == 2:
65            break
66    return out
67
68
69def one_run(n_tokens: int, off: int) -> dict:
70    body = {"model": MODEL, "max_tokens": MAX_NEW, "temperature": 0,
71            "chat_template_kwargs": {"enable_thinking": False},
72            "messages": [{"role": "user", "content": make_prompt(n_tokens, off)}]}
73    t0 = time.time()
74    r = post(body)
75    t = r.get("timings") or {}
76    u = r.get("usage") or {}
77    return {"prompt_target": n_tokens, "prompt_tokens": u.get("prompt_tokens"),
78            "cache_n": t.get("cache_n"), "generated": t.get("predicted_n") or u.get("completion_tokens"),
79            "prompt_tok_s": t.get("prompt_per_second"), "decode_tok_s": t.get("predicted_per_second"),
80            "draft_n": t.get("draft_n"), "draft_ok": t.get("draft_n_accepted"),
81            "total_s": round(time.time() - t0, 2), "wall_s": round(t.get("prompt_ms", 0) / 1000 + t.get("predicted_ms", 0) / 1000, 2),
82            **log_tails()}
83
84
85def ttft_run(n_tokens: int, off: int) -> float | None:
86    body = {"model": MODEL, "max_tokens": MAX_NEW, "temperature": 0, "stream": True,
87            "chat_template_kwargs": {"enable_thinking": False},
88            "messages": [{"role": "user", "content": make_prompt(n_tokens, off)}]}
89    req = urllib.request.Request(URL, data=json.dumps(body).encode(),
90                                 headers={"Content-Type": "application/json"})
91    t0 = time.time()
92    with urllib.request.urlopen(req, timeout=1800) as r:
93        for raw in r:
94            line = raw.decode("utf-8", "replace").strip()
95            if not line.startswith("data: ") or line == "data: [DONE]":
96                continue
97            try:
98                d = json.loads(line[6:])["choices"][0].get("delta") or {}
99            except (KeyError, ValueError):
100                continue
101            if d.get("content") or d.get("reasoning_content"):
102                return round(time.time() - t0, 2)
103    return None
104
105
106class Vram(threading.Thread):
107    def __init__(self) -> None:
108        super().__init__(daemon=True)
109        self.stop_at, self.mins = time.time() + 100000, []
110
111    def run(self) -> None:
112        while time.time() < self.stop_at:
113            try:
114                s = subprocess.run(["nvidia-smi", "-i", "0", "--query-gpu=memory.free",
115                                    "--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=10)
116                self.mins.append(int(s.stdout.strip()))
117            except Exception:
118                pass
119            time.sleep(5)
120
121
122def main() -> int:
123    vram = Vram()
124    vram.start()
125    rows = []
126    for L in LENGTHS:
127        for i in range(4):                                   # run 0 = warm-up, not counted
128            row = one_run(L, i * 1_000_003 + L)
129            row["length"], row["run"], row["warmup"] = L, i, i == 0
130            rows.append(row)
131            print(f"{L:>7} run {i}: prompt {row['prompt_tok_s']} tok/s, decode {row['decode_tok_s']} tok/s, "
132                  f"cache_n {row['cache_n']}, gen {row['generated']}, {row['total_s']} s", flush=True)
133        rows.append({"length": L, "ttft_s": ttft_run(L, 4 * 1_000_003 + L), "stream_ttft": True})
134        print(f"{L:>7} TTFT {rows[-1]['ttft_s']} s", flush=True)
135    vram.stop_at = time.time()
136    time.sleep(0.2)
137
138    print("\n| Prompt | prompt tok/s (3 runs) | decode tok/s (3 runs) | TTFT s | draft accept |")
139    print("| --- | --- | --- | --- | --- |")
140    for L in LENGTHS:
141        m = [r for r in rows if r.get("length") == L and not r.get("warmup") and not r.get("stream_ttft")]
142        p = [r["prompt_tok_s"] for r in m if r["prompt_tok_s"]]
143        d = [r["decode_tok_s"] for r in m if r["decode_tok_s"]]
144        tt = next((r["ttft_s"] for r in rows if r.get("length") == L and r.get("stream_ttft")), None)
145        dr = sum(r["draft_ok"] or 0 for r in m) / max(1, sum(r["draft_n"] or 0 for r in m))
146        med = statistics.median(d) if d else 0
147        stall = [r["decode_tok_s"] for r in m if r["decode_tok_s"] and r["decode_tok_s"] < 0.75 * med]
148        print(f"| {L:,} | {statistics.median(p):,.0f} ({min(p):,.0f}-{max(p):,.0f}) | "
149              f"{med:,.1f} ({min(d):,.1f}-{max(d):,.1f}) | {tt} | {dr:.0%} |"
150              + (f"  STALL: {stall}" if stall else ""))
151    reused = [r for r in rows if not r.get("warmup") and not r.get("stream_ttft") and r.get("cache_n")]
152    print(f"\nruns with prompt reuse (cache_n>0): {len(reused)}; VRAM free min during sweep: {min(vram.mins)} MiB")
153    OUT.write_text(json.dumps(rows, indent=1), encoding="utf-8")
154    print(f"wrote {OUT}")
155    return 0
156
157
158if __name__ == "__main__":
159    sys.exit(main())