okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c9fc15774
main
1#!/usr/bin/env python3 2"""Serial fresh-prompt benchmark, adapted from the 2026-09-30 community RTX 5090 script.""" 3import argparse 4import hashlib 5import json 6import statistics 7import subprocess 8import sys 9import threading 10import time 11import urllib .request 12from pathlib import Path 13 14 15def get (url ): 16with urllib .request .urlopen (url ,timeout = 30 )as response : 17return json .load (response ) 18 19 20def main (): 21parser = argparse .ArgumentParser (description = __doc__ ) 22parser .add_argument ("--root" ,type = Path ,default = Path (r"D:\AI\Strata" )) 23parser .add_argument ("--pack" ,type = Path ,default = Path (r"D:\AI\Strata-data\packs\iq3_xxs" )) 24parser .add_argument ("--url" ,default = "http://127.0.0.1:5310" ) 25parser .add_argument ("--out" ,type = Path ,default = Path (r"D:\AI\Strata-data\community-bench-20261004" )) 26parser .add_argument ("--targets" ,default = "4096,32768,128000" ) 27parser .add_argument ("--runs" ,type = int ,default = 3 ) 28args = parser .parse_args () 29args .out .mkdir (parents = True ,exist_ok = True ) 30sys .path [:0 ]= [str (args .root ),str (args .root / "tools" )] 31from strata_tokenizer import Tokenizer 32from serve .frontend import ChatTemplate ,openai_to_messages 33 34directory = args .pack / "tokenizer" 35vocab = json .loads ((directory / "vocab.json" ).read_text (encoding = "utf-8" )) 36tokens = [None ]* len (vocab ) 37for token ,number in vocab .items (): 38tokens [number ]= token 39tokenizer = Tokenizer (tokens , (directory / "merges.txt" ).read_text (encoding = "utf-8" ).splitlines (), 40json .loads ((directory / "token_type.json" ).read_text (encoding = "utf-8" ))) 41template = ChatTemplate (directory / "chat_template.jinja" ) 42initial = get (args .url + "/v1/status" ) 43 (args .out / "initial-status.json" ).write_text (json .dumps (initial ,indent = 2 )+ "\n" ,encoding = "utf-8" ) 44metrics0 = get (args .url + "/metrics" ) 45 (args .out / "initial-metrics.json" ).write_text (json .dumps (metrics0 ,indent = 2 )+ "\n" ,encoding = "utf-8" ) 46rows = [] 47stop = threading .Event () 48tel_path = args .out / "telemetry.csv" 49 50def sample (): 51if not tel_path .exists (): 52tel_path .write_text ("unix,mem_used_mib,util_gpu,pcie_gen,pcie_width,power_w\n" ,encoding = "utf-8" ) 53while not stop .is_set (): 54try : 55out = subprocess .check_output ( 56 ["nvidia-smi" , 57"--query-gpu=memory.used,utilization.gpu,pcie.link.gen.current,pcie.link.width.current,power.draw" , 58"--format=csv,noheader,nounits" ], 59text = True ,timeout = 15 ).strip () 60with tel_path .open ("a" ,encoding = "utf-8" )as fh : 61fh .write (f" { time . time ():.0f } , { out } \n" ) 62except (OSError ,subprocess .SubprocessError ): 63pass 64stop .wait (5 ) 65 66threading .Thread (target = sample ,daemon = True ).start () 67 68def request (content ,maximum = 256 ): 69return {"model" :"qwen3.8-flash-next-iq3_xxs" , 70"messages" : [{"role" :"user" ,"content" :content }], 71"temperature" :0 ,"reasoning_effort" :"none" ,"max_tokens" :maximum , 72"stream" :True ,"stream_options" : {"include_usage" :True }} 73 74def count (req ): 75messages ,tools ,kwargs = openai_to_messages (req ) 76return len (tokenizer .encode (template .render (messages ,tools ,** kwargs ),parse_special = True )) 77 78def perform (label ,req ,expected = None ): 79body = json .dumps (req ).encode () 80 (args .out / (label + "-request.json" )).write_bytes (body + b"\n" ) 81"start" ,label ,"tokens" ,expected ,flush = True ) 82chunks ,texts ,first ,finish = [], [],None ,None 83started = time .perf_counter () 84wire = urllib .request .Request (args .url + "/v1/chat/completions" ,data = body , 85headers = {"Content-Type" :"application/json" }) 86with urllib .request .urlopen (wire ,timeout = 1800 )as response : 87for line in response : 88if not line .startswith (b"data: " ): 89continue 90payload = line [6 :].strip () 91if payload == b"[DONE]" : 92break 93chunk = json .loads (payload ) 94chunks .append (chunk ) 95for choice in chunk .get ("choices" , []): 96delta = choice .get ("delta" , {}) 97text = (delta .get ("content" )or "" )+ (delta .get ("reasoning_content" )or "" ) 98if text : 99first = first if first is not None else time .perf_counter ()- started 100texts .append (text ) 101finish = choice .get ("finish_reason" )or finish 102elapsed = time .perf_counter ()- started 103metrics = get (args .url + "/metrics" ) 104engine = metrics ["requests" ][0 ] 105usage = next ((chunk ["usage" ]for chunk in reversed (chunks )if "usage" in chunk ), {}) 106row = {"label" :label ,"expected_prompt_tokens" :expected , 107"request_sha256" :hashlib .sha256 (body ).hexdigest (), 108"client_ttft_s" :first ,"client_elapsed_s" :elapsed ,"finish_reason" :finish , 109"usage" :usage ,"engine" :engine ,"text" :"" .join (texts )} 110if expected is not None and engine .get ("prompt_tokens" )!= expected : 111raise RuntimeError (f"token count mismatch: { expected } vs { engine . get ( 'prompt_tokens' ) } " ) 112if not texts : 113raise RuntimeError (f"no text received for { label } " ) 114 (args .out / (label + "-raw.json" )).write_text ( 115json .dumps ({"chunks" :chunks ,"row" :row },indent = 2 )+ "\n" ,encoding = "utf-8" ) 116rows .append (row ) 117 (args .out / "results.json" ).write_text (json .dumps (rows ,indent = 2 )+ "\n" ,encoding = "utf-8" ) 118"done" ,label ,json .dumps ({ 119"ttft_s" :first ,"elapsed_s" :elapsed , 120"prompt_tokens" :engine .get ("prompt_tokens" ),"reused" :engine .get ("reused" ), 121"prompt_ms" :engine .get ("prompt_ms" ),"decode_ms" :engine .get ("decode_ms" ), 122"engine_generated" :engine .get ("engine_generated" ), 123"finish" :finish }),flush = True ) 124return row 125 126try : 127perform ("warmup" ,request ("Reply with exactly the word READY." ,16 )) 128filler = "\n" .join ( 129f"def task_ { i :05d } (value: int) -> int: return (value * { ( i % 97 ) + 1 } + { i } ) % 100003" 130for i in range (12000 )) 131ending = ("\n\nWrite a detailed explanation of the code above. Discuss deterministic integer transforms, " 132"modulo arithmetic, testing, naming, complexity, and maintainability. Write at least 600 words." ) 133for target in map (int ,args .targets .split ("," )): 134for run in range (1 ,args .runs + 1 ): 135prefix = f"Benchmark nonce: series- { target } -trial- { run } .\nReview this synthetic Python module:\n" 136lo ,hi = 0 ,len (filler ) 137while lo < hi : 138middle = (lo + hi + 1 )// 2 139if count (request (prefix + filler [:middle ]+ ending ))<= target : 140lo = middle 141else : 142hi = middle - 1 143req = request (prefix + filler [:lo ]+ ending ) 144actual = count (req ) 145if actual < target - 20 or actual > target : 146raise RuntimeError (f"could not construct target { target } : { actual } " ) 147perform (f"tokens- { target } -run- { run } " ,req ,actual ) 148measured = [row for row in rows if row ["label" ]!= "warmup" ] 149groups = {} 150for target in map (int ,args .targets .split ("," )): 151subset = [r for r in measured if r ["label" ].startswith (f"tokens- { target } -" )] 152values = { 153"prompt_tokens" : [r ["engine" ]["prompt_tokens" ]for r in subset ], 154"cached_tokens" : [r ["engine" ].get ("reused" )or 0 for r in subset ], 155"output_tokens" : [r ["engine" ]["engine_generated" ]for r in subset ], 156"client_ttft_s" : [r ["client_ttft_s" ]for r in subset ], 157"client_elapsed_s" : [r ["client_elapsed_s" ]for r in subset ], 158"prefill_tok_s" : [ 159 (r ["engine" ]["prompt_tokens" ]- (r ["engine" ].get ("reused" )or 0 )) 160/ (r ["engine" ]["prompt_ms" ]/ 1000 )for r in subset ], 161"decode_tok_s" : [ 162r ["engine" ]["engine_generated" ]/ (r ["engine" ]["decode_ms" ]/ 1000 )for r in subset ], 163 } 164groups [str (target )]= { 165key : {"median" :statistics .median (v ),"min" :min (v ),"max" :max (v )} 166for key ,v in values .items ()} 167 (args .out / "summary.json" ).write_text (json .dumps (groups ,indent = 2 )+ "\n" ,encoding = "utf-8" ) 168"summary" ,json .dumps (groups ),flush = True ) 169finally : 170stop .set () 171 172 173if __name__ == "__main__" : 174main ()