okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cc86ad90d
main
1#!/usr/bin/env python3 2"""Measure Strata streaming latency and engine throughput using only Python's stdlib. 3 4Run against an already-started local server. This script does not install or start 5Strata, clear server state, or contact any host other than the configured URL. 6""" 7import argparse 8import hashlib 9import json 10import re 11import statistics 12import time 13import urllib .error 14import urllib .request 15from pathlib import Path 16 17 18DEFAULT_URL = "http://127.0.0.1:8080" 19DEFAULT_CASES = "short,4k,32k" 20ENGINE_LINE = re .compile ( 21r"prompt (?P<prompt>\d+) tokens = (?P<reused>\d+) reused \+ (?P<read>\d+)(?: of \d+)? read in " 22r"(?P<read_ms>[\d.]+) ms \((?P<prefill>[\d.]+) tok/s\), (?P<generated>\d+) generated in " 23r"(?P<decode_ms>[\d.]+) ms \((?P<decode>[\d.]+) tok/s\)" 24) 25 26 27def json_request (url ,payload = None ,headers = None ,timeout = 30 ): 28data = None if payload is None else json .dumps (payload ,ensure_ascii = False ).encode ("utf-8" ) 29request = urllib .request .Request (url ,data = data ,headers = headers or {}) 30with urllib .request .urlopen (request ,timeout = timeout )as response : 31return json .loads (response .read ().decode ("utf-8" )) 32 33 34def auth_headers (api_key ,content_type = False ): 35headers = {"Content-Type" :"application/json" }if content_type else {} 36if api_key : 37headers ["Authorization" ]= "Bearer " + api_key 38return headers 39 40 41def read_log_from (path ,offset ): 42if path is None : 43return "" 44try : 45with path .open ("rb" )as stream : 46stream .seek (0 ,2 ) 47end = stream .tell () 48stream .seek (min (offset ,end )) 49return stream .read ().decode ("utf-8" ,"replace" ) 50except OSError as exc : 51return f"[log read error: { exc } ]" 52 53 54def request_body (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 59 60def short_prompt (run_id ): 61return (f"Benchmark nonce: { run_id } . Write a complete Python module for a robust in-memory task queue. " 62"Include typed dataclasses, validation, stable priority ordering, enqueue/dequeue/peek/remove operations, " 63"clear exceptions, and a detailed unittest suite with edge cases. Explain behavior in docstrings and " 64"comments. Output the complete code only; make it production-quality and detailed." ) 65 66 67def sized_prompt (target_tokens ,run_id ,count_tokens ): 68"""Build a deterministic code-review prompt at the target rendered length.""" 69prefix = (f"Benchmark nonce: { run_id } . Treat this as an independent request.\n" 70"Review this synthetic Python module and explain its behavior, edge cases, tests, and complexity.\n" ) 71suffix = "\n\nGive a concise code review with concrete observations.\n" 72def build (lines ): 73filler = "" .join ( 74f"def transform_ { i :05d } (value: int, offset: int = { i } ) -> int:\n" 75f" return (value * { ( i % 97 ) + 1 } + offset + { i } ) % 100003\n\n" 76for i in range (lines ) 77 ) 78return prefix + filler + suffix 79 80# The count endpoint renders and tokenizes the prompt without running the 81# model. Binary search the generated lines; the actual OpenAI request usage 82# is retained too because the server reports that authoritative count. 83lo ,hi = 0 ,max (8 ,int (target_tokens / 12 )) 84while count_tokens (build (hi ))< target_tokens : 85hi *= 2 86while lo < hi : 87middle = (lo + hi + 1 )// 2 88if count_tokens (build (middle ))<= target_tokens : 89lo = middle 90else : 91hi = middle - 1 92return build (lo ) 93 94 95def history_record (metrics ,started_wall ): 96for record in metrics .get ("requests" , []): 97if record .get ("time" ,0 )>= started_wall - 0.1 : 98return record 99return None 100 101 102def summarize (values ): 103vals = [v for v in values if isinstance (v , (int ,float ))] 104if not vals : 105return {"median" :None ,"min" :None ,"max" :None } 106return {"median" :statistics .median (vals ),"min" :min (vals ),"max" :max (vals )} 107 108 109def main (): 110parser = argparse .ArgumentParser (description = __doc__ ) 111parser .add_argument ("--url" ,default = DEFAULT_URL ,help = "Strata base URL (default: %(default)s)" ) 112parser .add_argument ("--cases" ,default = DEFAULT_CASES ,help = "comma-separated subset of short,4k,32k" ) 113parser .add_argument ("--runs" ,type = int ,default = 3 ,help = "measured runs per case (default: %(default)s)" ) 114parser .add_argument ("--out" ,type = Path ,default = Path (__file__ ).resolve ().parent , 115help = "directory for raw.jsonl, summary.json, and log snippets" ) 116parser .add_argument ("--log" ,type = Path ,help = "optional Strata engine log to capture per-run appended lines" ) 117parser .add_argument ("--api-key" ,default = "" ,help = "API key, if the local server requires one" ) 118args = parser .parse_args () 119if args .runs < 1 : 120parser .error ("--runs must be at least 1" ) 121cases = [name .strip ().lower ()for name in args .cases .split ("," )if name .strip ()] 122unknown = sorted (set (cases )- {"short" ,"4k" ,"32k" }) 123if not cases or unknown : 124parser .error ("--cases must be a non-empty comma-separated subset of short,4k,32k" ) 125args .out .mkdir (parents = True ,exist_ok = True ) 126base = args .url .rstrip ("/" ) 127headers = auth_headers (args .api_key ,content_type = True ) 128get_headers = auth_headers (args .api_key ) 129 130initial = json_request (base + "/health" ,headers = get_headers ) 131 (args .out / "initial-health.json" ).write_text (json .dumps (initial ,indent = 2 )+ "\n" ,encoding = "utf-8" ) 132records = [] 133warmup_records = [] 134raw_path = args .out / "raw.jsonl" 135# Reset this harness's output for a new invocation; server/model state stays intact. 136raw_path .write_text ("" ,encoding = "utf-8" ) 137 138def perform (label ,content ,maximum = 256 ,warmup = False ,expected_prompt_tokens = None ): 139payload = request_body (content ,maximum ) 140wire = json .dumps (payload ,ensure_ascii = False ).encode ("utf-8" ) 141try : 142metrics_before = json_request (base + "/metrics" ,headers = get_headers ) 143except (urllib .error .URLError ,TimeoutError ,OSError ,ValueError )as exc : 144metrics_before = {"error" :str (exc )} 145started_wall = time .time () 146log_offset = 0 147if args .log : 148try : 149log_offset = args .log .stat ().st_size 150except OSError : 151pass 152started = time .perf_counter () 153first_text_at = None 154chunks ,text_parts ,reasoning_parts = [], [], [] 155finish_reason = None 156stream_error = None 157usage = None 158request = urllib .request .Request (base + "/v1/chat/completions" ,data = wire ,headers = headers ) 159try : 160with urllib .request .urlopen (request ,timeout = 1800 )as response : 161for line in response : 162if not line .startswith (b"data: " ): 163continue 164data = line [6 :].strip () 165if data == b"[DONE]" : 166break 167try : 168chunk = json .loads (data .decode ("utf-8" )) 169except (UnicodeDecodeError ,json .JSONDecodeError ): 170continue 171chunks .append (chunk ) 172if chunk .get ("error" ): 173stream_error = chunk ["error" ] 174if "usage" in chunk : 175usage = chunk ["usage" ] 176for choice in chunk .get ("choices" , []): 177delta = choice .get ("delta" )or {} 178text = delta .get ("content" )or "" 179reasoning = delta .get ("reasoning_content" )or "" 180if text or reasoning : 181if first_text_at is None : 182first_text_at = time .perf_counter ()- started 183text_parts .append (text ) 184reasoning_parts .append (reasoning ) 185finish_reason = choice .get ("finish_reason" )or finish_reason 186except (urllib .error .URLError ,TimeoutError ,OSError )as exc : 187stream_error = {"message" :str (exc ),"type" :"client_error" } 188elapsed = time .perf_counter ()- started 189metrics ,metric_error = {},None 190try : 191metrics = json_request (base + "/metrics" ,headers = get_headers ) 192except (urllib .error .URLError ,TimeoutError ,OSError ,ValueError )as exc : 193metric_error = str (exc ) 194engine = history_record (metrics ,started_wall ) 195log_text = read_log_from (args .log ,log_offset ) 196log_lines = [line .rstrip ()for line in log_text .splitlines ()if line .strip ()] 197parsed_log = [] 198for line in log_lines : 199match = ENGINE_LINE .search (line ) 200if match : 201parsed_log .append ({key : (float (value )if "." in value else int (value )) 202for key ,value in match .groupdict ().items ()}) 203stream_timings = next ((chunk ["timings" ]for chunk in reversed (chunks )if chunk .get ("timings" )),None ) 204if engine : 205fresh = max (0 , (engine .get ("prompt_tokens" )or 0 )- (engine .get ("reused" )or 0 )) 206engine_timings = { 207"prompt_tokens" :engine .get ("prompt_tokens" ),"fresh_prompt_tokens" :fresh , 208"reused_tokens" :engine .get ("reused" ),"prompt_ms" :engine .get ("prompt_ms" ), 209"prefill_tok_s" : (fresh / (engine ["prompt_ms" ]/ 1000 ) 210if engine .get ("prompt_ms" )else None ), 211"generated_tokens" :engine .get ("engine_generated" ),"decode_ms" :engine .get ("decode_ms" ), 212"decode_tok_s" :engine .get ("decode_tok_s" ), 213"drafts_offered" :engine .get ("drafts_offered" ), 214"drafts_accepted" :engine .get ("drafts_accepted" ), 215 } 216else : 217engine_timings = None 218row = { 219"label" :label ,"warmup" :warmup ,"target_prompt_tokens" :expected_prompt_tokens , 220"request_sha256" :hashlib .sha256 (wire ).hexdigest (), 221"request_body" :payload , 222"client_ttft_s" :first_text_at ,"client_total_latency_s" :elapsed , 223"finish_reason" :finish_reason ,"usage" :usage ,"engine" :engine , 224"metrics_before" :metrics_before ,"metrics_after" :metrics , 225"engine_timings" :stream_timings or engine_timings , 226"prefix_reused_tokens" : (engine or {}).get ("reused" ), 227"api_cached_tokens" : ((usage or {}).get ("prompt_tokens_details" )or {}).get ("cached_tokens" ), 228"output_text" :"" .join (text_parts ),"reasoning_text" :"" .join (reasoning_parts ), 229"raw_stream_chunks" :chunks ,"stream_error" :stream_error , 230"metrics_error" :metric_error ,"engine_log_lines" :log_lines [- 30 :], 231"parsed_engine_log_timings" :parsed_log , 232 } 233if warmup : 234warmup_records .append (row ) 235 (args .out / "warmup.json" ).write_text ( 236json .dumps (warmup_records ,indent = 2 ,ensure_ascii = False )+ "\n" ,encoding = "utf-8" ) 237else : 238records .append (row ) 239with raw_path .open ("a" ,encoding = "utf-8" )as stream : 240stream .write (json .dumps (row ,ensure_ascii = False )+ "\n" ) 241if args .log : 242safe_label = re .sub (r"[^A-Za-z0-9_.-]" ,"_" ,label ) 243 (args .out / f" { safe_label } .log-snippet.txt" ).write_text ( 244"\n" .join (log_lines )+ ("\n" if log_lines else "" ),encoding = "utf-8" ) 245json .dumps ({"run" :label ,"ttft_s" :first_text_at ,"total_s" :elapsed , 246"prompt_tokens" : (engine or {}).get ("prompt_tokens" ), 247"reused" : (engine or {}).get ("reused" ),"engine_timings" :row ["engine_timings" ], 248"error" :stream_error },ensure_ascii = False ),flush = True ) 249if stream_error : 250raise RuntimeError (f" { label } failed: { stream_error } " ) 251if not text_parts : 252raise RuntimeError (f" { label } produced no nonempty content delta" ) 253return row 254 255# Separate warm-up from the measured sample set. 256perform ("warmup" ,"Benchmark warm-up: explain in detail how a Python heap maintains priority order." , 257maximum = 256 ,warmup = True ) 258 (args .out / "warmup.json" ).write_text (json .dumps (warmup_records ,indent = 2 ,ensure_ascii = False )+ "\n" , 259encoding = "utf-8" ) 260for case in cases : 261for run in range (1 ,args .runs + 1 ): 262nonce = f"rx6900xt-coder- { case } -trial- { run } " 263if case == "short" : 264content ,maximum = short_prompt (nonce ),256 265label = f"short-run- { run } " 266else : 267target = 4096 if case == "4k" else 32768 268def count_tokens (text ): 269result = json_request (base + "/v1/messages/count_tokens" , 270 {"model" :"strata" ,"messages" : [{"role" :"user" ,"content" :text }]}, 271headers = headers ,timeout = 180 ) 272return int (result ["input_tokens" ]) 273content ,maximum = sized_prompt (target ,nonce ,count_tokens ),256 274expected_tokens = count_tokens (content ) 275label = f" { case } -run- { run } " 276if case == "short" : 277expected_tokens = None 278perform (label ,content ,maximum = maximum ,expected_prompt_tokens = expected_tokens ) 279 280grouped = {} 281for case in cases : 282subset = [row for row in records if row ["label" ].startswith (case + "-" )] 283def metric (row ,key ): 284engine = row .get ("engine" )or {} 285if key == "prompt_tok_s" : 286n = engine .get ("prompt_tokens" ,0 )- (engine .get ("reused" )or 0 ) 287ms = engine .get ("prompt_ms" ) 288return n / (ms / 1000 )if ms else None 289if key == "decode_tok_s" : 290n = engine .get ("engine_generated" )or 0 291ms = engine .get ("decode_ms" ) 292return n / (ms / 1000 )if ms else None 293return row .get (key ) 294grouped [case ]= { 295"runs" :len (subset ), 296"prompt_tokens" :summarize ([(r .get ("engine" )or {}).get ("prompt_tokens" )for r in subset ]), 297"prefix_reused_tokens" :summarize ([r .get ("prefix_reused_tokens" )for r in subset ]), 298"completion_tokens" :summarize ([(r .get ("usage" )or {}).get ("completion_tokens" )for r in subset ]), 299"client_ttft_s" :summarize ([metric (r ,"client_ttft_s" )for r in subset ]), 300"client_total_latency_s" :summarize ([metric (r ,"client_total_latency_s" )for r in subset ]), 301"prompt_tok_s" :summarize ([metric (r ,"prompt_tok_s" )for r in subset ]), 302"decode_tok_s" :summarize ([metric (r ,"decode_tok_s" )for r in subset ]), 303"finish_reasons" : [r .get ("finish_reason" )for r in subset ], 304 } 305summary = {"url" :base ,"cases" :cases ,"runs_per_case" :args .runs , 306"request_settings" : {"max_tokens" :256 ,"temperature" :0 ,"reasoning_effort" :"none" , 307"stream" :True ,"warmup_excluded" :True }, 308"cache_note" :"No server cache-clear API is used. Every measured prompt starts with a unique nonce; " 309"actual prefix reuse is taken from before/after engine history and API usage. The target " 310"size uses /v1/messages/count_tokens; completion usage is also retained for the actual " 311"OpenAI request." , 312"case_results" :grouped ,"raw_jsonl" :str (raw_path )} 313 (args .out / "summary.json" ).write_text (json .dumps (summary ,indent = 2 ,ensure_ascii = False )+ "\n" ,encoding = "utf-8" ) 314json .dumps (summary ,indent = 2 ,ensure_ascii = False )) 315 316 317if __name__ == "__main__" : 318main ()