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