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