okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6e1085c1d
main
1"""Bounded local benchmark for the approved four-pack plan.""" 2import argparse 3import csv 4import ctypes 5from ctypes import wintypes 6import datetime as dt 7import hashlib 8import json 9import os 10from pathlib import Path 11import random 12import socket 13import statistics 14import subprocess 15import sys 16import threading 17import time 18import urllib .error 19import urllib .request 20 21import psutil 22 23ROOT = Path (r"<workspace>\Strata" ) 24OUT = ROOT .parent / "results/2026-10-09-rtx3060-0141" 25SCRIPT = Path (__file__ ).resolve () 26MODELS = ["q2_0" ,"iq2_xs" ,"iq3_xxs" ,"iq3_s" ] 27PORT = 18080 28URL = f"http://127.0.0.1: { PORT } " 29FLAGS = subprocess .CREATE_NO_WINDOW if os .name == "nt" else 0 30 31 32def write (path ,data ): 33path .parent .mkdir (parents = True ,exist_ok = True ) 34temp = path .with_suffix (path .suffix + ".tmp" ) 35temp .write_text (json .dumps (data ,ensure_ascii = False ,indent = 2 )+ "\n" ,encoding = "utf-8" ) 36temp .replace (path ) 37 38 39def get (path ,timeout = 3 ): 40with urllib .request .urlopen (URL + path ,timeout = timeout )as r : 41return json .load (r ) 42 43 44def kill_tree (p ): 45try : 46children = psutil .Process (p .pid ).children (recursive = True ) 47except psutil .NoSuchProcess : 48children = [] 49for child in reversed (children ): 50try : 51child .terminate () 52except psutil .NoSuchProcess : 53pass 54if p .poll ()is None : 55p .terminate () 56_ ,alive = psutil .wait_procs (children ,timeout = 5 ) 57for child in alive : 58try : 59child .kill () 60except psutil .NoSuchProcess : 61pass 62try : 63p .wait (timeout = 5 ) 64except subprocess .TimeoutExpired : 65p .kill () 66p .wait () 67 68 69def worker (source ,dest ,cancel = False ): 70"""Only public benchmark data crosses this unauthenticated loopback socket.""" 71spec = json .loads (Path (source ).read_text (encoding = "utf-8" )) 72body = spec ["request" ] 73chunks ,texts ,reason ,calls = [], [], [], {} 74started = time .perf_counter () 75first = None 76finish = None 77try : 78req = urllib .request .Request (URL + "/v1/chat/completions" ,data = json .dumps (body ).encode (), 79headers = {"Content-Type" :"application/json" }) 80with urllib .request .urlopen (req ,timeout = 30 )as response : 81for line in response : 82if not line .startswith (b"data: " ): 83continue 84payload = line [6 :].strip () 85if payload == b"[DONE]" : 86break 87chunk = json .loads (payload ) 88chunks .append (chunk ) 89if chunk .get ("error" ): 90raise RuntimeError (json .dumps (chunk ["error" ])) 91for choice in chunk .get ("choices" , []): 92delta = choice .get ("delta" )or {} 93text = delta .get ("content" )or "" 94thinking = delta .get ("reasoning_content" )or "" 95if text or thinking or delta .get ("tool_calls" ): 96if first is None : 97first = time .perf_counter ()- started 98texts .append (text ) 99reason .append (thinking ) 100for call in delta .get ("tool_calls" )or []: 101i = call .get ("index" ,0 ) 102item = calls .setdefault (i , {"id" :"" ,"type" :"function" ,"function" : {"name" :"" ,"arguments" :"" }}) 103if call .get ("id" ): 104item ["id" ]= call ["id" ] 105for key in ("name" ,"arguments" ): 106item ["function" ][key ]+= (call .get ("function" )or {}).get (key )or "" 107finish = choice .get ("finish_reason" )or finish 108if cancel and first is not None : 109break 110result = {"ok" :True ,"client_ttft_s" :first ,"client_elapsed_s" :time .perf_counter ()- started , 111"text" :"" .join (texts ),"reasoning" :"" .join (reason ),"tool_calls" :list (calls .values ()), 112"finish_reason" :finish ,"cancelled" :cancel , 113"usage" :next ((c ["usage" ]for c in reversed (chunks )if c .get ("usage" )), {}),"chunks" :chunks } 114except urllib .error .HTTPError as exc : 115result = {"ok" :False ,"error_type" :"HTTPError" ,"http_status" :exc .code , 116"error" :exc .read (4096 ).decode ("utf-8" ,errors = "replace" ), 117"client_elapsed_s" :time .perf_counter ()- started } 118except (OSError ,ValueError ,RuntimeError )as exc : 119result = {"ok" :False ,"error_type" :type (exc ).__name__ ,"error" :str (exc ), 120"client_elapsed_s" :time .perf_counter ()- started } 121write (Path (dest ),result ) 122 123 124class CaseError (Exception ): 125pass 126 127 128class Monitor : 129def __init__ (self ,runner ): 130self .runner = runner 131self .done = threading .Event () 132self .low_since = None 133self .memory_stop = False 134self .last = {} 135self .thread = threading .Thread (target = self .loop ,daemon = True ) 136self .thread .start () 137 138def loop (self ): 139class PI (ctypes .Structure ): 140_fields_ = [("cb" ,wintypes .DWORD )]+ [(x ,ctypes .c_size_t )for x in 141 ("CommitTotal" ,"CommitLimit" ,"CommitPeak" ,"PhysicalTotal" ,"PhysicalAvailable" ,"SystemCache" , 142"KernelTotal" ,"KernelPaged" ,"KernelNonpaged" ,"PageSize" )]+ [ 143 ("HandleCount" ,wintypes .DWORD ), ("ProcessCount" ,wintypes .DWORD ), ("ThreadCount" ,wintypes .DWORD )] 144with (OUT / "telemetry.jsonl" ).open ("a" ,encoding = "utf-8" )as f : 145while not self .done .is_set (): 146t0 = time .monotonic () 147mem = psutil .virtual_memory () 148pi = PI () 149pi .cb = ctypes .sizeof (pi ) 150ok = ctypes .windll .psapi .GetPerformanceInfo (ctypes .byref (pi ),ctypes .sizeof (pi )) 151commit = pi .CommitTotal / pi .CommitLimit if ok and pi .CommitLimit else None 152row = {"epoch" :time .time (),"phase" :self .runner .phase ,"model" :self .runner .model , 153"case" :self .runner .current ,"ram_available_bytes" :mem .available , 154"ram_used_bytes" :mem .used ,"commit_fraction" :commit , 155"commit_total_bytes" :pi .CommitTotal * pi .PageSize if ok else None , 156"commit_limit_bytes" :pi .CommitLimit * pi .PageSize if ok else None } 157rss = 0 158if self .runner .server and self .runner .server .poll ()is None : 159try : 160proc = psutil .Process (self .runner .server .pid ) 161for p in [proc ]+ proc .children (recursive = True ): 162try : 163rss += p .memory_info ().rss 164except psutil .NoSuchProcess : 165pass 166except psutil .NoSuchProcess : 167pass 168row ["server_tree_rss_bytes" ]= rss 169try : 170q = subprocess .run (["nvidia-smi" ,"--query-gpu=memory.used,memory.total,utilization.gpu,temperature.gpu,clocks.current.graphics,clocks.current.memory,power.draw,power.limit,pcie.link.gen.current,pcie.link.width.current" , 171"--format=csv,noheader,nounits" ],capture_output = True ,text = True ,timeout = 3 ,creationflags = FLAGS ) 172if q .returncode == 0 : 173vals = q .stdout .strip ().split ("," ) 174keys = ["vram_mib" ,"vram_total_mib" ,"gpu_util_percent" ,"temperature_c" ,"graphics_mhz" ,"memory_mhz" , 175"gpu_power_w" ,"gpu_power_limit_w" ,"pcie_gen" ,"pcie_width" ] 176row .update ({k :float (v .strip ())if v .strip ().replace ("." ,"" ,1 ).isdigit ()else None for k ,v in zip (keys ,vals )}) 177except (OSError ,subprocess .TimeoutExpired ): 178row ["gpu_sensor_unavailable" ]= True 179io = psutil .disk_io_counters () 180if io : 181row .update (disk_read_bytes = io .read_bytes ,disk_write_bytes = io .write_bytes ) 182low = mem .available < 3 * 1024 ** 3 or (commit is not None and commit >= .90 ) 183if low and self .runner .server : 184self .low_since = self .low_since or time .monotonic () 185if time .monotonic ()- self .low_since >= 5 : 186self .memory_stop = True 187else : 188self .low_since = None 189self .last = row 190f .write (json .dumps (row )+ "\n" ) 191f .flush () 192self .done .wait (max (.05 ,1 - (time .monotonic ()- t0 ))) 193 194 195class Runner : 196def __init__ (self ): 197self .clock = json .loads ((OUT / "run-clock.json" ).read_text (encoding = "utf-8" )) 198self .start_epoch = self .clock ["start_epoch" ] 199self .hard = time .monotonic ()+ self .clock ["measurement_stop_epoch" ]- time .time () 200self .deadline = self .hard 201self .server = None 202self .log = None 203self .model = None 204self .phase = "preparation" 205self .current = None 206self .ctx = 0 207self .rows = [] 208self .gates = {} 209self .monitor = Monitor (self ) 210self .server_number = 0 211self .child_jobs = [] 212self .tokenizer = None 213self .template = None 214self .filler = None 215self .report_data = {} 216self .active_worker = None 217self .weights_mode = "native" 218 219def event (self ,kind ,** data ): 220row = {"utc" :dt .datetime .now (dt .timezone .utc ).isoformat (),"elapsed_s" :round (time .time ()- self .start_epoch ,1 ), 221"phase" :self .phase ,"model" :self .model ,"event" :kind ,** data } 222with (OUT / "events.jsonl" ).open ("a" ,encoding = "utf-8" )as f : 223f .write (json .dumps (row ,ensure_ascii = False )+ "\n" ) 224write (OUT / "status.json" , {** row ,"completed_requests" :len (self .rows ),"server_pid" :self .server .pid if self .server else None }) 225json .dumps ({k :row [k ]for k in row if k not in ("engine" ,"metrics" )},ensure_ascii = False ),flush = True ) 226 227def budget (self ,phase ,seconds ): 228self .phase = phase 229self .deadline = min (self .hard ,time .monotonic ()+ seconds ) 230self .event ("phase_start" ,budget_seconds = seconds ) 231 232def left (self ): 233return max (0 ,self .deadline - time .monotonic ()) 234 235def stop (self ): 236if self .server : 237kill_tree (self .server ) 238self .server = None 239if self .log : 240self .log .close () 241self .log = None 242self .ctx = 0 243self .monitor .memory_stop = False 244self .monitor .low_since = None 245 246def idle (self ,timeout = 15 ): 247until = min (self .deadline ,time .monotonic ()+ timeout ) 248while time .monotonic ()< until : 249try : 250m = get ("/metrics" ) 251if m .get ("live" , {}).get ("state" )== "idle" and not m .get ("live" , {}).get ("running" ,0 ): 252return m 253except (OSError ,ValueError ): 254pass 255if not self .server or self .server .poll ()is not None : 256break 257time .sleep (.15 ) 258return None 259 260def config (self ,model ,ctx ,parallel = 1 ,mtp = True ,cache = False ): 261c = json .loads ((ROOT / f"strata- { model } .json" ).read_text (encoding = "utf-8-sig" )) 262safe = {k :c [k ]for k in ("exe" ,"cwd" ,"tokenizer" ,"args" ,"lib_dirs" ,"gpu" )if k in c } 263args = list (safe ["args" ]) 264if any ("key" in a .lower ()or "token" in a .lower ()and a .startswith ("--api" )for a in args ): 265raise CaseError ("Unexpected credential argument in engine configuration" ) 266def setarg (key ,value ): 267if key in args : 268i = args .index (key ) 269args [i + 1 ]= str (value ) 270else : 271args .extend ([key ,str (value )]) 272setarg ("--max-context" ,ctx ) 273setarg ("--kv" ,"int8" ) 274setarg ("--kv-resident" ,min (ctx ,32768 )) 275setarg ("--expert-cache" ,"auto" ) 276setarg ("--prefill" ,"auto" ) 277setarg ("--spec" ,4 ) 278setarg ("--spec-min-p" ,.5 ) 279if not mtp and "--mtp" in args : 280i = args .index ("--mtp" ) 281del args [i :i + 2 ] 282if cache : 283setarg ("--conversation-cache-mib" ,512 ) 284setarg ("--conversation-cache-slots" ,4 ) 285safe .update (args = args ,model_name = "strata" ,port = PORT ,host = "127.0.0.1" ,open_browser = False , 286parallel = parallel ,fit_max_tokens = False ,lazy_load = False , 287log = str (OUT / "servers" / f" { self . server_number :03d } - { model } - { ctx } -engine.log" )) 288return safe 289 290def start (self ,model ,ctx = 131072 ,parallel = 1 ,mtp = True ,cache = False ,cpu_off = False ): 291self .stop () 292if self .left ()< 20 : 293raise CaseError ("insufficient phase time to start" ) 294self .model ,self .ctx = model ,ctx 295self .server_number += 1 296 (OUT / "servers" ).mkdir (parents = True ,exist_ok = True ) 297c = self .config (model ,ctx ,parallel ,mtp ,cache ) 298self .weights_mode = "resident" if "--resident-experts" in c ["args" ]else "mmap" if "--mmap-experts" in c ["args" ]else "native" 299path = OUT / "configs" / f" { self . server_number :03d } - { model } - { ctx } .json" 300write (path ,c ) 301self .log = (OUT / "servers" / f" { self . server_number :03d } - { model } - { ctx } -server.log" ).open ("w" ,encoding = "utf-8" ) 302env = dict (os .environ ,PYTHONUTF8 = "1" ,PYTHONUNBUFFERED = "1" ) 303if cpu_off : 304env ["STRATA_PREFILL_CPU_SHARE" ]= "0" 305else : 306env .pop ("STRATA_PREFILL_CPU_SHARE" ,None ) 307env .update (getattr (self ,"engine_environment" , {})) 308write (path .with_suffix (".environment.json" ), {** getattr (self ,"engine_environment" , {}), 309** ({"STRATA_PREFILL_CPU_SHARE" :"0" }if cpu_off else {})}) 310t0 = time .monotonic () 311self .server = subprocess .Popen ([sys .executable ,str (ROOT / "serve/server.py" ),"--engine" ,"strata" ,"--config" ,str (path ), 312"--host" ,"127.0.0.1" ,"--port" ,str (PORT )],cwd = ROOT ,env = env ,stdout = self .log ,stderr = subprocess .STDOUT ,creationflags = FLAGS ) 313self .event ("server_start" ,context = ctx ,parallel_requested = parallel ,mtp = mtp ,cpu_off = cpu_off ) 314until = min (self .deadline ,t0 + 300 ) 315while time .monotonic ()< until : 316if self .server .poll ()is not None : 317self .event ("server_exit" ,returncode = self .server .returncode ) 318self .stop () 319raise CaseError ("server exited during load" ) 320if self .monitor .memory_stop : 321self .event ("startup_memory_stop" ,available_bytes = psutil .virtual_memory ().available ) 322self .stop () 323raise CaseError ("startup memory threshold" ) 324try : 325health = get ("/health" ) 326if health .get ("loaded" ): 327if health .get ("max_context" )!= ctx : 328raise CaseError (f"context mismatch: requested { ctx } , actual { health . get ( 'max_context' ) } " ) 329break 330except (OSError ,ValueError ): 331pass 332time .sleep (.5 ) 333else : 334self .stop () 335raise CaseError ("startup deadline" ) 336self .event ("server_ready" ,context = ctx ,load_seconds = round (time .monotonic ()- t0 ,3 )) 337write (OUT / "servers" / f" { self . server_number :03d } -initial-metrics.json" ,get ("/metrics" )) 338self .perform (f"warmup- { self . server_number } " ,self .make (512 ,"warmup" ,0 ),512 ,group = "warmup" ,max_tokens = 128 ) 339if ctx == 262144 and psutil .virtual_memory ().available < 3 * 1024 ** 3 : 340self .stop () 341raise CaseError ("262K post-start free RAM below 3 GiB" ) 342 343def init_tokenizer (self ): 344sys .path [:0 ]= [str (ROOT ),str (ROOT / "tools" )] 345from strata_tokenizer import Tokenizer 346from serve .frontend import ChatTemplate ,openai_to_messages 347self .openai_to_messages = openai_to_messages 348directory = ROOT .parent / "Strata-data/packs/iq2_xs/tokenizer" 349vocab = json .loads ((directory / "vocab.json" ).read_text (encoding = "utf-8" )) 350tokens = [None ]* len (vocab ) 351for token ,number in vocab .items (): 352tokens [number ]= token 353self .tokenizer = Tokenizer (tokens , (directory / "merges.txt" ).read_text (encoding = "utf-8" ).splitlines (), 354json .loads ((directory / "token_type.json" ).read_text (encoding = "utf-8" ))) 355self .template = ChatTemplate (directory / "chat_template.jinja" ) 356code = "\n" .join (f"def task_ { i :05d } (value: int) -> int: return (value * { ( i % 97 ) + 1 } + { i } ) % 100003" for i in range (18000 )) 357self .filler = self .tokenizer .encode (code ) 358self .event ("tokenizer_ready" ,filler_tokens = len (self .filler )) 359 360def body (self ,text ,maximum = 256 ): 361return {"model" :"strata" ,"messages" : [{"role" :"user" ,"content" :text }],"temperature" :0 , 362"reasoning_effort" :"none" ,"max_tokens" :maximum ,"stream" :True , 363"stream_options" : {"include_usage" :True }} 364 365def count (self ,body ): 366messages ,tools ,kwargs = self .openai_to_messages (body ) 367return len (self .tokenizer .encode (self .template .render (messages ,tools ,** kwargs ),parse_special = True )) 368 369def make (self ,target ,language = "code" ,rep = 0 ,depth = 50 ): 370name = f" { target } - { language } - { rep } - { depth } " 371cached = OUT / "prompts" / (name + ".json" ) 372if cached .exists (): 373item = json .loads (cached .read_text (encoding = "utf-8" )) 374return item ["request" ]["messages" ][0 ]["content" ] 375prefix = f"Unique benchmark identifier { name } .\n" 376expected = f"amber-quartz- { target } - { rep } - { depth } " 377ending = "\nExplain the module in detail, covering testing, arithmetic, complexity and naming. Write at least 600 words." 378needle = f"\n# The code word to remember is { expected } .\n" 379if target >= 32768 : 380ending = f"\nFirst print the remembered code word exactly. Then explain the module in detail in at least 600 words." 381else : 382needle = "" 383if language == "ja" : 384base = self .tokenizer .encode ("春の図書館では、地域の資料を整理し、利用者が必要な情報を探せるようにしています。貸出記録と蔵書目録は別々に管理します。\n" * 200 ) 385ending = "\nこの文章の業務について、手順、注意点、改善案を日本語で詳しく説明してください。600字以上書いてください。" 386elif language == "en" : 387base = self .tokenizer .encode ("A public library maintains a catalogue and a separate record of loans. Clear procedures help readers find reliable information.\n" * 300 ) 388else : 389base = self .filler 390overhead = self .count (self .body (prefix + needle + ending )) 391n = max (1 ,target - overhead ) 392best = None 393for _ in range (8 ): 394if n > len (base ): 395raise CaseError ("filler too short" ) 396if needle : 397cut = int (n * depth / 100 ) 398content = prefix + self .tokenizer .decode (base [:cut ])+ needle + self .tokenizer .decode (base [cut :n ])+ ending 399else : 400content = prefix + self .tokenizer .decode (base [:n ])+ ending 401actual = self .count (self .body (content )) 402if actual <= target and (best is None or actual > best [0 ]): 403best = actual ,content 404if actual == target : 405break 406n += target - actual 407if best is None or best [0 ]< target - 20 : 408raise CaseError ("could not fit token target" ) 409write (cached , {"actual_tokens" :best [0 ],"expected_code_word" :expected if needle else None , 410"depth_percent" :depth ,"request" :self .body (best [1 ])}) 411return best [1 ] 412 413def perform (self ,label ,text = None ,target = None ,group = "speed" ,max_tokens = 256 ,body = None , 414expected = None ,cancel = False ): 415if self .left ()< 3 : 416raise CaseError ("phase deadline" ) 417if not self .server or self .server .poll ()is not None : 418raise CaseError ("no live benchmark server" ) 419body = body or self .body (text ,max_tokens ) 420local_count = self .count (body ) 421base = OUT / "requests" / f" { len ( self . rows ):05d } - { self . model } - { label } " 422write (base .with_suffix (".json" ), {"request" :body ,"expected_prompt_tokens" :local_count }) 423timeout = 900 if local_count > 131072 else 600 if local_count > 65536 else 180 424until = min (self .deadline ,time .monotonic ()+ timeout ) 425dest = base .with_suffix (".response.json" ) 426args = [sys .executable ,str (SCRIPT ),"--worker" ,str (base .with_suffix (".json" )),str (dest )] 427if cancel : 428args .append ("--cancel" ) 429p = subprocess .Popen (args ,stdout = subprocess .DEVNULL ,stderr = subprocess .DEVNULL ,creationflags = FLAGS ) 430self .active_worker = p 431self .current = label 432self .event ("request_start" ,label = label ,group = group ,local_prompt_tokens = local_count ) 433failure = None 434while p .poll ()is None : 435if self .monitor .memory_stop : 436failure = "memory_threshold" 437kill_tree (p ) 438break 439if time .monotonic ()>= until : 440failure = "deadline" 441kill_tree (p ) 442break 443if self .server .poll ()is not None : 444failure = "server_exited" 445kill_tree (p ) 446break 447time .sleep (.1 ) 448self .active_worker = None 449row = {"model" :self .model ,"context" :self .ctx ,"label" :label ,"group" :group ,"target" :target , 450"weights_mode" :self .weights_mode , 451"engine_environment" :dict (getattr (self ,"engine_environment" , {})), 452"local_prompt_tokens" :local_count ,"request_file" :str (base .with_suffix (".json" ).relative_to (OUT )), 453"epoch" :time .time (),"server_number" :self .server_number } 454if failure : 455row .update (ok = False ,error_type = failure ) 456elif dest .exists (): 457row .update (json .loads (dest .read_text (encoding = "utf-8" ))) 458else : 459row .update (ok = False ,error_type = "worker_no_result" ,worker_returncode = p .returncode ) 460metrics = self .idle () 461if metrics : 462hist = metrics .get ("requests" )or [] 463row ["engine" ]= hist [0 ]if hist else {} 464row ["engine_info" ]= metrics .get ("engine" , {}) 465write (base .with_suffix (".metrics.json" ),metrics ) 466else : 467row ["server_idle_confirmed" ]= False 468self .stop () 469eng = row .get ("engine" , {}) 470if row .get ("ok" )and not cancel : 471actual = eng .get ("prompt_total" )or eng .get ("prompt_tokens" )or row .get ("usage" , {}).get ("prompt_tokens" ) 472row ["token_count_matches" ]= actual == local_count 473if actual != local_count : 474row .update (ok = False ,error_type = "token_count_mismatch" ) 475if not (row .get ("text" )or row .get ("tool_calls" )): 476row .update (ok = False ,error_type = "empty_output" ) 477if expected is not None : 478row ["expected" ]= expected 479row ["correct" ]= expected in (row .get ("text" )or "" ) 480row .pop ("chunks" ,None ) 481self .rows .append (row ) 482with (OUT / "requests.jsonl" ).open ("a" ,encoding = "utf-8" )as f : 483f .write (json .dumps (row ,ensure_ascii = False )+ "\n" ) 484self .current = None 485self .event ("request_done" ,label = label ,group = group ,ok = row .get ("ok" ),error_type = row .get ("error_type" ), 486seconds = round (row .get ("client_elapsed_s" ,0 ),2 ),correct = row .get ("correct" ),reused = eng .get ("reused" )) 487if failure == "memory_threshold" : 488self .stop () 489raise CaseError ("memory threshold" ) 490if failure : 491raise CaseError (failure ) 492if not row .get ("ok" ): 493raise CaseError (row .get ("error_type" ,"request failed" )) 494return row 495 496def gate262 (self ,model ): 497free = psutil .virtual_memory ().available 498needed = (262144 - 131072 )* 13 * 1056 + 3 * 1024 ** 3 499allowed = self .monitor .last .get ("commit_fraction" )is not None and free >= needed 500self .gates [model ]= {"available_bytes_before_switch" :free ,"required_available_bytes" :needed , 501"allowed" :allowed ,"status" :"eligible" if allowed else "precheck_stopped" } 502write (OUT / "262k-gates.json" ,self .gates ) 503self .event ("262k_gate" ,** self .gates [model ]) 504return allowed 505 506def safe_block (self ,fn ,* args ,** kwargs ): 507try : 508return fn (* args ,** kwargs ) 509except CaseError as exc : 510self .event ("case_block_stopped" ,reason = str (exc )) 511self .stop () 512return None 513 514def speed_block (self ,model ,rep ,lengths ): 515self .start (model ) 516for target in lengths : 517if self .left ()< 5 : 518break 519self .perform (f"speed- { target } -r { rep } " ,self .make (target ,rep = rep ),target , 520expected = f"amber-quartz- { target } - { rep } -50" if target >= 32768 else None ) 521if rep == 1 : 522allowed = self .gate262 (model ) 523else : 524allowed = self .gates .get (model , {}).get ("allowed" ,False ) 525if allowed and self .left ()> 20 : 526try : 527self .start (model ,262144 ) 528self .perform (f"speed-260000-r { rep } " ,self .make (260000 ,rep = rep ),260000 , 529expected = f"amber-quartz-260000- { rep } -50" ) 530self .gates [model ]["status" ]= "completed" 531if rep == 1 : 532self .perform ("bridge-4096" ,self .make (4096 ,"bridge" ,0 ),4096 ,group = "bridge" ) 533except CaseError as exc : 534self .gates [model ].update (status = "runtime_stopped" ,reason = str (exc ),allowed = False ) 535raise 536finally : 537write (OUT / "262k-gates.json" ,self .gates ) 538 539def speed (self ): 540order = list (MODELS ) 541random .Random (141 ).shuffle (order ) 542for model in order : 543self .safe_block (self .speed_block ,model ,1 , [4096 ,128000 ,128 ,512 ,1024 ,32768 ,64000 ]) 544for rep in (2 ,3 ): 545for model in order [rep - 1 :]+ order [:rep - 1 ]: 546if self .left ()< 20 : 547return 548self .safe_block (self .speed_block ,model ,rep , [128000 ]) 549for rep in (2 ,3 ): 550for model in reversed (order )if rep == 2 else order : 551if self .left ()< 20 : 552return 553def short (): 554self .start (model ) 555for target in [128 ,512 ,1024 ,4096 ,32768 ,64000 ]: 556self .perform (f"speed- { target } -r { rep } " ,self .make (target ,rep = rep ),target , 557expected = f"amber-quartz- { target } - { rep } -50" if target >= 32768 else None ) 558self .safe_block (short ) 559for model in order : 560if self .left ()< 30 : 561return 562def languages (): 563self .start (model ) 564for lang in ("ja" ,"en" ): 565for rep in (1 ,2 ,3 ): 566self .perform (f"language- { lang } - { rep } " ,self .make (4096 ,lang ,rep ),4096 ,group = "language" ) 567self .safe_block (languages ) 568 569def recall (self ): 570# Complete every model's 10% position before attempting the 90% position. 571for depth in (10 ,90 ): 572for model in MODELS : 573if self .left ()< 20 : 574return 575def run (): 576self .start (model ) 577self .perform (f"recall-128000-d { depth } " ,self .make (128000 ,"code" ,9 ,depth ),128000 , 578group = "recall" ,max_tokens = 40 ,expected = f"amber-quartz-128000-9- { depth } " ) 579self .safe_block (run ) 580for model in MODELS [:2 ]: 581if self .left ()< 20 or not self .gates .get (model , {}).get ("allowed" ): 582continue 583def run262 (): 584self .start (model ,262144 ) 585for depth in (10 ,90 ): 586self .perform (f"recall-260000-d { depth } " ,self .make (260000 ,"code" ,9 ,depth ),260000 , 587group = "recall" ,max_tokens = 40 ,expected = f"amber-quartz-260000-9- { depth } " ) 588self .safe_block (run262 ) 589 590def quality (self ): 591ready = OUT / "eval-ready.json" 592if ready .exists ()and json .loads (ready .read_text (encoding = "utf-8" )).get ("ready" ): 593from evalplus .sanitize import sanitize 594dataset = json .loads ((OUT / "humaneval-subset.json" ).read_text (encoding = "utf-8" )) 595for model in MODELS : 596until = min (self .deadline ,time .monotonic ()+ 525 ) 597def generate (): 598self .start (model ) 599 (OUT / "code" ).mkdir (exist_ok = True ) 600with (OUT / "code" / f" { model } -samples.jsonl" ).open ("a" ,encoding = "utf-8" )as f : 601for tid in dataset ["ids" ]: 602if time .monotonic ()>= until : 603break 604old = self .deadline 605self .deadline = min (old ,until ) 606try : 607p = dataset ["problems" ][tid ] 608row = self .perform ("code-" + tid .replace ("/" ,"-" ), 609"Complete this Python function. Output valid Python code only, no explanations.\n\n" + p ["prompt" ], 610group = "code" ,max_tokens = 1024 ) 611solution = sanitize (row ["text" ],p ["entry_point" ]) 612f .write (json .dumps ({"task_id" :tid ,"solution" :solution })+ "\n" ) 613f .flush () 614finally : 615self .deadline = old 616self .safe_block (generate ) 617self .stop () 618self .evaluate (min (720 ,self .left ())) 619else : 620self .event ("code_evaluation_unavailable" ) 621# All assertions are fixed before any answers are seen. 622cases = [ 623 ("17×19を計算し、整数だけを答えてください。" ,"323" ), 624 ("123から58を引き、整数だけを答えてください。" ,"65" ), 625 ("文字列abcdeを逆順にし、その文字列だけを答えてください。" ,"edcba" ), 626 ("[8, 3, 5, 1]を昇順に並べ、JSON配列だけを答えてください。" , [1 ,3 ,5 ,8 ]), 627 ("JSONだけで答えてください。キーnameの値を東京、キーcountの値を3にしてください。" , {"name" :"東京" ,"count" :3 }), 628 ("りんごが7個あり3個食べました。残りの個数を整数だけで答えてください。" ,"4" ), 629 ("次の文章に含まれる都市名だけを答えてください:私は昨日、大阪で友人と会いました。" ,"大阪" ), 630 ("A=5、B=9です。A+Bの結果を整数だけで答えてください。" ,"14" ), 631 ("東京、大阪、京都の3つをその順でJSON配列として答えてください。" , ["東京" ,"大阪" ,"京都" ]), 632 ("英単語catを日本語のひらがなに訳し、訳語だけを答えてください。" ,"ねこ" ), 633 ("次の文字列の英小文字aの個数を整数だけで答えてください:banana" ,"3" ), 634 ("次のJSONのvalueだけを整数で答えてください:{\"value\":42,\"other\":7}" ,"42" )] 635write (OUT / "japanese-cases.json" ,cases ) 636tools = [{"type" :"function" ,"function" : {"name" :"add" ,"description" :"Add two integers." , 637"parameters" : {"type" :"object" ,"properties" : {"a" : {"type" :"integer" },"b" : {"type" :"integer" }}, 638"required" : ["a" ,"b" ],"additionalProperties" :False }}}] 639pairs = [(2 ,3 ), (17 ,19 ), (- 4 ,9 ), (100 ,23 ), (0 ,7 ), (81 ,- 12 ), (999 ,1 ), (14 ,28 )] 640write (OUT / "tool-cases.json" , {"schema" :tools ,"pairs" :pairs }) 641for model in MODELS : 642if self .left ()< 20 : 643break 644def small (): 645self .start (model ) 646for i , (prompt ,expected )in enumerate (cases ): 647row = self .perform (f"japanese- { i } " ,prompt ,group = "japanese" ,max_tokens = 128 ) 648text = row ["text" ].strip ().strip ("`" ).strip () 649try : 650actual = json .loads (text )if isinstance (expected , (list ,dict ))else text 651except ValueError : 652actual = None 653self .event ("japanese_grade" ,index = i ,passed = actual == expected ) 654with (OUT / "grades.jsonl" ).open ("a" ,encoding = "utf-8" )as f : 655f .write (json .dumps ({"model" :model ,"group" :"japanese" ,"index" :i ,"pass" :actual == expected })+ "\n" ) 656for i , (a ,b )in enumerate (pairs ): 657body = self .body (f"Use the add tool to add { a } and { b } . Do not compute it yourself." ,128 ) 658body ["tools" ]= tools 659row = self .perform (f"tool- { i } " ,body = body ,group = "tool" ) 660calls = row ["tool_calls" ] 661call = calls [0 ]if len (calls )== 1 else None 662try : 663valid = bool (call and call ["function" ]["name" ]== "add" and json .loads (call ["function" ]["arguments" ])== {"a" :a ,"b" :b }) 664except ValueError : 665valid = False 666if valid : 667follow = self .body ("" ,128 ) 668follow ["tools" ]= tools 669follow ["messages" ]= body ["messages" ]+ [{"role" :"assistant" ,"content" :row ["text" ],"tool_calls" :calls }, 670 {"role" :"tool" ,"tool_call_id" :call ["id" ],"content" :str (a + b )}, 671 {"role" :"user" ,"content" :"Reply with only the integer result returned by the tool." }] 672reply = self .perform (f"tool-followup- { i } " ,body = follow ,group = "tool_followup" ) 673valid = reply ["text" ].strip ()== str (a + b ) 674with (OUT / "grades.jsonl" ).open ("a" ,encoding = "utf-8" )as f : 675f .write (json .dumps ({"model" :model ,"group" :"tool" ,"index" :i ,"pass" :valid })+ "\n" ) 676self .safe_block (small ) 677 678def evaluate (self ,seconds ): 679if seconds < 5 : 680return 681self .stop () 682log = (OUT / "eval.log" ).open ("a" ,encoding = "utf-8" ) 683p = subprocess .Popen (["wsl.exe" ,"-d" ,"Ubuntu" ,"--" ,"<home>/strata-bench-0141/.venv/bin/python" , 684"<workspace>/tmp/strata_eval_subset.py" ,"--out" , 685"<workspace>/results/2026-10-09-rtx3060-0141" ,"--limit-seconds" ,str (max (1 ,seconds - 15 ))], 686stdout = log ,stderr = subprocess .STDOUT ,creationflags = FLAGS ) 687try : 688p .wait (timeout = seconds ) 689self .event ("code_eval_exit" ,returncode = p .returncode ) 690except subprocess .TimeoutExpired : 691kill_tree (p ) 692# Stop only this benchmark's WSL evaluator, never the distribution or other sessions. 693subprocess .run (["wsl.exe" ,"-d" ,"Ubuntu" ,"--" ,"pkill" ,"-f" ,"^<home>/strata-bench-0141/.venv/bin/python <workspace>/tmp/strata_eval_subset.py --out" ], 694stdout = subprocess .DEVNULL ,stderr = subprocess .DEVNULL ,creationflags = FLAGS ,timeout = 15 ) 695self .event ("code_eval_deadline" ) 696finally : 697log .close () 698 699def features (self ): 700for model in MODELS : 701if self .left ()< 20 : 702return 703def cache (): 704self .start (model ,cache = True ) 705for rep in (1 ,2 ,3 ): 706for pattern in ("continue" ,"restore" ): 707a = self .body (self .make (4096 ,"code" ,20 + rep + (10 if pattern == "restore" else 0 )),64 ) 708r = self .perform (f"cache- { pattern } - { rep } -a" ,body = a ,group = "cache" ) 709if pattern == "restore" : 710self .perform (f"cache- { pattern } - { rep } -b" ,self .make (4096 ,"code" ,60 + rep ),4096 ,group = "cache" ,max_tokens = 64 ) 711a ["messages" ]+= [{"role" :"assistant" ,"content" :r ["text" ]}, 712 {"role" :"user" ,"content" :"Continue with two concrete testing examples." }] 713self .perform (f"cache- { pattern } - { rep } -return" ,body = a ,group = "cache" ,max_tokens = 64 ) 714self .safe_block (cache ) 715for model in MODELS : 716for off in (False ,True ): 717if self .left ()< 20 : 718return 719def cpu (): 720self .start (model ,cpu_off = off ) 721for target in (512 ,1024 ): 722for rep in (1 ,2 ,3 ): 723self .perform (f"cpu- { 'off' if off else 'default' } - { target } - { rep } " ,self .make (target ,rep = 40 + rep ),target ,group = "cpu" ) 724self .safe_block (cpu ) 725for model in ("iq2_xs" ,"iq3_s" ): 726for mtp in (True ,False ): 727if self .left ()< 20 : 728return 729def draft (): 730self .start (model ,mtp = mtp ) 731for rep in (1 ,2 ,3 ): 732self .perform (f"mtp- { 'on' if mtp else 'off' } - { rep } " ,self .make (4096 ,rep = 50 + rep ),4096 ,group = "mtp" ,max_tokens = 1024 ) 733self .safe_block (draft ) 734 735def soak (self ): 736self .start ("iq2_xs" ) 737began = time .monotonic () 738i = 0 739while self .left ()> 5 : 740if i % 4 == 0 : 741self .perform (f"soak-check- { i } " ,"Calculate 17 multiplied by 19. Reply only with the integer result." ,group = "soak" ,max_tokens = 16 ,expected = "323" ) 742else : 743target = (512 ,32768 ,128000 )[(i - 1 )% 3 ] 744self .perform (f"soak- { i } " ,self .make (target ,rep = 100 + i ),target ,group = "soak" ,max_tokens = 512 ) 745i += 1 746self .event ("soak_complete" ,observed_seconds = time .monotonic ()- began ,requests = i ) 747 748def concurrency (self ): 749for model in MODELS : 750for parallel in (1 ,2 ): 751if self .left ()< 20 : 752return 753def burst (): 754self .start (model ,8192 ,parallel = parallel ) 755for clients in (1 ,2 ,4 ): 756jobs = [] 757started = time .monotonic () 758for client in range (clients ): 759base = OUT / "concurrency" / f" { model } -p { parallel } -c { clients } -i { client } " 760write (base .with_suffix (".json" ), {"request" :self .body (self .make (512 ,rep = 200 + client ),128 )}) 761dest = base .with_suffix (".response.json" ) 762p = subprocess .Popen ([sys .executable ,str (SCRIPT ),"--worker" ,str (base .with_suffix (".json" )),str (dest )], 763stdout = subprocess .DEVNULL ,stderr = subprocess .DEVNULL ,creationflags = FLAGS ) 764self .child_jobs .append (p ) 765jobs .append ((p ,dest )) 766until = min (self .deadline ,started + 180 ) 767while any (p .poll ()is None for p ,_ in jobs )and time .monotonic ()< until and not self .monitor .memory_stop : 768time .sleep (.1 ) 769answers = [] 770for p ,dest in jobs : 771if p .poll ()is None : 772kill_tree (p ) 773if dest .exists (): 774answers .append (json .loads (dest .read_text (encoding = "utf-8" ))) 775self .child_jobs .remove (p ) 776metrics = self .idle () 777write (OUT / "concurrency" / f" { model } -p { parallel } -c { clients } -burst.json" , 778 {"model" :model ,"parallel_requested" :parallel ,"clients" :clients , 779"seconds" :time .monotonic ()- started ,"answers" :answers ,"metrics" :metrics }) 780self .event ("burst_done" ,parallel_requested = parallel ,clients = clients ,results = len (answers )) 781if parallel == 1 : 782try : 783self .perform ("boundary-oversize" ,self .make (9000 ,rep = 201 ),group = "boundary" ,max_tokens = 32 ) 784except CaseError : 785pass 786if self .server : 787self .perform ("cancel" ,"Write a very long explanation of Python testing, at least 2000 words." ,group = "boundary" ,max_tokens = 1024 ,cancel = True ) 788self .perform ("after-cancel" ,"What is 17 times 19? Reply only with the integer." ,group = "boundary" ,max_tokens = 16 ,expected = "323" ) 789self .safe_block (burst ) 790 791def inventory (self ): 792write (OUT / "environment.json" , {"source_commit" :subprocess .check_output (["git" ,"rev-parse" ,"HEAD" ],cwd = ROOT ,text = True ).strip (), 793"engine_build" :json .loads ((ROOT / "engine/BUILD.json" ).read_text (encoding = "utf-8" )),"python" :sys .version , 794"cpu_logical" :psutil .cpu_count (),"cpu_physical" :psutil .cpu_count (False ),"ram_bytes" :psutil .virtual_memory ().total , 795"disk_free_bytes" :psutil .disk_usage (str (ROOT )).free ,"start_clock" :self .clock , 796"background_gpu" :subprocess .check_output (["nvidia-smi" ,"--query-gpu=name,memory.total,memory.used,driver_version,power.limit,pcie.link.gen.max,pcie.link.width.max" , 797"--format=csv" ],text = True ,creationflags = FLAGS )}) 798artifacts = [] 799seen = {} 800for model in MODELS : 801config = json .loads ((ROOT / f"strata- { model } .json" ).read_text (encoding = "utf-8-sig" )) 802for p in (ROOT .parent / "Strata-data/models" / model .upper ()).glob ("*.gguf" ): 803stat = p .stat () 804key = (stat .st_dev ,stat .st_ino ,stat .st_size ) 805if key not in seen : 806self .event ("hash_start" ,file = p .name ,bytes = stat .st_size ) 807h = hashlib .sha256 () 808with p .open ("rb" )as f : 809for block in iter (lambda :f .read (16 * 1024 * 1024 ),b"" ): 810if self .left ()<= 0 : 811raise CaseError ("preparation deadline during model hashes" ) 812h .update (block ) 813seen [key ]= h .hexdigest () 814artifacts .append ({"model" :model ,"file" :str (p ),"bytes" :stat .st_size ,"sha256" :seen [key ]}) 815directory = Path (config ["tokenizer" ]) 816hashes = {name :hashlib .sha256 ((directory / name ).read_bytes ()).hexdigest ()for name in ("vocab.json" ,"merges.txt" ,"token_type.json" ,"chat_template.jinja" )} 817artifacts .append ({"model" :model ,"tokenizer_hashes" :hashes }) 818write (OUT / "model-manifest.json" ,artifacts ) 819tokenizers = [r ["tokenizer_hashes" ]for r in artifacts if "tokenizer_hashes" in r ] 820if any (t != tokenizers [0 ]for t in tokenizers ): 821raise CaseError ("the four model tokenizers differ" ) 822 823def report (self ): 824self .phase = "report" 825self .stop () 826self .monitor .done .set () 827self .monitor .thread .join (timeout = 5 ) 828groups = {} 829for row in self .rows : 830if row .get ("group" )not in ("speed" ,"language" ,"bridge" ,"recall" ): 831continue 832key = (row ["model" ],row ["group" ],row .get ("target" ),row ["context" ]) 833groups .setdefault (key , []).append (row ) 834summaries = [] 835for key ,rows in sorted (groups .items (),key = str ): 836model ,group ,target ,context = key 837valid = [r for r in rows if r .get ("ok" )and not r .get ("engine" , {}).get ("reused" )and r .get ("token_count_matches" )] 838item = {"model" :model ,"group" :group ,"target" :target ,"context" :context ,"attempts" :len (rows ),"valid_fresh" :len (valid ), 839"recall_pass" :sum (r .get ("correct" ,False )for r in rows if r .get ("ok" )), 840"recall_trials" :sum ("correct" in r and r .get ("ok" ,False )for r in rows )} 841for metric in ("prefill_tok_s" ,"decode_tok_s" ,"ttft_s" ,"total_s" ): 842values = [] 843for row in valid : 844e = row .get ("engine" , {}) 845if metric == "prefill_tok_s" : 846value = (e .get ("prompt_tokens" ,0 )- (e .get ("reused" )or 0 ))/ (e ["prompt_ms" ]/ 1000 )if e .get ("prompt_ms" )else None 847elif metric == "decode_tok_s" : 848value = e ["engine_generated" ]/ (e ["decode_ms" ]/ 1000 )if e .get ("decode_ms" )and e .get ("engine_generated" )else None 849else : 850value = row .get ("client_ttft_s" if metric == "ttft_s" else "client_elapsed_s" ) 851if value is not None : 852values .append (value ) 853item [metric ]= statistics .median (values )if values else None 854item [metric + "_min" ]= min (values )if values else None 855item [metric + "_max" ]= max (values )if values else None 856summaries .append (item ) 857write (OUT / "summary.json" , {"groups" :summaries ,"gates" :self .gates ,"requests" :len (self .rows ), 858"completed_utc" :dt .datetime .now (dt .timezone .utc ).isoformat (),"elapsed_minutes" : (time .time ()- self .start_epoch )/ 60 }) 859if summaries : 860with (OUT / "summary.csv" ).open ("w" ,encoding = "utf-8-sig" ,newline = "" )as f : 861writer = csv .DictWriter (f ,fieldnames = list (summaries [0 ])) 862writer .writeheader () 863writer .writerows (summaries ) 864lines = ["# RTX 3060 12 GB/64 GiB RAM:Strata 0.1.41 ベンチマーク" ,"" ,"計測中の自動集計。最終報告時に失敗・品質評価・資源ピークを確認する。" ,"" , 865"| モデル | 入力目標 | 有効な新規入力測定 | 入力 tok/s 中央値 | 生成 tok/s 中央値 | TTFT 秒 中央値 | 中央検索 |" , 866"| --- | ---: | ---: | ---: | ---: | ---: | ---: |" ] 867for s in summaries : 868if s ["group" ]!= "speed" : 869continue 870def fmt (x ): 871return "未測定" if x is None else f" { x :.2f } " 872lines .append (f"| { s [ 'model' ] } | { s [ 'target' ] } | { s [ 'valid_fresh' ] } | { fmt ( s [ 'prefill_tok_s' ]) } | { fmt ( s [ 'decode_tok_s' ]) } | { fmt ( s [ 'ttft_s' ]) } | { s [ 'recall_pass' ] } / { s [ 'recall_trials' ] } |" ) 873lines += ["" ,"## 約262Kの実行判断" ,"" ,"判断の詳細は262k-gates.jsonを参照。事前停止は動作不可能やOOMを意味しない。" ,"" , 874"## 測定条件" ,"" ,"元のQwen3.8-Flash-Nextの4量子化。Windows推論、INT8 KV、常駐KV 32768、auto cache/prefill、MTP、reasoning off、temperature 0。" ,"" , 875"主測定は検索付き合成コード入力。公式表と同じ入力ではなく、GPU・エンジンも異なる。128K以下の最大コンテキストは131072、約262Kは262144。" ,"" , 876"生データはrequests.jsonl、監視はtelemetry.jsonl、起動ログはservers/、秘密を含まない実設定はconfigs/。" ,"" , 877"コード評価は先頭40問の部分集合。全164問のHumanEval+スコアではない。GPU電力はPC全体の消費電力ではない。" ] 878 (OUT / "REPORT.md" ).write_text ("\n" .join (lines )+ "\n" ,encoding = "utf-8" ) 879self .event ("run_finished" ,requests = len (self .rows ),elapsed_minutes = round ((time .time ()- self .start_epoch )/ 60 ,2 )) 880 881def run (self ): 882# A second monitor can kill this process tree if HTTP, GPU tools or native code hang. 883supervisor = subprocess .Popen ([sys .executable ,str (SCRIPT ),"--watchdog" ,str (os .getpid ()),str (self .clock ["measurement_stop_epoch" ]+ 300 )], 884stdout = subprocess .DEVNULL ,stderr = subprocess .DEVNULL ,creationflags = FLAGS ) 885try : 886self .deadline = min (self .hard ,time .monotonic ()+ self .start_epoch + 115 * 60 - time .time ()) 887while not (OUT / "models-ready.json" ).exists (): 888if self .left ()<= 0 : 889raise CaseError ("additional models not ready by preparation deadline" ) 890time .sleep (1 ) 891self .init_tokenizer () 892self .inventory () 893# Preparation smoke tests also establish counts and startup timings. 894for model in MODELS : 895self .start (model ) 896self .perform ("preparation-4096" ,self .make (4096 ,rep = 0 ),4096 ,group = "preparation" ) 897self .stop () 898# Carry unused preparation time into the highest-priority measurement. 899preparation_credit = max (0 ,self .start_epoch + 90 * 60 - time .time ()) 900self .budget ("speed" ,190 * 60 + preparation_credit ) 901self .speed () 902self .stop () 903self .budget ("recall" ,55 * 60 ) 904self .recall () 905self .stop () 906self .budget ("quality" ,55 * 60 ) 907self .quality () 908self .stop () 909self .budget ("features" ,30 * 60 ) 910self .features () 911self .stop () 912self .budget ("soak" ,30 * 60 ) 913self .safe_block (self .soak ) 914self .stop () 915self .budget ("concurrency" ,15 * 60 ) 916self .concurrency () 917self .stop () 918self .budget ("reserve" ,min (25 * 60 ,self .hard - time .monotonic ())) 919# Prioritize completing generated code evaluation, then missing key speed runs. 920if (OUT / "code" ).exists (): 921self .evaluate (min (720 ,self .left ())) 922for model in MODELS : 923if self .left ()< 30 : 924break 925missing = [t for t in (128000 ,32768 ,64000 ,4096 ,1024 ,512 ,128 ) 926if sum (r .get ("ok" ,False )for r in self .rows if r .get ("group" )== "speed" and r ["model" ]== model and r .get ("target" )== t )< 3 ] 927if missing : 928def fill_missing (): 929self .start (model ) 930for target in missing : 931completed = sum (r .get ("ok" ,False )for r in self .rows if r .get ("group" )== "speed" and r ["model" ]== model and r .get ("target" )== target ) 932for rep in range (completed + 1 ,4 ): 933self .perform (f"reserve- { target } -r { rep } " ,self .make (target ,rep = rep ),target , 934expected = f"amber-quartz- { target } - { rep } -50" if target >= 32768 else None ) 935self .safe_block (fill_missing ) 936self .report () 937except Exception as exc : 938self .event ("run_error" ,error_type = type (exc ).__name__ ,reason = str (exc )) 939self .report () 940raise 941finally : 942if self .active_worker and self .active_worker .poll ()is None : 943kill_tree (self .active_worker ) 944for job in self .child_jobs : 945kill_tree (job ) 946self .stop () 947self .monitor .done .set () 948if supervisor .poll ()is None : 949supervisor .terminate () 950 951 952def main (): 953ap = argparse .ArgumentParser () 954ap .add_argument ("--worker" ,nargs = 2 ) 955ap .add_argument ("--cancel" ,action = "store_true" ) 956ap .add_argument ("--watchdog" ,nargs = 2 ) 957a = ap .parse_args () 958if a .worker : 959return worker (* a .worker ,cancel = a .cancel ) 960if a .watchdog : 961pid ,until = int (a .watchdog [0 ]),float (a .watchdog [1 ]) 962while time .time ()< until : 963if not psutil .pid_exists (pid ): 964return 965time .sleep (1 ) 966try : 967p = psutil .Process (pid ) 968for child in reversed (p .children (recursive = True )): 969if child .pid != os .getpid (): 970try : 971child .kill () 972except psutil .NoSuchProcess : 973pass 974p .kill () 975except psutil .NoSuchProcess : 976pass 977return 978with socket .socket ()as sock : 979if sock .connect_ex (("127.0.0.1" ,PORT ))== 0 : 980raise RuntimeError ("benchmark port is already occupied; existing service preserved" ) 981OUT .mkdir (parents = True ,exist_ok = True ) 982with (OUT / "runner.pid" ).open ("w" )as f : 983f .write (str (os .getpid ())) 984Runner ().run () 985 986 987if __name__ == "__main__" : 988main ()