okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
1"""`strata bench run` for the standard benchmark protocol (docs/BENCHMARK_PROTOCOL.md). 2 3The runner sends the frozen requests of bench/prompts/standard-v1 to a Strata server through streaming chat completions, in the 4protocol's order, and writes a `strata-standard-benchmark` result that other people's results can be compared with: 5 6warm-up (1, excluded) -> performance (short, prompt-4k, prompt-16k, three times) -> sanity (I1-I4, R1-R4, T1-T4) 7-> optional concurrency (four short requests released together, three rounds) 8 9Speeds are the engine's own timings (the `timings` of the last stream chunk); first-token times are the client's monotonic clock. A value 10that cannot be read stays `None` with a reason in `missing`; nothing is estimated from chunks, characters or words. Prompts, answers and 11timings are saved without home folders, host names, private addresses or keys. 12""" 13 14from __future__import annotations 15 16import contextlib 17import hashlib 18import http .client 19import json 20import math 21import os 22import re 23import socket 24import statistics 25import subprocess 26import sys 27import threading 28import time 29import urllib .parse 30import uuid 31from concurrent .futures import ThreadPoolExecutor 32from datetime import datetime ,timezone 33from pathlib import Path 34 35from strata_cli import bench_facts as facts 36from strata_cli .bench import _private_mkdir ,_write_new 37from strata_control .profiles import ProfileError 38 39FORMAT = "strata-standard-benchmark" 40SCHEMA_VERSION = 1 41PROTOCOL_ID = "strata-qwen38-thinking-v1-draft.1" 42PROFILE = "qwen3.8-flash-next-thinking" 43SUITE = "standard-v1" 44#: The model-card revision the profile was defined from. The owner has not pinned one yet, so every result says so. 45MODEL_CARD_REVISION :str | None = None 46MODEL_CARD_URL = "https://huggingface.co/Qwen/Qwen3.8-Flash-Next" 47 48REQUEST_TIMEOUT_S = 1800.0 49#: Prompt tokens the cache may report beyond the longest prefix a request shares with the rest of the bundle before the 50#: user payload counts as reused. The slack covers token merges at the boundary. 51REUSE_SLACK_TOKENS = 8 52LENGTH_TOLERANCE = 0.02 53 54SAMPLING = {"temperature" :1.0 ,"top_p" :0.95 ,"top_k" :20 ,"min_p" :0.0 ,"presence_penalty" :0.0 , 55"repetition_penalty" :1.0 ,"reasoning_effort" :"xhigh" } 56TEMPLATE_KWARGS = {"enable_thinking" :True ,"preserve_thinking" :True } 57PHASES = ("warmup" ,"performance" ,"sanity" ,"concurrency" ) 58PLANNED = {"warmup" :1 ,"performance" :9 ,"sanity" :12 ,"concurrency" :12 } 59PERFORMANCE_CASES = ("short" ,"prompt-4k" ,"prompt-16k" ) 60METRICS = (("prompt_tps" ,"tokens/s" ), ("decode_tps" ,"tokens/s" ), ("ttft_s" ,"s" ), 61 ("first_answer_s" ,"s" ), ("total_s" ,"s" )) 62HEX64 = re .compile (r"^[0-9a-f]{64}$" ) 63 64 65class CorpusError (ProfileError ): 66pass 67 68 69def _now ()-> str : 70return datetime .now (timezone .utc ).strftime ("%Y-%m-%dT%H:%M:%SZ" ) 71 72 73def _number (value )-> float | None : 74if isinstance (value ,bool )or not isinstance (value , (int ,float )): 75return None 76return float (value )if math .isfinite (value )and value >= 0 else None 77 78 79def _count (value )-> int | None : 80if isinstance (value ,bool )or not isinstance (value ,int )or value < 0 : 81if isinstance (value ,float )and value .is_integer ()and value >= 0 and math .isfinite (value ): 82return int (value ) 83return None 84return value 85 86 87# ------------------------------------------------------------------------------------------------------------ the fixtures 88class Corpus : 89def __init__ (self ,sha256 :str ,specs :list [dict ],build :dict ,manifest :bytes ,directory :Path ): 90self .sha256 ,self .specs ,self .build ,self .manifest ,self .directory = sha256 ,specs ,build ,manifest ,directory 91 92 93def corpus_dir ()-> Path : 94return Path (__file__ ).resolve ().parents [1 ]/ "bench" / "prompts" / SUITE 95 96 97def load_corpus (directory :Path | None = None )-> Corpus : 98"""Read the fixture bundle and check every file against its manifest. Any difference is an error: the run would not be the protocol's.""" 99root = Path (directory )if directory else corpus_dir () 100try : 101manifest = (root / "MANIFEST.sha256" ).read_bytes () 102lines = manifest .decode ("utf-8" ).splitlines () 103except (OSError ,UnicodeError ): 104raise CorpusError ("the standard benchmark fixtures are missing (bench/prompts/standard-v1/MANIFEST.sha256)" ,5 )from None 105entries :dict [str ,str ]= {} 106for line in lines : 107digest ,_ ,name = line .partition (" " ) 108if not HEX64 .match (digest )or not name or name .startswith (("/" ,"\\" ))or ".." in Path (name ).parts : 109raise CorpusError ("the fixture manifest is malformed" ,5 ) 110entries [name ]= digest 111for name ,digest in entries .items (): 112try : 113data = (root / name ).read_bytes () 114except OSError : 115raise CorpusError (f"fixture file missing: { name } " ,5 )from None 116if hashlib .sha256 (data ).hexdigest ()!= digest : 117raise CorpusError (f"fixture file changed: { name } (line endings converted? bench/prompts is hashed byte for byte)" ,5 ) 118extra = {p .relative_to (root ).as_posix ()for p in (root / "requests" ).glob ("*.json" )}- set (entries ) 119if extra : 120raise CorpusError (f"fixture file not in the manifest: { sorted ( extra )[ 0 ] } " ,5 ) 121try : 122build = json .loads ((root / "build.json" ).read_text (encoding = "utf-8" )) 123specs = [json .loads ((root / "requests" / f" { row [ 'id' ] } .json" ).read_text (encoding = "utf-8" ))for row in build ["requests" ]] 124except (OSError ,ValueError ,KeyError ,TypeError ): 125raise CorpusError ("the fixture bundle is unreadable" ,5 )from None 126counts = {p :sum (1 for s in specs if s .get ("phase" )== p )for p in PHASES } 127if counts != PLANNED or len ({s ["id" ]for s in specs })!= len (specs )or build .get ("protocol_id" )!= PROTOCOL_ID : 128raise CorpusError ("the fixture bundle does not match this protocol" ,5 ) 129return Corpus (hashlib .sha256 (manifest ).hexdigest (),specs ,build ,manifest ,root ) 130 131 132# ------------------------------------------------------------------------------------------------------------ HTTP 133class Target : 134def __init__ (self ,root :str ,key :str | None ): 135parts = urllib .parse .urlsplit (root ) 136self .scheme ,self .host = parts .scheme ,parts .hostname or "" 137self .port = parts .port or (443 if parts .scheme == "https" else 80 ) 138self .key = key 139self .root = root .rstrip ("/" ) 140 141@property 142def loopback (self )-> bool : 143return self .host in facts .LOOPBACK 144 145def connection (self ,timeout :float )-> http .client .HTTPConnection : 146cls = http .client .HTTPSConnection if self .scheme == "https" else http .client .HTTPConnection 147return cls (self .host ,self .port ,timeout = timeout ) 148 149def headers (self ,extra :dict | None = None )-> dict : 150out = {"User-Agent" :"Strata-Bench/1" ,"Accept" :"application/json" ,"Connection" :"close" ,** (extra or {})} 151if self .key : 152out ["Authorization" ]= "Bearer " + self .key 153return out 154 155def get (self ,path :str ,timeout :float = 10 )-> dict | None : 156conn = self .connection (timeout ) 157try : 158conn .request ("GET" ,path ,headers = self .headers ()) 159response = conn .getresponse () 160body = response .read (8 << 20 ) 161if response .status != 200 : 162return None 163value = json .loads (body ) 164return value if isinstance (value ,dict )else None 165except (OSError ,http .client .HTTPException ,ValueError ): 166return None 167finally : 168conn .close () 169 170 171def payload_of (spec :dict ,model :str | None )-> dict : 172"""The request body: the protocol's sampling and thinking settings, every one explicit, plus the fixture's messages and tools.""" 173body = {"model" :model or "strata" ,"messages" :spec ["messages" ],"stream" :True , 174"stream_options" : {"include_usage" :True },"max_tokens" :spec ["max_output_tokens" ],"seed" :spec ["seed" ], 175** SAMPLING ,"reasoning_budget_tokens" :0 ,"chat_template_kwargs" :dict (TEMPLATE_KWARGS )} 176if spec .get ("tools" ): 177body ["tools" ]= spec ["tools" ] 178body ["tool_choice" ]= spec .get ("tool_choice" )or "auto" 179return body 180 181 182def stream_chat (target :Target ,spec :dict ,model :str | None ,* ,timeout_s :float , 183gate :threading .Event | None = None )-> dict : 184"""Send one streamed request and keep what the client saw, with monotonic offsets from the moment of dispatch.""" 185body = json .dumps (payload_of (spec ,model )).encode ("utf-8" ) 186raw :dict = {"http_status" :None ,"error" :None ,"finish_reason" :None ,"usage" :None ,"timings" :None , 187"events" : [],"reasoning" : [],"content" : [],"tool_calls" : {},"done" :False , 188"timed_out" :False ,"interrupted" :False } 189if gate is not None : 190gate .wait () 191raw ["t0" ]= start = time .monotonic_ns () 192conn = target .connection (timeout_s ) 193 194def expire (): 195raw ["timed_out" ]= True 196sock = getattr (conn ,"sock" ,None ) 197if sock is not None : 198try : 199sock .shutdown (socket .SHUT_RDWR ) 200except OSError : 201pass 202try : 203sock .close () 204except OSError : 205pass 206timer = threading .Timer (timeout_s ,expire ) 207timer .daemon = True 208timer .start () 209 210def offset ()-> float : 211return round ((time .monotonic_ns ()- start )/ 1e9 ,6 ) 212 213def mark (kind :str )-> None : 214raw ["events" ].append ([offset (),kind ]) 215 216try : 217conn .request ("POST" ,"/v1/chat/completions" ,body , 218target .headers ({"Content-Type" :"application/json" ,"Accept" :"text/event-stream" })) 219response = conn .getresponse () 220raw ["http_status" ]= response .status 221if response .status != 200 : 222text = response .read (4096 ).decode ("utf-8" ,"replace" ) 223raw ["error" ]= {"kind" :f"http_ { response . status } " ,"message" :text .strip ()[:300 ]or f"HTTP { response . status } " } 224else : 225while True : 226line = response .readline (1 << 20 ) 227if not line : 228break 229if not line .startswith (b"data:" ): 230continue 231data = line [5 :].strip () 232if data == b"[DONE]" : 233raw ["done" ]= True 234break 235try : 236event = json .loads (data ) 237except ValueError : 238raw ["error" ]= {"kind" :"malformed_stream" ,"message" :"a stream event was not JSON" } 239break 240if not isinstance (event ,dict ): 241raw ["error" ]= {"kind" :"malformed_stream" ,"message" :"a stream event was not an object" } 242break 243if "error" in event : 244err = event ["error" ] 245kind = (err .get ("code" )or err .get ("type" ))if isinstance (err ,dict )else None 246raw ["error" ]= {"kind" :str (kind or "stream_error" )[:60 ], 247"message" :str (err .get ("message" )if isinstance (err ,dict )else err )[:300 ]} 248break 249if isinstance (event .get ("usage" ),dict ): 250raw ["usage" ]= event ["usage" ] 251if isinstance (event .get ("timings" ),dict ): 252raw ["timings" ]= event ["timings" ] 253for choice in event .get ("choices" )or []: 254if not isinstance (choice ,dict ): 255continue 256delta = choice .get ("delta" )if isinstance (choice .get ("delta" ),dict )else {} 257reasoning ,text = delta .get ("reasoning_content" ),delta .get ("content" ) 258if isinstance (reasoning ,str )and reasoning : 259raw ["reasoning" ].append (reasoning ) 260mark ("reasoning" ) 261if isinstance (text ,str )and text : 262raw ["content" ].append (text ) 263mark ("answer" ) 264calls = delta .get ("tool_calls" ) 265if isinstance (calls ,list ): 266qualifies = False 267for call in calls : 268if not isinstance (call ,dict ): 269continue 270slot = raw ["tool_calls" ].setdefault (call .get ("index" ,len (raw ["tool_calls" ])), 271 {"id" :"" ,"name" :"" ,"arguments" :"" }) 272function = call .get ("function" )if isinstance (call .get ("function" ),dict )else {} 273for field ,value in (("id" ,call .get ("id" )), ("name" ,function .get ("name" )), 274 ("arguments" ,function .get ("arguments" ))): 275if isinstance (value ,str )and value : 276slot [field ]+= value 277qualifies = True 278if qualifies : 279mark ("tool_call" ) 280if choice .get ("finish_reason" ): 281raw ["finish_reason" ]= str (choice ["finish_reason" ]) 282if raw ["error" ]is None : 283if not raw ["done" ]: 284raw ["error" ]= {"kind" :"malformed_stream" ,"message" :"the stream ended without [DONE]" } 285elif raw ["finish_reason" ]is None : 286raw ["error" ]= {"kind" :"malformed_stream" ,"message" :"the stream carried no finish_reason" } 287except KeyboardInterrupt : 288raw ["interrupted" ]= True 289raw ["error" ]= {"kind" :"cancelled" ,"message" :"cancelled by the operator" } 290except (OSError ,http .client .HTTPException ,ValueError )as exc : 291if raw ["timed_out" ]or isinstance (exc ,TimeoutError ):# the socket's own timeout can fire just before the timer does (Windows) 292raw ["error" ]= {"kind" :"timeout" ,"message" :f"no complete answer within { timeout_s :g } seconds" } 293else : 294raw ["error" ]= {"kind" :"connection_" + type (exc ).__name__ ,"message" :str (exc )[:200 ]or type (exc ).__name__ } 295finally : 296timer .cancel () 297try : 298conn .close () 299except OSError : 300pass 301if raw ["timed_out" ]and raw ["error" ]is None : 302raw ["error" ]= {"kind" :"timeout" ,"message" :f"no complete answer within { timeout_s :g } seconds" } 303raw ["t_end" ]= time .monotonic_ns () 304return raw 305 306 307# ------------------------------------------------------------------------------------------------------------ scoring 308def strict_json (text :str ): 309"""One complete JSON value: no duplicate keys, no NaN or Infinity, no prose or fence around it.""" 310def pairs (items ): 311out = {} 312for key ,value in items : 313if key in out : 314raise ValueError (f"duplicate key { key !r } " ) 315out [key ]= value 316return out 317 318def constant (name ): 319raise ValueError (f" { name } is not JSON" ) 320return json .loads (text .strip (" \t\r\n\x0b\x0c" ),object_pairs_hook = pairs ,parse_constant = constant ) 321 322 323def same_json (a ,b )-> bool : 324"""Equal values of equal JSON types (true is not 1, 3 is not 3.0); object key order does not matter.""" 325if isinstance (a ,bool )or isinstance (b ,bool ): 326return isinstance (a ,bool )and isinstance (b ,bool )and a == b 327if isinstance (a ,dict )and isinstance (b ,dict ): 328return a .keys ()== b .keys ()and all (same_json (a [k ],b [k ])for k in a ) 329if isinstance (a ,list )and isinstance (b ,list ): 330return len (a )== len (b )and all (same_json (x ,y )for x ,y in zip (a ,b )) 331return type (a )is type (b )and a == b 332 333 334def evaluate (spec :dict ,status :str ,answer :str ,calls :list [dict ])-> dict : 335expected = spec ["expected" ] 336category = spec ["category" ] 337 338def verdict (passed :bool ,reason :str )-> dict : 339return {"category" :category ,"passed" :passed ,"reason" :reason } 340if status != "completed" : 341return verdict (False , {"truncated" :"the output cap was reached before the answer was complete" , 342"failed" :"the request failed" ,"skipped" :"the request was skipped" }[status ]) 343kind = expected ["kind" ] 344if kind == "tool_call" : 345if len (calls )!= 1 : 346return verdict (False ,f"expected one structured tool call, got { len ( calls ) } " ) 347call = calls [0 ] 348if call ["name" ]!= expected ["name" ]: 349return verdict (False ,f"wrong function { call [ 'name' ]!r } " ) 350try : 351arguments = strict_json (call ["arguments" ]or "{}" ) 352except ValueError as exc : 353return verdict (False ,f"the tool arguments are not strict JSON ( { exc } )" ) 354if not isinstance (arguments ,dict )or not same_json (arguments ,expected ["arguments" ]): 355return verdict (False ,"the tool arguments differ from the expected values" ) 356return verdict (True ,"the expected tool call" ) 357if kind == "text" : 358text = answer .strip (" \t\r\n\x0b\x0c" ) 359return verdict (text == expected ["value" ], 360"the exact expected text" if text == expected ["value" ]else "the answer text differs from the expected text" ) 361try : 362value = strict_json (answer ) 363except ValueError as exc : 364return verdict (False ,f"the answer is not one strict JSON value ( { exc } )" ) 365return verdict (same_json (value ,expected ["value" ]), 366"the expected JSON value" if same_json (value ,expected ["value" ])else "the JSON value differs from the expected value" ) 367 368 369# ------------------------------------------------------------------------------------------------------------ one request 370def _round (value :float | None )-> float | None : 371return None if value is None else round (value ,6 ) 372 373 374def record_of (spec :dict ,raw :dict ,meta :dict ,why :facts .Why | None = None )-> tuple [dict ,dict ,dict ]: 375"""-> (the report's request record, evidence for outputs.jsonl, extras for the report's `extensions`).""" 376usage = raw ["usage" ]if isinstance (raw .get ("usage" ),dict )else {} 377timings = raw ["timings" ]if isinstance (raw .get ("timings" ),dict )else {} 378details = usage .get ("prompt_tokens_details" )if isinstance (usage .get ("prompt_tokens_details" ),dict )else {} 379error = raw ["error" ] 380finish = raw ["finish_reason" ] 381if error is not None : 382status = "failed" 383elif finish == "length" : 384status = "truncated" 385elif finish in ("stop" ,"tool_calls" ): 386status = "completed" 387else : 388status = "failed" 389error = {"kind" :"unexpected_finish_reason" ,"message" :f"finish_reason { finish !r } " } 390t0 = raw ["t0" ] 391events = raw ["events" ] 392first = events [0 ]if events else None 393answer = next ((e for e in events if e [1 ]in ("answer" ,"tool_call" )),None ) 394 395input_tokens ,output_tokens = _count (usage .get ("prompt_tokens" )),_count (usage .get ("completion_tokens" )) 396cached ,cached_source = _count (details .get ("cached_tokens" )),"usage.prompt_tokens_details.cached_tokens" 397if cached is None : 398cached ,cached_source = _count (timings .get ("cache_n" )),"timings.cache_n" 399read ,read_source = _count (timings .get ("prompt_n" )),"timings.prompt_n" 400if read is None and input_tokens is not None and cached is not None and cached <= input_tokens : 401read ,read_source = input_tokens - cached ,"derived: usage.prompt_tokens - cached tokens" 402prompt_s = _number (timings .get ("prompt_ms" )) 403prompt_s = prompt_s / 1000 if prompt_s is not None else None 404decode_s = _number (timings .get ("predicted_ms" )) 405decode_s = decode_s / 1000 if decode_s is not None else None 406rate ,predicted_n = _number (timings .get ("predicted_per_second" )),_count (timings .get ("predicted_n" )) 407decode_tokens ,decode_source ,note = None ,None ,None 408if rate is not None and decode_s : 409implied = round (rate * decode_s ) 410# the engine rounds its rate to 0.1 tokens/s, so the implied count is good to about 0.05 * decode_s tokens 411if predicted_n is not None and abs (predicted_n - implied )<= 0.05 * decode_s + 1 : 412decode_tokens ,decode_source = predicted_n ,"timings.predicted_n (agrees with timings.predicted_per_second x predicted_ms)" 413else : 414decode_tokens = implied 415decode_source = "derived: timings.predicted_per_second x timings.predicted_ms / 1000 (the count the engine's rate used)" 416if predicted_n is not None : 417note = (f"timings.predicted_n is { predicted_n } but the engine's decode rate and time imply { implied } tokens; " 418"the implied count is used because it is the one the rate was computed from" ) 419elif predicted_n is not None : 420decode_tokens ,decode_source = predicted_n ,"timings.predicted_n (no decode rate to check it against)" 421if note is None and output_tokens is not None and decode_tokens is not None and output_tokens != decode_tokens : 422note = (f"API usage.completion_tokens is { output_tokens } ; the engine's decode count is { decode_tokens } . The engine count " 423"feeds decode_tps; the API count feeds the concurrent aggregate" ) 424prompt_tps = read / prompt_s if read and prompt_s else None 425decode_tps = decode_tokens / decode_s if decode_tokens and decode_s else None 426 427text = "" .join (raw ["content" ]) 428calls = [raw ["tool_calls" ][k ]for k in sorted (raw ["tool_calls" ],key = lambda k : (not isinstance (k ,int ),k ))] 429ttft ,first_answer = (first [0 ]if first else None ), (answer [0 ]if answer else None ) 430total = round ((raw ["t_end" ]- t0 )/ 1e9 ,6 ) 431kind_names = {"reasoning" :"reasoning" ,"answer" :"answer" ,"tool_call" :"tool_call" } 432record = { 433"id" :spec ["id" ],"phase" :spec ["phase" ],"case_id" :spec ["case_id" ],"repetition" :spec ["repetition" ], 434"seed" :spec ["seed" ],"max_output_tokens" :spec ["max_output_tokens" ],"concurrency" :spec ["concurrency" ], 435"round" :spec ["round" ],"status" :status ,"finish_reason" :finish , 436"error" :None if status in ("completed" ,"truncated" )else error , 437"tokens" : {"input_tokens" :input_tokens ,"cached_tokens" :cached ,"read_tokens" :read , 438"output_tokens" :output_tokens ,"decode_tokens" :decode_tokens }, 439"timings" : {"prompt_s" :_round (prompt_s ),"decode_s" :_round (decode_s ),"ttft_s" :_round (ttft ), 440"first_answer_s" :_round (first_answer ),"total_s" :total }, 441"metrics" : {"prompt_tps" :_round (prompt_tps ),"decode_tps" :_round (decode_tps )}, 442"sources" : {"input_tokens" :"usage.prompt_tokens of the final stream chunk" if input_tokens is not None else None , 443"cached_tokens" :cached_source if cached is not None else None , 444"read_tokens" :read_source if read is not None else None , 445"output_tokens" :"usage.completion_tokens of the final stream chunk" if output_tokens is not None else None , 446"decode_tokens" :decode_source , 447"engine_timings" : ("timings.prompt_ms, timings.predicted_ms, timings.predicted_per_second of the final stream " 448"chunk (raw values in outputs.jsonl)" )if timings else None , 449"client_timings" : ("client monotonic clock from dispatch; event offsets in outputs.jsonl" )}, 450"first_delta_kind" :kind_names .get (first [1 ])if first else None , 451"token_accounting_note" :note ,"evaluation" :None } 452if spec ["phase" ]== "sanity" : 453record ["evaluation" ]= evaluate (spec ,status ,text , [c for c in calls if c ["name" ]or c ["arguments" ]]) 454reuse_limit = meta ["max_shared_prefix_tokens" ]+ REUSE_SLACK_TOKENS 455extras = {"max_shared_prefix_tokens" :meta ["max_shared_prefix_tokens" ], 456"frozen_input_tokens" :meta ["input_tokens" ], 457"unexpected_payload_reuse" :bool (cached is not None and cached > reuse_limit ), 458"length_outside_tolerance" :bool (spec .get ("target_input_tokens" )and input_tokens is not None and 459abs (input_tokens - spec ["target_input_tokens" ])> 460LENGTH_TOLERANCE * spec ["target_input_tokens" ])} 461evidence = {"request_id" :spec ["id" ],"phase" :spec ["phase" ],"case_id" :spec ["case_id" ], 462"request" : {k :v for k ,v in payload_of (spec ,None ).items ()if k not in ("messages" ,"tools" ,"model" )}, 463"messages" :spec ["messages" ],"tools" :spec .get ("tools" ), 464"final_answer" :text ,"reasoning" :"" .join (raw ["reasoning" ]), 465"tool_calls" : [{"id" :c ["id" ],"name" :c ["name" ],"arguments" :c ["arguments" ]}for c in calls ], 466"finish_reason" :finish ,"usage" :raw .get ("usage" ),"timings" :raw .get ("timings" ),"error" :error , 467"http_status" :raw ["http_status" ],"dispatch_offset_s" :0.0 ,"end_offset_s" :total , 468"first_delta" : {"offset_s" :first [0 ],"kind" :first [1 ]}if first else None , 469"first_answer_offset_s" :first_answer ,"client_events" :events } 470return record ,evidence ,extras 471 472 473def skipped_record (spec :dict ,reason :str )-> tuple [dict ,dict ,dict ]: 474record = {"id" :spec ["id" ],"phase" :spec ["phase" ],"case_id" :spec ["case_id" ],"repetition" :spec ["repetition" ], 475"seed" :spec ["seed" ],"max_output_tokens" :spec ["max_output_tokens" ],"concurrency" :spec ["concurrency" ], 476"round" :spec ["round" ],"status" :"skipped" ,"finish_reason" :None , 477"error" : {"kind" :"skipped" ,"message" :reason }, 478"tokens" : {k :None for k in ("input_tokens" ,"cached_tokens" ,"read_tokens" ,"output_tokens" ,"decode_tokens" )}, 479"timings" : {k :None for k in ("prompt_s" ,"decode_s" ,"ttft_s" ,"first_answer_s" ,"total_s" )}, 480"metrics" : {"prompt_tps" :None ,"decode_tps" :None }, 481"sources" : {k :None for k in ("input_tokens" ,"cached_tokens" ,"read_tokens" ,"output_tokens" ,"decode_tokens" , 482"engine_timings" ,"client_timings" )}, 483"first_delta_kind" :None ,"token_accounting_note" :None ,"evaluation" :None } 484if spec ["phase" ]== "sanity" : 485record ["evaluation" ]= {"category" :spec ["category" ],"passed" :False ,"reason" :"the request was skipped: " + reason } 486return record , {"request_id" :spec ["id" ],"skipped" :reason }, {"unexpected_payload_reuse" :False , 487"length_outside_tolerance" :False } 488 489 490# ------------------------------------------------------------------------------------------------------------ the run 491class Collector : 492"""Runs the scheduled requests in order and keeps their records.""" 493 494def __init__ (self ,target :Target ,corpus :Corpus ,model :str | None ,log ,timeout_s :float ): 495self .target ,self .corpus ,self .model ,self .log ,self .timeout_s = target ,corpus ,model ,log ,timeout_s 496self .meta = {row ["id" ]:row for row in corpus .build ["requests" ]} 497self .results :dict [str ,tuple [dict ,dict ,dict ]]= {} 498self .abort :str | None = None 499self .number = 0 500self .total = sum (PLANNED [p ]for p in ("warmup" ,"performance" ,"sanity" )) 501 502def finish (self ,spec :dict ,raw :dict )-> dict : 503result = record_of (spec ,raw ,self .meta [spec ["id" ]]) 504self .results [spec ["id" ]]= result 505return result [0 ] 506 507def alive (self )-> bool : 508health = self .target .get ("/health" ,timeout = 5 ) 509return bool (health and health .get ("service" )== "strata" ) 510 511def one (self ,spec :dict )-> None : 512if self .abort : 513self .results [spec ["id" ]]= skipped_record (spec ,self .abort ) 514return 515self .number += 1 516self .log (f"[ { self . number } / { self . total } ] { spec [ 'id' ] } (up to { spec [ 'max_output_tokens' ] } tokens)" ) 517raw = stream_chat (self .target ,spec ,self .model ,timeout_s = self .timeout_s ) 518record = self .finish (spec ,raw ) 519timing = record ["timings" ] 520speed = record ["metrics" ] 521self .log (f" { record [ 'status' ] } : prompt { speed [ 'prompt_tps' ] or 'n/a' } tok/s, decode { speed [ 'decode_tps' ] or 'n/a' } tok/s, " 522f"first token { timing [ 'ttft_s' ] if timing [ 'ttft_s' ] is not None else 'n/a' } s" 523+ (f"; { record [ 'error' ][ 'kind' ] } " if record ["error" ]else "" )) 524if raw ["interrupted" ]: 525self .abort = "the operator cancelled the run" 526elif record ["status" ]== "failed" : 527if spec ["phase" ]== "warmup" : 528self .abort = f"the warm-up request failed ( { record [ 'error' ][ 'kind' ] } ); the measured stages were not run" 529elif not self .alive (): 530self .abort = f"the server stopped answering after { spec [ 'id' ] } ( { record [ 'error' ][ 'kind' ] } )" 531 532def concurrent_round (self ,specs :list [dict ])-> dict : 533gate = threading .Event () 534raws :dict [str ,dict ]= {} 535 536def work (spec ): 537raws [spec ["id" ]]= stream_chat (self .target ,spec ,self .model ,timeout_s = self .timeout_s ,gate = gate ) 538with ThreadPoolExecutor (max_workers = len (specs ))as pool : 539futures = [pool .submit (work ,spec )for spec in specs ] 540time .sleep (0.05 ) 541gate .set () 542for future in futures : 543future .result () 544records = [self .finish (spec ,raws [spec ["id" ]])for spec in specs ] 545start = min (raws [s ["id" ]]["t0" ]for s in specs ) 546end = max (raws [s ["id" ]]["t_end" ]for s in specs ) 547wall = round ((end - start )/ 1e9 ,6 ) 548counted = [r for r in records if r ["status" ]in ("completed" ,"truncated" )] 549outputs = [r ["tokens" ]["output_tokens" ]for r in counted ] 550total = sum (outputs )if outputs and all (o is not None for o in outputs )else None 551failed = sum (r ["status" ]== "failed" for r in records ) 552self .log (f" round { specs [ 0 ][ 'round' ] } : { len ( counted ) } completed or capped, { failed } failed, { wall } s" ) 553if any (raws [s ["id" ]]["interrupted" ]for s in specs ): 554self .abort = "the operator cancelled the run" 555return {"round" :specs [0 ]["round" ],"request_ids" : [s ["id" ]for s in specs ],"wall_s" :wall , 556"output_tokens" :total ,"aggregate_tps" :_round (total / wall )if total is not None and wall > 0 else None , 557"failed" :failed } 558 559 560def summaries_of (records :list [dict ],extras :dict ,phase :str ,cases :tuple [str , ...],concurrency :int )-> list [dict ]: 561rows = [] 562for case in cases : 563group = [r for r in records if r ["phase" ]== phase and r ["case_id" ]== case ] 564for metric ,unit in METRICS : 565included ,excluded ,values = [], [], [] 566for r in group : 567reason = None 568if r ["status" ]== "skipped" : 569reason = "skipped: " + r ["error" ]["message" ] 570elif r ["status" ]== "failed" : 571reason = "failed: " + r ["error" ]["kind" ] 572elif extras [r ["id" ]]["unexpected_payload_reuse" ]: 573reason = (f"unexpected cache reuse: { r [ 'tokens' ][ 'cached_tokens' ] } cached tokens exceed the " 574f" { extras [ r [ 'id' ]][ 'max_shared_prefix_tokens' ] } -token shared template prefix" ) 575else : 576value = r ["metrics" ].get (metric )if metric in ("prompt_tps" ,"decode_tps" )else r ["timings" ].get (metric ) 577if value is None : 578reason = f" { metric } is not available for this request" 579else : 580values .append (value ) 581included .append (r ["id" ]) 582if reason : 583excluded .append ({"request_id" :r ["id" ],"reason" :reason }) 584rows .append ({"phase" :phase ,"case_id" :case ,"concurrency" :concurrency ,"metric" :metric ,"unit" :unit , 585"median" :_round (statistics .median (values ))if values else None , 586"min" :_round (min (values ))if values else None ,"max" :_round (max (values ))if values else None , 587"n" :len (values ),"included_request_ids" :included ,"excluded" :excluded }) 588return rows 589 590 591def counts_of (records :list [dict ],phase :str ,planned :int )-> dict : 592rows = [r for r in records if r ["phase" ]== phase ] 593tally = {s :sum (r ["status" ]== s for r in rows )for s in ("completed" ,"truncated" ,"failed" ,"skipped" )} 594attempted = tally ["completed" ]+ tally ["truncated" ]+ tally ["failed" ] 595return {"planned" :planned ,"attempted" :attempted ,** tally } 596 597 598def quality_of (records :list [dict ])-> dict : 599sanity = [r for r in records if r ["phase" ]== "sanity" ] 600cats = {name : {"passed" :sum (r ["evaluation" ]["passed" ]for r in sanity if r ["evaluation" ]["category" ]== name ), 601"total" :4 }for name in ("instruction" ,"retrieval" ,"tool_call" )} 602return {"passed" :sum (c ["passed" ]for c in cats .values ()),"total" :12 ,"categories" :cats } 603 604 605def scan_nulls (value ,path :str = "" ): 606if value is None : 607yield path 608elif isinstance (value ,dict ): 609for key ,item in value .items (): 610if path == "" and key in ("missing" ,"extensions" ): 611continue 612yield from scan_nulls (item ,path + facts .pointer (key )) 613elif isinstance (value ,list ): 614for index ,item in enumerate (value ): 615yield from scan_nulls (item ,path + facts .pointer (index )) 616 617 618def default_reason (doc :dict ,pointer :str )-> str : 619parts = [p .replace ("~1" ,"/" ).replace ("~0" ,"~" )for p in pointer .split ("/" )[1 :]] 620if parts [0 ]== "requests" and len (parts )>= 3 : 621record = doc ["requests" ][int (parts [1 ])] 622field = "." .join (parts [2 :]) 623if record ["status" ]== "skipped" : 624return "not measured: the request was skipped (" + record ["error" ]["message" ]+ ")" 625if field == "error" : 626return "none: the request ended normally" 627if field == "round" : 628return "not applicable outside the concurrency stage" 629if field == "evaluation" : 630return "not applicable outside the sanity stage" 631if field == "token_accounting_note" : 632return "none: the API and engine counts agree or only one exists" 633if field == "finish_reason" : 634return "the server sent no finish_reason" 635if field == "first_delta_kind" : 636return "no nonempty reasoning, answer or tool-call delta arrived" 637if field in ("timings.ttft_s" ,"timings.first_answer_s" ): 638return ("no nonempty delta arrived" if field == "timings.ttft_s" 639else "no answer text or tool call arrived (reasoning alone does not count)" ) 640if field .startswith ("metrics." ): 641return ("the rate needs a nonzero freshly read count (or generated count) and an engine duration, and one is missing or zero" ) 642if field .startswith ("sources." ): 643return "no source: the value was not reported" 644if record ["status" ]== "failed" : 645return f"the request failed ( { record [ 'error' ][ 'kind' ] } ) before this value was reported" 646return "the server's response did not include this value (usage or timings)" 647if parts [0 ]== "summaries" and len (parts )>= 3 : 648row = doc ["summaries" ][int (parts [1 ])] 649return f"no valid samples of { row [ 'metric' ] } for { row [ 'case_id' ] } ( { len ( row [ 'excluded' ]) } excluded)" 650if parts [0 ]== "concurrency_rounds" : 651return "an included request has no output token count, or the round wall time is zero" 652if parts [0 ]== "run" and parts [1 ]== "optional_duration_s" : 653return "the optional concurrency stage was not selected or did not run" 654if parts [0 ]== "protocol" and parts [1 ]== "model_card_revision" : 655return "the profile's model-card revision is not pinned yet (protocol draft)" 656return "not available" 657 658 659def _start_wait (target :Target ,proc ,timeout_s :float ,log ,log_path :Path | None )-> bool : 660began ,announced = time .monotonic (),0.0 661while time .monotonic ()- began < timeout_s : 662if proc is not None and proc .poll ()is not None : 663return False 664health = target .get ("/health" ,timeout = 5 ) 665if health and health .get ("service" )== "strata" and health .get ("loaded" ): 666return True 667if time .monotonic ()- announced > 30 : 668log (f"waiting for the model to load ( { int ( time . monotonic () - began ) } s) ..." ) 669announced = time .monotonic () 670time .sleep (2 ) 671return False 672 673 674def start_engine (ref :str ,target :Target ,log_path :Path ,log ,timeout_s :float ): 675"""Start `strata serve --profile REF` as a child of this run. -> the process.""" 676root = Path (__file__ ).resolve ().parents [1 ] 677command = [sys .executable ,str (root / "strata.py" ),"serve" ,"--profile" ,ref ,"--quiet" ] 678handle = open (log_path ,"wb" ) 679kwargs = {} 680if os .name == "nt" : 681kwargs ["creationflags" ]= getattr (subprocess ,"CREATE_NEW_PROCESS_GROUP" ,0 ) 682else : 683kwargs ["start_new_session" ]= True 684proc = subprocess .Popen (command ,cwd = str (root ),stdout = handle ,stderr = subprocess .STDOUT ,** kwargs ) 685proc ._strata_log = handle # closed by stop_engine 686if os .name == "nt" : 687# Windows has no process group to signal: the engine tree is put in a job object this run owns, which ends every process in it in one call 688# and cannot be refused for a single member (a per-process taskkill was "Access is denied" on a tree this very user started, #4260) 689from serve import winjob 690proc ._strata_job = winjob .contain (proc ) 691log ("starting the engine (the model load is not part of the benchmark time) ..." ) 692try : 693ready = _start_wait (target ,proc ,timeout_s ,log ,log_path ) 694except BaseException :# Ctrl+C (or a SIGTERM turned into one) while the model loads: the caller never gets `proc`, so end it here 695stop_engine (proc ) 696raise 697if not ready : 698stuck = stop_engine (proc ) 699tail = "" 700try : 701tail = log_path .read_text (encoding = "utf-8" ,errors = "replace" )[- 600 :] 702except OSError : 703pass 704raise ProfileError ("the engine did not become ready" + (": " + tail .strip ().splitlines ()[- 1 ]if tail .strip ()else "" )+ 705 ("; and it could not be stopped (" + stuck + "): it may still hold the port" if stuck else "" ),6 ) 706return proc 707 708 709def engine_log_since (console_log :Path ,run_log :Path | None ,offset :int )-> Path : 710"""The log to keep with a result when the runner started the engine. `strata serve --quiet` prints nothing, so the 711console capture is empty; the engine's own lines are in the run config's `log` file, from `offset` (its size before 712the start). Falls back to the console capture when there is no such file or nothing new in it.""" 713try : 714if run_log is not None and run_log .is_file ()and run_log .stat ().st_size > offset : 715with run_log .open ("rb" )as stream : 716stream .seek (offset ) 717data = stream .read () 718if data .strip (): 719merged = console_log .with_name ("engine-run.log" ) 720merged .write_bytes (data ) 721return merged 722except OSError : 723pass 724return console_log 725 726 727@ contextlib . contextmanager 728def term_is_interrupt (): 729"""While a run owns an engine it started, SIGTERM (and Ctrl+Break on Windows) end the run the way Ctrl+C does: the `finally` that stops the engine 730runs. Without this a plain `kill` (a service stop, a script's timeout, the app's Stop) ended only the runner and left the server and the engine 731holding the port and the GPU. Main thread only; the earlier handlers come back afterwards.""" 732import signal 733if threading .current_thread ()is not threading .main_thread (): 734yield 735return 736 737def handler (signum ,frame ): 738raise KeyboardInterrupt 739 740saved = [] 741for name in ("SIGTERM" ,"SIGBREAK" ): 742number = getattr (signal ,name ,None ) 743if number is None : 744continue 745try : 746saved .append ((number ,signal .signal (number ,handler ))) 747except (ValueError ,OSError ): 748pass 749try : 750yield 751finally : 752for number ,old in saved : 753try : 754signal .signal (number ,old ) 755except (ValueError ,OSError ,TypeError ): 756pass 757 758 759def stop_engine (proc )-> str | None : 760"""Stop only the process this run started. -> None when it is gone, else a plain sentence on why it may still be running 761(a failed taskkill / signal, or a process that outlives the wait): the caller must not report a normal finish then, because 762a process that is still alive can hold the server's port and the GPU (#3438).""" 763if proc is None : 764return None 765problem = None 766try : 767if proc .poll ()is None : 768if os .name == "nt" : 769# 1. the job this run put the engine in (ends the whole tree at once); 2. taskkill of the tree; 3. the process itself. 770# The next step runs only when the one before left the process running, and a refusal is reported only if all of them fail. 771if getattr (proc ,"_strata_job" ,False ): 772from serve import winjob 773winjob .terminate () 774try : 775proc .wait (10 ) 776except subprocess .TimeoutExpired : 777pass 778if proc .poll ()is None : 779try : 780done = subprocess .run (["taskkill" ,"/PID" ,str (proc .pid ),"/T" ,"/F" ],capture_output = True ,timeout = 60 ) 781if done .returncode != 0 and proc .poll ()is None : 782said = (done .stderr or done .stdout or b"" ).decode ("utf-8" ,errors = "replace" ).strip () 783problem = f"taskkill for process { proc . pid } failed (exit { done . returncode } ) { ': ' + said [: 200 ] if said else '' } " 784except subprocess .TimeoutExpired : 785problem = f"taskkill for process { proc . pid } did not finish in 60 s" 786except OSError as error : 787problem = f"taskkill could not run for process { proc . pid } : { error } " 788if proc .poll ()is None : 789try : 790proc .kill ()# this run's own child, by the handle it holds 791except OSError : 792pass 793else : 794import signal 795try : 796os .killpg (proc .pid ,signal .SIGTERM ) 797except OSError : 798proc .terminate () 799try : 800proc .wait (90 ) 801except subprocess .TimeoutExpired : 802try : 803os .killpg (proc .pid ,signal .SIGKILL ) 804except OSError : 805proc .kill () 806try : 807proc .wait (30 ) 808except subprocess .TimeoutExpired : 809pass 810if proc .poll ()is None : 811problem = (problem + "; " if problem else "" )+ f"process { proc . pid } is still running 30 s after it was told to stop" 812else : 813problem = None # it is gone: an earlier refusal that a later step got around is not news 814finally : 815handle = getattr (proc ,"_strata_log" ,None ) 816if handle is not None : 817handle .close () 818return problem 819 820 821def slug (text :str ,limit :int = 40 )-> str : 822cleaned = re .sub (r"(?i)\b(nvidia|geforce|amd|radeon|intel|graphics|corporation)\b" ," " ,text or "" ) 823return re .sub (r"[^a-z0-9]+" ,"-" ,cleaned .lower ()).strip ("-" )[:limit ].strip ("-" )or "unknown" 824 825 826def run (target :Target ,out :Path | None ,* ,out_root :Path | None = None ,optional_concurrency :bool = False , 827corpus :Corpus | None = None ,declared :dict | None = None ,plan :dict | None = None , 828engine_log :Path | None = None ,engine_run_log :tuple [Path | None ,int ]| None = None ,command :str = "strata bench run --suite standard-v1" , 829log = lambda message :None ,timeout_s :float = REQUEST_TIMEOUT_S ,started_engine :bool = False , 830hash_model :bool = True )-> tuple [dict ,Path ]: 831"""Run the protocol against `target` and write the report into the new directory `out` (or a new folder named 832<date>-standard-<gpu>-<run id> under `out_root`). -> (the result, the folder).""" 833declared = {"track" :"custom" ,"track_notes" :"no notes given by the operator" ,** (declared or {})} 834if declared ["track" ]not in ("default" ,"custom" ): 835raise ProfileError ("--track must be default or custom" ,2 ) 836corpus = corpus or load_corpus () 837if out is not None and (out .exists ()or out .is_symlink ()): 838raise ProfileError ("benchmark output directory already exists" ,2 ) 839if out is None and out_root is None : 840raise ProfileError ("benchmark needs an output directory" ,2 ) 841health = target .get ("/health" ,timeout = 10 ) 842if not health or health .get ("service" )!= "strata" : 843raise ProfileError ("no Strata server answers at that address" ,5 ) 844if health .get ("loaded" )is not True : 845raise ProfileError ("the server has no model loaded; the benchmark needs a loaded model" ,5 ) 846props = target .get ("/props" ,timeout = 15 ) 847status = target .get ("/v1/status" ,timeout = 15 )or {} 848if props is None : 849raise ProfileError ("the server did not answer /props (an API key may be needed: STRATA_API_KEY)" ,5 ) 850redact = facts .redactor (target .key or "" ) 851why = facts .Why () 852reasons_nonconforming :list [str ]= [] 853if not target .loopback : 854reasons_nonconforming .append ("the server is not on loopback: standard latency is measured over loopback" ) 855 856served_model = props .get ("model_alias" )or status .get ("model" ) 857prior = ((status .get ("activity" )or {}).get ("requests" )) 858# the server's own view of its hardware and build 859machine = target .get ("/metrics" ,timeout = 20 )or {} 860static = machine .get ("hardware_static" )or {} 861served_gpu = ((status .get ("machine" )or {}).get ("gpu" )or {}).get ("name" )or static .get ("gpu_name" ) 862engine_version = ((machine .get ("engine" )or {}).get ("version" )or status .get ("engine" ) 863or (str (props .get ("build_info" ,"" )).replace ("Strata " ,"" )or None )) 864 865plan = plan or {} 866options = facts .parse_options (plan ["engine_argv" ])if plan .get ("engine_argv" )else None 867model_paths = [str (props .get ("model_path" )or "" )]+ [str (v )for v in (plan .get ("engine_argv" )or [])] 868files = facts .model_files_from ([p for p in model_paths if p ])if hash_model else [] 869model_dir = files [0 ].parent if files else None 870selected = facts .gpu_selection (plan .get ("config" ),plan .get ("engine_argv" )) 871template_text = props .get ("chat_template" )if isinstance (props .get ("chat_template" ),str )else None 872 873hardware_block ,machine_facts = facts .hardware (why ,selected = selected ,served_gpu = served_gpu ,model_dir = model_dir , 874declared_background = list (declared .get ("background" )or [])) 875software_block = facts .software (why ,machine_facts ,engine_version = engine_version , 876build_options = declared .get ("build_options" ), 877engine_build = facts .engine_build_runtime (plan .get ("engine_exe" ))) 878model_block = facts .model (why ,props = props ,status = status ,files = files ,declared = declared ,log = log ) 879template_ref = {"path" :"provenance/chat_template.jinja" ,"sha256" :facts .sha256_text (template_text )}if template_text else None 880configuration_block ,other_options = facts .configuration ( 881why ,options = options ,env = (plan .get ("config" )or {}).get ("env" )if isinstance (plan .get ("config" ),dict )else None , 882props = props ,declared = declared , 883sampling = {"sampling" :SAMPLING ,"chat_template_kwargs" :TEMPLATE_KWARGS },template_ref = template_ref ) 884 885if software_block ["strata_commit" ]is None : 886reasons_nonconforming .append ("the Strata commit is unknown (not a git checkout and no COMMIT file)" ) 887if not model_block ["files" ]: 888reasons_nonconforming .append ("no model file could be hashed" ) 889if template_ref is None : 890reasons_nonconforming .append ("the effective chat template could not be read from the server" ) 891if props .get ("is_sleeping" ): 892reasons_nonconforming .append ("the server reported its model as sleeping" ) 893 894run_id = datetime .now (timezone .utc ).strftime ("%Y%m%dT%H%M%SZ" )+ "-" + uuid .uuid4 ().hex [:8 ] 895if out is None : 896names = "-plus-" .join (slug (g ["name" ],30 )for g in hardware_block ["gpus" ])or "cpu" 897out = out_root / (datetime .now (timezone .utc ).strftime ("%Y-%m-%d" )+ "-standard-" + names [:60 ].strip ("-" )+ "-" + run_id [- 8 :]) 898out_root .mkdir (parents = True ,exist_ok = True ) 899_private_mkdir (out ,parents = False ,exist_ok = False ) 900started_at = _now () 901collector = Collector (target ,corpus ,served_model ,log ,timeout_s ) 902by_phase = {p : [s for s in corpus .specs if s ["phase" ]== p ]for p in PHASES } 903required_start = time .monotonic () 904interrupted = False 905try : 906for phase in ("warmup" ,"performance" ,"sanity" ): 907for spec in by_phase [phase ]: 908collector .one (spec ) 909required_duration = round (time .monotonic ()- required_start ,3 ) 910optional_duration = None 911rounds :list [dict ]= [] 912if optional_concurrency : 913optional_start = time .monotonic () 914specs = by_phase ["concurrency" ] 915for round_no in (1 ,2 ,3 ): 916group = [s for s in specs if s ["round" ]== round_no ] 917if collector .abort : 918for spec in group : 919collector .results [spec ["id" ]]= skipped_record (spec ,collector .abort ) 920rounds .append ({"round" :round_no ,"request_ids" : [s ["id" ]for s in group ],"wall_s" :None , 921"output_tokens" :None ,"aggregate_tps" :None ,"failed" :0 }) 922continue 923log (f"concurrency round { round_no } /3: four requests released together" ) 924rounds .append (collector .concurrent_round (group )) 925if not collector .abort and any (collector .results [s ["id" ]][0 ]["status" ]== "failed" for s in group ) \ 926and not collector .alive (): 927collector .abort = "the server stopped answering during the concurrency stage" 928optional_duration = round (time .monotonic ()- optional_start ,3 ) 929except KeyboardInterrupt : 930interrupted = True 931required_duration = round (time .monotonic ()- required_start ,3 ) 932optional_duration ,rounds = None , [] 933collector .abort = "the operator cancelled the run" 934for spec in corpus .specs : 935if spec ["id" ]not in collector .results and (spec ["phase" ]!= "concurrency" or optional_concurrency ): 936collector .results [spec ["id" ]]= skipped_record (spec ,collector .abort ) 937for spec in corpus .specs :# a stage that never started is skipped, not missing 938if spec ["id" ]not in collector .results and (spec ["phase" ]!= "concurrency" or optional_concurrency ): 939collector .results [spec ["id" ]]= skipped_record (spec ,collector .abort or "not run" ) 940 941selected_specs = [s for s in corpus .specs if s ["id" ]in collector .results ] 942records = [collector .results [s ["id" ]][0 ]for s in selected_specs ] 943evidence = [collector .results [s ["id" ]][1 ]for s in selected_specs ] 944extras = {s ["id" ]:collector .results [s ["id" ]][2 ]for s in selected_specs } 945 946for r in records : 947if r ["phase" ]== "performance" and extras [r ["id" ]]["unexpected_payload_reuse" ]: 948reasons_nonconforming .append (f"unexpected reuse of the user payload in { r [ 'id' ] } " ) 949if extras [r ["id" ]]["length_outside_tolerance" ]: 950reasons_nonconforming .append (f" { r [ 'id' ] } measured { r [ 'tokens' ][ 'input_tokens' ] } prompt tokens, outside 2% of its target" ) 951if r ["status" ]== "failed" and r ["error" ]["kind" ]in ("http_400" ,"http_422" ): 952reasons_nonconforming .append (f"the server refused the protocol's required settings in { r [ 'id' ] } ( { r [ 'error' ][ 'kind' ] } )" ) 953skipped_required = any (r ["status" ]== "skipped" for r in records if r ["phase" ]!= "concurrency" ) 954skipped_optional = any (r ["status" ]== "skipped" for r in records if r ["phase" ]== "concurrency" ) 955run_status = ("nonconforming" if reasons_nonconforming else 956"partial" if skipped_required or interrupted else "complete" ) 957reasons_nonconforming = list (dict .fromkeys (reasons_nonconforming )) 958 959# the artifacts first, so the report can hash their final bytes 960artifacts :list [dict ]= [] 961 962def put (kind :str ,relative :str ,data :bytes )-> None : 963path = out / relative 964path .parent .mkdir (parents = True ,exist_ok = True ) 965_write_new (path ,data ) 966artifacts .append ({"kind" :kind ,"path" :relative ,"sha256" :hashlib .sha256 (data ).hexdigest ()}) 967lines = [json .dumps (facts .redact_object (row ,redact ),ensure_ascii = False ,allow_nan = False )for row in evidence ] 968put ("outputs" ,"outputs.jsonl" , ("\n" .join (lines )+ "\n" ).encode ("utf-8" )) 969config_doc = facts .redact_object ({"engine_options" :options ,"other_engine_options" :other_options , 970"server_defaults" : (props .get ("default_generation_settings" )or {}).get ("params" ), 971"total_slots" :props .get ("total_slots" ),"context" :configuration_block ["context_tokens" ], 972"source" :"effective engine arguments of the profile" if options is not None 973else "the server was already running; its engine options are not exposed" },redact ) 974put ("config" ,"config.json" , (json .dumps (config_doc ,ensure_ascii = False ,indent = 2 ,allow_nan = False )+ "\n" ).encode ("utf-8" )) 975if engine_log is not None and engine_run_log is not None : 976engine_log = engine_log_since (engine_log ,* engine_run_log ) 977if engine_log is not None and engine_log .is_file (): 978text = engine_log .read_text (encoding = "utf-8" ,errors = "replace" )[- 2_000_000 :] 979put ("engine_log" ,"engine.log" ,redact (text ).encode ("utf-8" )) 980if template_text : 981put ("provenance" ,"provenance/chat_template.jinja" ,template_text .encode ("utf-8" )) 982put ("provenance" ,"provenance/corpus-manifest.sha256" ,corpus .manifest ) 983put ("provenance" ,"provenance/corpus-build.json" , (corpus .directory / "build.json" ).read_bytes ()) 984 985summaries = summaries_of (records ,extras ,"performance" ,PERFORMANCE_CASES ,1 ) 986if optional_concurrency : 987summaries += summaries_of (records ,extras ,"concurrency" , ("short-burst" ,),4 ) 988doc = { 989"format" :FORMAT ,"schema_version" :SCHEMA_VERSION , 990"protocol" : {"id" :PROTOCOL_ID ,"git_commit" :software_block ["runner_commit" ],"profile" :PROFILE , 991"corpus_sha256" :corpus .sha256 ,"model_card_revision" :MODEL_CARD_REVISION }, 992"run" : {"id" :run_id ,"started_at" :started_at ,"status" :run_status ,"required_duration_s" :required_duration , 993"optional_duration_s" :optional_duration ,"optional_concurrency" :bool (optional_concurrency ), 994"command" :command }, 995"hardware" :hardware_block ,"software" :software_block ,"model" :model_block , 996"configuration" :configuration_block , 997"request_counts" : {p :counts_of (records ,p ,PLANNED [p ]if p != "concurrency" or optional_concurrency else 0 ) 998for p in PHASES }, 999"requests" :records ,"summaries" :summaries ,"concurrency_rounds" :rounds if optional_concurrency else [], 1000"quality" :quality_of (records ),"artifacts" :artifacts ,"missing" : {}, 1001"extensions" : {"suite" :SUITE ,"runner" :"strata_cli.bench_standard" , 1002"status_reasons" :reasons_nonconforming or ( 1003 [collector .abort ]if collector .abort else []), 1004"started_engine" :started_engine , 1005"server_requests_before_run" :prior if isinstance (prior ,int )else None , 1006"other_engine_options" :other_options , 1007"request_checks" : {rid :v for rid ,v in extras .items ()}, 1008"optional_stage_skipped" :skipped_optional , 1009"api_key_sent" :bool (target .key )}} 1010doc = facts .redact_document (doc ,redact )# results.json gets what the README and the other files get (#4484) 1011if doc ["run" ]["optional_duration_s" ]is None : 1012why .add ("/run/optional_duration_s" ,"the optional concurrency stage was not selected" if not optional_concurrency 1013else "the optional concurrency stage did not run" ) 1014for pointer_text in scan_nulls (doc ): 1015doc ["missing" ][pointer_text ]= why .get (pointer_text )or default_reason (doc ,pointer_text ) 1016problems = validate (doc ) 1017if problems : 1018raise ProfileError ("the benchmark report failed its own validation: " + problems [0 ],6 ) 1019encoded = (json .dumps (doc ,ensure_ascii = False ,indent = 2 ,allow_nan = False )+ "\n" ).encode ("utf-8" ) 1020_write_new (out / "results.json" ,encoded ) 1021_write_new (out / "README.md" ,report_markdown (doc ,redact ).encode ("utf-8" )) 1022return doc ,out 1023 1024 1025# ------------------------------------------------------------------------------------------------------------ validation 1026def validate (doc :dict )-> list [str ]: 1027"""A strict check of the result contract: shape, types, count identities, null reasons and summaries rebuilt from the requests.""" 1028bad :list [str ]= [] 1029 1030def need (condition :bool ,message :str )-> None : 1031if not condition : 1032bad .append (message ) 1033 1034if not isinstance (doc ,dict ): 1035return ["the result is not an object" ] 1036need (doc .get ("format" )== FORMAT and doc .get ("schema_version" )== SCHEMA_VERSION ,"unknown format or schema version" ) 1037required = ("protocol" ,"run" ,"hardware" ,"software" ,"model" ,"configuration" ,"request_counts" ,"requests" ,"summaries" , 1038"concurrency_rounds" ,"quality" ,"artifacts" ,"missing" ) 1039for key in required : 1040need (key in doc ,f"missing top-level field { key } " ) 1041if bad : 1042return bad 1043allowed = {"format" ,"schema_version" ,* required ,"extensions" } 1044need (set (doc )<= allowed ,"unknown top-level fields must be under extensions" ) 1045protocol ,run_block = doc ["protocol" ],doc ["run" ] 1046need (all (k in protocol for k in ("id" ,"git_commit" ,"profile" ,"corpus_sha256" ,"model_card_revision" )),"protocol fields" ) 1047need (isinstance (protocol .get ("corpus_sha256" ),str )and bool (HEX64 .match (protocol ["corpus_sha256" ])),"corpus_sha256 is not a SHA-256" ) 1048for field in ("id" ,"started_at" ,"status" ,"required_duration_s" ,"optional_duration_s" ,"optional_concurrency" ,"command" ): 1049need (field in run_block ,f"run. { field } missing" ) 1050need (run_block .get ("status" )in ("complete" ,"partial" ,"nonconforming" ),"run.status" ) 1051need (bool (re .fullmatch (r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ" ,str (run_block .get ("started_at" )))),"run.started_at is not UTC ISO 8601" ) 1052for field in ("gpus" ,"cpu" ,"ram_bytes" ,"storage" ,"background_workloads" ): 1053need (field in doc ["hardware" ],f"hardware. { field } missing" ) 1054for gpu in doc ["hardware" ].get ("gpus" )or []: 1055need (gpu .get ("memory_kind" )in ("dedicated" ,"shared" ),"gpu memory_kind" ) 1056need (isinstance (gpu .get ("device_index" ),int ),"gpu device_index" ) 1057for field in ("os" ,"drivers" ,"runtime" ,"strata_commit" ,"engine_version" ,"build_kind" ,"runner_commit" ,"build_options" ): 1058need (field in doc ["software" ],f"software. { field } missing" ) 1059need (doc ["software" ].get ("build_kind" )in ("release" ,"source" ),"software.build_kind" ) 1060for field in ("id" ,"revision" ,"source_revision" ,"quantization" ,"files" ,"tokenizer_revision" ,"custom_pack" ): 1061need (field in doc ["model" ],f"model. { field } missing" ) 1062for entry in doc ["model" ].get ("files" )or []: 1063need (bool (HEX64 .match (str (entry .get ("sha256" ))))and "/" not in str (entry .get ("path" ))and "\\" not in str (entry .get ("path" )), 1064"model file entry" ) 1065cfg = doc ["configuration" ] 1066for field in ("track" ,"track_notes" ,"context_tokens" ,"server_capacity" ,"kv_cache" ,"expert_cache" ,"offloading" ,"prefill" , 1067"mtp" ,"calibration" ,"experimental_options" ,"template" ,"sampling" ,"chat_template_kwargs" ): 1068need (field in cfg ,f"configuration. { field } missing" ) 1069need (cfg .get ("track" )in ("default" ,"custom" ),"configuration.track" ) 1070need (all (k in cfg .get ("sampling" , {})for k in SAMPLING ),"configuration.sampling" ) 1071 1072records = doc ["requests" ] 1073ids = [r .get ("id" )for r in records ] 1074need (len (set (ids ))== len (ids ),"duplicate request ids" ) 1075need (len (records )in (22 ,34 ),"the requests array has neither 22 nor 34 records" ) 1076sanity_ids = {f"sanity- { n } " for n in ("I1" ,"I2" ,"I3" ,"I4" ,"R1" ,"R2" ,"R3" ,"R4" ,"T1" ,"T2" ,"T3" ,"T4" )} 1077need (sanity_ids <= set (ids ),"a sanity case is missing" ) 1078for r in records : 1079need (r .get ("status" )in ("completed" ,"truncated" ,"failed" ,"skipped" ),f" { r . get ( 'id' ) } : status" ) 1080need (r .get ("phase" )in PHASES ,f" { r . get ( 'id' ) } : phase" ) 1081if r .get ("status" )in ("completed" ,"truncated" ): 1082need (r .get ("error" )is None ,f" { r . get ( 'id' ) } : error on a finished request" ) 1083else : 1084need (isinstance (r .get ("error" ),dict )and "kind" in r ["error" ]and "message" in r ["error" ],f" { r . get ( 'id' ) } : error object" ) 1085for group ,keys in (("tokens" , ("input_tokens" ,"cached_tokens" ,"read_tokens" ,"output_tokens" ,"decode_tokens" )), 1086 ("timings" , ("prompt_s" ,"decode_s" ,"ttft_s" ,"first_answer_s" ,"total_s" )), 1087 ("metrics" , ("prompt_tps" ,"decode_tps" )), 1088 ("sources" , ("input_tokens" ,"cached_tokens" ,"read_tokens" ,"output_tokens" ,"decode_tokens" , 1089"engine_timings" ,"client_timings" ))): 1090need (isinstance (r .get (group ),dict )and all (k in r [group ]for k in keys ),f" { r . get ( 'id' ) } : { group } " ) 1091for k ,v in (r .get ("tokens" )or {}).items (): 1092need (v is None or (isinstance (v ,int )and not isinstance (v ,bool )and v >= 0 ),f" { r . get ( 'id' ) } : tokens. { k } " ) 1093for group in ("timings" ,"metrics" ): 1094for k ,v in (r .get (group )or {}).items (): 1095need (v is None or (isinstance (v , (int ,float ))and not isinstance (v ,bool )and math .isfinite (v )and v >= 0 ), 1096f" { r . get ( 'id' ) } : { group } . { k } " ) 1097if r .get ("phase" )== "sanity" : 1098need (isinstance (r .get ("evaluation" ),dict )and isinstance (r ["evaluation" ].get ("passed" ),bool ),f" { r . get ( 'id' ) } : evaluation" ) 1099else : 1100need (r .get ("evaluation" )is None ,f" { r . get ( 'id' ) } : evaluation outside sanity" ) 1101need ((r .get ("round" )is not None )== (r .get ("phase" )== "concurrency" ),f" { r . get ( 'id' ) } : round" ) 1102counts = doc ["request_counts" ] 1103for phase in PHASES : 1104rows = [r for r in records if r .get ("phase" )== phase ] 1105c = counts .get (phase )or {} 1106need (c .get ("attempted" )== c .get ("completed" ,0 )+ c .get ("truncated" ,0 )+ c .get ("failed" ,0 ),f" { phase } : attempted identity" ) 1107need (c .get ("planned" )== c .get ("attempted" ,0 )+ c .get ("skipped" ,0 ),f" { phase } : planned identity" ) 1108need (len (rows )== c .get ("planned" ),f" { phase } : record count" ) 1109need (doc ["quality" ]== quality_of (records )if len (records )>= 22 else False ,"quality does not match the sanity verdicts" ) 1110need (isinstance (run_block .get ("optional_concurrency" ),bool ),"run.optional_concurrency" ) 1111need ((counts ["concurrency" ]["planned" ]== 12 )== bool (run_block .get ("optional_concurrency" )),"concurrency count" ) 1112 1113extras = {k :v for k ,v in (doc .get ("extensions" )or {}).get ("request_checks" , {}).items ()} 1114if extras : 1115rebuilt = summaries_of (records ,extras ,"performance" ,PERFORMANCE_CASES ,1 ) 1116if run_block .get ("optional_concurrency" ): 1117rebuilt += summaries_of (records ,extras ,"concurrency" , ("short-burst" ,),4 ) 1118need (rebuilt == doc ["summaries" ],"summaries cannot be rebuilt from the request records" ) 1119for row in doc ["summaries" ]: 1120need (row ["n" ]== len (row ["included_request_ids" ]),"summary n" ) 1121if row ["n" ]== 0 : 1122need (row ["median" ]is None and row ["min" ]is None and row ["max" ]is None ,"empty summary must be null" ) 1123for artifact in doc ["artifacts" ]: 1124need (artifact .get ("kind" )in ("config" ,"engine_log" ,"outputs" ,"provenance" )and bool (HEX64 .match (str (artifact .get ("sha256" )))) 1125and not str (artifact .get ("path" )).startswith (("/" ,"\\" ))and ".." not in Path (str (artifact .get ("path" ))).parts 1126and not re .match (r"^[A-Za-z]:" ,str (artifact .get ("path" ))),"artifact entry" ) 1127nulls = set (scan_nulls (doc )) 1128need (nulls == set (doc ["missing" ]),"missing must list exactly the null values: " 1129f" { sorted ( nulls ^ set ( doc [ 'missing' ]))[: 3 ] } " ) 1130need (all (isinstance (v ,str )and v for v in doc ["missing" ].values ()),"every missing entry needs a reason" ) 1131try : 1132json .dumps (doc ,allow_nan = False ) 1133except ValueError : 1134bad .append ("the result contains NaN or infinity" ) 1135return bad 1136 1137 1138# ------------------------------------------------------------------------------------------------------------ reading it out 1139def _span (row :dict | None ,digits :int = 1 )-> str : 1140if not row or row ["n" ]== 0 : 1141return "not measured" 1142return f" { row [ 'median' ]:.{ digits }f } ( { row [ 'min' ]:.{ digits }f } - { row [ 'max' ]:.{ digits }f } ) n= { row [ 'n' ] } " 1143 1144 1145def _find (doc :dict ,phase :str ,case :str ,metric :str )-> dict | None : 1146return next ((s for s in doc ["summaries" ]if s ["phase" ]== phase and s ["case_id" ]== case and s ["metric" ]== metric ),None ) 1147 1148 1149def _minutes (seconds :float | None )-> str : 1150if seconds is None : 1151return "not measured" 1152return f" { int ( seconds // 60 ) } min { int ( seconds % 60 ) } s" 1153 1154 1155SHORT_PROMPT_NOTE = ("short is a prompt of about 80 tokens: its prompt rate is dominated by the fixed cost of a request, so it is not " 1156"shown; read prompt speed from prompt-4k and prompt-16k" ) 1157CAP_NOTE = ("Capped = requests that reached the 512-token cap, reasoning and answer together. A capped request's total time is the " 1158"time to the cap, not to an answer, and it has no first-answer time when it was still reasoning" ) 1159 1160 1161def capped (doc :dict ,phase :str ,case :str )-> str : 1162"""'k/n': how many of the case's measured requests stopped at the output cap.""" 1163rows = [r for r in doc ["requests" ]if r ["phase" ]== phase and r ["case_id" ]== case ] 1164return f" { sum ( 1 for r in rows if r [ 'status' ] == 'truncated' ) } / { len ( rows ) } " 1165 1166 1167def prompt_cell (doc :dict ,phase :str ,case :str ,digits :int = 1 )-> str : 1168return "n/a" if case == "short" else _span (_find (doc ,phase ,case ,"prompt_tps" ),digits ) 1169 1170 1171def table_lines (doc :dict ,phase :str ,cases :tuple [str , ...])-> list [str ]: 1172head = ["Case" ,"Prompt tok/s" ,"Decode tok/s" ,"TTFT s" ,"Total s" ,"Capped" ] 1173rows = [head ] 1174for case in cases : 1175rows .append ([case ,prompt_cell (doc ,phase ,case ),_span (_find (doc ,phase ,case ,"decode_tps" )), 1176_span (_find (doc ,phase ,case ,"ttft_s" ),2 ),_span (_find (doc ,phase ,case ,"total_s" ),1 ), 1177capped (doc ,phase ,case )]) 1178widths = [max (len (r [i ])for r in rows )for i in range (len (head ))] 1179return ([" " + " " .join (cell .ljust (widths [i ])for i ,cell in enumerate (row )).rstrip ()for row in rows ] 1180+ [" " + SHORT_PROMPT_NOTE + "." ," " + CAP_NOTE + "." ]) 1181 1182 1183def format_plain (doc :dict )-> str : 1184"""The summary printed at the end of a run: what ran, how fast, what passed, what to be careful about.""" 1185hw ,sw ,run_block = doc ["hardware" ],doc ["software" ],doc ["run" ] 1186gpu = ", " .join (g ["name" ]for g in hw ["gpus" ])or "no GPU found" 1187counts = doc ["request_counts" ] 1188done = sum (counts [p ]["completed" ]+ counts [p ]["truncated" ]for p in ("performance" ,"sanity" )) 1189quality = doc ["quality" ] 1190lines = [f"Strata standard benchmark ( { doc [ 'protocol' ][ 'id' ] } )" , 1191f"Status: { run_block [ 'status' ] } . { done } of 21 required requests finished, " 1192f" { sum ( counts [ p ][ 'failed' ] for p in PHASES ) } failed, { sum ( counts [ p ][ 'skipped' ] for p in PHASES ) } skipped. " 1193f"Time after the model loaded: { _minutes ( run_block [ 'required_duration_s' ]) } ." , 1194f"Machine: { gpu } ; { hw [ 'cpu' ] or 'CPU not read' } ; " 1195f" { round ( hw [ 'ram_bytes' ] / 2 ** 30 ) if hw [ 'ram_bytes' ] else 'unknown' } GB RAM; { sw [ 'os' ][ 'name' ] } { sw [ 'os' ][ 'version' ] } ." , 1196f"Model: { doc [ 'model' ][ 'id' ] or 'unknown' } , { doc [ 'model' ][ 'quantization' ] or 'quantization not read' } , " 1197f"context { doc [ 'configuration' ][ 'context_tokens' ] or 'unknown' } ; engine { sw [ 'engine_version' ] or 'unknown' } ; " 1198f"track { doc [ 'configuration' ][ 'track' ] } ." ,"" , 1199"Speed (median, min-max, n; the engine's own prompt and decode timings, the client's first-token time):" ] 1200lines += table_lines (doc ,"performance" ,PERFORMANCE_CASES ) 1201lines += ["" ,f"Sanity checks: { quality [ 'passed' ] } of 12 passed " 1202f"(instruction { quality [ 'categories' ][ 'instruction' ][ 'passed' ] } /4, retrieval " 1203f" { quality [ 'categories' ][ 'retrieval' ][ 'passed' ] } /4, tool calls { quality [ 'categories' ][ 'tool_call' ][ 'passed' ] } /4)." ] 1204failed = [r ["evaluation" ]and f" { r [ 'case_id' ] } : { r [ 'evaluation' ][ 'reason' ] } " for r in doc ["requests" ] 1205if r ["phase" ]== "sanity" and not r ["evaluation" ]["passed" ]] 1206lines += [" Not passed: " + "; " .join (failed )]if failed else [] 1207if doc ["run" ]["optional_concurrency" ]: 1208rounds = [r ["aggregate_tps" ]for r in doc ["concurrency_rounds" ]if r ["aggregate_tps" ]is not None ] 1209lines += ["" ,"Four requests at once (server capacity " 1210f" { doc [ 'configuration' ][ 'server_capacity' ] or 'unknown' } ): " 1211+ (", " .join (f" { v :.1f } " for v in rounds )+ " tok/s in total per round" if rounds else "no round finished" )] 1212reasons = doc ["extensions" ]["status_reasons" ] 1213if run_block ["status" ]!= "complete" and reasons : 1214lines += ["" ,"Why this is not a complete standard result:" ]+ [f" - { r } " for r in reasons ] 1215failures = [f" { r [ 'id' ] } : { r [ 'error' ][ 'kind' ] } " for r in doc ["requests" ]if r ["status" ]== "failed" ] 1216if failures : 1217lines += ["" ,"Failed requests: " + "; " .join (failures )] 1218return "\n" .join (lines ) 1219 1220 1221def report_markdown (doc :dict ,redact = lambda text :text )-> str : 1222hw ,sw ,run_block ,model ,cfg = doc ["hardware" ],doc ["software" ],doc ["run" ],doc ["model" ],doc ["configuration" ] 1223counts = doc ["request_counts" ] 1224quality = doc ["quality" ] 1225gpu = "; " .join (("%s (%.1f GiB %s)" % (g ["name" ],g ["memory_bytes" ]/ 2 ** 30 ,g ["memory_kind" ]))if g ["memory_bytes" ] 1226else g ["name" ]for g in hw ["gpus" ])or "not measured" 1227nm = "not measured" 1228ram = "%.1f GiB" % (hw ["ram_bytes" ]/ 2 ** 30 )if hw ["ram_bytes" ]else nm 1229storage = ", " .join ("%s %s (%s)" % (s ["kind" ],s ["model" ],s ["bus" ])for s in hw ["storage" ])if hw ["storage" ]else nm 1230drivers = ", " .join ("%s %s" % (d ["name" ],d ["version" ])for d in sw ["drivers" ])if sw ["drivers" ]else nm 1231runtime = ", " .join ("%s %s" % (d ["name" ],d ["version" ])for d in sw ["runtime" ])if sw ["runtime" ]else nm 1232lines = [ 1233"# Strata standard benchmark: %s" % (", " .join (g ["name" ]for g in hw ["gpus" ])or "unknown GPU" ),"" , 1234"Protocol `%s` (draft), run `%s`, started %s. **Status: %s.**" % (doc ["protocol" ]["id" ],run_block ["id" ], 1235run_block ["started_at" ],run_block ["status" ]),"" , 1236"Written by `strata bench run`. The machine-readable result is [results.json](results.json); every request, its raw usage " 1237"and timings and the client event offsets are in [outputs.jsonl](outputs.jsonl)." ,"" ] 1238reasons = doc ["extensions" ]["status_reasons" ] 1239if run_block ["status" ]!= "complete" : 1240lines += ["This run is not a complete standard result:" ,"" ]+ ["- " + r for r in reasons ]+ ["" ] 1241lines += [ 1242"## Hardware and software" ,"" , 1243"- GPU: " + gpu , 1244"- CPU: %s; RAM: %s" % (hw ["cpu" ]or nm ,ram ), 1245"- Storage of the model files: " + storage , 1246"- OS: %s %s; drivers: %s; runtime: %s" % (sw ["os" ]["name" ],sw ["os" ]["version" ],drivers ,runtime ), 1247"- Strata commit: `%s`; engine %s; %s build" % (sw ["strata_commit" ]or nm ,sw ["engine_version" ]or nm ,sw ["build_kind" ]), 1248"- Background work: " + ("; " .join (hw ["background_workloads" ])if hw ["background_workloads" ]else nm ),"" , 1249"## Model and configuration" ,"" , 1250f"- Model: { model [ 'id' ] or nm } ; quantization { model [ 'quantization' ] or nm } ; revision { model [ 'revision' ] or nm } ; " 1251f"source revision { model [ 'source_revision' ] or nm } " , 1252f"- Files: " + ("; " .join (f"` { f [ 'path' ] } ` ` { f [ 'sha256' ][: 16 ] } ...`" for f in model ['files' ])if model ['files' ]else nm ), 1253f"- Track: ** { cfg [ 'track' ] } ** ( { cfg [ 'track_notes' ] } )" , 1254f"- Context { cfg [ 'context_tokens' ] or nm } tokens; server capacity { cfg [ 'server_capacity' ] or nm } slot(s)" , 1255f"- Sampling: " + ", " .join (f" { k } { v } " for k ,v in cfg ["sampling" ].items ())+ "; thinking on, preserved" , 1256f"- Engine options: `config.json`; chat template: `provenance/chat_template.jinja`" ,"" , 1257"## Method" ,"" , 1258f"The frozen requests of `bench/prompts/standard-v1` (corpus ` { doc [ 'protocol' ][ 'corpus_sha256' ][: 16 ] } ...`) were sent over " 1259"loopback HTTP, streaming, one at a time, in this order: 1 warm-up (excluded), 3 repetitions of the short, 4K and 16K prompts, " 1260"and the twelve sanity checks. Prompt and decode speed are the engine's own `timings`; time to first token is the client's " 1261"monotonic clock from dispatch to the first nonempty reasoning, answer or tool-call delta. No request was retried. " 1262f"Time after the model loaded: { _minutes ( run_block [ 'required_duration_s' ]) } ." ,"" , 1263"## Results" ,"" ] 1264lines += ["| Case | Prompt tok/s | Decode tok/s | TTFT s | First answer s | Total s | Capped |" ,"| --- | --- | --- | --- | --- | --- | --- |" ] 1265for case in PERFORMANCE_CASES : 1266lines .append (f"| { case } | " + prompt_cell (doc ,"performance" ,case )+ " | " + " | " .join ( 1267_span (_find (doc ,"performance" ,case ,m ),d )for m ,d in (("decode_tps" ,1 ), ("ttft_s" ,2 ), 1268 ("first_answer_s" ,2 ), ("total_s" ,1 ))) 1269+ f" | { capped ( doc , 'performance' , case ) } |" ) 1270lines += ["" ,"Cells are median (min-max) n=samples. " + SHORT_PROMPT_NOTE [0 ].upper ()+ SHORT_PROMPT_NOTE [1 :]+ ". " + CAP_NOTE + "." ,"" , 1271"| Phase | Planned | Completed | Truncated | Failed | Skipped |" ,"| --- | ---: | ---: | ---: | ---: | ---: |" ] 1272for phase in PHASES : 1273c = counts [phase ] 1274lines .append (f"| { phase } | { c [ 'planned' ] } | { c [ 'completed' ] } | { c [ 'truncated' ] } | { c [ 'failed' ] } | { c [ 'skipped' ] } |" ) 1275lines += ["" ,f"Sanity checks: ** { quality [ 'passed' ] } of 12**." ,"" ,"| Case | Result | Reason |" ,"| --- | --- | --- |" ] 1276for r in doc ["requests" ]: 1277if r ["phase" ]== "sanity" : 1278lines .append (f"| { r [ 'case_id' ] } | { 'pass' if r [ 'evaluation' ][ 'passed' ] else 'fail' } | { r [ 'evaluation' ][ 'reason' ] } |" ) 1279if run_block ["optional_concurrency" ]: 1280lines += ["" ,"Concurrency rounds (four requests released together):" ,"" , 1281"| Round | Wall s | Output tokens | Aggregate tok/s | Failed |" ,"| ---: | ---: | ---: | ---: | ---: |" ] 1282for r in doc ["concurrency_rounds" ]: 1283lines .append (f"| { r [ 'round' ] } | { r [ 'wall_s' ] } | { r [ 'output_tokens' ] } | { r [ 'aggregate_tps' ] } | { r [ 'failed' ] } |" ) 1284failures = [r for r in doc ["requests" ]if r ["status" ]== "failed" ] 1285lines += ["" ,"## Failures, exclusions and limitations" ,"" ] 1286lines += [f"- { r [ 'id' ] } failed: { r [ 'error' ][ 'kind' ] } ( { r [ 'error' ][ 'message' ] } )" for r in failures ]or ["- No request failed." ] 1287excluded = {(e ["request_id" ],e ["reason" ])for s in doc ["summaries" ]for e in s ["excluded" ]} 1288lines += [f"- Excluded from speed summaries: { rid } : { reason } " for rid ,reason in sorted (excluded )] 1289lines += ["- Prompt-prefix reuse is the shared template prefix only; the cache was not emptied between requests, and the expert " 1290"cache stays warm and evolves. These are not cold-model measurements." , 1291"- Output caps include reasoning; a request that reaches its cap is `truncated` and fails its sanity check." , 1292"- The runner cannot see other programs on the machine, the repeat-stop and loop-recovery switches of the server, or " 1293"the quantization repository's revision; see `missing` in results.json for every value it could not read." , 1294f"- The server had answered { doc [ 'extensions' ][ 'server_requests_before_run' ] } request(s) before this run." 1295if doc ["extensions" ]["server_requests_before_run" ]else 1296 ("- The server had answered no request before this run (a freshly loaded engine)." 1297if doc ["extensions" ]["server_requests_before_run" ]== 0 else 1298"- The runner could not tell whether the server was freshly loaded." ),"" ] 1299return redact ("\n" .join (lines )) 1300 1301 1302def load (path :Path )-> dict : 1303"""Read a saved standard result and validate it. A result in another format or schema version is refused, never merged.""" 1304target = path / "results.json" if path .is_dir ()else path 1305try : 1306if target .stat ().st_size > 64 << 20 : 1307raise ProfileError ("benchmark result is larger than 64 MiB" ,5 ) 1308doc = json .loads (target .read_text (encoding = "utf-8" )) 1309except (OSError ,UnicodeError ,ValueError ): 1310raise ProfileError ("cannot read the benchmark result" ,5 )from None 1311problems = validate (doc ) 1312if problems : 1313raise ProfileError ("not a valid standard benchmark result: " + problems [0 ],5 ) 1314return doc 1315 1316 1317def load_if_standard (path :Path )-> dict | None : 1318"""The validated result at `path` when it is a standard benchmark result; None when it is another kind of report.""" 1319target = path / "results.json" if path .is_dir ()else path 1320try : 1321head = json .loads (target .read_text (encoding = "utf-8" )) 1322except (OSError ,UnicodeError ,ValueError ): 1323return None 1324if not isinstance (head ,dict )or head .get ("format" )!= FORMAT : 1325return None 1326return load (path )