okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
eb4e0c4b4
main
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 8per-request `timings` (prompt_n / cache_n / prompt_ms / predicted_n / predicted_ms / 9draft_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 11only 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): 17STRATA_URL default http://127.0.0.1:8081 18STRATA_KEY default "local" 19STRATA_MODEL default qwen3.8-flash-next-iq3_s 20STRATA_RUNS default 3 21STRATA_MAXTOK default 256 22STRATA_TARGETS default 4096,32768,131072 23STRATA_TTFT default 1 (also run one streaming TTFT run per size) 24 25Outputs (next to this script): 26results.json meta + every run + summary 27raw/*.json the complete response of every non-streaming run 28samples.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 66engine report the exact prompt token count.""" 67want = int (target_tokens * 3.9 ) 68parts ,n = [],0 69while n < want : 70parts .append (FILLER ) 71n += len (FILLER ) 72body = "" .join (parts ) 73return f"[run { tag } ] " + body + TASK ,len (parts ) 74 75 76def gpu_mem (): 77try : 78out = subprocess .run ( 79 ["nvidia-smi" ,"--query-gpu=index,memory.used" ,"--format=csv,noheader,nounits" ], 80capture_output = True ,text = True ,timeout = 10 ).stdout 81return {int (a ):int (b )for a ,b in (l .split ("," )for l in out .strip ().splitlines ())} 82except Exception : 83return {} 84 85 86def ram (): 87info = {} 88with open ("/proc/meminfo" )as fh : 89for line in fh : 90k ,v = line .split (":" ,1 ) 91info [k ]= int (v .split ()[0 ]) 92mib = 1048576.0 93return {"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 (): 103while 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 ): 109req = urllib .request .Request ( 110URL + path ,data = json .dumps (payload ).encode (), 111headers = {"Content-Type" :"application/json" ,"Authorization" :f"Bearer { API_KEY } " }, 112method = "POST" ) 113return urllib .request .urlopen (req ,timeout = timeout ) 114 115 116def run_nonstream (tag ,target ,repeat ): 117prompt ,reps = build_prompt (tag ,target ) 118payload = {"model" :MODEL ,"messages" : [{"role" :"user" ,"content" :prompt }], 119"max_tokens" :MAXTOK ,"temperature" :0 ,"stream" :False } 120t0 = time .perf_counter () 121with post ("/v1/chat/completions" ,payload )as resp : 122raw = resp .read ().decode ("utf-8" ,"replace" ) 123wall = time .perf_counter ()- t0 124obj = json .loads (raw ) 125with open (os .path .join (RAW ,f" { tag } .json" ),"w" )as fh : 126json .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 ) 129usage ,tim = obj .get ("usage" )or {},obj .get ("timings" )or {} 130ch = (obj .get ("choices" )or [{}])[0 ] 131msg = ch .get ("message" )or {} 132return { 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 ): 150prompt ,reps = build_prompt (tag ,target ) 151payload = {"model" :MODEL ,"messages" : [{"role" :"user" ,"content" :prompt }], 152"max_tokens" :MAXTOK ,"temperature" :0 ,"stream" :True } 153t0 = time .perf_counter () 154ttft = None 155n_content = n_reason = 0 156with post ("/v1/chat/completions" ,payload )as resp : 157for rawline in resp : 158line = rawline .decode ("utf-8" ,"replace" ).strip () 159if not line .startswith ("data:" ): 160continue # keep-alive comments 161data = line [5 :].strip () 162if data == "[DONE]" : 163break 164try : 165obj = json .loads (data ) 166except Exception : 167continue 168delta = ((obj .get ("choices" )or [{}])[0 ].get ("delta" ))or {} 169if ttft is None and (delta .get ("content" )or delta .get ("reasoning_content" )): 170ttft = time .perf_counter ()- t0 171if delta .get ("content" ): 172n_content += 1 173if delta .get ("reasoning_content" ): 174n_reason += 1 175wall = time .perf_counter ()- t0 176return {"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 (): 184def sh (cmd ): 185try : 186return subprocess .run (cmd ,capture_output = True ,text = True ,timeout = 15 ).stdout .strip () 187except Exception : 188return "" 189gpu = 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" ]) 192return { 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 (): 210os .makedirs (RAW ,exist_ok = True ) 211"== health ==" ) 212try : 213with urllib .request .urlopen (URL + "/health" ,timeout = 10 )as r : 214r .read ().decode ()) 215except Exception as e : 216"health failed:" ,e ) 217return 1 218m = meta () 219json .dumps (m ["host" ],indent = 1 )[:1200 ]) 220 221t = threading .Thread (target = _sampler ,daemon = True ) 222t .start () 223runs = [] 224for target in TARGETS : 225for i in range (1 ,RUNS + 1 ): 226tag = f"nonstream- { target } -r { i } " 227f"[ { time . strftime ( '%H:%M:%S' ) } ] { tag } ..." ,flush = True ) 228try : 229rec = run_nonstream (tag ,target ,None ) 230except Exception as e : 231rec = {"run" :tag ,"mode" :"nonstream" ,"target_prompt_tokens" :target , 232"error" :f" { type ( e ). __name__ } : { e } " } 233rec ["gpu_mib_after" ]= gpu_mem () 234rec ["ram_after" ]= ram () 235runs .append (rec ) 236" ->" , {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 ) 239if DO_TTFT : 240for target in TARGETS : 241tag = f"stream- { target } -r1" 242f"[ { time . strftime ( '%H:%M:%S' ) } ] { tag } (TTFT) ..." ,flush = True ) 243try : 244rec = run_stream (tag ,target ) 245except Exception as e : 246rec = {"run" :tag ,"mode" :"stream" ,"target_prompt_tokens" :target , 247"error" :f" { type ( e ). __name__ } : { e } " } 248runs .append (rec ) 249" -> 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) 253summary = {} 254for target in TARGETS : 255rs = [r for r in runs if r .get ("mode" )== "nonstream" 256and r .get ("target_prompt_tokens" )== target and "error" not in r ] 257if not rs : 258continue 259def med (key ): 260vals = [r [key ]for r in rs if isinstance (r .get (key ), (int ,float ))] 261return {"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 264summary [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 } 273out = {"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 ) 275for k in (0 ,1 )}, 276"ram_peak_used_gb" :max ((s ["ram" ]["used_gb" ]for s in _samples ),default = None )} 277with open (os .path .join (OUTDIR ,"results.json" ),"w" )as fh : 278json .dump (out ,fh ,indent = 1 ) 279with open (os .path .join (OUTDIR ,"samples.jsonl" ),"w" )as fh : 280for s in _samples : 281fh .write (json .dumps (s )+ "\n" ) 282"\n== summary ==" ) 283json .dumps (summary ,indent = 1 )) 284"gpu_peak_mib:" ,out ["gpu_peak_mib" ],"ram_peak_used_gb:" ,out ["ram_peak_used_gb" ]) 285"wrote results.json / samples.jsonl / raw/" ) 286return 0 287 288 289if __name__ == "__main__" : 290sys .exit (main ())