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