okami.mom/strata

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

lfontanezCommunity benchmark: RTX 4070 Ti SUPER 16 GiB (Shin-BlackMamba, upstream 6f32ec07) (#995)09fadfee6

main
13.1 KiB349 linesraw
1#!/usr/bin/env python3
2"""Strata benchmark harness with pluggable model name.
3
4For each configured --max-context, finds a chat content that lands the prompt
5near 92 % of capacity, runs:
6  - 1 cold-prefill probe (max_tokens=1, non-stream) for the real prefill
7    throughput number (the number the README's 2,000+ t/s headlines measure)
8  - 3 SSE stream /v1/chat/completions calls (run once each, with `reasoning_effort=minimal`)
9  - no extra reference non-stream call
10
11Why two prefill numbers:
12  - SSE's `timings.prompt_per_second` is "time to FIRST decode chunk after
13    prefilled chunk" (first-chunk-completion throughput). With --prefill auto
14    doing 8192-token chunks, the engine starts streaming before the entire
15    prompt is in. So SSE reports a smaller denominator than the cold prefill.
16  - Cold-prefill non-stream (max_tokens=1) reports end-of-prompt throughput.
17    Useful for apples-to-apples comparison with the README's stated numbers.
18"""
19from __future__ import annotations
20
21import argparse
22import json
23import statistics
24import time
25from dataclasses import dataclass, asdict, field
26from pathlib import Path
27from typing import List, Optional
28import requests
29
30TARGET_FRACTION = 0.92
31CHAR_PER_TOKEN = 4.0
32PEER_WINDOW = 32
33
34FILLER = (
35    "Strata models a pagoda of experts and policies; during a long context "
36    "session the persistent graph speculatively drafts the next token while "
37    "the verifier follows. The verifier commits the draft when the "
38    "distributions agree, else resamples and re-aligns. On a workstation with "
39    "a single 16 GB card, the expert cache holds about a thousand experts "
40    "and the README warns that context past 65 k degrades without KV-cache "
41    "compression. The MTP draft layer is a five-token head tuned from the "
42    "1.3 B Qwen3 base and imported unchanged. "
43)
44
45
46def render_prompt(target_chars: int) -> str:
47    out, cur = [], 0
48    while cur < target_chars:
49        out.append(FILLER)
50        cur += len(FILLER)
51    return "".join(out)[:target_chars]
52
53
54@dataclass
55class Run:
56    seq: int
57    target_ctx: int
58    target_fill_chars: int
59    prompt_tokens_actual: int
60    completion_tokens: int
61    content_chunks: int
62    reasoning_chunks: int
63    ttft_ms: float
64    decode_avg_tps: float
65    decode_peak_tps: float
66    eng_predicted_per_second: float
67    eng_predicted_per_token_ms: float
68    eng_prompt_per_second: float
69    sse_prompt_per_second: float
70    eng_draft_n: int
71    eng_draft_n_accepted: int
72    eng_predicted_ms: float
73    eng_total_request_ms: float
74    finish_reason: str
75    elapsed_ms: float
76
77
78@dataclass
79class ColdPrefill:
80    prompt_tokens_actual: int
81    prompt_total_ms: float
82    prompt_per_second: float
83    completion_tokens: int
84
85
86def lookup_v1_models(base_url: str, model_name: str) -> str:
87    r = requests.get(f"{base_url}/v1/models", timeout=20)
88    r.raise_for_status()
89    data = r.json().get("data", [])
90    for m in data:
91        if m["id"] == model_name:
92            return model_name
93    if data:
94        print(f"  WARN: {model_name} not in /v1/models; server reports: {data[0]['id']}")
95    return data[0]["id"] if data else model_name
96
97
98def calibration(base_url: str, fill_chars: int, model_name: str) -> int:
99    body = {
100        "model": model_name,
101        "stream": False,
102        "reasoning_effort": "minimal",
103        "messages": [{"role": "user", "content": render_prompt(fill_chars)}],
104        "max_tokens": 4,
105        "temperature": 0,
106    }
107    r = requests.post(f"{base_url}/v1/chat/completions", json=body, timeout=900)
108    r.raise_for_status()
109    return r.json()["usage"]["prompt_tokens"]
110
111
112def find_sweet_fill_chars(base_url: str, target_ctx: int, model_name: str):
113    goal = int(target_ctx * TARGET_FRACTION)
114    lo = int(target_ctx * 0.50 / CHAR_PER_TOKEN)
115    hi = int(target_ctx * 0.97 / CHAR_PER_TOKEN)
116    n_lo = calibration(base_url, lo, model_name)
117    n_hi = calibration(base_url, hi, model_name)
118    if n_hi == n_lo:
119        return hi, n_hi
120    slope = (n_hi - n_lo) / (hi - lo)
121    fill = max(1, int(lo + (goal - n_lo) / slope))
122    best_c, best_n = fill, calibration(base_url, fill, model_name)
123    for d in (-2048, -1024, 0, +1024, +2048):
124        c = max(1, fill + d)
125        if c < lo or c > hi:
126            continue
127        n = calibration(base_url, c, model_name)
128        if abs(n - goal) < abs(best_n - goal):
129            best_c, best_n = c, n
130    return best_c, best_n
131
132
133def force_cold_prefill_state(base_url: str) -> None:
134    # Upstream (>= 6f32ec07) requires Content-Type: application/json on POST
135    # /unload; the server returns HTTP 415 without it. Older (rc/0.1.30) was
136    # tolerant. Send an explicit JSON header.
137    try:
138        r = requests.post(
139            f"{base_url}/unload",
140            data=b"{}",
141            headers={"Content-Type": "application/json"},
142            timeout=60,
143        )
144        r.raise_for_status()
145    except Exception as e:
146        print(f"  warn: /unload failed: {e!r}")
147    try:
148        for _ in range(60):
149            r = requests.get(f"{base_url}/health", timeout=5)
150            if r.status_code == 200:
151                j = r.json()
152                if j.get("loaded"):
153                    break
154            time.sleep(1)
155    except Exception:
156        pass
157
158
159def cold_prefill(base_url: str, fill_chars: int, model_name: str,
160                 target_ctx: int) -> ColdPrefill:
161    force_cold_prefill_state(base_url)
162    body = {
163        "model": model_name,
164        "stream": False,
165        "reasoning_effort": "minimal",
166        "messages": [{"role": "user", "content": render_prompt(fill_chars)}],
167        "max_tokens": 1,
168        "temperature": 0,
169    }
170    r = requests.post(f"{base_url}/v1/chat/completions", json=body, timeout=1800)
171    r.raise_for_status()
172    data = r.json()
173    usage = data.get("usage", {}) or {}
174    timings = data.get("timings", {}) or {}
175    prompt_n = timings.get("prompt_n") or usage.get("prompt_tokens", 0)
176    prompt_ms = timings.get("prompt_ms", 0.0)
177    prompt_per_s = timings.get("prompt_per_second", float(prompt_n) * 1000.0 / max(1.0, prompt_ms)) if prompt_ms else 0.0
178    return ColdPrefill(
179        prompt_tokens_actual=prompt_n,
180        prompt_total_ms=round(prompt_ms, 1),
181        prompt_per_second=round(prompt_per_s, 1),
182        completion_tokens=timings.get("predicted_n") or usage.get("completion_tokens", 0),
183    )
184
185
186def stream_run(base_url: str, fill_chars: int, seq: int, target_ctx: int,
187               model_name: str) -> Run:
188    body = {
189        "model": model_name,
190        "stream": True,
191        "reasoning_effort": "minimal",
192        "messages": [{"role": "user", "content": render_prompt(fill_chars)}],
193        "max_tokens": 192,
194        "temperature": 0,
195    }
196    t_req = time.perf_counter()
197    content_ts: List[float] = []
198    n_content, n_reasoning = 0, 0
199    final_event = None
200    finish_reason = None
201
202    with requests.post(f"{base_url}/v1/chat/completions", json=body,
203                       stream=True, timeout=1800) as r:
204        r.raise_for_status()
205        # first chunk timestamp — proxy for server "received by client" latency
206        first_remote = None
207        for raw in r.iter_lines(decode_unicode=True):
208            if not raw or not raw.startswith("data:"):
209                continue
210            payload = raw[5:].strip()
211            if payload == "[DONE]": break
212            try:
213                c = json.loads(payload)
214            except json.JSONDecodeError:
215                continue
216            t = time.perf_counter()
217            delta = (c["choices"][0].get("delta", {}) if c.get("choices") else {})
218            if "content" in delta and delta["content"]:
219                content_ts.append(t)
220                n_content += 1
221            if "reasoning_content" in delta and delta["reasoning_content"]:
222                n_reasoning += 1
223            if c.get("choices") and c["choices"][0].get("finish_reason"):
224                finish_reason = c["choices"][0]["finish_reason"]
225            if c.get("timings"):
226                final_event = c
227        last_remote = time.perf_counter()
228
229    usage = (final_event or {}).get("usage", {}) or {}
230    timings = (final_event or {}).get("timings", {}) or {}
231    prompt_tokens = usage.get("prompt_tokens", 0)
232    completion_tokens = usage.get("completion_tokens", 0)
233
234    ttft_ms = ((content_ts[0] - t_req) * 1000) if content_ts else 0.0
235    decode_avg_tps, decode_peak_tps = 0.0, 0.0
236    if content_ts and completion_tokens > 0:
237        decode_dt = max(0.001, content_ts[-1] - content_ts[0])
238        decode_avg_tps = completion_tokens / decode_dt
239        if len(content_ts) > PEER_WINDOW:
240            for i in range(len(content_ts) - PEER_WINDOW):
241                w = content_ts[i + PEER_WINDOW - 1] - content_ts[i]
242                if w > 0:
243                    rate = PEER_WINDOW / w
244                    if rate > decode_peak_tps:
245                        decode_peak_tps = rate
246    elapsed = ((content_ts[-1] - t_req) * 1000) if content_ts else 0.0
247    total_request_ms = (last_remote - t_req) * 1000
248
249    return Run(
250        seq=seq,
251        target_ctx=target_ctx,
252        target_fill_chars=fill_chars,
253        prompt_tokens_actual=prompt_tokens,
254        completion_tokens=completion_tokens,
255        content_chunks=n_content,
256        reasoning_chunks=n_reasoning,
257        ttft_ms=round(ttft_ms, 2),
258        decode_avg_tps=round(decode_avg_tps, 2),
259        decode_peak_tps=round(decode_peak_tps, 2),
260        eng_predicted_per_second=round(timings.get("predicted_per_second", 0.0), 2),
261        eng_predicted_per_token_ms=round(timings.get("predicted_per_token_ms", 0.0), 2),
262        eng_prompt_per_second=round(timings.get("prompt_per_second", 0.0), 2),
263        sse_prompt_per_second=round(timings.get("prompt_per_second", 0.0), 2),
264        eng_draft_n=timings.get("draft_n", 0),
265        eng_draft_n_accepted=timings.get("draft_n_accepted", 0),
266        eng_predicted_ms=round(timings.get("predicted_ms", 0.0), 2),
267        eng_total_request_ms=round(total_request_ms, 1),
268        finish_reason=str(finish_reason or "stop"),
269        elapsed_ms=round(elapsed, 1),
270    )
271
272
273def measure_window(base_url: str, target_ctx: int, model_name: str) -> dict:
274    print(f"\n=== {model_name} @ ctx {target_ctx} ===")
275    lookup_v1_models(base_url, model_name)
276    fill_chars, prompt_tokens_actual = find_sweet_fill_chars(base_url, target_ctx, model_name)
277    print(f"  calibration: fill_chars={fill_chars}, prompt_tokens={prompt_tokens_actual}")
278
279    print(f"  cold-prefill probe (max_tokens=1, non-stream) ...")
280    cp = cold_prefill(base_url, fill_chars, model_name, target_ctx)
281    print(f"  coldfill  prompt_n={cp.prompt_tokens_actual:5d}  "
282          f"prompt_total_ms={cp.prompt_total_ms:8.1f}  prompt_per_second={cp.prompt_per_second:7.1f} t/s")
283
284    runs: List[Run] = []
285    for i in range(1, 4):
286        time.sleep(1.5)
287        r = stream_run(base_url, fill_chars, seq=i, target_ctx=target_ctx,
288                       model_name=model_name)
289        runs.append(r)
290        print(
291            f"  seq={r.seq} prompt_tok={r.prompt_tokens_actual:5d} "
292            f"completion_tok={r.completion_tokens:3d} ttft={r.ttft_ms:7.0f}ms "
293            f"avg={r.decode_avg_tps:6.2f} t/s peak={r.decode_peak_tps:6.2f} t/s "
294            f"(eng_pred={r.eng_predicted_per_second:6.2f}, "
295            f"sse-prompt-rpt={r.sse_prompt_per_second:6.1f}, "
296            f"draft+={r.eng_draft_n_accepted}/{r.eng_draft_n}) "
297            f"finish={r.finish_reason}"
298        )
299
300    avgs = [r.decode_avg_tps for r in runs if r.decode_avg_tps]
301    peaks = [r.decode_peak_tps for r in runs if r.decode_peak_tps]
302    engs = [r.eng_predicted_per_second for r in runs if r.eng_predicted_per_second]
303    return {
304        "target_ctx": target_ctx,
305        "model_name": model_name,
306        "target_prompt_tokens": prompt_tokens_actual,
307        "fill_chars": fill_chars,
308        "cold_prefill": asdict(cp),
309        "runs": [asdict(r) for r in runs],
310        "avg_decode_avg_tps": round(statistics.mean(avgs), 2) if avgs else 0.0,
311        "avg_peak_decode_tps": round(statistics.mean(peaks), 2) if peaks else 0.0,
312        "peak_decode_tps_overall": round(max(peaks), 2) if peaks else 0.0,
313        "engine_predicted_avg_tps": round(statistics.mean(engs), 2) if engs else 0.0,
314        "engine_predicted_per_run": engs,
315        "ttft_ms_per_run": [r.ttft_ms for r in runs],
316        "engine_prefill_per_run": [r.eng_prompt_per_second for r in runs],
317        "finish_reasons": [r.finish_reason for r in runs],
318    }
319
320
321def main():
322    ap = argparse.ArgumentParser()
323    ap.add_argument("--base-url", default="http://127.0.0.1:8090")
324    ap.add_argument("--model", required=True)
325    ap.add_argument("--contexts", type=int, nargs="+", default=[32768])
326    ap.add_argument("--out", required=True)
327    ap.add_argument("--note", default="")
328    args = ap.parse_args()
329
330    out = {
331        "engine": "Strata",
332        "model_name": args.model,
333        "host": "Shin-BlackMamba",
334        "started_at_utc": int(time.time()),
335        "contexts": args.contexts,
336        "note": args.note,
337        "results": [],
338    }
339    for ctx in args.contexts:
340        out["results"].append(measure_window(args.base_url, ctx, args.model))
341
342    out["finished_at_utc"] = int(time.time())
343    Path(args.out).parent.mkdir(parents=True, exist_ok=True)
344    Path(args.out).write_text(json.dumps(out, indent=2))
345    print("\nWrote", args.out)
346
347
348if __name__ == "__main__":
349    main()