okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fd19246dc
main
1#!/usr/bin/env python3 2"""One command that measures this Strata install the way it is used, and writes a report you can share. 3 4BENCH.bat (Windows) ./bench.sh (Linux) python tools/strata_bench.py 5 6It starts the server with your existing settings (the newest strata-*.json of this folder, or --config FILE), or uses 7the one already running (it checks the config's port, or --url http://host:port), and sends a fixed suite through the 8real HTTP API, three runs each, medians reported: 9 101. chat three short questions (about 100 tokens out): decode tok/s and time to first token 112. 4K prompt a prompt of about 4,096 tokens: prompt tok/s and time to first token (fresh every run: no cache help) 123. 16K prompt the same at about 16,384 tokens (skipped when the context is smaller) 134. agent a coding-agent style session: system prompt + four tools, then five turns, each adding about 1,500 words 14of a file to the conversation and continuing from the model's own earlier replies - how many prompt 15tokens the conversation cache reused, how many had to be read again, time to first token per turn 165. --clients N N requests at once (the server needs --batch for them to run together): total tok/s, p50/p95 latency 176. --long 32K the same prompt test at about 32,768 tokens 18 19Speeds are the engine's own timings (the `timings` of the answer: prompt_per_second, predicted_per_second); time to first 20token and latency are measured by this client. Thinking is off for the suite (--think turns it on), so the answers are 21short and the runs comparable. The default run takes about 3-10 minutes after the model has loaded (the slower the card, the longer). 22 23The result goes to bench/results/<date>-community-<gpu>-<model>/ : README.md in the format of 24docs/COMMUNITY_BENCHMARKS.md, results.json (every request) and an engine log excerpt. Home folders, user and host names, 25IP addresses and API keys are replaced by placeholders before anything is written; read it once before you share it. 26`--compare <older results folder>` prints the two side by side. Standard library only. 27This is the quick speed check, not the standard benchmark: `strata bench run` follows docs/BENCHMARK_PROTOCOL.md (fixed prompts, thinking on, 28the model card sampling, twelve sanity checks) and writes results other people can compare with. 29""" 30from __future__import annotations 31 32import argparse 33import datetime 34import getpass 35import json 36import os 37import platform 38import re 39import socket 40import statistics 41import subprocess 42import sys 43import tempfile 44import threading 45import time 46import urllib .error 47import urllib .request 48from pathlib import Path 49 50ROOT = Path (__file__ ).resolve ().parents [1 ] 51sys .path .insert (0 ,str (Path (__file__ ).resolve ().parent )) 52from ab_engine import PROMPTS ,long_prompt # noqa: E402 the same three short questions and word list 53from agent_turns_bench import SYSTEM ,TOOLS # noqa: E402 the same agent system prompt and tool list 54import serve_load # noqa: E402 the burst client for --clients 55 56SCHEMA = 1 57CHAT_MAX_TOKENS = 100 58LONG_MAX_TOKENS = 24 59AGENT_MAX_TOKENS = 64 60AGENT_TURNS = 5 61AGENT_WORDS = 1500 62AGENT_MIN_CONTEXT = 10240 # the last turn of the session holds about 10K tokens 63BURST_MAX_TOKENS = 128 64 65 66# --------------------------------------------------------------------------------------------------------- redaction 67def usable_key (value )-> str : 68"""An API key as a client may send it: "" for nothing, blanks, or "none" in any case (the server's word for no key, #4483).""" 69if isinstance (value , (list ,tuple )):# a config may list several keys: the first one is the client's 70value = value [0 ]if value else None 71text = "" if value is None else str (value ).strip () 72return "" if text .lower ()== "none" else text 73 74 75def redactor (extra :list [str ]= (),key :str = "" ): 76"""-> f(text) -> text with this machine's home folders, user and host names, the Strata folder, IP addresses and the 77API key replaced. Applied to everything that is written or printed from the server's or the machine's own text.""" 78subs :list [tuple [re .Pattern ,str ,int ]]= [] 79 80def add (value ,label ,word = False ,exact = False ): 81if value and len (str (value ))>= 4 : 82v = str (value ) 83for form in sorted ({v ,v .replace ("\\" ,"/" ),v .replace ("/" ,"\\" )},key = len ,reverse = True ): 84pat = re .escape (form ) 85subs .append ((re .compile (r"(?<![\w-])" + pat + r"(?![\w-])" if word else pat ,0 if exact else re .I ),label ,len (form ))) 86 87add (ROOT ,"<strata>" ) 88add (Path .home (),"<home>" ) 89add (tempfile .gettempdir (),"<tmp>" ) 90try : 91add (getpass .getuser (),"<user>" ,True ) 92except Exception :# noqa: BLE001 93pass 94add (socket .gethostname (),"<host>" ,True ) 95add (platform .node (),"<host>" ,True ) 96for x in extra : 97add (x ,"<private>" ,True ) 98add (usable_key (key ),"<key>" ,word = True ,exact = True ) 99subs .sort (key = lambda s :- s [2 ])# by the text that is replaced: the word wrappers would make a short user name outrank the folder holding it 100path_user = re .compile (r"(?i)([A-Za-z]:)?([\\/])(Users|home)([\\/])(?!<)[^\\/\s\"':;,]+" ) 101ip4 = re .compile (r"\b(?:192\.168|10\.\d{1,3}|172\.(?:1[6-9]|2\d|3[01])|100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])|169\.254)\.\d{1,3}\.\d{1,3}\b" ) 102bearer = re .compile (r"(?i)(bearer\s+)[A-Za-z0-9._~+/=-]{8,}" ) 103 104def f (text ): 105if not isinstance (text ,str ): 106return text 107for pat ,label ,_ in subs : 108text = pat .sub (label ,text ) 109text = path_user .sub (lambda m :f" { m . group ( 1 ) or '' } { m . group ( 2 ) } { m . group ( 3 ) } { m . group ( 4 ) } <user>" ,text ) 110text = bearer .sub (r"\1<key>" ,text ) 111return ip4 .sub ("<ip>" ,text ) 112return f 113 114 115def redact_obj (obj ,red ): 116if isinstance (obj ,dict ): 117return {red (k )if isinstance (k ,str )else k :redact_obj (v ,red )for k ,v in obj .items ()} 118if isinstance (obj ,list ): 119return [redact_obj (v ,red )for v in obj ] 120return red (obj )if isinstance (obj ,str )else obj 121 122 123# ---------------------------------------------------------------------------------------------------------- HTTP 124def http_json (base :str ,path :str ,key :str = "" ,timeout :float = 20 ): 125req = urllib .request .Request (base + path ,headers = {"Authorization" :"Bearer " + key }if key else {}) 126with urllib .request .urlopen (req ,timeout = timeout )as r : 127return json .loads (r .read ()) 128 129 130def try_json (base ,path ,key = "" ,timeout = 20 ): 131try : 132return http_json (base ,path ,key ,timeout ) 133except Exception :# noqa: BLE001 134return None 135 136 137def chat (base :str ,key :str ,messages :list ,max_tokens :int ,think :bool = False ,tools = None ,timeout :float = 3600 )-> dict : 138"""One streamed chat request -> {first, total, text, usage, timings, err}. `first` is the seconds to the first 139non-empty content or reasoning piece (keep-alives and empty deltas ignored).""" 140body = {"model" :"strata" ,"stream" :True ,"max_tokens" :max_tokens ,"temperature" :0 ,"messages" :messages } 141if tools : 142body ["tools" ]= tools 143if not think : 144body ["reasoning_effort" ]= "none" 145body ["chat_template_kwargs" ]= {"enable_thinking" :False } 146req = urllib .request .Request (base + "/v1/chat/completions" ,data = json .dumps (body ).encode (), 147headers = {"Content-Type" :"application/json" , 148** ({"Authorization" :"Bearer " + key }if key else {})}) 149t0 = time .perf_counter () 150first ,text ,usage ,timings ,err ,pieces = None , [],None ,None ,None ,0 151try : 152with urllib .request .urlopen (req ,timeout = timeout )as r : 153for raw in r : 154line = raw .decode ("utf-8" ,"replace" ).strip () 155if not line .startswith ("data:" ): 156continue 157d = line [5 :].strip () 158if d == "[DONE]" : 159break 160try : 161j = json .loads (d ) 162except ValueError : 163continue 164if j .get ("error" ): 165err = str (j ["error" ])[:300 ] 166for ch in j .get ("choices" )or []: 167dl = ch .get ("delta" )or {} 168piece = (dl .get ("content" )or "" )+ (dl .get ("reasoning_content" )or "" ) 169if piece : 170if first is None : 171first = time .perf_counter ()- t0 172pieces += 1 173text .append (dl .get ("content" )or "" ) 174if j .get ("usage" ): 175usage = j ["usage" ] 176if j .get ("timings" ): 177timings = j ["timings" ] 178except urllib .error .HTTPError as e : 179err = f"HTTP { e . code } : { e . read ()[: 200 ]!r } " 180except Exception as e :# noqa: BLE001 181err = repr (e )[:300 ] 182total = time .perf_counter ()- t0 183if os .environ .get ("STRATA_BENCH_ANSWERS" ): 184try : 185with open (os .environ ["STRATA_BENCH_ANSWERS" ],"a" ,encoding = "utf-8" )as _f : 186_f .write (json .dumps ({"messages" :messages [- 1 :],"text" :"" .join (text ),"usage" :usage , 187"err" :err })+ "\n" ) 188except Exception :# noqa: BLE001 189pass 190return {"first" :first ,"total" :total ,"text" :"" .join (text ),"usage" :usage ,"timings" :timings ,"err" :err , 191"pieces" :pieces } 192 193 194def digest (r :dict )-> dict : 195"""The numbers of one request, the engine's own where it reported them.""" 196u ,t = r .get ("usage" )or {},r .get ("timings" )or {} 197gen = u .get ("completion_tokens" )or r .get ("pieces" )or 0 198prompt_tokens = u .get ("prompt_tokens" ) 199cached = (u .get ("prompt_tokens_details" )or {}).get ("cached_tokens" ) 200if cached is None : 201cached = t .get ("cache_n" ) 202read = t .get ("prompt_n" ) 203if read is None and prompt_tokens is not None and cached is not None : 204read = prompt_tokens - cached 205dec ,dsrc = t .get ("predicted_per_second" ),"engine" 206if dec is None and r .get ("first" )is not None and gen > 1 and r ["total" ]> r ["first" ]: 207dec ,dsrc = round ((gen - 1 )/ (r ["total" ]- r ["first" ]),1 ),"client" 208pp ,psrc = t .get ("prompt_per_second" ),"engine" 209if pp is None : 210pp ,psrc = None ,None 211return {"ok" :r .get ("err" )is None and r .get ("first" )is not None , 212"err" :r .get ("err" ),"ttft_s" :None if r .get ("first" )is None else round (r ["first" ],3 ), 213"total_s" :round (r ["total" ],3 ),"prompt_tokens" :prompt_tokens ,"reused_tokens" :cached , 214"read_tokens" :read ,"generated_tokens" :gen ,"prompt_tps" :pp ,"prompt_tps_source" :psrc , 215"decode_tps" :dec ,"decode_tps_source" :dsrc if dec is not None else None , 216"prompt_ms" :t .get ("prompt_ms" ),"decode_ms" :t .get ("predicted_ms" ), 217"drafts_offered" :t .get ("draft_n" ),"drafts_accepted" :t .get ("draft_n_accepted" )} 218 219 220# ----------------------------------------------------------------------------------------------------- statistics 221def stat (values )-> dict | None : 222v = [x for x in values if isinstance (x , (int ,float ))] 223if not v : 224return None 225return {"median" :round (statistics .median (v ),3 ),"min" :round (min (v ),3 ),"max" :round (max (v ),3 ),"n" :len (v )} 226 227 228def fmt (s ,digits = 1 ,unit = "" )-> str : 229if not s : 230return "not measured" 231d = digits 232return f" { s [ 'median' ]:.{ d }f } { unit } ( { s [ 'min' ]:.{ d }f } - { s [ 'max' ]:.{ d }f } )" 233 234 235def pctl (values ,p ): 236return serve_load .pct (values ,p ) 237 238 239# ---------------------------------------------------------------------------------------------------- the suite 240class Suite : 241def __init__ (self ,base ,key ,ctx ,runs ,think ,log = want_clients = 0 ,want_long = False ,quick = False ): 242self .base ,self .key ,self .ctx ,self .runs ,self .think ,self .log = base ,key ,ctx ,runs ,think ,log 243self .clients ,self .want_long = want_clients ,want_long 244self .quick = quick 245self .nonce = str (int (time .time ())) 246self .tokens_per_word ,self .overhead = 1.1 ,40 247self .out :dict = {"chat" : {},"prompts" : {},"agent" : {},"clients" : {},"skipped" : {},"failures" : []} 248 249def tag (self ,* parts )-> str : 250return "-" .join ([* map (str ,parts ),self .nonce ]) 251 252def fail (self ,where ,d ): 253self .out ["failures" ].append ({"where" :where ,"error" :d .get ("err" )or "no token came back" }) 254self .log (f" FAILED: { d . get ( 'err' ) or 'no token came back' } " ) 255 256def calibrate (self ): 257"""Words that make a prompt of a wanted size: two tiny requests (200 and 800 words) give the tokens per word as a 258slope, so the template's fixed part does not skew it.""" 259pts = [] 260for words in (200 ,800 ): 261r = digest (chat (self .base ,self .key , [{"role" :"user" ,"content" :f"[ { self . tag ( 'cal' , words ) } ]\n" + long_prompt (words )}],1 )) 262pts .append (r .get ("prompt_tokens" )) 263slope = (pts [1 ]- pts [0 ])/ 600 if all (pts )and pts [1 ]> pts [0 ]else None 264self .tokens_per_word = slope or 1.1 265self .overhead = max (0 , (pts [0 ]or 0 )- 200 * self .tokens_per_word )if slope else 40 266self .log (f" calibrated: about { self . tokens_per_word :.2f } tokens per word" ) 267 268def prompt_for (self ,tokens :int ,run :int )-> list : 269words = max (50 ,int ((tokens - self .overhead )/ self .tokens_per_word )) 270return [{"role" :"user" ,"content" :f"[bench { self . tag ( run , tokens , 'p' ) } ]\n" + long_prompt (words )}] 271 272def warm_up (self ): 273self .log ("warming up (not measured) ..." ) 274chat (self .base ,self .key , [{"role" :"user" ,"content" :PROMPTS [0 ]}],24 ,self .think ) 275self .calibrate () 276chat (self .base ,self .key ,self .prompt_for (1024 ,- 1 ),8 ,self .think ) 277 278def run_chat (self ): 279self .log (f"chat: { len ( PROMPTS ) } short questions x { self . runs } runs, up to { CHAT_MAX_TOKENS } new tokens" ) 280rows = [] 281for run in range (self .runs ): 282for i ,p in enumerate (PROMPTS ): 283d = digest (chat (self .base ,self .key , [{"role" :"user" ,"content" :f"[ { self . tag ( run , i , 'c' ) } ] { p } " }], 284CHAT_MAX_TOKENS ,self .think )) 285d .update (run = run ,prompt = i ) 286rows .append (d ) 287if not d ["ok" ]: 288self .fail ("chat" ,d ) 289else : 290self .log (f" run { run + 1 } q { i + 1 } : decode { d [ 'decode_tps' ] } tok/s, first token { d [ 'ttft_s' ] } s, " 291f" { d [ 'generated_tokens' ] } tokens" ) 292good = [r for r in rows if r ["ok" ]] 293self .out ["chat" ]= {"requests" :rows ,"decode_tps" :stat (r ["decode_tps" ]for r in good ), 294"ttft_s" :stat (r ["ttft_s" ]for r in good ),"generated_tokens" :stat (r ["generated_tokens" ]for r in good ), 295"prompt_tokens" :stat (r ["prompt_tokens" ]for r in good )} 296 297def run_prompt (self ,tokens :int ,label :str ): 298if self .ctx and tokens + LONG_MAX_TOKENS + 256 > self .ctx : 299self .out ["skipped" ][label ]= f"the context is { self . ctx } tokens" 300self .log (f" { label } prompt: skipped (the context is { self . ctx } tokens)" ) 301return 302self .log (f" { label } prompt: { self . runs } fresh prompts of about { tokens } tokens, { LONG_MAX_TOKENS } new tokens" ) 303rows = [] 304for run in range (self .runs ): 305d = digest (chat (self .base ,self .key ,self .prompt_for (tokens ,run ),LONG_MAX_TOKENS ,self .think )) 306d ["run" ]= run 307rows .append (d ) 308if not d ["ok" ]: 309self .fail (label ,d ) 310else : 311self .log (f" run { run + 1 } : { d [ 'prompt_tokens' ] } tokens, prompt { d [ 'prompt_tps' ] } tok/s " 312f"( { d [ 'reused_tokens' ] or 0 } reused), first token { d [ 'ttft_s' ] } s" ) 313good = [r for r in rows if r ["ok" ]] 314self .out ["prompts" ][label ]= {"target_tokens" :tokens ,"requests" :rows , 315"prompt_tps" :stat (r ["prompt_tps" ]for r in good ), 316"ttft_s" :stat (r ["ttft_s" ]for r in good ), 317"prompt_tokens" :stat (r ["prompt_tokens" ]for r in good ), 318"reused_tokens" :stat (r ["reused_tokens" ]or 0 for r in good )} 319 320def agent_files (self )-> list [tuple [str ,str ]]: 321"""Five pieces of text a coding agent would read: this folder's own documents when they exist (nothing personal), 322else generated filler of the same size.""" 323names = [] 324for rel in ("README.md" ,"docs/HOW_IT_WORKS.md" ,"docs/DETAILS.md" ,"docs/INSTALL.md" ,"docs/MODELS.md" ,"docs/COMMUNITY_BENCHMARKS.md" ): 325p = ROOT / rel 326if p .is_file (): 327words = p .read_text (encoding = "utf-8" ,errors = "replace" ).split () 328if len (words )>= AGENT_WORDS // 2 : 329names .append ((rel ," " .join (words [:AGENT_WORDS ]))) 330i = 0 331while len (names )< AGENT_TURNS : 332names .append ((f"generated/part { i } .txt" ,long_prompt (AGENT_WORDS ))) 333i += 1 334return names [:AGENT_TURNS ] 335 336def agent_session (self ,run :int )-> list [dict ]: 337files = self .agent_files () 338msgs = [{"role" :"system" ,"content" :f" { SYSTEM } \n(session { self . tag ( run , 'a' ) } )" }, 339 {"role" :"user" ,"content" :"I will show you files from a project one at a time. After each file, answer in " 340"one or two sentences what it is for. Do not call tools." }] 341turns = [] 342for t in range (AGENT_TURNS + 1 ): 343if t > 0 : 344rel ,body = files [t - 1 ] 345msgs .append ({"role" :"user" ,"content" :f"File { rel } :\n { body } \n\nWhat is this file for? Two sentences." }) 346r = chat (self .base ,self .key ,msgs ,AGENT_MAX_TOKENS ,self .think ,tools = TOOLS ) 347d = digest (r ) 348d .update (run = run ,turn = t ) 349turns .append (d ) 350if not d ["ok" ]: 351self .fail ("agent" ,d ) 352break 353msgs .append ({"role" :"assistant" ,"content" :r ["text" ]or "Understood." }) 354return turns 355 356def run_agent (self ): 357if self .ctx and self .ctx < AGENT_MIN_CONTEXT : 358self .out ["skipped" ]["agent" ]= f"context { self . ctx } is below ~10K" 359self .log (f"agent: skipped: context { self . ctx } is below ~10K" ) 360return 361self .log (f"agent: a session of { AGENT_TURNS + 1 } turns with four tools, x { self . runs } runs" ) 362sessions = [] 363for run in range (self .runs ): 364turns = self .agent_session (run ) 365sessions .append (turns ) 366for d in turns : 367if d ["ok" ]: 368self .log (f" run { run + 1 } turn { d [ 'turn' ] } : prompt { d [ 'prompt_tokens' ] } , reused { d [ 'reused_tokens' ] } , " 369f"read { d [ 'read_tokens' ] } , first token { d [ 'ttft_s' ] } s" ) 370follow = [[d for d in s if d ["ok" ]and d ["turn" ]> 0 ]for s in sessions ] 371hit = [sum (d ["reused_tokens" ]or 0 for d in s )/ max (1 ,sum (d ["prompt_tokens" ]or 0 for d in s ))* 100 372for s in follow if s ] 373# earlier conversation read again: what the previous turn held (prompt + its reply) minus what this turn reused 374reread ,fresh = [], [] 375for s in sessions : 376s = [d for d in s if d ["ok" ]] 377reread .append (sum (max (0 , (p ["prompt_tokens" ]or 0 )+ (p ["generated_tokens" ]or 0 )- (d ["reused_tokens" ]or 0 )) 378for p ,d in zip (s ,s [1 :]))) 379fresh .append (sum (d ["read_tokens" ]or 0 for d in s [1 :])- reread [- 1 ]) 380self .out ["agent" ]= {"sessions" :sessions ,"hit_pct" :stat (hit ),"reread_tokens" :stat (reread ),"new_tokens" :stat (fresh ), 381"turn_ttft_s" :stat (d ["ttft_s" ]for s in follow for d in s ), 382"last_turn_prompt_tokens" :stat (s [- 1 ]["prompt_tokens" ]for s in follow if s ), 383"turn_decode_tps" :stat (d ["decode_tps" ]for s in follow for d in s ), 384"first_turn_ttft_s" :stat (s [0 ]["ttft_s" ]for s in sessions if s and s [0 ]["ok" ])} 385 386def run_clients (self ,n :int ): 387self .log (f"concurrency: { n } requests at once x { self . runs } rounds, { BURST_MAX_TOKENS } new tokens each" ) 388rows = [] 389for rd in range (self .runs ): 390res :dict = {} 391th = [] 392t0 = time .perf_counter () 393for i in range (n ): 394t = threading .Thread (target = serve_load .one ,args = (self .base ,self .key ,"strata" ,i ,400 ,BURST_MAX_TOKENS ,res , {}, 395self .think ,f" { self . tag ( 'b' , n , rd ) } " )) 396t .start () 397th .append (t ) 398for t in th : 399t .join () 400wall = time .perf_counter ()- t0 401toks = sum (r ["tokens" ]for r in res .values ()) 402errs = [r ["err" ]for r in res .values ()if r ["err" ]] 403rows .append ({"round" :rd ,"wall_s" :round (wall ,2 ),"tokens" :toks ,"total_tps" :round (toks / wall ,2 ), 404"first_s" : [r ["first" ]for r in res .values ()if r ["first" ]is not None ], 405"latency_s" : [r ["total" ]for r in res .values ()],"errors" :errs [:3 ],"error_count" :len (errs )}) 406self .log (f" round { rd + 1 } : { toks } tokens in { wall :.1f } s = { toks / wall :.1f } tok/s total" 407+ (f" ERRORS { errs [: 1 ] } " if errs else "" )) 408firsts = [x for r in rows for x in r ["first_s" ]] 409lats = [x for r in rows for x in r ["latency_s" ]] 410self .out ["clients" ]= {"clients" :n ,"rounds" :rows ,"total_tps" :stat (r ["total_tps" ]for r in rows ), 411"ttft_p50_s" :round (pctl (firsts ,.5 ),3 )if firsts else None , 412"ttft_p95_s" :round (pctl (firsts ,.95 ),3 )if firsts else None , 413"latency_p50_s" :round (pctl (lats ,.5 ),3 )if lats else None , 414"latency_p95_s" :round (pctl (lats ,.95 ),3 )if lats else None , 415"errors" :sum (r ["error_count" ]for r in rows )} 416 417def run (self ): 418self .warm_up () 419self .run_chat () 420self .run_prompt (4096 ,"4K" ) 421self .run_prompt (16384 ,"16K" ) 422self .run_agent () 423if self .clients : 424self .run_clients (self .clients ) 425if self .want_long : 426self .run_prompt (32768 ,"32K" ) 427return self .out 428 429 430def summary_metrics (out :dict )-> dict : 431"""The flat {name: stat} the --compare table and the README table read.""" 432m = {"chat decode tok/s" :out ["chat" ].get ("decode_tps" ),"chat first token (s)" :out ["chat" ].get ("ttft_s" )} 433for k ,v in out ["prompts" ].items (): 434m [f" { k } prompt tok/s" ]= v .get ("prompt_tps" ) 435m [f" { k } first token (s)" ]= v .get ("ttft_s" ) 436a = out ["agent" ] 437if a : 438m ["agent cache hit %" ]= a .get ("hit_pct" ) 439m ["agent re-read tokens/session" ]= a .get ("reread_tokens" ) 440m ["agent turn first token (s)" ]= a .get ("turn_ttft_s" ) 441m ["agent decode tok/s" ]= a .get ("turn_decode_tps" ) 442c = out ["clients" ] 443if c : 444m [f" { c [ 'clients' ] } clients total tok/s" ]= c .get ("total_tps" ) 445return m 446 447 448# -------------------------------------------------------------------------------------------------- the machine 449def run_cmd (cmd ,timeout = 15 )-> str : 450try : 451r = subprocess .run (cmd ,capture_output = True ,text = True ,timeout = timeout ,encoding = "utf-8" ,errors = "replace" ) 452return r .stdout if r .returncode == 0 else "" 453except (OSError ,subprocess .SubprocessError ): 454return "" 455 456 457def total_ram_gib ()-> float | None : 458try : 459import psutil 460return round (psutil .virtual_memory ().total / 2 ** 30 ,1 ) 461except Exception :# noqa: BLE001 462pass 463try : 464for line in Path ("/proc/meminfo" ).read_text ().splitlines (): 465if line .startswith ("MemTotal:" ): 466return round (int (line .split ()[1 ])/ 2 ** 20 ,1 ) 467except OSError : 468pass 469if os .name == "nt" : 470try : 471import ctypes 472 473class MS (ctypes .Structure ): 474_fields_ = [("l" ,ctypes .c_ulong ), ("load" ,ctypes .c_ulong ), ("total" ,ctypes .c_ulonglong )]+ [ 475 (n ,ctypes .c_ulonglong )for n in ("a" ,"b" ,"c" ,"d" ,"e" )] 476ms = MS () 477ms .l = ctypes .sizeof (MS ) 478ctypes .windll .kernel32 .GlobalMemoryStatusEx (ctypes .byref (ms )) 479return round (ms .total / 2 ** 30 ,1 ) 480except Exception :# noqa: BLE001 481pass 482return None 483 484 485def cpu_name ()-> str | None : 486try : 487for line in Path ("/proc/cpuinfo" ).read_text ().splitlines (): 488if line .lower ().startswith ("model name" ): 489return line .split (":" ,1 )[1 ].strip () 490except OSError : 491pass 492if os .name == "nt" : 493out = run_cmd (["powershell" ,"-NoProfile" ,"-Command" ,"(Get-CimInstance Win32_Processor | Select-Object -First 1).Name" ]) 494if out .strip (): 495return out .strip () 496return platform .processor ()or None 497 498 499def gpu_info_local ()-> dict : 500out = run_cmd (["nvidia-smi" ,"--query-gpu=name,memory.total,driver_version,power.limit,power.draw,pcie.link.gen.current,pcie.link.width.current,pstate,temperature.gpu" , 501"--format=csv,noheader,nounits" ]) 502gpus = [] 503for line in out .splitlines (): 504p = [x .strip ()for x in line .split ("," )] 505if len (p )>= 3 : 506g = {"name" :p [0 ],"vram_mib" :int (float (p [1 ]))if p [1 ].replace ("." ,"" ).isdigit ()else None ,"driver" :p [2 ]} 507if len (p )>= 9 : 508g .update ({"power_limit_w" :p [3 ],"power_draw_w" :p [4 ],"pcie" :f"gen { p [ 5 ] } x { p [ 6 ] } " , 509"pstate" :p [7 ],"temp_c" :p [8 ]}) 510gpus .append (g ) 511if not gpus : 512out = run_cmd (["nvidia-smi" ,"--query-gpu=name,memory.total,driver_version" ,"--format=csv,noheader,nounits" ]) 513for line in out .splitlines (): 514p = [x .strip ()for x in line .split ("," )] 515if len (p )>= 3 : 516gpus .append ({"name" :p [0 ],"vram_mib" :int (float (p [1 ]))if p [1 ].replace ("." ,"" ).isdigit ()else None ,"driver" :p [2 ]}) 517info = {"gpus" :gpus } 518head = run_cmd (["nvidia-smi" ]) 519m = re .search (r"CUDA(?: UMD)? Version:\s*([\d.]+)" ,head ) 520if m : 521info ["cuda" ]= m .group (1 ) 522if not gpus : 523rocm = run_cmd (["rocm-smi" ,"--showproductname" ]) 524names = re .findall (r"Card [Ss]eries:\s*(.+)" ,rocm )or re .findall (r"Card [Mm]odel:\s*(.+)" ,rocm ) 525info ["gpus" ]= [{"name" :n .strip (),"vram_mib" :None ,"driver" :None }for n in names ] 526v = run_cmd (["rocm-smi" ,"--showdriverversion" ]) 527m2 = re .search (r"Driver version:\s*(\S+)" ,v ) 528if m2 : 529info ["rocm_driver" ]= m2 .group (1 ) 530if not info ["gpus" ]and os .name != "nt" : 531# ROCm 7 and newer ship `amd-smi` and no `rocm-smi`, so a Radeon wrote the server's vendor stub ("AMD 532# Radeon", `...-community-unknown-...`) and `GPU driver: not read`. `static --asic` gives the marketing 533# name, `static --driver` the kernel driver's version, the PCI address only comes from `amd-smi list` and 534# the VRAM size is the amdgpu driver's sysfs file for that address (same probe as strata_cli/bench_facts.py). 535def amd_json (args ): 536try : 537return json .loads (run_cmd (["amd-smi" ,"static" ]+ args + ["--json" ]).strip ()or "{}" ).get ("gpu_data" )or [] 538except ValueError :# noqa: BLE001 - a report without the card's name is a report 539return [] 540try : 541bdf = {e .get ("gpu" ): (e .get ("bdf" )or "" )for e in json .loads (run_cmd (["amd-smi" ,"list" ,"--json" ]).strip ()or "[]" )} 542except ValueError : 543bdf = {} 544drv = {e .get ("gpu" ): ((e .get ("driver" )or {}).get ("version" )or "" )for e in amd_json (["--driver" ])} 545cards = [] 546for e in amd_json (["--asic" ]): 547name = ((e .get ("asic" )or {}).get ("market_name" )or "" ).strip () 548if not name : 549continue 550d = drv .get (e .get ("gpu" ),"" ) 551d = d if d .upper ()not in ("" ,"N/A" )else None 552if d : 553info ["rocm_driver" ]= info .get ("rocm_driver" )or d 554vram = None 555for dev in Path ("/sys/class/drm" ).glob ("card[0-9]*/device" ): 556try : 557if bdf .get (e .get ("gpu" ))and os .path .basename (os .path .realpath (dev )).lower ()== bdf [e ["gpu" ]].lower (): 558vram = int ((dev / "mem_info_vram_total" ).read_text (encoding = "utf-8" ).strip ())>> 20 559except (OSError ,ValueError ): 560pass 561cards .append ({"name" :name ,"vram_mib" :vram ,"driver" :d }) 562info ["gpus" ]= cards 563if not info ["gpus" ]and os .name == "nt" : 564# #1587: Windows with only an AMD card has neither nvidia-smi nor rocm-smi; the display class in the registry 565# names the card, its VRAM and its driver (the run was labelled "CPU only" before) 566try : 567if str (ROOT )not in sys .path : 568sys .path .insert (0 ,str (ROOT )) 569from serve .telemetry import windows_amd_cards 570info ["gpus" ]= [{"name" :c ["name" ],"vram_mib" : (c ["vram_bytes" ]>> 20 )if c ["vram_bytes" ]else None , 571"driver" :c ["driver" ]}for c in windows_amd_cards ()] 572except Exception :# noqa: BLE001 - a report without the card's name is still a report 573pass 574return info 575 576 577def storage_info ()-> str | None : 578if os .name == "nt" : 579out = run_cmd (["powershell" ,"-NoProfile" ,"-Command" , 580"Get-PhysicalDisk | Select-Object -First 4 FriendlyName,MediaType,BusType | " 581"ForEach-Object { $_.FriendlyName + ' ' + $_.MediaType + '/' + $_.BusType }" ]) 582names = [x .strip ()for x in out .splitlines ()if x .strip ()and "FriendlyName" not in x ] 583return "; " .join (names )or None 584if sys .platform == "darwin" : 585out = run_cmd (["system_profiler" ,"SPNVMeDataType" ,"SPSerialATADataType" ]) 586names = re .findall (r"Model:\s*(.+)" ,out ) 587if names : 588return "; " .join (n .strip ()for n in names ) 589return None 590out = run_cmd (["lsblk" ,"-d" ,"-o" ,"NAME,MODEL,TRAN" ,"-n" ,"-e" ,"7" ])# -e 7: skip loop devices (snap mounts) 591if out .strip (): 592return "; " .join (x .strip ()for x in out .splitlines ()if x .strip ())or None 593return None 594 595 596def engine_build (cfg :dict | None )-> dict | None : 597"""BUILD.json next to the engine exe: the toolkit/archs it was compiled with, unlike nvidia-smi's driver ceiling.""" 598exe = (cfg or {}).get ("exe" ) 599if not exe : 600return None 601try : 602b = json .loads ((Path (exe ).parent / "BUILD.json" ).read_text (encoding = "utf-8" )) 603except (OSError ,ValueError ): 604return None 605return {k :b [k ]for k in ("version" ,"source" ,"cuda" ,"rocm" ,"archs" ,"ptx" ,"portable" )if b .get (k )is not None }or None 606 607 608QUANT = re .compile (r"(?i)(?:^|[-_.])((?:UD-)?(?:IQ\d_[A-Z]+|Q\d_[A-Z0-9_]+|Q\d_K(?:_[A-Z]+)?|IQ\d_?[A-Z]*|BF16|F16|Q\d))(?=[-_.]|$)" ) 609SECRET_KEY = re .compile (r"(?i)key|token|secret|password|auth" ) 610 611 612def base_if_path (v ): 613if isinstance (v ,str )and (("/" in v or "\\" in v )or re .search (r"\.(gguf|bin|json|pack|txt|jinja|so|dll|exe)$" ,v ,re .I )): 614return re .split (r"[\\/]" ,v .rstrip ("\\/" ))[- 1 ] 615return v 616 617 618def config_view (cfg :dict )-> dict : 619"""The settings worth reporting, with paths cut to file names and secrets dropped.""" 620out = {} 621for k ,v in cfg .items (): 622if SECRET_KEY .search (k )or k in ("log" ,"cwd" ,"env" ): 623continue 624if k == "exe" : 625out [k ]= base_if_path (v ) 626elif k == "args" and isinstance (v ,list ): 627out [k ]= [base_if_path (x )if isinstance (x ,str )else x for x in v ] 628elif isinstance (v , (str ,int ,float ,bool ))or v is None : 629out [k ]= base_if_path (v ) 630elif isinstance (v , (list ,dict )): 631out [k ]= json .loads (json .dumps (v )) 632env = cfg .get ("env" ) 633if isinstance (env ,dict ): 634out ["env" ]= {k :base_if_path (str (v ))for k ,v in env .items ()if k .startswith (("STRATA_" ,"HIP_" ,"CUDA_" ,"ROCR_" ,"ONEAPI_" ,"SYCL_" ))and not SECRET_KEY .search (k )} 635return out 636 637 638def launch_line (view :dict )-> str : 639args = " " .join (f'" { a } "' if " " in str (a )else str (a )for a in view .get ("args" , [])) 640return f" { view . get ( 'exe' , 'strata' ) } { args } " .strip () 641 642 643def detect_quant (view :dict )-> str | None : 644names = [a for a in view .get ("args" , [])if isinstance (a ,str )and re .search (r"\.(gguf|pack)$|^[\w.-]+$" ,a )] 645names += [str (view .get ("model_name" )or "" )] 646for n in names : 647m = QUANT .search (n ) 648if m : 649return m .group (1 ).upper () 650return None 651 652 653def project_version ()-> str | None : 654try : 655# UTF-8 as setup.py reads it, whatever the locale's code page (#2792) 656m = re .search (r"project\(strata VERSION ([\d.]+)" , (ROOT / "CMakeLists.txt" ).read_text (encoding = "utf-8" )) 657return m .group (1 )if m else None 658except OSError : 659return None 660 661 662def git_commit ()-> str | None : 663if not (ROOT / ".git" ).exists (): 664return None 665out = run_cmd (["git" ,"-C" ,str (ROOT ),"rev-parse" ,"--short=8" ,"HEAD" ]).strip () 666return out or None 667 668 669def gpu_selection (cfg :dict | None ,gpu_arg :str | None = None )-> list [int ]: 670"""#1985: the GPU numbers (as nvidia-smi numbers them) the engine is told to use: the bench's --gpu when it starts 671the server, else the config's "gpu" (one card, a list or "0,2"), else a "--gpu" in the config's args. [] when 672nothing says.""" 673def parse (v ): 674if v is None or v == "" : 675return [] 676items = v if isinstance (v , (list ,tuple ))else str (v ).split ("," ) 677out = [] 678for x in items : 679x = str (x ).strip () 680if x .isdigit (): 681out .append (int (x )) 682return out 683sel = parse (gpu_arg )or parse ((cfg or {}).get ("gpu" )) 684if not sel : 685args = [str (x )for x in ((cfg or {}).get ("args" )or [])] 686if "--gpu" in args and args .index ("--gpu" )+ 1 < len (args ): 687sel = parse (args [args .index ("--gpu" )+ 1 ]) 688return sel 689 690 691def collect_machine (base :str ,key :str ,cfg :dict | None ,gpu_arg :str | None = None )-> dict : 692status = try_json (base ,"/v1/status" ,key )or {} 693metrics = try_json (base ,"/metrics" ,key ,30 )or {} 694props = try_json (base ,"/props" ,key )or {} 695models = try_json (base ,"/v1/models" ,key )or {} 696static = metrics .get ("hardware_static" )or {} 697eng = metrics .get ("engine" )or {} 698local = gpu_info_local () 699view = config_view (cfg )if cfg else {} 700# #1985: only the GPUs the engine uses - the config's / --gpu selection; with none given the engine runs on one card 701# (the one the server reports), not on every card the PC has 702used = local ["gpus" ] 703sel = gpu_selection (cfg ,gpu_arg ) 704if sel : 705used = [local ["gpus" ][i ]for i in sel if 0 <= i < len (local ["gpus" ])]or used 706elif len (used )> 1 and static .get ("gpu_name" ): 707named = [g for g in used if g ["name" ]== static ["gpu_name" ]] 708used = named [:1 ]or used [:1 ] 709gpu_names = [g ["name" ]for g in used ]or ([static ["gpu_name" ]]if static .get ("gpu_name" )else []) 710m = status .get ("machine" )or {} 711vram_mib = (m .get ("gpu" )or {}).get ("total_mib" )or None 712# #2001: the server names the cards it reads (" + " between them). A name nvidia-smi does not list means the 713# engine runs on another vendor's card (an Intel Arc beside a GeForce): the server's names are the right ones, and 714# so is its VRAM total - the PC's NVIDIA cards were not used. 715served = [n for n in (static .get ("gpu_name" )or "" ).split (" + " )if n and n != "?" ] 716# the engine's own stub when the driver names no card is the vendor alone ("AMD Radeon"), not a card name: 717# taking it as one would throw away the real name amd-smi read (same guard as strata_cli/bench_facts.py) 718served = [n for n in served if not re .fullmatch (r"(?i)\s*(nvidia|amd|intel|advanced micro devices)" 719r"([ -](geforce|radeon|graphics|arc))?\s*" ,n )] 720if served and not all (n in {g ["name" ]for g in local ["gpus" ]}for n in served ): 721gpu_names ,used = served , [] 722local = {** local ,"cuda" :None }# the PC's CUDA belongs to cards the engine did not use 723elif used and used [0 ].get ("vram_mib" ): 724vram_mib = sum (g .get ("vram_mib" )or 0 for g in used ) 725n_ctx = None 726for d in models .get ("data" )or []: 727n_ctx = (d .get ("meta" )or {}).get ("n_ctx" )or n_ctx 728n_ctx = n_ctx or (props .get ("default_generation_settings" )or {}).get ("n_ctx" ) 729return { 730"gpu" :gpu_names ,"gpu_vram_mib" :vram_mib ,"gpu_driver" : (used [0 ].get ("driver" )if used else local .get ("rocm_driver" )), 731"gpu_detail" : [{k :v for k ,v in g .items ()if k not in ("name" ,"vram_mib" ,"driver" )}for g in used ]or None , 732"cuda" :local .get ("cuda" ),"engine_build" :engine_build (cfg ), 733"cpu" :static .get ("cpu_name" )or cpu_name (),"cpu_cores" :static .get ("cores" ), 734"storage" :storage_info (), 735"cpu_threads" :static .get ("threads" )or os .cpu_count (),"ram_gib" :total_ram_gib (), 736"os" :f" { platform . system () } { '11' if int ( platform . version (). split ( '.' )[ - 1 ] or 0 ) >= 22000 else platform . release () } ( { platform . version () } )" if os .name == "nt" else f" { platform . system () } { platform . release () } " , 737"python" :platform .python_version (), 738"strata_version" :project_version (),"strata_commit" :git_commit (), 739"engine_version" : (eng .get ("version" )or status .get ("engine" )or str (props .get ("build_info" ,"" )).replace ("Strata " ,"" )or None ), 740"model" :view .get ("model_name" )or status .get ("model" )or props .get ("model_alias" ), 741"quant" :detect_quant (view )if view else None , 742"context" :n_ctx or eng .get ("max_context" ),"parallel_slots" :props .get ("total_slots" ), 743"config" :view ,"launch" :launch_line (view )if view else None , 744"engine_info" : {k :v for k ,v in eng .items ()if isinstance (v , (str ,int ,float ,bool ,dict ))and k not in ("model_path" ,)}, 745"vram_after" : (status .get ("vram" )or {}), 746 } 747 748 749# --------------------------------------------------------------------------------------------------- the server 750def find_configs (folder :Path = ROOT )-> list [Path ]: 751out = [] 752for p in folder .glob ("strata-*.json" ): 753if p .name .endswith (".shared-settings.json" ): 754continue 755try : 756c = json .loads (p .read_text (encoding = "utf-8-sig" )) 757except (OSError ,ValueError ): 758continue 759if isinstance (c ,dict )and c .get ("exe" )and isinstance (c .get ("args" ),list ): 760out .append (p ) 761return sorted (out ,key = lambda p :p .stat ().st_mtime ,reverse = True ) 762 763 764def is_strata (base :str ,key :str )-> bool : 765h = try_json (base ,"/health" ,key ,5 ) 766return bool (h and h .get ("service" )== "strata" ) 767 768 769def without_profile_save (cfg :dict )-> tuple [dict ,bool ]: 770"""#2088: the config without `--expert-profile-save FILE` (and its value) - the engine writes that profile when the 771server quits, and a benchmark's short prompts must not replace the user's calibrated one. -> (config, removed).""" 772args = list (cfg .get ("args" )or []) 773out ,i ,removed = [],0 ,False 774while i < len (args ): 775if args [i ]== "--expert-profile-save" : 776i ,removed = i + 2 ,True 777elif isinstance (args [i ],str )and args [i ].startswith ("--expert-profile-save=" ): 778i ,removed = i + 1 ,True 779else : 780out .append (args [i ]) 781i += 1 782return ({** cfg ,"args" :out }if removed else cfg ),removed 783 784 785def start_server (cfg_path :Path ,port :int ,gpu :str | None ,log_path :Path ): 786try : 787cfg = json .loads (cfg_path .read_text (encoding = "utf-8-sig" )) 788except (OSError ,ValueError ): 789cfg = None 790if isinstance (cfg ,dict ): 791safe ,removed = without_profile_save (cfg ) 792if removed :# a copy beside the log: the user's config file is not touched 793"Note: the bench starts this model without --expert-profile-save, so its short prompts do not " 794"overwrite your saved expert profile." ,file = sys .stderr ) 795tmp = log_path .with_suffix (".config.json" ) 796tmp .write_text (json .dumps (safe ),encoding = "utf-8" ) 797cfg_path = tmp 798cmd = [sys .executable ,str (ROOT / "serve" / "server.py" ),"--engine" ,"strata" ,"--config" ,str (cfg_path ),"--port" ,str (port )] 799if gpu : 800cmd += ["--gpu" ,gpu ] 801logf = open (log_path ,"w" ,encoding = "utf-8" ,errors = "replace" ) 802return subprocess .Popen (cmd ,cwd = str (ROOT ),stdout = logf ,stderr = subprocess .STDOUT ) 803 804 805def wait_ready (base :str ,key :str ,proc ,timeout :float ,log = -> bool : 806t0 ,last = time .time (),0 807while time .time ()- t0 < timeout : 808if proc is not None and proc .poll ()is not None : 809return False 810h = try_json (base ,"/health" ,key ,5 ) 811if h and h .get ("service" )== "strata" and h .get ("loaded" ): 812return True 813if time .time ()- last > 30 : 814log (f" still loading ( { int ( time . time () - t0 ) } s) ..." ) 815last = time .time () 816time .sleep (3 ) 817return False 818 819 820def stop_server (proc ): 821if proc is None or proc .poll ()is not None : 822return 823proc .terminate () 824try : 825proc .wait (90 ) 826except subprocess .TimeoutExpired : 827proc .kill () 828 829 830def log_excerpt (path :Path ,limit :int = 80 )-> list [str ]: 831try : 832lines = path .read_text (encoding = "utf-8" ,errors = "replace" ).splitlines () 833except OSError : 834return [] 835keep = re .compile (r"(?i)expert cache|slots|vram|ready|resident|kv |context|backend|gpu|prefill|mtp|spec|batch|version|hit" ) 836out = [x for x in lines if keep .search (x )and "[strata] done:" not in x ] 837return out [:limit ] 838 839 840# --------------------------------------------------------------------------------------------------- the report 841def slug (text :str ,limit :int = 40 )-> str : 842s = re .sub (r"[^a-z0-9]+" ,"-" , (text or "" ).lower ()).strip ("-" ) 843return s [:limit ].strip ("-" )or "unknown" 844 845 846def gpu_slug (machine :dict )-> str : 847names = machine .get ("gpu" )or [] 848if not names : 849return "cpu" 850# #2062: the cards one by one when they differ (rtx-5070-ti-plus-rtx-a4000), "2x-" only for identical ones 851groups :list [list ]= []# [name, count], in the order the cards are listed 852for name in names : 853same = next ((g for g in groups if g [0 ]== name ),None ) 854if same : 855same [1 ]+= 1 856else : 857groups .append ([name ,1 ]) 858parts = [] 859for name ,count in groups : 860n = re .sub (r"(?i)\b(nvidia|geforce|amd|radeon|intel|graphics|corporation)\b" ," " ,name ) 861parts .append (slug (n ,30 )if count == 1 else f" { count } x- { slug ( n , 30 ) } " ) 862return "-plus-" .join (parts )[:80 ].strip ("-" ) 863 864 865def model_label (machine :dict )-> str : 866model ,q = machine .get ("model" )or "model" ,machine .get ("quant" ) 867return model if not q or slug (q )in slug (model ,200 )else f" { model } - { q } " 868 869 870def results_dir_name (machine :dict ,date :str )-> str : 871return f" { date } -community- { gpu_slug ( machine ) } - { slug ( model_label ( machine ), 40 ) } " 872 873 874def unique_dir (parent :Path ,name :str )-> Path : 875p ,n = parent / name ,2 876while p .exists (): 877p = parent / f" { name } - { n } " 878n += 1 879return p 880 881 882def row (label ,prompt_tokens ,reused ,gen ,runs ,pp ,dec ,ttft ): 883return f"| { label } | { prompt_tokens } | { reused } | { gen } | { runs } | { pp } | { dec } | { ttft } |" 884 885 886def results_table (out :dict )-> list [str ]: 887lines = ["| Configuration | Actual prompt tokens | Reused tokens | Generated tokens | Runs | Prompt tok/s median and range | " 888"Decode tok/s median and range | TTFT seconds median and range |" , 889"| --- | ---: | ---: | ---: | ---: | --- | --- | --- |" ] 890c = out ["chat" ] 891if c : 892lines .append (row ("short chat" ,fmt (c .get ("prompt_tokens" ),0 ),"0" ,fmt (c .get ("generated_tokens" ),0 ), 893 (c .get ("ttft_s" )or {}).get ("n" ,0 ),"not measured" ,fmt (c .get ("decode_tps" )),fmt (c .get ("ttft_s" ),2 ))) 894for k ,v in out ["prompts" ].items (): 895lines .append (row (f" { k } prompt, fresh" ,fmt (v .get ("prompt_tokens" ),0 ),fmt (v .get ("reused_tokens" ),0 ),str (LONG_MAX_TOKENS )+ " cap" , 896 (v .get ("ttft_s" )or {}).get ("n" ,0 ),fmt (v .get ("prompt_tps" )),"not measured" ,fmt (v .get ("ttft_s" ),2 ))) 897a = out ["agent" ] 898if a : 899n = len ([s for s in a ["sessions" ]if len (s )> 1 ]) 900lines .append (row ("agent session, follow-up turns" ,fmt (a .get ("last_turn_prompt_tokens" ),0 )+ " at the last turn" , 901"see below" ,f"up to { AGENT_MAX_TOKENS } " ,n ,"see below" ,fmt (a .get ("turn_decode_tps" )), 902fmt (a .get ("turn_ttft_s" ),2 ))) 903return lines 904 905 906def render_readme (res :dict )-> str : 907mc ,out ,p = res ["machine" ],res ["results" ],res ["params" ] 908gpu = " + " .join (mc .get ("gpu" )or [])or "CPU only" 909vram = f" { mc [ 'gpu_vram_mib' ] / 1024 :.0f } GiB VRAM" if mc .get ("gpu_vram_mib" )else "VRAM not read" 910model = (model_label (mc )if mc .get ("model" )else mc .get ("quant" ))or "model not read" 911L = [f"# Community benchmark on { gpu } " ,"" , 912f"Measured on { res [ 'date' ] } with `tools/strata_bench.py` (suite { SCHEMA } , { p [ 'runs' ] } runs per test, medians with ranges). " 913f"Speeds are the engine's own timings; first-token times are measured by the client over HTTP. Speed only: no " 914f"correctness check was run." ,"" , 915"## Hardware and software" ,"" , 916f"- GPU and VRAM: { gpu } , { vram } " , 917f"- CPU: { mc . get ( 'cpu' ) or 'not read' } ( { mc . get ( 'cpu_cores' ) or '?' } cores, { mc . get ( 'cpu_threads' ) or '?' } threads); " 918f"installed RAM: { mc . get ( 'ram_gib' ) or '?' } GiB; storage: { mc . get ( 'storage' ) or 'not read' } " , 919f"- OS: { mc . get ( 'os' ) } ; GPU driver: { mc . get ( 'gpu_driver' ) or 'not read' } ; " 920f"CUDA (driver supports up to): { mc . get ( 'cuda' ) or 'not read' } " 921+ (f"; engine built for CUDA { ( mc . get ( 'engine_build' ) or {}). get ( 'cuda' ) } " if (mc .get ('engine_build' )or {}).get ('cuda' )else "" ), 922f"- Strata: project { mc . get ( 'strata_version' ) or '?' } , commit { mc . get ( 'strata_commit' ) or 'not a git checkout' } ; " 923f"engine { mc . get ( 'engine_version' ) or 'not read' } " ] 924for g in (mc .get ("gpu_detail" )or []): 925if g : 926L .append ("- GPU detail (after the run, near idle): " + ", " .join (f" { k } = { v } " for k ,v in g .items ()if v is not None )) 927L += ["- Background workloads: not recorded (GPU power limit/draw read above)" ,"" , 928"## Model and configuration" ,"" , 929f"- Model and quantization: { model } " , 930f"- Context: { mc . get ( 'context' ) or 'not read' } tokens; parallel slots: { mc . get ( 'parallel_slots' ) or 1 } " , 931f"- Settings: the install's own configuration, unchanged { ' (' + mc [ 'config' ][ 'backend' ] + ' backend)' if mc . get ( 'config' , {}). get ( 'backend' ) else '' } ; thinking " 932f" { 'on' if p [ 'think' ] else 'off' } for the suite; temperature 0" ,"" ] 933if mc .get ("launch" ): 934L += ["```text" ,mc ["launch" ],"```" ,"" ] 935env = (mc .get ("config" )or {}).get ("env" ) 936if env : 937L += ["Environment of the config: " + ", " .join (f"` { k } = { v } `" for k ,v in env .items ()),"" ] 938L += ["## Method" ,"" , 939f"Run by ` { p [ 'command' ] } ` against the HTTP API of a Strata server " 940f"( { 'started by the benchmark from the install configuration' if p [ 'started_server' ] else 'already running' } ); model loading is not " 941f"timed. One warm-up chat and a 1K prompt are discarded first. Every prompt starts with a unique tag, so the conversation " 942f"cache cannot help the fresh-prompt tests." ,"" , 943f"- short chat: the three questions of `tools/ab_engine.py`, up to { CHAT_MAX_TOKENS } new tokens, { p [ 'runs' ] } runs" , 944f"- 4K / 16K { ' / 32K' if 'prompt' in res [ 'results' ] and '32K' in res [ 'results' ][ 'prompts' ] else '' } prompts: generated word lists sized by a calibration request, " 945f" { LONG_MAX_TOKENS } new tokens, { p [ 'runs' ] } fresh prompts each" , 946f"- agent session: system prompt and four tools, then { AGENT_TURNS } turns that each add about { AGENT_WORDS } words of a project file " 947f"and continue from the model's own earlier answers (the way agent clients resend a conversation), { AGENT_MAX_TOKENS } new tokens per turn, " 948f" { p [ 'runs' ] } sessions; the cache numbers come from the answer's usage (`cached_tokens`) and timings (`prompt_n`)" , 949"- concurrency (when run): N requests sent at the same moment, total tokens over the wall time of the burst, " 950"latency over all requests" ,"" , 951"## Results" ,"" ] 952L += results_table (out ) 953L += ["" ,"Ranges are the lowest and highest of the runs; `Runs` counts requests that returned a token." ] 954ag = out ["agent" ] 955if ag and ag .get ("sessions" ): 956L += ["" ,"### Agent session (conversation cache)" ,"" , 957f"Cache hit over the follow-up turns: { fmt ( ag . get ( 'hit_pct' ), 1 , ' %' ) } ; earlier-turn tokens read again per session: " 958f" { fmt ( ag . get ( 'reread_tokens' ), 0 ) } (earlier turns that the cache did not hold; the { fmt ( ag . get ( 'new_tokens' ), 0 ) } new tokens of the files are read once); first turn (nothing cached) first token: { fmt ( ag . get ( 'first_turn_ttft_s' ), 2 , ' s' ) } ." ,"" , 959"| Turn (run 1) | Prompt tokens | Reused | Read | Prompt tok/s | First token (s) | Decode tok/s |" ,"| ---: | ---: | ---: | ---: | ---: | ---: | ---: |" ] 960for d in ag ["sessions" ][0 ]: 961if d ["ok" ]: 962L .append (f"| { d [ 'turn' ] } | { d [ 'prompt_tokens' ] } | { d [ 'reused_tokens' ] } | { d [ 'read_tokens' ] } | { d [ 'prompt_tps' ] or '-' } | { d [ 'ttft_s' ] } | { d [ 'decode_tps' ] or '-' } |" ) 963cl = out ["clients" ] 964if cl : 965L += ["" ,f"### Concurrency: { cl [ 'clients' ] } clients" ,"" , 966f"Total { fmt ( cl . get ( 'total_tps' ), 1 , ' tok/s' ) } ; first token p50 { cl . get ( 'ttft_p50_s' ) } s, p95 { cl . get ( 'ttft_p95_s' ) } s; " 967f"request latency p50 { cl . get ( 'latency_p50_s' ) } s, p95 { cl . get ( 'latency_p95_s' ) } s; errors { cl . get ( 'errors' ) } . " 968f"Server parallel slots: { mc . get ( 'parallel_slots' ) or 1 } (requests beyond that wait their turn)." ] 969if out ["skipped" ]or out ["failures" ]: 970L += ["" ,"### Skipped and failed" ,"" ] 971L += [f"- skipped { k } : { v } " for k ,v in out ["skipped" ].items ()] 972L += [f"- failed { f [ 'where' ] } : { f [ 'error' ] } " for f in out ["failures" ]] 973L += ["" ,"Per-request data: `results.json`. Engine log lines from the start: `engine-log-excerpt.txt` (when this run started the server)." ,"" , 974"## Correctness and limitations" ,"" , 975"Not measured: this is a speed suite. The conversation uses the model's own replies, so token counts differ a little between runs. " 976"Machine details come from the server, `nvidia-smi`/`rocm-smi` and the OS; background load is not recorded. " 977f"Total time of the suite: { res [ 'elapsed_s' ]:.0f } s." ,"" ] 978return "\n" .join (L ) 979 980 981def compare_table (old :dict ,new :dict )-> str : 982a ,b = summary_metrics (old ["results" ]),summary_metrics (new ["results" ]) 983rows = [f" { '' :32s } { 'old' :>12s } { 'new' :>12s } { 'change' :>9s } " ] 984for k in dict .fromkeys ([* a ,* b ]): 985x ,y = (a .get (k )or {}).get ("median" ), (b .get (k )or {}).get ("median" ) 986if x is None and y is None : 987continue 988ch = f" { ( y - x ) / x * 100 :+.1f } %" if x and y is not None else "" 989rows .append (f" { k :32s } { ( '-' if x is None else format ( x , '.2f' )):>12s } { ( '-' if y is None else format ( y , '.2f' )):>12s } { ch :>9s } " ) 990ho ,hn = old ["machine" ],new ["machine" ] 991notes = [f" { n } : { ho . get ( f ) } -> { hn . get ( f ) } " for n ,f in (("GPU" ,"gpu" ), ("engine" ,"engine_version" ), ("model" ,"model" ), ("quant" ,"quant" ), 992 ("context" ,"context" ))if ho .get (f )!= hn .get (f )] 993return "\n" .join (rows + (["" ,"differences:" ]+ notes if notes else [])) 994 995 996def load_results (path :Path )-> dict : 997p = Path (path ) 998if p .is_dir (): 999p = p / "results.json" 1000return json .loads (p .read_text (encoding = "utf-8" )) 1001 1002 1003def short_table (res :dict )-> str : 1004m = summary_metrics (res ["results" ]) 1005lines = [] 1006for k ,v in m .items (): 1007if v : 1008lines .append (f" { k :32s } { v [ 'median' ]:>10.2f } ( { v [ 'min' ]:.2f } - { v [ 'max' ]:.2f } , n= { v [ 'n' ] } )" ) 1009return "\n" .join (lines ) 1010 1011 1012def write_results (res :dict ,parent :Path ,red ,log_lines :list [str ])-> Path : 1013d = unique_dir (parent ,results_dir_name (res ["machine" ],res ["date" ])) 1014d .mkdir (parents = True ) 1015clean = redact_obj (res ,red ) 1016 (d / "results.json" ).write_text (json .dumps (clean ,indent = 1 ,ensure_ascii = False ),encoding = "utf-8" ) 1017 (d / "README.md" ).write_text (red (render_readme (res )),encoding = "utf-8" ) 1018if log_lines : 1019 (d / "engine-log-excerpt.txt" ).write_text (red ("\n" .join (log_lines ))+ "\n" ,encoding = "utf-8" ) 1020return d 1021 1022 1023# --------------------------------------------------------------------------------------------------------- main 1024def server_base (host ,port )-> str : 1025"""The address to talk to for a locally started server. The config's `host` is the interface the server 1026binds - a specific IP, or a wildcard that is not connectable as written - so it cannot be polled as-is. 1027An explicit `--url` bypasses this; there the caller knows the address.""" 1028host = host or "127.0.0.1" 1029host = {"0.0.0.0" :"127.0.0.1" ,"::" :"::1" }.get (host ,host )# wildcard binds accept loopback 1030authority = f"[ { host } ]" if ":" in host and not host .startswith ("[" )else host 1031return f"http:// { authority } : { port } " 1032 1033 1034def main (argv = None )-> int : 1035ap = argparse .ArgumentParser (description = "Measure this Strata install and write a shareable report (see the top of this file)." ) 1036ap .add_argument ("--config" ,help = "the model config to run (default: the newest strata-*.json of this folder)" ) 1037ap .add_argument ("--url" ,help = "use the server already running at this address (http://127.0.0.1:8080) instead of starting one" ) 1038ap .add_argument ("--port" ,type = int ,help = "the port to start the server on (default: the config's)" ) 1039ap .add_argument ("--gpu" ,help = "start the server on this GPU only (as the server's --gpu)" ) 1040ap .add_argument ("--api-key" ,default = os .environ .get ("STRATA_KEY" ,"" ),help = "the server's API key, if it has one (or STRATA_KEY)" ) 1041ap .add_argument ("--runs" ,type = int ,default = 3 ,help = "runs per test (default 3)" ) 1042ap .add_argument ("--clients" ,type = int ,default = 0 ,metavar = "N" ,help = "also send N requests at once" ) 1043ap .add_argument ("--long" ,action = "store_true" ,help = "also a prompt of about 32,768 tokens" ) 1044ap .add_argument ("--think" ,action = "store_true" ,help = "leave thinking on (the default suite turns it off)" ) 1045ap .add_argument ("--out" ,help = "where to write the results folder (default: bench/results)" ) 1046ap .add_argument ("--compare" ,metavar = "DIR" ,help = "a results folder (or its results.json) to put beside this run" ) 1047ap .add_argument ("--compare-only" ,metavar = "NEW" ,help = "print --compare of two existing results folders and stop" ) 1048ap .add_argument ("--ready-timeout" ,type = float ,default = 1800 ,help = "seconds to wait for the model to load" ) 1049ap .add_argument ("--quiet" ,action = "store_true" ) 1050a = ap .parse_args (argv ) 1051say = (lambda * x ,** k :None )if a .quiet else (lambda * x ,** k :* x ,** k ,flush = True )) 1052 1053if a .compare_only : 1054if not a .compare : 1055ap .error ("--compare-only NEW needs --compare OLD" ) 1056compare_table (load_results (Path (a .compare )),load_results (Path (a .compare_only )))) 1057return 0 1058 1059cfg_path ,cfg ,proc ,log_path = None ,None ,None ,None 1060if a .config or not a .url : 1061if a .config : 1062cfg_path = Path (a .config ) 1063if not cfg_path .is_absolute ()and not cfg_path .exists (): 1064cfg_path = ROOT / a .config 1065else : 1066found = find_configs () 1067if found : 1068cfg_path = found [0 ] 1069if len (found )> 1 : 1070say (f"Several models are installed; using { cfg_path . name } (the one used last). Pick another with --config FILE." ) 1071if cfg_path is None or not cfg_path .is_file (): 1072"No Strata model is set up in this folder: run START-HERE.bat (Windows) or ./setup.sh (Linux) first, " 1073"or give --url of a running server." ,file = sys .stderr ) 1074return 2 1075cfg = json .loads (cfg_path .read_text (encoding = "utf-8-sig" )) 1076key = usable_key (a .api_key )or usable_key ((cfg or {}).get ("api_key" )) 1077if a .url : 1078base = a .url .rstrip ("/" ) 1079else : 1080port = a .port or int (cfg .get ("port" ,8080 )) 1081base = server_base (cfg .get ("host" ),port ) 1082red = redactor (key = key ) 1083started = False 1084try : 1085if is_strata (base ,key ): 1086say (f"Using the Strata server already running at { base } ." ) 1087elif a .url : 1088f"No Strata server answers at { base } ." ,file = sys .stderr ) 1089return 2 1090else : 1091if try_json (base ,"/health" ,key ,3 )is not None : 1092f"Port { port } is used by something that is not Strata: pass --port N." ,file = sys .stderr ) 1093return 2 1094log_path = Path (tempfile .gettempdir ())/ f"strata-bench- { os . getpid () } .log" 1095say (f"Starting { cfg_path . name } on port { port } (loading takes 1-3 minutes; the PC may be slow meanwhile) ..." ) 1096proc = start_server (cfg_path ,port ,a .gpu ,log_path ) 1097started = True 1098if not wait_ready (base ,key ,proc ,a .ready_timeout ,say ): 1099tail = log_path .read_text (encoding = "utf-8" ,errors = "replace" ).splitlines ()[- 15 :]if log_path .exists ()else [] 1100"The server did not become ready. Last log lines:\n" + red ("\n" .join (tail )),file = sys .stderr ) 1101return 1 1102t0 = time .time () 1103pre = collect_machine (base ,key ,cfg ,a .gpu ) 1104suite = Suite (base ,key ,pre .get ("context" ),max (1 ,a .runs ),a .think ,log = say ,want_clients = a .clients ,want_long = a .long ) 1105slots = pre .get ("parallel_slots" )or 1 1106if a .clients and a .clients > slots : 1107say (f"Note: the server runs { slots } request(s) at a time (--batch), so { a . clients } clients will partly wait their turn." ) 1108say ("Running the suite (about 3-10 minutes) ..." ) 1109out = suite .run () 1110machine = collect_machine (base ,key ,cfg ,a .gpu )# again: VRAM and the cache after the work 1111if not machine .get ("gpu" ): 1112machine ["gpu" ]= pre .get ("gpu" ) 1113res = {"schema" :SCHEMA ,"tool" :"tools/strata_bench.py" ,"date" :datetime .date .today ().isoformat (), 1114"params" : {"runs" :suite .runs ,"think" :a .think ,"clients" :a .clients ,"long" :a .long ,"started_server" :started , 1115"command" :"python tools/strata_bench.py" + "" .join ( 1116f" { x } " for x in (f"--clients { a . clients } " if a .clients else "" ,"--long" if a .long else "" , 1117"--think" if a .think else "" ,f"--runs { a . runs } " if a .runs != 3 else "" )if x )}, 1118"elapsed_s" :time .time ()- t0 ,"machine" :machine ,"results" :out } 1119parent = Path (a .out )if a .out else ROOT / "bench" / "results" 1120d = write_results (res ,parent ,red ,log_excerpt (log_path )if log_path else []) 1121say ("\nResults (median, range over the runs):" ) 1122say (red (short_table (res ))) 1123if out ["failures" ]or out ["skipped" ]: 1124say (f" ( { len ( out [ 'failures' ]) } failed request(s), { len ( out [ 'skipped' ]) } skipped test(s): see the report)" ) 1125if a .compare : 1126say ("\nCompared with " + a .compare + ":" ) 1127say (red (compare_table (load_results (Path (a .compare )),redact_obj (res ,lambda s :s )))) 1128try : 1129shown = d .relative_to (ROOT ) 1130except ValueError : 1131shown = d 1132say (f"\nReport: { shown / 'README.md' } \nShare it: open a pull request that adds the folder { shown } (see docs/COMMUNITY_BENCHMARKS.md), " 1133f"or paste README.md into a GitHub issue. Home folders, user and host names and IP addresses are already replaced; " 1134f"read it once before you share it." ) 1135say ("For results other people can compare with, run the standard benchmark: strata bench run (docs/BENCHMARK_PROTOCOL.md)." ) 1136return 1 if out ["failures" ]and not any (out [k ]for k in ("chat" ,"prompts" ,"agent" ))else 0 1137finally : 1138if started : 1139stop_server (proc ) 1140 1141 1142if __name__ == "__main__" : 1143sys .exit (main ())