okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2e0f28e7d
main
1#!/usr/bin/env python3 2"""Serial fresh-prompt benchmark, adapted from the community MI50/RTX 5090 harness. 3 4Start a dedicated Strata server separately. This script never starts or stops it. 5Expert adaptation and the OS file cache stay warm between requests; prefix reuse 6is rejected. Engine file-tier counters describe decode, not physical disk reads. 7""" 8from __future__import annotations 9 10import argparse 11import hashlib 12import json 13import platform 14import statistics 15import subprocess 16import sys 17import threading 18import time 19import urllib .error 20import urllib .request 21import uuid 22from pathlib import Path 23 24 25def write_json (path ,value ): 26path .write_text (json .dumps (value ,indent = 2 ,ensure_ascii = False )+ "\n" ,encoding = "utf-8" ) 27 28 29def get (url ,timeout = 30 ): 30with urllib .request .urlopen (url ,timeout = timeout )as response : 31return json .load (response ) 32 33 34def digest (value ): 35return hashlib .sha256 (json .dumps (value ,sort_keys = True ).encode ("utf-8" )).hexdigest () 36 37 38def executable_record (config ): 39"""Resolve the configured binary exactly as serve/server.py does, without executing it.""" 40executable = Path (config ["exe" ]) 41if not executable .is_absolute (): 42executable = Path (config .get ("cwd" )or "." )/ executable 43executable = executable .resolve () 44checksum = hashlib .sha256 () 45with executable .open ("rb" )as source : 46for block in iter (lambda :source .read (1024 * 1024 ),b"" ): 47checksum .update (block ) 48return {"path" :str (executable ),"sha256" :checksum .hexdigest (),"size_bytes" :executable .stat ().st_size } 49 50 51def engine_provenance_record (path ,executable ): 52"""Keep compact build provenance and verify its executable artifact, when recorded.""" 53path = path .resolve () 54raw = path .read_bytes () 55source = json .loads (raw .decode ("utf-8-sig" )) 56artifacts = source .get ("artifacts" , {}) 57if isinstance (artifacts ,list ): 58entries = [(entry ["file" ],entry )for entry in artifacts ] 59elif isinstance (artifacts ,dict ): 60entries = list (artifacts .items ()) 61else : 62raise ValueError ("Provenance artifacts must be a list or dictionary" ) 63matches = [entry for name ,entry in entries 64if Path (name ).name .casefold ()== Path (executable ["path" ]).name .casefold ()] 65if len (matches )> 1 : 66raise ValueError ("Provenance has multiple artifacts matching the configured executable" ) 67expected = matches [0 ]["sha256" ].lower ()if matches else None 68if expected is not None and expected != executable ["sha256" ]: 69raise ValueError ("Provenance executable SHA-256 does not match the configured executable" ) 70toolchain_keys = ("cmake" ,"ninja" ,"msvc" ,"windows_sdk" ,"nvcc" ,"cuda" ,"cuda_architectures" , 71"cxx_standard" ,"cuda_standard" ,"build_type" ,"portable_avx2" ,"msvc_runtime" , 72"parallel_jobs" ,"tests_built" ) 73toolchain = {key :value for key ,value in source .get ("toolchain" , {}).items ()if key in toolchain_keys } 74# Release BUILD.json records CUDA and target architectures at the top level. 75toolchain .update ({key :source [key ]for key in ("cuda" ,"archs" ,"ptx" ,"portable" )if key in source }) 76return {"path" :str (path ),"sha256" :hashlib .sha256 (raw ).hexdigest (), 77"version" :source .get ("strata_version" ,source .get ("version" )),"commit" :source .get ("commit" ), 78"fingerprint" :source .get ("engine_source_fingerprint" ,source .get ("source_fingerprint" )), 79"toolchain" :toolchain ,"repository" :source .get ("fork_repository" ), 80"llama_cpp_commit" :source .get ("llama_cpp_pinned_commit" ), 81"executable_hash_verified" :expected is not None ,"recorded_executable_sha256" :expected } 82 83 84def validate_completion (before ,after ,chunks ,expected ,finish ,done ,text ): 85if not done : 86raise RuntimeError ("The stream ended without [DONE]" ) 87if not text : 88raise RuntimeError ("The response contained no text" ) 89if finish not in ("length" ,"stop" ): 90raise RuntimeError (f"Unsuccessful finish reason: { finish !r } " ) 91if after ["totals" ]["requests" ]!= before ["totals" ]["requests" ]+ 1 : 92raise RuntimeError ("Request counter mismatch; another client or engine restart invalidated this trial" ) 93if after ["live" ]["state" ]!= "idle" or after ["live" ].get ("queued" ,0 ): 94raise RuntimeError ("The dedicated server was not idle after the request" ) 95engine = after ["requests" ][0 ] 96usage_chunk = next ((chunk for chunk in reversed (chunks )if "usage" in chunk ),None ) 97if not usage_chunk or not usage_chunk .get ("timings" ): 98raise RuntimeError ("The final stream chunk lacks usage or engine timings" ) 99usage ,timings = usage_chunk ["usage" ],usage_chunk ["timings" ] 100if engine .get ("reused" )!= 0 or usage ["prompt_tokens_details" ]["cached_tokens" ]!= 0 : 101raise RuntimeError ("Fresh prompt reused cached tokens; restart this arm before resuming" ) 102if engine ["prompt_tokens" ]!= expected or usage ["prompt_tokens" ]!= expected : 103raise RuntimeError (f"Prompt token count mismatch; expected { expected } " ) 104if engine .get ("prompt_total" )!= expected or engine .get ("prompt_read" )!= expected : 105raise RuntimeError ("The engine did not report reading the complete prompt" ) 106if engine ["finish" ]!= finish or engine ["output_tokens" ]!= usage ["completion_tokens" ]: 107raise RuntimeError ("Stream usage or finish reason does not match /metrics" ) 108if timings ["prompt_n" ]!= expected or timings ["predicted_n" ]!= usage ["completion_tokens" ]: 109raise RuntimeError ("Final stream timings do not match the completed request" ) 110for name ,timing_name in (("prompt_ms" ,"prompt_ms" ), ("decode_ms" ,"predicted_ms" )): 111if engine [name ]<= 0 or abs (engine [name ]- timings [timing_name ])> 0.11 : 112raise RuntimeError (f"Invalid or mismatched engine timing: { name } " ) 113if engine ["engine_generated" ]<= 0 : 114raise RuntimeError ("The engine reported no generated tokens" ) 115return engine ,usage ,timings 116 117 118def perform (url ,out ,session ,label ,attempt ,req ,expected ,interval = 1.0 ,timeout = 1800 ): 119stem = f" { label } -attempt- { attempt } " 120body = json .dumps (req ,ensure_ascii = False ).encode ("utf-8" ) 121 (out / f" { stem } -request.json" ).write_bytes (body + b"\n" ) 122row = {"label" :label ,"attempt" :attempt ,"session" :session ,"status" :"failed" , 123"expected_prompt_tokens" :expected ,"request_sha256" :hashlib .sha256 (body ).hexdigest (), 124"started_epoch_s" :time .time (),"raw_stream" :f" { stem } -sse.jsonl" , 125"telemetry" :f" { stem } -telemetry.jsonl" ,"text" :"" ,"reasoning" :"" } 126chunks ,texts ,reasoning ,telemetry_errors = [], [], [], [] 127stop = threading .Event () 128monitor = None 129started = None 130 131def sample (output ): 132metrics = get (url + "/metrics" ) 133hardware = dict (metrics ["hardware" ]) 134if hardware .get ("ram_total" )is not None and hardware .get ("ram_used" )is not None : 135hardware ["ram_available" ]= hardware ["ram_total" ]- hardware ["ram_used" ] 136sample_row = {"epoch_s" :time .time (),"metrics_time" :metrics .get ("time" ), 137"live" :metrics ["live" ],"hardware" :hardware , 138"completed_requests" :metrics ["totals" ]["requests" ]} 139output .write (json .dumps (sample_row )+ "\n" ) 140output .flush () 141 142def monitor_loop (output ): 143while not stop .wait (interval ): 144try : 145sample (output ) 146except Exception as error : 147telemetry_errors .append (f" { type ( error ). __name__ } : { error } " ) 148output .write (json .dumps ({"epoch_s" :time .time (),"error" :telemetry_errors [- 1 ]})+ "\n" ) 149output .flush () 150break 151 152try : 153before = get (url + "/metrics" ) 154row ["metrics_before" ]= before 155if before ["live" ]["state" ]!= "idle" or before ["live" ].get ("queued" ,0 ): 156raise RuntimeError ("The dedicated server must already be loaded and idle" ) 157if expected + req ["max_tokens" ]> before ["engine" ]["max_context" ]: 158raise RuntimeError ("Prompt plus output cap exceeds the configured context" ) 159with (out / row ["telemetry" ]).open ("w" ,encoding = "utf-8" )as telemetry : 160sample (telemetry ) 161monitor = threading .Thread (target = monitor_loop ,args = (telemetry ,),daemon = True ) 162monitor .start () 163try : 164with (out / row ["raw_stream" ]).open ("w" ,encoding = "utf-8" )as raw : 165started = time .perf_counter () 166first ,finish ,done = None ,None ,False 167wire = urllib .request .Request (url + "/v1/chat/completions" ,data = body , 168headers = {"Content-Type" :"application/json" }) 169with urllib .request .urlopen (wire ,timeout = timeout )as response : 170for line in response : 171raw .write (json .dumps ({"elapsed_s" :time .perf_counter ()- started , 172"line" :line .decode ("utf-8" )},ensure_ascii = False )+ "\n" ) 173raw .flush () 174if not line .startswith (b"data:" ): 175continue 176payload = line [5 :].strip () 177if payload == b"[DONE]" : 178done = True 179break 180chunk = json .loads (payload ) 181chunks .append (chunk ) 182if chunk .get ("error" ): 183raise RuntimeError (f"Stream error: { chunk [ 'error' ] } " ) 184for choice in chunk .get ("choices" , []): 185delta = choice .get ("delta" , {}) 186content = delta .get ("content" )or "" 187thought = delta .get ("reasoning_content" )or "" 188if (content or thought )and first is None : 189first = time .perf_counter ()- started 190texts .append (content ) 191reasoning .append (thought ) 192finish = choice .get ("finish_reason" )or finish 193row .update (client_ttft_s = first ,client_elapsed_s = time .perf_counter ()- started , 194finish_reason = finish ,stream_done = done ) 195after = get (url + "/metrics" ) 196row ["metrics_after" ]= after 197engine ,usage ,timings = validate_completion (before ,after ,chunks ,expected , 198finish ,done ,"" .join (texts + reasoning )) 199row .update (engine = engine ,usage = usage ,timings = timings , 200prefill_tok_s = expected / (engine ["prompt_ms" ]/ 1000 ), 201decode_tok_s = engine ["engine_generated" ]/ (engine ["decode_ms" ]/ 1000 )) 202finally : 203stop .set () 204monitor .join () 205try : 206sample (telemetry ) 207except Exception as error : 208telemetry_errors .append (f" { type ( error ). __name__ } : { error } " ) 209if telemetry_errors : 210raise RuntimeError ("Telemetry failed: " + "; " .join (telemetry_errors )) 211row ["status" ]= "ok" 212except urllib .error .HTTPError as error : 213row ["error" ]= {"type" :type (error ).__name__ ,"message" :str (error ),"http_status" :error .code , 214"body" :error .read ().decode ("utf-8" ,errors = "replace" )} 215except Exception as error : 216row ["error" ]= {"type" :type (error ).__name__ ,"message" :str (error )} 217finally : 218stop .set () 219if monitor is not None and monitor .is_alive (): 220monitor .join () 221row .update (text = "" .join (texts ),reasoning = "" .join (reasoning ),finished_epoch_s = time .time ()) 222if started is not None and "client_elapsed_s" not in row : 223row ["client_elapsed_s" ]= time .perf_counter ()- started 224write_json (out / f" { stem } -record.json" ,row ) 225write_json (out / f" { stem } -chunks.json" ,chunks ) 226return row 227 228 229def summary (rows ,targets ): 230groups = {} 231for target in targets : 232selected = [r for r in rows if r ["label" ].startswith (f"tokens- { target } -" )] 233good = [r for r in selected if r ["status" ]== "ok" ] 234fields = ("client_ttft_s" ,"client_elapsed_s" ,"prefill_tok_s" ,"decode_tok_s" ) 235groups [str (target )]= {"successful_runs" :len (good ),"failed_attempts" :len (selected )- len (good ), 236** {field : {"median" :statistics .median (v ),"min" :min (v ),"max" :max (v )} 237for field in fields if (v := [r [field ]for r in good ])}} 238return groups 239 240 241def main (): 242parser = argparse .ArgumentParser (description = __doc__ ) 243parser .add_argument ("--root" ,type = Path ,default = Path (__file__ ).resolve ().parents [3 ]) 244parser .add_argument ("--pack" ,type = Path ,required = True ) 245parser .add_argument ("--config" ,type = Path ,help = "Server configuration, saved with relevant fields only" ) 246parser .add_argument ("--engine-provenance" ,type = Path , 247help = "Build provenance JSON or release BUILD.json; requires --config" ) 248parser .add_argument ("--url" ,default = "http://127.0.0.1:18080" ) 249parser .add_argument ("--model" ,default = "strata" ) 250parser .add_argument ("--label" ,required = True ,help = "Configuration label, such as iq2-xs-3090-resident" ) 251parser .add_argument ("--out" ,type = Path ,required = True ,help = "A separate directory for each configuration" ) 252parser .add_argument ("--targets" ,default = "1024,4096,16384" ) 253parser .add_argument ("--runs" ,type = int ,default = 3 ) 254parser .add_argument ("--max-tokens" ,type = int ,default = 256 ) 255parser .add_argument ("--timeout" ,type = float ,default = 1800 ) 256parser .add_argument ("--telemetry-interval" ,type = float ,default = 1.0 ) 257parser .add_argument ("--resume" ,action = "store_true" ,help = "Keep completed trials and preserve failed attempts" ) 258args = parser .parse_args () 259targets = [int (value )for value in args .targets .split ("," )] 260if not targets or min (targets )<= 0 or len (set (targets ))!= len (targets ): 261parser .error ("Targets must be unique positive token counts" ) 262if args .runs < 1 or args .max_tokens < 1 or args .timeout <= 0 or args .telemetry_interval <= 0 : 263parser .error ("Runs, output cap, timeout, and telemetry interval must be positive" ) 264if args .engine_provenance and not args .config : 265parser .error ("--engine-provenance requires --config to identify the executable" ) 266args .root ,args .pack ,args .out = args .root .resolve (),args .pack .resolve (),args .out .resolve () 267url = args .url .rstrip ("/" ) 268sys .path [:0 ]= [str (args .root ),str (args .root / "tools" )] 269from strata_tokenizer import Tokenizer 270from serve .frontend import ChatTemplate ,openai_to_messages 271 272directory = args .pack / "tokenizer" 273vocab = json .loads ((directory / "vocab.json" ).read_text (encoding = "utf-8" )) 274tokens = [None ]* len (vocab ) 275for token ,number in vocab .items (): 276tokens [number ]= token 277tokenizer = Tokenizer (tokens , (directory / "merges.txt" ).read_text (encoding = "utf-8" ).splitlines (), 278json .loads ((directory / "token_type.json" ).read_text (encoding = "utf-8" ))) 279template = ChatTemplate (directory / "chat_template.jinja" ) 280 281def request (content ,maximum = args .max_tokens ): 282return {"model" :args .model ,"messages" : [{"role" :"user" ,"content" :content }], 283"temperature" :0 ,"reasoning_effort" :"none" ,"max_tokens" :maximum , 284"stream" :True ,"stream_options" : {"include_usage" :True }} 285 286def count (req ): 287messages ,tools ,kwargs = openai_to_messages (req ) 288return len (tokenizer .encode (template .render (messages ,tools ,** kwargs ),parse_special = True )) 289 290initial = get (url + "/metrics" ) 291if initial ["live" ]["state" ]!= "idle" or initial ["live" ].get ("queued" ,0 ): 292raise RuntimeError ("Start a dedicated, loaded and idle server before this benchmark" ) 293config = {} 294executable = None 295if args .config : 296source = json .loads (args .config .read_text (encoding = "utf-8-sig" )) 297executable = executable_record (source ) 298keys = ("exe" ,"cwd" ,"args" ,"gpu" ,"layer_split" ,"split_skip_if_fits" ,"backend" ,"tokenizer" ,"log" , 299"model_name" ,"parallel" ,"expert_profile_save" ,"expert_profile_save_every" ) 300config = {key :source [key ]for key in keys if key in source } 301compute_variables = {"CUDA_VISIBLE_DEVICES" ,"CUDA_DEVICE_ORDER" ,"STRATA_STAGE_TRIM" ,"STRATA_SPLIT_OWN" , 302"STRATA_ARENA_PIN_GIB" ,"STRATA_RESIDENT_PIN" ,"STRATA_RESIDENT_HEADROOM_GIB" , 303"STRATA_ARENA_MMAP" ,"STRATA_PREFILL_HELP" ,"STRATA_FETCH_THREADS" ,"STRATA_LOOKAHEAD" , 304"STRATA_DECODE_TIMING" ,"STRATA_SPLIT_TIMING" ,"STRATA_VERIFY_PROFILE" , 305"STRATA_SPLIT_MISS_MS" ,"STRATA_PF_FUSED" ,"STRATA_FILE_RELEASE" } 306config ["env" ]= {key :value for key ,value in source .get ("env" , {}).items () 307if key in compute_variables } 308revision = subprocess .run (["git" ,"-c" ,f"safe.directory= { args . root . as_posix () } " ,"rev-parse" ,"HEAD" ], 309cwd = args .root ,capture_output = True ,text = True ,check = True ).stdout .strip () 310provenance = engine_provenance_record (args .engine_provenance ,executable )if args .engine_provenance else None 311manifest = {"label" :args .label ,"frontend_source_commit" :revision ,"pack" :str (args .pack ), 312"config" :config ,"engine_executable" :executable , 313"engine_provenance" :provenance ,"engine_reported_version" :initial ["engine" ].get ("version" ), 314"targets" :targets ,"runs" :args .runs ,"max_tokens" :args .max_tokens , 315"model" :args .model ,"server_model" :initial ["engine" ]["model" ], 316"max_context" :initial ["engine" ]["max_context" ], 317"hardware_static" :initial .get ("hardware_static" ), 318"tokenizer_sha256" : {name :hashlib .sha256 ((directory / name ).read_bytes ()).hexdigest () 319for name in ("vocab.json" ,"merges.txt" ,"token_type.json" ,"chat_template.jinja" )}, 320"script_sha256" :hashlib .sha256 (Path (__file__ ).read_bytes ()).hexdigest (), 321"method" :"Serial warm-engine trials; default adaptive expert state retained; zero prompt reuse required" , 322"disk_counter_note" :"file_mb is the decode file tier, possibly OS-cached; disk_read_mb is system-wide physical I/O" } 323manifest_path = args .out / "manifest.json" 324if manifest_path .exists (): 325if not args .resume : 326raise RuntimeError ("Output already has a manifest; use a new output directory or --resume" ) 327if digest (json .loads (manifest_path .read_text (encoding = "utf-8" )))!= digest (manifest ): 328raise RuntimeError ("Resume manifest differs; use a new output directory" ) 329elif args .resume : 330raise RuntimeError ("Cannot resume: output has no manifest" ) 331args .out .mkdir (parents = True ,exist_ok = True ) 332write_json (manifest_path ,manifest ) 333rows_path = args .out / "results.json" 334rows = json .loads (rows_path .read_text (encoding = "utf-8" ))if args .resume and rows_path .exists ()else [] 335session = uuid .uuid4 ().hex [:12 ] 336write_json (args .out / f"session- { session } .json" , {"session" :session ,"epoch_s" :time .time (), 337"python" :sys .version ,"platform" :platform .platform (),"initial_metrics" :initial , 338"initial_status" :get (url + "/v1/status" ),"resumed" :args .resume }) 339 340def run (label ,req ): 341if any (row ["label" ]== label and row ["status" ]== "ok" for row in rows ): 342"skip completed" ,label ,flush = True ) 343return 344attempt = sum (row ["label" ]== label for row in rows )+ 1 345"start" ,args .label ,label ,"tokens" ,count (req ),flush = True ) 346row = perform (url ,args .out ,session ,label ,attempt ,req ,count (req ), 347args .telemetry_interval ,args .timeout ) 348rows .append (row ) 349write_json (rows_path ,rows ) 350write_json (args .out / "summary.json" ,summary (rows ,targets )) 351row ["status" ],label ,json .dumps ({key :row .get (key )for key in 352 ("client_ttft_s" ,"prefill_tok_s" ,"decode_tok_s" ,"error" )}),flush = True ) 353if row ["status" ]!= "ok" : 354raise RuntimeError (f"Benchmark stopped after failed trial { label } ; evidence was retained" ) 355 356run (f"warmup- { session } " ,request (f"Warmup { session } . Reply with exactly the word READY." ,16 )) 357filler = "\n" .join (f"def task_ { i :05d } (value: int) -> int: return (value * { ( i % 97 ) + 1 } + { i } ) % 100003" 358for i in range (12000 )) 359ending = ("\n\nWrite a detailed explanation of the code above. Discuss deterministic integer transforms, " 360"modulo arithmetic, testing, naming, complexity, and maintainability. Write at least 600 words." ) 361for target in targets : 362for trial in range (1 ,args .runs + 1 ): 363# Checkpoints cover a complete turn or >=16K prompt tokens by default; 364# this early differing nonce prevents a whole checkpoint from matching. 365prefix = f"Benchmark nonce: series- { target } -trial- { trial } .\nReview this synthetic Python module:\n" 366low ,high = 0 ,len (filler ) 367while low < high : 368middle = (low + high + 1 )// 2 369if count (request (prefix + filler [:middle ]+ ending ))<= target : 370low = middle 371else : 372high = middle - 1 373req = request (prefix + filler [:low ]+ ending ) 374if not target - 20 <= count (req )<= target : 375raise RuntimeError (f"Could not construct target { target } : { count ( req ) } " ) 376run (f"tokens- { target } -run- { trial } " ,req ) 377"Complete:" ,args .out / "summary.json" ,flush = True ) 378 379 380if __name__ == "__main__" : 381main ()