okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
53623e56f
main
1#!/usr/bin/env python3 2"""Serial, fresh-prompt Strata benchmark (Windows-capable). 3 4Derived from bench/results/2026-09-30-community-rtx-5090/benchmark.py: same synthetic prompts, nonces, 5token targets, greedy decoding, reasoning off and 256-token output cap, so the numbers are comparable. 6Changes: runs with Strata's own Windows venv; a failed or cancelled run is recorded with its error and 7excluded from the statistics instead of stopping the suite; peak host RAM and GPU memory are sampled 8every 0.5 s during each request. 9 10.venv\\Scripts\\python.exe benchmark.py --root . --pack <data-dir>\\packs\\q2_0 --url http://127.0.0.1:18096 --out results 11""" 12import argparse 13import hashlib 14import json 15import statistics 16import subprocess 17import sys 18import threading 19import time 20import urllib .request 21from pathlib import Path 22 23import psutil 24 25 26def get (url ): 27with urllib .request .urlopen (url ,timeout = 30 )as response : 28return json .load (response ) 29 30 31class Peak : 32"""Samples system-wide host RAM in use (total - available) and GPU memory used while a request runs.""" 33 34def __init__ (self ,interval = 0.5 ): 35self .interval ,self .ram ,self .vram ,self ._stop = interval ,0 ,0 ,threading .Event () 36 37def _gpu_mib (self ): 38try : 39out = subprocess .check_output (["nvidia-smi" ,"--query-gpu=memory.used" ,"--format=csv,noheader,nounits" ], 40text = True ,timeout = 5 ) 41return int (out .strip ().splitlines ()[0 ]) 42except Exception : 43return 0 44 45def _run (self ): 46while not self ._stop .is_set (): 47vm = psutil .virtual_memory () 48self .ram = max (self .ram ,vm .total - vm .available ) 49self .vram = max (self .vram ,self ._gpu_mib ()) 50self ._stop .wait (self .interval ) 51 52def __enter__ (self ): 53self ._thread = threading .Thread (target = self ._run ,daemon = True ) 54self ._thread .start () 55return self 56 57def __exit__ (self ,* exc ): 58self ._stop .set () 59self ._thread .join () 60 61def as_dict (self ): 62return {"peak_host_ram_used_gib" :round (self .ram / 2 ** 30 ,2 ),"peak_gpu_memory_used_mib" :self .vram } 63 64 65def main (): 66parser = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 67parser .add_argument ("--root" ,type = Path ,default = Path ("." )) 68parser .add_argument ("--pack" ,type = Path ,required = True ) 69parser .add_argument ("--url" ,default = "http://127.0.0.1:18096" ) 70parser .add_argument ("--out" ,type = Path ,default = Path ("results" )) 71parser .add_argument ("--targets" ,default = "4096,32768,128000" ) 72parser .add_argument ("--runs" ,type = int ,default = 3 ) 73args = parser .parse_args () 74args .out .mkdir (parents = True ,exist_ok = True ) 75sys .path [:0 ]= [str (args .root ),str (args .root / "tools" )] 76from strata_tokenizer import Tokenizer 77from serve .frontend import ChatTemplate ,openai_to_messages 78directory = args .pack / "tokenizer" 79vocab = json .loads ((directory / "vocab.json" ).read_text (encoding = "utf-8" )) 80tokens = [None ]* len (vocab ) 81for token ,number in vocab .items (): 82tokens [number ]= token 83tokenizer = Tokenizer (tokens , (directory / "merges.txt" ).read_text (encoding = "utf-8" ).splitlines (), 84json .loads ((directory / "token_type.json" ).read_text (encoding = "utf-8" ))) 85template = ChatTemplate (directory / "chat_template.jinja" ) 86initial = get (args .url + "/v1/status" ) 87 (args .out / "initial-status.json" ).write_text (json .dumps (initial ,indent = 2 )+ "\n" ,encoding = "utf-8" ) 88rows = [] 89 90def request (content ,maximum = 256 ): 91return {"model" :"strata" ,"messages" : [{"role" :"user" ,"content" :content }], 92"temperature" :0 ,"reasoning_effort" :"none" ,"max_tokens" :maximum , 93"stream" :True ,"stream_options" : {"include_usage" :True }} 94 95def count (req ): 96messages ,tools ,kwargs = openai_to_messages (req ) 97return len (tokenizer .encode (template .render (messages ,tools ,** kwargs ),parse_special = True )) 98 99def save (): 100 (args .out / "results.json" ).write_text (json .dumps (rows ,indent = 2 )+ "\n" ,encoding = "utf-8" ) 101 102def perform (label ,req ,expected = None ): 103body = json .dumps (req ).encode () 104 (args .out / (label + "-request.json" )).write_bytes (body + b"\n" ) 105"start" ,label ,"tokens" ,expected ,flush = True ) 106chunks ,texts ,first ,finish = [], [],None ,None 107started = time .perf_counter () 108try : 109with Peak ()as peak : 110wire = urllib .request .Request (args .url + "/v1/chat/completions" ,data = body , 111headers = {"Content-Type" :"application/json" }) 112with urllib .request .urlopen (wire ,timeout = 1800 )as response : 113for line in response : 114if not line .startswith (b"data: " ): 115continue 116payload = line [6 :].strip () 117if payload == b"[DONE]" : 118break 119chunk = json .loads (payload ) 120chunks .append (chunk ) 121for choice in chunk .get ("choices" , []): 122delta = choice .get ("delta" , {}) 123text = (delta .get ("content" )or "" )+ (delta .get ("reasoning_content" )or "" ) 124if text : 125first = first if first is not None else time .perf_counter ()- started 126texts .append (text ) 127finish = choice .get ("finish_reason" )or finish 128elapsed = time .perf_counter ()- started 129engine = get (args .url + "/metrics" )["requests" ][0 ] 130usage = next ((chunk ["usage" ]for chunk in reversed (chunks )if "usage" in chunk ), {}) 131row = {"label" :label ,"status" :"ok" ,"expected_prompt_tokens" :expected , 132"request_sha256" :hashlib .sha256 (body ).hexdigest (), 133"client_ttft_s" :first ,"client_elapsed_s" :elapsed ,"finish_reason" :finish , 134"usage" :usage ,"engine" :engine ,"memory" :peak .as_dict (),"text" :"" .join (texts )} 135if expected is not None and engine ["prompt_tokens" ]!= expected : 136raise RuntimeError (f"token count mismatch: { expected } vs { engine [ 'prompt_tokens' ] } " ) 137if not texts : 138raise RuntimeError (f"no text received for { label } " ) 139except Exception as error :# recorded, excluded from the statistics 140row = {"label" :label ,"status" :"failed" ,"error" :repr (error ),"expected_prompt_tokens" :expected , 141"request_sha256" :hashlib .sha256 (body ).hexdigest (), 142"client_elapsed_s" :time .perf_counter ()- started ,"text" :"" .join (texts )} 143 (args .out / (label + "-raw.json" )).write_text (json .dumps ({"chunks" :chunks ,"row" :row },indent = 2 )+ "\n" , 144encoding = "utf-8" ) 145rows .append (row ) 146save () 147"done" ,label ,row ["status" ],json .dumps ({k :row .get (k )for k in ("client_ttft_s" ,"client_elapsed_s" ,"memory" )}), 148flush = True ) 149return row 150 151perform ("warmup" ,request ("Reply with exactly the word READY." ,16 )) 152# Each nonce occurs before the filler so previous long prompts cannot be reused. 153filler = "\n" .join (f"def task_ { i :05d } (value: int) -> int: return (value * { ( i % 97 ) + 1 } + { i } ) % 100003" 154for i in range (12000 )) 155ending = ("\n\nWrite a detailed explanation of the code above. Discuss deterministic integer transforms, " 156"modulo arithmetic, testing, naming, complexity, and maintainability. Write at least 600 words." ) 157for target in map (int ,args .targets .split ("," )): 158for run in range (1 ,args .runs + 1 ): 159prefix = f"Benchmark nonce: series- { target } -trial- { run } .\nReview this synthetic Python module:\n" 160lo ,hi = 0 ,len (filler ) 161while lo < hi : 162middle = (lo + hi + 1 )// 2 163if count (request (prefix + filler [:middle ]+ ending ))<= target : 164lo = middle 165else : 166hi = middle - 1 167req = request (prefix + filler [:lo ]+ ending ) 168actual = count (req ) 169if actual < target - 20 or actual > target : 170raise RuntimeError (f"could not construct target { target } : { actual } " ) 171perform (f"tokens- { target } -run- { run } " ,req ,actual ) 172measured = [row for row in rows if row ["label" ]!= "warmup" and row ["status" ]== "ok" ] 173groups = {} 174for target in map (int ,args .targets .split ("," )): 175subset = [r for r in measured if r ["label" ].startswith (f"tokens- { target } -" )] 176failed = [r ["label" ]for r in rows if r ["label" ].startswith (f"tokens- { target } -" )and r ["status" ]!= "ok" ] 177if not subset : 178groups [str (target )]= {"runs_ok" :0 ,"failed" :failed } 179continue 180values = { 181"prompt_tokens" : [r ["engine" ]["prompt_tokens" ]for r in subset ], 182"cached_tokens" : [r ["engine" ].get ("reused" ,0 )for r in subset ], 183"output_tokens" : [r ["engine" ]["engine_generated" ]for r in subset ], 184"client_ttft_s" : [r ["client_ttft_s" ]for r in subset ], 185"client_elapsed_s" : [r ["client_elapsed_s" ]for r in subset ], 186"prefill_tok_s" : [(r ["engine" ]["prompt_tokens" ]- (r ["engine" ].get ("reused" )or 0 ))/ (r ["engine" ]["prompt_ms" ]/ 1000 )for r in subset ], 187"decode_tok_s" : [r ["engine" ]["engine_generated" ]/ (r ["engine" ]["decode_ms" ]/ 1000 )for r in subset ], 188"peak_host_ram_used_gib" : [r ["memory" ]["peak_host_ram_used_gib" ]for r in subset ], 189"peak_gpu_memory_used_mib" : [r ["memory" ]["peak_gpu_memory_used_mib" ]for r in subset ], 190 } 191groups [str (target )]= {"runs_ok" :len (subset ),"failed" :failed , 192** {key : {"median" :statistics .median (v ),"min" :min (v ),"max" :max (v )}for key ,v in values .items ()}} 193 (args .out / "summary.json" ).write_text (json .dumps (groups ,indent = 2 )+ "\n" ,encoding = "utf-8" ) 194"summary" ,json .dumps (groups ),flush = True ) 195 196 197if __name__ == "__main__" : 198main ()