okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
34ee68774
main
1#!/usr/bin/env python3 2""" 3Strata community benchmark harness — standard library only. 4 5Measures prompt processing (prefill) and decode through the local Strata server, 6mirroring the method used in bench/results/2026-09-30-community-rtx-5090: 7 8* synthetic Python-like filler of a requested size, 9* a unique nonce near the start of every request (defeats conversation-prefix 10reuse so every run processes its whole prompt), 11* greedy decoding, fixed output cap, 12* actual token counts taken from the engine's own log line, 13* client-side time-to-first-token and total latency, 14* optional needle-in-a-haystack recall checks. 15 16Outputs bench-output.json, bench-output.md and bench-output.txt next to this file. 17 18Usage (run from the folder that has this file): 19.venv\\Scripts\\python.exe benchmark.py --url http://127.0.0.1:8080/v1/chat/completions \ 20--log D:\\AI\\Strata\\Strata-main\\Strata-main\\strata-iq2_xs.log \ 21--lengths 4096,32768,128000 --reps 3 --needle-lengths 32768,128000 --needle-depths 10,50,90 22""" 23 24from __future__import annotations 25 26import argparse 27import json 28import os 29import re 30import statistics 31import sys 32import time 33import urllib .error 34import urllib .request 35from pathlib import Path 36 37HERE = Path (__file__ ).resolve ().parent 38NEEDLE = "7-BLUE-MAGNET-4417" 39PROMPT_LINE = re .compile ( 40r"prompt (\d+) tokens = (\d+) reused \+ (\d+) read in (\d+) ms \(([\d.]+) tok/s\), " 41r"(\d+) generated in (\d+) ms \(([\d.]+) tok/s\)" 42) 43 44 45# ----------------------------------------------------------------------------- prompts 46def code_filler (chars :int ,seed :int )-> str : 47"""Deterministic Python-like filler of roughly `chars` characters.""" 48out = [] 49n = 0 50size = 0 51while size < chars : 52n += 1 53k = (seed + n )% 97 + 3 54block = ( 55f"def transform_ { seed :04d } _ { n :05d } (value: int, scale: int = { k } ) -> int:\n" 56f' """Scale a value by { k } and fold it into the working range."""\n' 57f" folded = (value * scale + { n } * 17) % { 1000003 + n } \n" 58f" if folded % { k } == 0:\n" 59f" return folded // { k } + { n } \n" 60f" return folded - { n } * scale\n" 61f"\n" 62 ) 63out .append (block ) 64size += len (block ) 65return "" .join (out )[:chars ] 66 67 68def build_prompt (target_tokens :int ,seed :int ,chars_per_token :float ,needle_depth :int | None )-> str : 69"""Assemble one benchmark request: instruction + nonce + filler (+ needle).""" 70filler_chars = max (2000 ,int (target_tokens * chars_per_token )) 71body = code_filler (filler_chars ,seed ) 72nonce = f" { seed :04d } - { int ( time . time () * 1000 ) % 100000 :05d } " 73head = ( 74f"You are reviewing a Python file. The file starts with the marker NONCE { nonce } .\n" 75f"Explain in three short paragraphs what the functions in this file do.\n\n" 76f"# NONCE { nonce } \n" 77 ) 78if needle_depth is not None : 79cut = int (len (body )* needle_depth / 100.0 ) 80# move the cut to the next newline so the file stays syntactically plausible 81cut = body .find ("\n" ,cut ) 82cut = len (body )if cut < 0 else cut 83body = body [:cut ]+ f'\nVAULT_CODE = " { NEEDLE } " # keep this exact value\n' + body [cut :] 84head = ( 85f"You are reviewing a Python file. The file starts with the marker NONCE { nonce } .\n" 86f"Answer the question about the file at the end, using only what the file says.\n\n" 87f"# NONCE { nonce } \n" 88 ) 89tail = "\n\nQuestion: what is the exact value assigned to VAULT_CODE in this file? " \ 90"Answer with the value only, nothing else.\n" 91else : 92tail = "\n\nAnswer in English, three short paragraphs.\n" 93return head + body + tail 94 95 96# ----------------------------------------------------------------------------- engine log 97class EngineLog : 98def __init__ (self ,path :Path | None ): 99self .path = path 100self .offset = 0 101if path and path .exists (): 102self .offset = path .stat ().st_size 103 104def new_lines (self )-> list [str ]: 105if not self .path or not self .path .exists (): 106return [] 107try : 108with self .path .open ("r" ,encoding = "utf-8" ,errors = "replace" )as fh : 109fh .seek (self .offset ) 110data = fh .read () 111self .offset = fh .tell () 112except OSError : 113return [] 114return [ln .strip ()for ln in data .replace ("\r" ,"\n" ).split ("\n" )if ln .strip ()] 115 116def last_request_stats (self )-> dict | None : 117for line in reversed (self .new_lines ()): 118m = PROMPT_LINE .search (line ) 119if m : 120return { 121"engine_prompt_tokens" :int (m .group (1 )), 122"reused_tokens" :int (m .group (2 )), 123"new_prompt_tokens" :int (m .group (3 )), 124"read_ms" :int (m .group (4 )), 125"read_tok_s" :float (m .group (5 )), 126"generated_tokens" :int (m .group (6 )), 127"gen_ms" :int (m .group (7 )), 128"decode_tok_s" :float (m .group (8 )), 129 } 130return None 131 132 133# ----------------------------------------------------------------------------- HTTP 134def post_chat (url :str ,payload :dict ,timeout :int ): 135"""POST /v1/chat/completions. Returns (ttft_s, total_s, text, reasoning, usage, finish_reason).""" 136body = json .dumps (payload ).encode () 137req = urllib .request .Request (url ,data = body ,headers = {"Content-Type" :"application/json" }) 138started = time .time () 139ttft = None 140text_parts :list [str ]= [] 141reasoning_parts :list [str ]= [] 142usage = None 143finish = None 144with urllib .request .urlopen (req ,timeout = timeout )as resp : 145ctype = resp .headers .get ("Content-Type" ,"" ) 146if "text/event-stream" in ctype : 147for raw in resp : 148line = raw .decode ("utf-8" ,"replace" ).strip () 149if not line .startswith ("data:" ): 150continue 151chunk = line [5 :].strip () 152if chunk in ("" ,"[DONE]" ): 153continue 154try : 155obj = json .loads (chunk ) 156except json .JSONDecodeError : 157continue 158if obj .get ("usage" ): 159usage = obj ["usage" ] 160for choice in obj .get ("choices" , []): 161if choice .get ("finish_reason" ): 162finish = choice ["finish_reason" ] 163delta = choice .get ("delta" )or {} 164piece = delta .get ("content" )or "" 165think = delta .get ("reasoning_content" )or delta .get ("reasoning" )or "" 166if think : 167reasoning_parts .append (think ) 168if piece : 169if ttft is None : 170ttft = time .time ()- started 171text_parts .append (piece ) 172else : 173obj = json .loads (resp .read ().decode ("utf-8" ,"replace" )) 174usage = obj .get ("usage" ) 175for choice in obj .get ("choices" , []): 176finish = choice .get ("finish_reason" )or finish 177msg = choice .get ("message" )or {} 178content = msg .get ("content" )or "" 179if msg .get ("reasoning_content" ): 180reasoning_parts .append (msg ["reasoning_content" ]) 181if content and ttft is None : 182ttft = time .time ()- started 183text_parts .append (content ) 184total = time .time ()- started 185return ttft ,total ,"" .join (text_parts ),"" .join (reasoning_parts ),usage ,finish 186 187 188def detect_model (url :str )-> str : 189base = url .split ("/v1/" )[0 ] 190try : 191with urllib .request .urlopen (base + "/v1/models" ,timeout = 15 )as resp : 192data = json .loads (resp .read ().decode ()) 193items = data .get ("data" )or data .get ("models" )or [] 194if items : 195return items [0 ].get ("id" )or items [0 ].get ("name" )or "strata" 196except Exception : 197pass 198return "strata" 199 200 201# ----------------------------------------------------------------------------- measurement 202def one_request (url :str ,model :str ,prompt :str ,cap :int ,log :EngineLog ,timeout :int )-> dict : 203base = { 204"model" :model , 205"messages" : [{"role" :"user" ,"content" :prompt }], 206"temperature" :0 , 207"max_tokens" :cap , 208 } 209# "reasoning_effort": "none" -> the engine renders the prompt without thinking 210# (serve/frontend.py EFFORT map). Without it the model spends the whole output cap 211# on reasoning_content and message.content stays empty. 212no_think = dict (base ,reasoning_effort = "none" ) 213variants = [ 214dict (no_think ,stream = True ,stream_options = {"include_usage" :True }), 215dict (no_think ,stream = True ), 216dict (no_think ,stream = False ), 217dict (base ,stream = True ,stream_options = {"include_usage" :True }), 218dict (base ,stream = False ), 219 ] 220row :dict = {"ok" :False } 221last_error = None 222for idx ,payload in enumerate (variants ): 223try : 224ttft ,total ,text ,reasoning ,usage ,finish = post_chat (url ,payload ,timeout ) 225row .update ( 226ok = True , 227payload_variant = idx , 228thinking_off = "reasoning_effort" in payload , 229ttft_s = round (ttft ,3 )if ttft is not None else None , 230total_s = round (total ,3 ), 231text = text , 232answer_len = len (text ), 233reasoning_len = len (reasoning ), 234reasoning_text = reasoning [:2000 ], 235finish_reason = finish , 236 ) 237if usage : 238row ["usage" ]= usage 239last_error = None 240break 241except urllib .error .HTTPError as exc : 242body = exc .read ()[:400 ].decode ("utf-8" ,"replace" ) 243last_error = f"HTTP { exc . code } : { body } " 244if exc .code not in (400 ,404 ,415 ,422 ): 245break 246except Exception as exc :# noqa: BLE001 247last_error = f" { type ( exc ). __name__ } : { exc } " 248break 249if last_error : 250row ["error" ]= last_error 251stats = log .last_request_stats () 252if stats : 253row .update (stats ) 254# Bind the log line to this request: the server reports the same prompt token 255# count in the response usage. A mismatch means the line belongs to another 256# request (or none) and the row must not be trusted. 257server_tokens = (row .get ("usage" )or {}).get ("prompt_tokens" ) 258if server_tokens is None : 259row ["pairing_ok" ]= None 260else : 261row ["pairing_ok" ]= abs (int (server_tokens )- int (stats ["engine_prompt_tokens" ]))<= 1 262if not row ["pairing_ok" ]: 263row ["pairing_note" ]= (f"server reported { server_tokens } prompt tokens, the engine log line " 264f"has { stats [ 'engine_prompt_tokens' ] } - the log line may belong to another request" ) 265return row 266 267 268def summarise (rows :list [dict ])-> str : 269cols = ["target" ,"actual prompt tok" ,"reused" ,"new read" ,"prefill tok/s" ,"read s" , 270"gen tok" ,"decode tok/s" ,"thinking off" ,"answer len" ,"finish" ,"TTFT s" ,"total s" ] 271lines = ["| " + " | " .join (cols )+ " |" ,"|" + "---|" * len (cols )] 272for r in rows : 273if not r .get ("ok" ): 274lines .append ("| " + " | " .join ([str (r .get ("target" ))]+ 275 [f"FAILED: { str ( r . get ( 'error' ))[: 60 ] } " ]+ 276 ["" ]* (len (cols )- 2 ))+ " |" ) 277continue 278vals = [ 279r .get ("target" ),r .get ("engine_prompt_tokens" ,"?" ),r .get ("reused_tokens" ,"?" ), 280r .get ("new_prompt_tokens" ,"?" ),r .get ("read_tok_s" ,"?" ), 281f" { ( r . get ( 'read_ms' ) or 0 ) / 1000 :.1f } " , 282r .get ("generated_tokens" ,"?" ),r .get ("decode_tok_s" ,"?" ), 283r .get ("thinking_off" ),r .get ("answer_len" ),r .get ("finish_reason" ), 284r .get ("ttft_s" ),r .get ("total_s" ), 285 ] 286lines .append ("| " + " | " .join (str (v )for v in vals )+ " |" ) 287groups :dict [int ,list [float ]]= {} 288for r in rows : 289if r .get ("ok" )and r .get ("read_tok_s" ): 290groups .setdefault (r .get ("target" ), []).append (r ["read_tok_s" ]) 291lines .append ("" ) 292for target ,vals in sorted (groups .items ()): 293dec = [r ["decode_tok_s" ]for r in rows if r .get ("ok" )and r .get ("target" )== target and r .get ("decode_tok_s" )] 294lines .append ( 295f"* { target } prompt tokens: prefill median { statistics . median ( vals ):.1f } tok/s " 296f"(range { min ( vals ):.1f } - { max ( vals ):.1f } , n= { len ( vals ) } )" 297+ (f"; decode median { statistics . median ( dec ):.1f } tok/s " 298f"(range { min ( dec ):.1f } - { max ( dec ):.1f } )" if dec else "" ) 299 ) 300return "\n" .join (lines ) 301 302 303def main ()-> int : 304ap = argparse .ArgumentParser () 305ap .add_argument ("--url" ,default = "http://127.0.0.1:8080/v1/chat/completions" ) 306ap .add_argument ("--log" ,default = r"D:\AI\Strata\Strata-main\Strata-main\strata-iq2_xs.log" ) 307ap .add_argument ("--lengths" ,default = "4096,32768,128000" ) 308ap .add_argument ("--reps" ,type = int ,default = 3 ) 309ap .add_argument ("--needle-lengths" ,default = "32768,128000" ) 310ap .add_argument ("--needle-depths" ,default = "10,50,90" ) 311ap .add_argument ("--cap" ,type = int ,default = 256 ) 312ap .add_argument ("--timeout" ,type = int ,default = 1800 ) 313ap .add_argument ("--wait-ready" ,type = int ,default = 0 , 314help = "poll /v1/models until the engine answers, up to this many seconds" ) 315ap .add_argument ("--tag" ,default = "" ,help = "suffix for the output files (bench-output-<tag>.json)" ) 316ap .add_argument ("--skip-needles" ,action = "store_true" ) 317ap .add_argument ("--model" ,default = None ) 318args = ap .parse_args () 319 320log = EngineLog (Path (args .log )if args .log else None ) 321model = args .model or detect_model (args .url ) 322f"server : { args . url } " ) 323f"model id : { model } " ) 324f"engine : { args . log } " ) 325if args .tag : 326f"tag : { args . tag } " ) 327 328if args .wait_ready : 329base = args .url .split ("/v1/" )[0 ] 330ready = False 331deadline = time .time ()+ args .wait_ready 332while time .time ()< deadline : 333try : 334with urllib .request .urlopen (base + "/v1/models" ,timeout = 10 )as resp : 335if resp .status == 200 : 336ready = True 337break 338except Exception : 339pass 340" waiting for the engine to come up ..." ,flush = True ) 341time .sleep (5 ) 342if not ready : 343f"the engine did not answer within { args . wait_ready } s - stopping." ) 344return 2 345"engine is up\n" ,flush = True ) 346 347results :dict = { 348"started" :time .strftime ("%Y-%m-%d %H:%M:%S" ), 349"url" :args .url , 350"model" :model , 351"engine_log" :args .log , 352"cap_tokens" :args .cap , 353"reps" :args .reps , 354"speed" : [], 355"needles" : [], 356"notes" : [], 357 } 358 359# --- calibration: one small request to learn characters-per-token ----------- 360"\n[calibration] 8,000-char request ..." ,flush = True ) 361cal_prompt = ("You are reviewing a Python file.\n\n# NONCE 0001\n" 362+ code_filler (8000 ,1 )+ "\n\nAnswer in one short paragraph.\n" ) 363cal = one_request (args .url ,model ,cal_prompt ,64 ,log ,args .timeout ) 364chars = 8000 365if cal .get ("ok" )and cal .get ("engine_prompt_tokens" ): 366# prompt tokens includes the instruction wrapper (~40 tok) 367ratio = (cal ["engine_prompt_tokens" ]- 40 )/ chars # tokens per character 368ratio = min (1.5 ,max (0.15 ,ratio ))# sane bounds 369chars_per_token = 1.0 / ratio 370f"[calibration] { cal [ 'engine_prompt_tokens' ] } prompt tokens for { chars } chars " 371f"-> { chars_per_token :.3f } chars/token" ,flush = True ) 372else : 373chars_per_token = 4.0 374results ["notes" ].append ("calibration failed; assumed 4.0 chars/token" ) 375f"[calibration] FAILED ( { cal . get ( 'error' ) } ); assuming 4.0 chars/token" ,flush = True ) 376results ["calibration" ]= {k :v for k ,v in cal .items ()if k != "text" } 377results ["chars_per_token" ]= chars_per_token 378"warming up (one 2,000-token request) ..." ,flush = True ) 379warm = one_request (args .url ,model ,build_prompt (2000 ,7 ,chars_per_token ,None ),32 ,log ,args .timeout ) 380results ["warmup" ]= {k :v for k ,v in warm .items ()if k != "text" } 381 382# --- speed runs ------------------------------------------------------------ 383seed = 100 384for target in [int (x )for x in args .lengths .split ("," )if x .strip ()]: 385for rep in range (1 ,args .reps + 1 ): 386seed += 1 387prompt = build_prompt (target ,seed ,chars_per_token ,None ) 388f"[speed] target { target } rep { rep } / { args . reps } " 389f"( { len ( prompt ):, } chars) ..." ,flush = True ) 390row = one_request (args .url ,model ,prompt ,args .cap ,log ,args .timeout ) 391row .update (target = target ,rep = rep ,chars = len (prompt )) 392row .pop ("text" ,None ) 393results ["speed" ].append (row ) 394if row .get ("ok" ): 395f" -> prompt { row . get ( 'engine_prompt_tokens' ) } tok, " 396f"reused { row . get ( 'reused_tokens' ) } , prefill { row . get ( 'read_tok_s' ) } tok/s, " 397f"decode { row . get ( 'decode_tok_s' ) } tok/s, TTFT { row . get ( 'ttft_s' ) } s" ,flush = True ) 398else : 399f" -> FAILED: { row . get ( 'error' ) } " ,flush = True ) 400 401# --- needle checks --------------------------------------------------------- 402if not args .skip_needles : 403for target in [int (x )for x in args .needle_lengths .split ("," )if x .strip ()]: 404for depth in [int (x )for x in args .needle_depths .split ("," )if x .strip ()]: 405seed += 1 406prompt = build_prompt (target ,seed ,chars_per_token ,depth ) 407f"[needle] target { target } depth { depth } % ..." ,flush = True ) 408row = one_request (args .url ,model ,prompt ,32 ,log ,args .timeout ) 409found = NEEDLE in ((row .get ("text" )or "" )+ (row .get ("reasoning_text" )or "" )) 410row .update (target = target ,depth = depth ,needle_found = found ,chars = len (prompt )) 411results ["needles" ].append (row ) 412f" -> needle { 'FOUND' if found else 'MISSED' } ; " 413f"prompt { row . get ( 'engine_prompt_tokens' ) } tok, " 414f"prefill { row . get ( 'read_tok_s' ) } tok/s" ,flush = True ) 415 416results ["finished" ]= time .strftime ("%Y-%m-%d %H:%M:%S" ) 417results ["tag" ]= args .tag 418suffix = f"- { args . tag } " if args .tag else "" 419out_json = HERE / f"bench-output { suffix } .json" 420out_json .write_text (json .dumps (results ,indent = 2 ),encoding = "utf-8" ) 421 422table = summarise (results ["speed" ]) 423needle_lines = ["" ,"Needle checks (exact string recall):" ] 424for r in results ["needles" ]: 425needle_lines .append ( 426f"* { r . get ( 'target' ) } tokens, depth { r . get ( 'depth' ) } %: " 427f" { 'FOUND' if r . get ( 'needle_found' ) else 'MISSED' } " 428f"(prompt { r . get ( 'engine_prompt_tokens' ) } tok, prefill { r . get ( 'read_tok_s' ) } tok/s)" 429 ) 430report = ( 431f"# Strata benchmark output\n\n" 432f"started { results [ 'started' ] } , finished { results [ 'finished' ] } \n" 433f"server { args . url } , model id ` { model } `, output cap { args . cap } tokens, " 434f" { args . reps } reps per length\n\n## Speed\n\n { table } \n" 435+ ("\n" .join (needle_lines )if results ["needles" ]else "" )+ "\n" 436 ) 437 (HERE / f"bench-output { suffix } .md" ).write_text (report ,encoding = "utf-8" ) 438 (HERE / f"bench-output { suffix } .txt" ).write_text (report ,encoding = "utf-8" ) 439"\n" + report ) 440f"saved: { out_json } " ) 441f"saved: { HERE / f'bench-output { suffix } .md' } " ) 442"\nDONE - tell Hermes the run is finished." ) 443return 0 444 445 446if __name__ == "__main__" : 447sys .exit (main ())