okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c97ad41eb
main
1#!/usr/bin/env python3 2"""Serial, fresh-prompt Strata benchmark — adapted for the MI50 (gfx906) container. 3 4Based on bench/results/2026-09-30-community-rtx-5090/benchmark.py. Runs INSIDE the 5strata container (imports strata_tokenizer and serve.frontend from /opt/strata). 6Added: --api-key (Strata's server requires an Authorization header). 7""" 8import argparse 9import hashlib 10import json 11import statistics 12import sys 13import time 14import urllib .request 15from pathlib import Path 16 17 18def main (): 19parser = argparse .ArgumentParser (description = __doc__ ) 20parser .add_argument ("--root" ,type = Path ,default = Path ("/opt/strata" )) 21parser .add_argument ("--pack" ,type = Path ,default = Path ("/data/packs/iq2_xs" )) 22parser .add_argument ("--url" ,default = "http://127.0.0.1:8085" ) 23parser .add_argument ("--api-key" ,default = "" ) 24parser .add_argument ("--out" ,type = Path ,default = Path ("/work/bench/results" )) 25parser .add_argument ("--targets" ,default = "4096,32768" ) 26parser .add_argument ("--runs" ,type = int ,default = 3 ) 27args = parser .parse_args () 28args .out .mkdir (parents = True ,exist_ok = True ) 29sys .path [:0 ]= [str (args .root ),str (args .root / "tools" )] 30from strata_tokenizer import Tokenizer 31from serve .frontend import ChatTemplate ,openai_to_messages 32 33auth = {"Content-Type" :"application/json" } 34if args .api_key : 35auth ["Authorization" ]= "Bearer " + args .api_key 36 37def get (url ): 38request = urllib .request .Request (url ,headers = auth ) 39with urllib .request .urlopen (request ,timeout = 30 )as response : 40return json .load (response ) 41 42directory = args .pack / "tokenizer" 43vocab = json .loads ((directory / "vocab.json" ).read_text ()) 44tokens = [None ]* len (vocab ) 45for token ,number in vocab .items (): 46tokens [number ]= token 47tokenizer = Tokenizer (tokens , (directory / "merges.txt" ).read_text ().splitlines (), 48json .loads ((directory / "token_type.json" ).read_text ())) 49template = ChatTemplate (directory / "chat_template.jinja" ) 50initial = get (args .url + "/v1/status" ) 51 (args .out / "initial-status.json" ).write_text (json .dumps (initial ,indent = 2 )+ "\n" ) 52rows = [] 53 54def request (content ,maximum = 256 ): 55return {"model" :"strata" ,"messages" : [{"role" :"user" ,"content" :content }], 56"temperature" :0 ,"reasoning_effort" :"none" ,"max_tokens" :maximum , 57"stream" :True ,"stream_options" : {"include_usage" :True }} 58 59def count (req ): 60messages ,tools ,kwargs = openai_to_messages (req ) 61return len (tokenizer .encode (template .render (messages ,tools ,** kwargs ),parse_special = True )) 62 63def perform (label ,req ,expected = None ): 64body = json .dumps (req ).encode () 65 (args .out / (label + "-request.json" )).write_bytes (body + b"\n" ) 66"start" ,label ,"tokens" ,expected ,flush = True ) 67chunks ,texts ,first ,finish = [], [],None ,None 68started = time .perf_counter () 69wire = urllib .request .Request (args .url + "/v1/chat/completions" ,data = body ,headers = auth ) 70with urllib .request .urlopen (wire ,timeout = 1800 )as response : 71for line in response : 72if not line .startswith (b"data: " ): 73continue 74payload = line [6 :].strip () 75if payload == b"[DONE]" : 76break 77chunk = json .loads (payload ) 78chunks .append (chunk ) 79for choice in chunk .get ("choices" , []): 80delta = choice .get ("delta" , {}) 81text = (delta .get ("content" )or "" )+ (delta .get ("reasoning_content" )or "" ) 82if text : 83first = first if first is not None else time .perf_counter ()- started 84texts .append (text ) 85finish = choice .get ("finish_reason" )or finish 86elapsed = time .perf_counter ()- started 87metrics = get (args .url + "/metrics" ) 88engine = metrics ["requests" ][0 ] 89usage = next ((chunk ["usage" ]for chunk in reversed (chunks )if "usage" in chunk ), {}) 90row = {"label" :label ,"expected_prompt_tokens" :expected , 91"request_sha256" :hashlib .sha256 (body ).hexdigest (), 92"client_ttft_s" :first ,"client_elapsed_s" :elapsed ,"finish_reason" :finish , 93"usage" :usage ,"engine" :engine ,"text" :"" .join (texts )} 94if expected is not None and engine ["prompt_tokens" ]!= expected : 95raise RuntimeError (f"token count mismatch: { expected } vs { engine [ 'prompt_tokens' ] } " ) 96if not texts : 97raise RuntimeError (f"no text received for { label } " ) 98 (args .out / (label + "-raw.json" )).write_text (json .dumps ({"chunks" :chunks ,"row" :row },indent = 2 )+ "\n" ) 99rows .append (row ) 100 (args .out / "results.json" ).write_text (json .dumps (rows ,indent = 2 )+ "\n" ) 101"done" ,label ,json .dumps ({"ttft_s" :first ,"elapsed_s" :elapsed ,"engine" :engine }),flush = True ) 102return row 103 104perform ("warmup" ,request ("Reply with exactly the word READY." ,16 )) 105filler = "\n" .join (f"def task_ { i :05d } (value: int) -> int: return (value * { ( i % 97 ) + 1 } + { i } ) % 100003" 106for i in range (12000 )) 107ending = ("\n\nWrite a detailed explanation of the code above. Discuss deterministic integer transforms, " 108"modulo arithmetic, testing, naming, complexity, and maintainability. Write at least 600 words." ) 109for target in map (int ,args .targets .split ("," )): 110for run in range (1 ,args .runs + 1 ): 111prefix = f"Benchmark nonce: series- { target } -trial- { run } .\nReview this synthetic Python module:\n" 112lo ,hi = 0 ,len (filler ) 113while lo < hi : 114middle = (lo + hi + 1 )// 2 115if count (request (prefix + filler [:middle ]+ ending ))<= target : 116lo = middle 117else : 118hi = middle - 1 119req = request (prefix + filler [:lo ]+ ending ) 120actual = count (req ) 121if actual < target - 20 or actual > target : 122raise RuntimeError (f"could not construct target { target } : { actual } " ) 123perform (f"tokens- { target } -run- { run } " ,req ,actual ) 124measured = [row for row in rows if row ["label" ]!= "warmup" ] 125groups = {} 126for target in map (int ,args .targets .split ("," )): 127subset = [r for r in measured if r ["label" ].startswith (f"tokens- { target } -" )] 128values = { 129"prompt_tokens" : [r ["engine" ]["prompt_tokens" ]for r in subset ], 130"cached_tokens" : [r ["engine" ].get ("reused" ,0 )for r in subset ], 131"output_tokens" : [r ["engine" ]["engine_generated" ]for r in subset ], 132"client_ttft_s" : [r ["client_ttft_s" ]for r in subset ], 133"client_elapsed_s" : [r ["client_elapsed_s" ]for r in subset ], 134"prefill_tok_s" : [(r ["engine" ]["prompt_tokens" ]- (r ["engine" ].get ("reused" )or 0 ))/ (r ["engine" ]["prompt_ms" ]/ 1000 )for r in subset ], 135"decode_tok_s" : [r ["engine" ]["engine_generated" ]/ (r ["engine" ]["decode_ms" ]/ 1000 )for r in subset ], 136 } 137groups [str (target )]= {key : {"median" :statistics .median (v ),"min" :min (v ),"max" :max (v )} 138for key ,v in values .items ()} 139 (args .out / "summary.json" ).write_text (json .dumps (groups ,indent = 2 )+ "\n" ) 140"summary" ,json .dumps (groups ),flush = True ) 141 142 143if __name__ == "__main__" : 144main ()