okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
140a8730a
main
1#!/usr/bin/env python3 2"""Strata benchmark harness (contribution plan, PR 1 step 1.2). 3 4Follows the upstream method (bench/results/2026-09-28-speed-0114): one code-agent prompt per 5length, greedy, 256 generated tokens, MTP as configured by setup. Every run gets a unique 6prefix, so conversation checkpoints cannot skip the prompt. Numbers come from the engine log 7lines the owner asks for in issue #74. /metrics and API timing are stored as cross-checks. 8 9Stdlib only. Examples: 10./strata-bench.py --label IQ3_XXS-1x3090 --log ./strata-iq3_xxs.log 11./strata-bench.py --label Coder-2x3090-auto --contexts 16k,28k --mode needle 12./strata-bench.py --url http://127.0.0.1:9292 --model flash-next-strata --label via-llama-swap 13""" 14 15import argparse 16import json 17import os 18import re 19import statistics 20import sys 21import time 22import urllib .error 23import urllib .request 24import uuid 25from datetime import datetime 26from pathlib import Path 27 28NOMINAL = {"1k" :1024 ,"2.7k" :2765 ,"4k" :4096 ,"8k" :8192 ,"16k" :16384 ,"28k" :28672 , 29"32k" :32768 ,"64k" :65536 ,"128k" :131072 ,"262k" :262144 } 30CODE_EXT = {".py" ,".cpp" ,".cc" ,".h" ,".hpp" ,".cu" ,".cuh" ,".js" ,".md" ,".txt" ,".cmake" } 31SKIP_DIRS = {".git" ,".venv" ,"build" ,"engine" ,"third_party" ,"node_modules" ,"models" , 32"packs" ,"mtp" ,"bench" ,"data" ,"__pycache__" ,"Strata-data" } 33LOG_PATTERNS = [ 34re .compile (r"decode expert cache hit rate" ,re .I ), 35re .compile (r"\bPCIe\b" ), 36re .compile (r"prompt .*tok/s.*generated .*tok/s" ,re .I ), 37re .compile (r"reus|checkpoint" ,re .I ), 38re .compile (r"layer split" ,re .I ), 39] 40TOKS_PER_S = re .compile (r"([\d][\d,]*(?:\.\d+)?)\s*tok(?:ens)?/s" ,re .I ) 41 42 43def load_corpus (dirs ): 44parts = [] 45for d in dirs : 46root = Path (d ) 47for p in sorted (root .rglob ("*" )): 48if p .suffix .lower ()not in CODE_EXT or not p .is_file (): 49continue 50if any (s in SKIP_DIRS for s in p .relative_to (root ).parts [:- 1 ]): 51continue 52text = p .read_text (encoding = "utf-8" ,errors = "ignore" ) 53if text .strip (): 54parts .append (f"### { p . relative_to ( root ). as_posix () } \n```\n { text } \n```\n" ) 55if not parts : 56sys .exit (f"no source files found in { dirs } " ) 57return parts 58 59 60def build_text (parts ,n_chars ): 61out ,size ,i ,repeated = [],0 ,0 ,False 62while size < n_chars : 63if i and i % len (parts )== 0 : 64repeated = True 65chunk = parts [i % len (parts )] 66out .append (chunk ) 67size += len (chunk ) 68i += 1 69return "" .join (out )[:n_chars ],repeated 70 71 72def post_stream (url ,payload ,api_key ,timeout ): 73req = urllib .request .Request ( 74f" { url } /v1/chat/completions" ,data = json .dumps (payload ).encode (), 75headers = {"Content-Type" :"application/json" ,"Authorization" :f"Bearer { api_key or 'none' } " }) 76t0 = time .perf_counter () 77t_first ,text ,reasoning ,usage ,chunks = None , [], [], {},0 78with urllib .request .urlopen (req ,timeout = timeout )as resp : 79for raw in resp : 80line = raw .decode ("utf-8" ,errors = "ignore" ).strip () 81if not line .startswith ("data:" ): 82continue 83data = line [5 :].strip () 84if data == "[DONE]" : 85break 86try : 87chunk = json .loads (data ) 88except json .JSONDecodeError : 89continue 90if chunk .get ("usage" ): 91usage = chunk ["usage" ] 92for ch in chunk .get ("choices" )or []: 93delta = ch .get ("delta" )or {} 94piece = delta .get ("content" )or "" 95rpiece = delta .get ("reasoning_content" )or "" 96if (piece or rpiece )and t_first is None : 97t_first = time .perf_counter () 98if piece or rpiece : 99chunks += 1 100text .append (piece ) 101reasoning .append (rpiece ) 102t_end = time .perf_counter () 103return {"t_start" :t0 ,"t_first" :t_first or t_end ,"t_end" :t_end ,"text" :"" .join (text ), 104"reasoning" :"" .join (reasoning ),"usage" :usage ,"chunks" :chunks } 105 106 107def get_json (url ,path ,api_key ,timeout = 10 ): 108try : 109req = urllib .request .Request (f" { url } { path } " ,headers = {"Authorization" :f"Bearer { api_key or 'none' } " }) 110with urllib .request .urlopen (req ,timeout = timeout )as r : 111body = r .read ().decode ("utf-8" ,errors = "ignore" ) 112try : 113return json .loads (body ) 114except json .JSONDecodeError : 115return body 116except (urllib .error .URLError ,TimeoutError )as e : 117return {"error" :str (e )} 118 119 120def wait_healthy (url ,api_key ,timeout ): 121deadline = time .time ()+ timeout 122while time .time ()< deadline : 123h = get_json (url ,"/health" ,api_key ,timeout = 5 ) 124if not (isinstance (h ,dict )and "error" in h ): 125return True 126time .sleep (5 ) 127return False 128 129 130def log_offset (log ): 131return log .stat ().st_size if log and log .exists ()else 0 132 133 134def log_lines_since (log ,offset ): 135if not log or not log .exists (): 136return [] 137time .sleep (0.5 ) 138with log .open ("r" ,encoding = "utf-8" ,errors = "ignore" )as f : 139f .seek (offset ) 140new = f .read ().splitlines () 141return [ln for ln in new if any (p .search (ln )for p in LOG_PATTERNS )] 142 143 144def engine_numbers (lines ): 145"""Best effort: the last 'prompt ... tok/s ... generated ... tok/s' line -> (prompt, decode).""" 146for ln in reversed (lines ): 147if LOG_PATTERNS [2 ].search (ln ): 148vals = [float (v .replace ("," ,"" ))for v in TOKS_PER_S .findall (ln )] 149if len (vals )>= 2 : 150return vals [0 ],vals [1 ] 151return None ,None 152 153 154def target_tokens (key ,max_tokens ): 155n = NOMINAL [key ] 156# leave room for the answer, like upstream's 259,943-token "262K" prompt 157return n - max_tokens - 1024 if n >= 32768 else n 158 159 160def make_messages (mode ,parts ,n_chars ,run_id ): 161body ,repeated = build_text (parts ,n_chars ) 162system = f"[bench run { run_id } ] You are a coding agent working in the repository shown below." 163if mode == "needle" : 164word = uuid .uuid4 ().hex [:8 ].upper () 165mid = len (body )// 2 166body = f" { body [: mid ] } \n# NOTE: the secret code word is { word } .\n { body [ mid :] } " 167task = "What is the secret code word mentioned in the files above? Answer with the word only." 168else : 169word = None 170task = ("Task: explain what the last file above does, then propose one concrete improvement " 171"as a unified diff." ) 172msgs = [{"role" :"system" ,"content" :system }, 173 {"role" :"user" ,"content" :f"Repository files:\n\n { body } \n\n { task } " }] 174return msgs ,word ,repeated 175 176 177def run_once (a ,parts ,key ,run ,cpt ): 178tgt = target_tokens (key ,a .max_tokens ) 179run_id = uuid .uuid4 ().hex [:12 ] 180msgs ,word ,repeated = make_messages (a .mode ,parts ,int (tgt * cpt ),run_id ) 181payload = {"model" :a .model ,"messages" :msgs ,"max_tokens" :a .max_tokens ,"stream" :True , 182"stream_options" : {"include_usage" :True },"temperature" :0 , 183"reasoning_effort" :a .reasoning_effort } 184off = log_offset (a .log ) 185rec = {"label" :a .label ,"mode" :a .mode ,"ctx" :key ,"target_tokens" :tgt ,"run" :run , 186"run_id" :run_id ,"corpus_repeated" :repeated ,"time" :datetime .now ().isoformat (timespec = "seconds" )} 187try : 188r = post_stream (a .url ,payload ,a .api_key ,a .timeout ) 189except Exception as e :# noqa: BLE001 - record and continue with the next cell 190rec ["error" ]= str (e )[:300 ] 191return rec ,cpt 192pt = r ["usage" ].get ("prompt_tokens" ) 193ct = r ["usage" ].get ("completion_tokens" )or r ["chunks" ] 194ttft = r ["t_first" ]- r ["t_start" ] 195dec_t = r ["t_end" ]- r ["t_first" ] 196lines = log_lines_since (a .log ,off ) 197e_prompt ,e_decode = engine_numbers (lines ) 198rec .update ({ 199"prompt_tokens" :pt ,"completion_tokens" :ct , 200"ttft_s" :round (ttft ,3 ),"e2e_s" :round (r ["t_end" ]- r ["t_start" ],3 ), 201"api_prompt_tps" :round (pt / ttft ,1 )if pt and ttft > 0 else None , 202"api_decode_tps" :round ((ct - 1 )/ dec_t ,1 )if ct and ct > 1 and dec_t > 0 else None , 203"engine_prompt_tps" :e_prompt ,"engine_decode_tps" :e_decode , 204"log_lines" :lines ,"answer_head" :r ["text" ][:300 ], 205 }) 206if word : 207rec ["needle_found" ]= word in r ["text" ].upper ()or word in r ["reasoning" ].upper () 208if a .mode == "two-turn" : 209follow = msgs + [{"role" :"assistant" ,"content" :r ["text" ]}, 210 {"role" :"user" ,"content" :"Summarize your answer in one sentence." }] 211off2 = log_offset (a .log ) 212r2 = post_stream (a .url , {** payload ,"messages" :follow ,"max_tokens" :64 },a .api_key ,a .timeout ) 213rec ["turn2_ttft_s" ]= round (r2 ["t_first" ]- r2 ["t_start" ],3 ) 214rec ["turn2_prompt_tokens" ]= r2 ["usage" ].get ("prompt_tokens" ) 215rec ["turn2_log_lines" ]= log_lines_since (a .log ,off2 ) 216if pt : 217cpt = (int (tgt * cpt )+ 400 )/ pt # refine chars per token for the next cells 218return rec ,cpt 219 220 221def write_md (path ,recs ,label ): 222def med (vals ): 223vals = [v for v in vals if v is not None ] 224return round (statistics .median (vals ),1 )if vals else None 225 226rows = ["| ctx | prompt tokens | runs | TTFT s (med) | prompt tok/s engine / API (med) " 227"| decode tok/s engine / API (run 1) | decode tok/s engine / API (med) | needle |" , 228"|---|---|---|---|---|---|---|---|" ] 229for key in dict .fromkeys (r ["ctx" ]for r in recs ): 230rs = [r for r in recs if r ["ctx" ]== key and "error" not in r ] 231errs = sum (1 for r in recs if r ["ctx" ]== key and "error" in r ) 232if not rs : 233rows .append (f"| { key } | - | 0 ( { errs } errors) | | | | | |" ) 234continue 235first = rs [0 ] 236needle = "" if rs [0 ].get ("needle_found" )is None else f" { sum ( r [ 'needle_found' ] for r in rs ) } / { len ( rs ) } " 237rows .append ( 238f"| { key } | { rs [ 0 ][ 'prompt_tokens' ] } | { len ( rs ) } { f' ( { errs } err)' if errs else '' } " 239f"| { med ( r [ 'ttft_s' ] for r in rs ) } " 240f"| { med ( r [ 'engine_prompt_tps' ] for r in rs ) } / { med ( r [ 'api_prompt_tps' ] for r in rs ) } " 241f"| { first [ 'engine_decode_tps' ] } / { first [ 'api_decode_tps' ] } " 242f"| { med ( r [ 'engine_decode_tps' ] for r in rs ) } / { med ( r [ 'api_decode_tps' ] for r in rs ) } | { needle } |" ) 243path .write_text (f"# { label } \n\n" + "\n" .join (rows )+ "\n" ,encoding = "utf-8" ) 244 245 246def main (): 247ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 248ap .add_argument ("--url" ,default = "http://127.0.0.1:8090" ) 249ap .add_argument ("--model" ,default = "strata" ,help = "model name sent (llama-swap: the model id)" ) 250ap .add_argument ("--api-key" ,default = os .environ .get ("STRATA_API_KEY" ,"" )) 251ap .add_argument ("--label" ,required = True ,help = "e.g. IQ3_XXS-1x3090-calibrated" ) 252ap .add_argument ("--contexts" ,default = "1k,4k,32k,128k" ,help = f"comma list of { ',' . join ( NOMINAL ) } " ) 253ap .add_argument ("--repeats" ,type = int ,default = 3 ) 254ap .add_argument ("--max-tokens" ,type = int ,default = 256 ) 255ap .add_argument ("--reasoning-effort" ,default = "none" ) 256ap .add_argument ("--mode" ,choices = ["speed" ,"needle" ,"two-turn" ],default = "speed" ) 257ap .add_argument ("--source-dir" ,action = "append" ,default = None , 258help = "code corpus for the prompts (default: current directory, the Strata repo)" ) 259ap .add_argument ("--log" ,type = Path ,default = None , 260help = "engine log, e.g. ./strata-iq3_xxs.log" ) 261ap .add_argument ("--out" ,type = Path ,default = Path (f"./benchmark-output/ { datetime . now ():%Y-%m-%d } " )) 262ap .add_argument ("--timeout" ,type = float ,default = 1800 ,help = "per request, seconds (262K prefill takes minutes)" ) 263ap .add_argument ("--chars-per-token" ,type = float ,default = 3.4 ,help = "start value, refined after each run" ) 264a = ap .parse_args () 265 266keys = [k .strip ().lower ()for k in a .contexts .split ("," )if k .strip ()] 267bad = [k for k in keys if k not in NOMINAL ] 268if bad : 269sys .exit (f"unknown context(s): { bad } " ) 270parts = load_corpus (a .source_dir or ["." ]) 271if a .log and not a .log .exists (): 272f"warning: log { a . log } not found; engine numbers will be empty" ,file = sys .stderr ) 273if not wait_healthy (a .url ,a .api_key ,900 ): 274sys .exit (f" { a . url } /health not reachable" ) 275 276out = a .out / a .label 277 (out / "data" ).mkdir (parents = True ,exist_ok = True ) 278recs ,cpt = [],a .chars_per_token 279for key in keys : 280for run in range (1 ,a .repeats + 1 ): 281rec ,cpt = run_once (a ,parts ,key ,run ,cpt ) 282rec ["metrics_after" ]= get_json (a .url ,"/metrics" ,a .api_key ) 283recs .append (rec ) 284 (out / "data" / f" { a . mode } - { key } - { run } .json" ).write_text (json .dumps (rec ,indent = 1 ),encoding = "utf-8" ) 285status = rec .get ("error" )or (f"prompt { rec [ 'prompt_tokens' ] } tok, TTFT { rec [ 'ttft_s' ] } s, " 286f"decode engine { rec [ 'engine_decode_tps' ] } / API { rec [ 'api_decode_tps' ] } tok/s" ) 287f"[ { a . label } ] { a . mode } { key } run { run } : { status } " ,flush = True ) 288 289matrix_path = out / "matrix.json" 290merged = {} 291if matrix_path .exists (): 292for record in json .loads (matrix_path .read_text (encoding = "utf-8" )): 293merged [(record ["mode" ],record ["ctx" ],record ["run" ])]= record 294for record in recs : 295key = (record ["mode" ],record ["ctx" ],record ["run" ]) 296merged [key ]= {k :v for k ,v in record .items ()if k != "metrics_after" } 297combined = list (merged .values ()) 298matrix_path .write_text (json .dumps (combined ,indent = 1 ),encoding = "utf-8" ) 299write_md (out / "matrix.md" ,combined ,f" { a . label } ( { a . mode } )" ) 300f"written: { out } /matrix.md, matrix.json, data/" ) 301 302 303if __name__ == "__main__" : 304main ()