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