okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
407ea8192
main
1"""Matched OpenAI-compatible smoke benchmark; never executes generated code/tools.""" 2import argparse 3import ctypes 4import json 5import threading 6import time 7import urllib .request 8from pathlib import Path 9 10AUTH_HEADERS = {} 11 12 13class MemoryStatus (ctypes .Structure ): 14_fields_ = [("length" ,ctypes .c_ulong ), ("load" ,ctypes .c_ulong )]+ [ 15 (name ,ctypes .c_ulonglong )for name in 16 ("total_physical" ,"available_physical" ,"total_pagefile" ,"available_pagefile" , 17"total_virtual" ,"available_virtual" ,"available_extended" ) 18 ] 19 20 21def available_ram (): 22status = MemoryStatus () 23status .length = ctypes .sizeof (status ) 24if not ctypes .windll .kernel32 .GlobalMemoryStatusEx (ctypes .byref (status )): 25raise ctypes .WinError () 26return status .available_physical / 2 ** 30 27 28 29def get_json (base ,route ): 30req = urllib .request .Request (base + route ,headers = AUTH_HEADERS ) 31with urllib .request .urlopen (req ,timeout = 10 )as response : 32return json .load (response ) 33 34 35def assert_idle (base ): 36slots = get_json (base ,"/slots" ) 37if not isinstance (slots ,list ): 38raise RuntimeError ("Unrecognized slots response; cannot confirm idle" ) 39if any (slot .get ("is_processing" )for slot in slots ): 40raise RuntimeError ("Model is already working; not interrupting it" ) 41 42 43def request (base ,model ,label ,prompt ,run ,tools = None ,* ,response_format = None ,reasoning_effort = "low" ,max_tokens = 1024 ): 44assert_idle (base ) 45# Different first messages minimize shared-prefix reuse; residual cache is reported. 46payload = { 47"model" :model ,"messages" : [{"role" :"user" ,"content" :f"Benchmark { label } run { run } .\n { prompt } " }], 48"temperature" :1.0 ,"top_p" :0.95 ,"top_k" :20 ,"min_p" :0.0 , 49"repeat_penalty" :1.0 ,"repetition_penalty" :1.0 , 50"presence_penalty" :0.0 ,"frequency_penalty" :0.0 , 51"reasoning_effort" :reasoning_effort ,"seed" :42 ,"max_tokens" :max_tokens , 52"cache_prompt" :False ,"strata_checkpoint" :False , 53"experimental_speed_projection" :False , 54"stream" :True ,"stream_options" : {"include_usage" :True }, 55 } 56if tools : 57payload .update (tools = tools ,tool_choice = "auto" ) 58if response_format is not None : 59payload ['response_format' ]= response_format 60before = available_ram () 61samples = [before ] 62stop = threading .Event () 63 64def sample (): 65while not stop .wait (0.5 ): 66samples .append (available_ram ()) 67 68monitor = threading .Thread (target = sample ,daemon = True ) 69monitor .start () 70started = time .perf_counter () 71first_delta = first_content = None 72text ,reasoning ,calls = "" ,"" , {} 73usage ,timings ,finish = {}, {},None 74error = None 75try : 76req = urllib .request .Request (base + "/v1/chat/completions" ,json .dumps (payload ).encode (), 77 {"Content-Type" :"application/json" ,** AUTH_HEADERS }) 78with urllib .request .urlopen (req ,timeout = 900 )as response : 79for raw in response : 80line = raw .decode ("utf-8" ).strip () 81if not line .startswith ("data:" ): 82continue 83data = line [5 :].strip () 84if data == "[DONE]" : 85break 86event = json .loads (data ) 87if event .get ("error" ): 88raise RuntimeError (str (event ["error" ])) 89if event .get ("usage" ): 90usage = event ["usage" ] 91if event .get ("timings" ): 92timings = event ["timings" ] 93for choice in event .get ("choices" , []): 94delta = choice .get ("delta" , {}) 95content = delta .get ("content" )or "" 96thought = delta .get ("reasoning_content" )or delta .get ("reasoning" )or "" 97if content or thought or delta .get ("tool_calls" ): 98first_delta = first_delta if first_delta is not None else time .perf_counter ()- started 99if content : 100first_content = first_content if first_content is not None else time .perf_counter ()- started 101text += content 102reasoning += thought 103for call in delta .get ("tool_calls" , []): 104target = calls .setdefault (call .get ("index" ,0 ), {"name" :"" ,"arguments" :"" }) 105function = call .get ("function" , {}) 106target ["name" ]+= function .get ("name" )or "" 107target ["arguments" ]+= function .get ("arguments" )or "" 108finish = choice .get ("finish_reason" )or finish 109except Exception as exc : 110error = str (exc ) 111finally : 112elapsed = time .perf_counter ()- started 113stop .set () 114monitor .join (timeout = 2 ) 115samples .append (available_ram ()) 116return { 117"case" :label ,"run" :run ,"wall_seconds" :round (elapsed ,3 ), 118"first_token_seconds" :first_delta ,"first_answer_seconds" :first_content , 119"usage" :usage ,"timings" :timings ,"finish_reason" :finish , 120"answer" :text ,"reasoning" :reasoning ,"tool_calls" :list (calls .values ()), 121"available_ram_before_GiB" :before ,"minimum_available_ram_GiB" :min (samples ), 122"available_ram_after_GiB" :samples [- 1 ],"error" :error , 123 } 124 125 126def validate (row ,strict = False ): 127if row ["error" ]or row ["finish_reason" ]== "length" : 128return False 129if row ["case" ]== "tool_call" : 130calls = row ["tool_calls" ] 131try : 132return len (calls )== 1 and calls [0 ]["name" ]== "read_file" and json .loads (calls [0 ]["arguments" ])== {"path" :"package.json" } 133except (ValueError ,KeyError ): 134return False 135raw_answer = row ["answer" ].strip () 136if not strict and raw_answer .startswith ("```" )and raw_answer .endswith ("```" ): 137raw_answer = "\n" .join (raw_answer .splitlines ()[1 :- 1 ]) 138try : 139answer = json .loads (raw_answer ) 140except ValueError : 141return False 142if row ["case" ]== "quote_math" : 143expected = {"subtotal" :780 ,"discounted" :702 ,"tax" :91.26 ,"total" :793.26 } 144return isinstance (answer ,dict )and answer .keys ()== expected .keys ()and all ( 145isinstance (answer [k ], (int ,float ))and abs (answer [k ]- v )< 0.005 for k ,v in expected .items ()) 146if row ["case" ]== "validation_logic" : 147return answer == {"accepted" : [0 ,1.5 ,3 ],"rejected" : [None ,"4" ,- 2 ]} 148return answer == {"start" :"CLENEX-4181" ,"middle" :"STRATA-8081" ,"end" :"LONDON-9060" } 149 150 151def main (): 152parser = argparse .ArgumentParser () 153parser .add_argument ("--base" ) 154parser .add_argument ("--model" ) 155parser .add_argument ("--rescore" ,type = Path ) 156parser .add_argument ("--connection" ,type = Path ) 157parser .add_argument ("--output" ,type = Path ,required = True ) 158parser .add_argument ("--runs" ,type = int ,default = 2 ) 159args = parser .parse_args () 160if args .output .exists (): 161raise SystemExit ("Output already exists; choose a new filename to preserve results" ) 162if args .rescore : 163results = json .loads (args .rescore .read_text (encoding = "utf-8" )) 164results ["scoring_note" ]= "Content accuracy and exact output formatting are scored separately; original evidence retained." 165for row in results ["results" ]: 166row ["original_check_passed" ]= row ["check_passed" ] 167row ["check_passed" ]= validate (row ) 168row ["strict_format_passed" ]= validate (row ,strict = True ) 169args .output .write_text (json .dumps (results ,indent = 2 ),encoding = "utf-8" ) 170json .dumps ({"content_passed" :sum (r ["check_passed" ]for r in results ["results" ]), 171"strict_format_passed" :sum (r ["strict_format_passed" ]for r in results ["results" ]), 172"total" :len (results ["results" ])})) 173return 174if args .connection : 175conn = json .loads (args .connection .read_text (encoding = "utf-8-sig" )) 176args .base = conn ["baseURL" ].removesuffix ("/v1" ) 177args .model = conn ["model" ] 178AUTH_HEADERS ["Authorization" ]= "Bearer " + Path (conn ["keyFile" ]).read_text ().strip () 179if not args .base or not args .model : 180parser .error ("--base and --model are required for live benchmarking" ) 181assert_idle (args .base ) 182cases = [ 183 ("quote_math" ,"An office quote includes four visits at $120 each, three floor jobs at $85 each, and $45 materials. Apply 10% discount to the subtotal then 13% tax. Return only JSON with numeric subtotal, discounted, tax and total." ,None ), 184 ("validation_logic" ,'Accept only JSON numbers which are finite and nonnegative (zero is valid); reject null, strings and negatives. Classify [0, null, "4", -2, 1.5, 3]. Return only JSON with arrays accepted and rejected, preserving their relative order.' ,None ), 185 ("tool_call" ,"Use the read_file tool to inspect package.json before suggesting a test command. Do not guess its contents. Call the tool exactly once; no other actions." , [{"type" :"function" ,"function" : {"name" :"read_file" ,"description" :"Read a file in the current project" ,"parameters" : {"type" :"object" ,"properties" : {"path" : {"type" :"string" }},"required" : ["path" ],"additionalProperties" :False }}}]), 186 ] 187filler = "This is irrelevant background about routine office cleaning schedules. Ignore it when extracting marked keys.\n" 188for label ,repeats in [("recall_short" ,25 ), ("recall_long" ,300 )]: 189document = "START_KEY=CLENEX-4181\n" + filler * repeats + "MIDDLE_KEY=STRATA-8081\n" + filler * repeats + "END_KEY=LONDON-9060\n" 190cases .append ((label ,document + 'Return only JSON with start, middle and end holding the three marked key values.' ,None )) 191results = {"started_at" :time .strftime ("%Y-%m-%dT%H:%M:%S%z" ),"base" :args .base , 192"model" :args .model ,"runs" :args .runs ,"results" : [], 193"notes" :"Same text/settings; token counts may differ. RAM is whole-system, sampled at 0.5 s. No generated tools/code are executed. TTFT includes reasoning. Low effort can mean different budgets across models. This compares whole stacks, not model or engine in isolation." } 194args .output .parent .mkdir (parents = True ,exist_ok = True ) 195for label ,prompt ,tools in cases : 196for run in range (1 ,args .runs + 1 ): 197row = request (args .base ,args .model ,label ,prompt ,run ,tools ) 198row ["check_passed" ]= validate (row ) 199row ["strict_format_passed" ]= validate (row ,strict = True ) 200results ["results" ].append (row ) 201args .output .write_text (json .dumps (results ,indent = 2 ),encoding = "utf-8" ) 202json .dumps ({k :row [k ]for k in ("case" ,"run" ,"wall_seconds" ,"usage" ,"timings" ,"check_passed" ,"error" )}),flush = True ) 203if row ["error" ]: 204raise SystemExit ("Request failed; stopping instead of retrying or restarting the server" ) 205 206 207if __name__ == "__main__" : 208main ()