okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
1"""Tune the engine's hardware-dependent settings on this PC (setup's --calibrate). 2 3Three settings depend on the machine more than on the model, and the defaults are right for the PC they were 4measured on (a Ryzen 5 7600 + RTX 5070 on PCIe 5): 5--pcie-frac the share of the experts missing from VRAM that are copied over PCIe and run on the GPU instead of 6on the CPU. A fast PCIe link and a slow CPU want more; a laptop's x8 link or a fast CPU want less. 7--spec-min-p how sure the draft layer must be to extend a verify window by another guess. A slower CPU pays more 8per extra window row (more experts per window), so it wants a higher floor. 9--pool-workers the CPU threads that compute experts. Every physical core is not always best: on hybrid CPUs the 10efficiency cores can make the whole window wait for them. 11--adapt-every / --adapt-swaps / --adapt-decay 12how the VRAM expert tier follows the conversation: how often, how many experts it swaps in, how fast 13its use counts fade. A PC whose CPU reads the missed experts slowly (DDR3, ~24 GB/s) gains from 14swapping more: 160 swaps every window measured +7.9% over the default tier on a Xeon E5-2673 v3 (DDR3) with an 15RTX 4060 Ti on PCIe 3.0 x8 (Q2_0; with the swaps taking effect a window later, #764). 16--prefill-pipe a layer split only: the prompt chunks that keep the stages reading at once. The best chunk count 17depends on b/a, the fixed cost of a chunk over that of a token, which differs by an order of 18magnitude between rigs (about 700 tokens on four GP100 dies, 5000 on two RTX 3090 Ti) and costs 19when it is wrong (a fixed 1024 read 22-36% slower on two RTX 4090) - so it is measured here, once, 20as the prompt read speed of fresh prompts, rather than guessed or learned while the PC serves. 21STRATA_SH_STREAM (AMD only) 22the shared expert on its own stream. Off by default on HIP (#816: an RX 6800 on Windows and 4x R9700 23decode 12-45% faster without it), but the same card family on another PC goes the other way (#1272: 242x RX 6900 XT on Linux, 6-11% faster with it), so it is measured here, per PC, and written into the 25config's "env" only when it wins. The output is identical either way (same token ids). 26 27The first two and the prompt chunks are measured through one engine (per-request `strata_tune` keys); the worker 28count, the adaptive tier and the shared-expert stream need a restart per value. Those are decode speed: the prompt 29path streams every expert whatever they say. 30 31A setting is kept only when it beats the default by more than MIN_GAIN in an interleaved re-measurement - the 32adaptive expert tier and the OS make single measurements noisy by a few percent. 33 34python tools/calibrate.py strata-q2_0.json # measure and print; setup.py --calibrate also saves it 35""" 36from __future__import annotations 37 38import json 39import statistics 40import sys 41import threading 42import time 43from pathlib import Path 44 45ROOT = Path (__file__ ).resolve ().parents [1 ] 46sys .path .insert (0 ,str (ROOT / "tools" )) 47sys .path .insert (0 ,str (ROOT )) 48 49MIN_GAIN = 0.03 # a setting must beat the default by this much to be kept 50PCIE_FRACS = (0.0 ,0.2 ,0.35 ,0.55 ,0.75 ,0.9 ,1.0 )# 1.0: every miss over PCIe, the CPU pool gets no expert 51SPEC_MIN_PS = (0.3 ,0.5 ,0.7 ) 52SWEEP_ROUNDS = 3 # how many times the sweep visits each value (see `sweep`) 53# the adaptive tier's candidates (every, swaps, decay) against the engine's own (None): swapping more and remembering 54# longer, the rest of the set as the engine has it 55# HIP: the shared-expert stream fork, off (the HIP default) against on; an engine environment variable, not an argument 56SH_STREAM = "STRATA_SH_STREAM" 57ADAPT_CANDIDATES = (None , ("1" ,"80" ,"0.97" ), ("1" ,"160" ,"0.97" )) 58ADAPT_FLAGS = ("--adapt-every" ,"--adapt-swaps" ,"--adapt-decay" ) 59MAX_NEW = 128 60# the expert tier follows a text over some windows: 128-token answers end before it shows (on a Xeon E5-2673 v3 with 61# DDR3, every 1 / 160 / 0.97 measured +0.7% with 128 tokens and +7.9% with 512-token answers), so its step uses these 62TIER_MAX_NEW = 512 63# --prefill-pipe's values: 0 the buffers' chunks (the engine default), 1 their count evened out, then b/a in tokens 64PIPE_VALUES = (0 ,1 ,768 ,1536 ,3072 ,6144 ) 65PIPE_TOKENS = (2048 ,8192 )# fresh prompts read per value (their text: the install's docs/*.md) 66PROMPTS = ( 67"Write a Python function that merges two sorted lists into one sorted list, with a docstring and two tests." , 68"Explain in two paragraphs how a refrigerator moves heat from inside to outside." , 69"List twelve European capitals with one sentence about each." , 70) 71 72 73class CalibrationCancelled (RuntimeError ): 74"""An operator requested a stop; no partial sample may enter the report.""" 75 76 77def _check_cancel (cancel_event ): 78if cancel_event is not None and cancel_event .is_set (): 79raise CalibrationCancelled ("calibration cancelled" ) 80 81 82def _progress (callback ,stage :str ,completed :int ,total :int ): 83if callback is not None : 84callback (stage ,completed ,total ) 85 86 87def chat_ids (tok ,text :str )-> list [int ]: 88return tok .encode (f"<|im_start|>user\n { text } <|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n" , 89parse_special = True ) 90 91 92def arg_value (args :list [str ],flag :str )-> str | None : 93return args [args .index (flag )+ 1 ]if flag in args and args .index (flag )+ 1 < len (args )else None 94 95 96def with_arg (args :list [str ],flag :str ,value :str | None )-> list [str ]: 97"""`args` with `flag value` set (replaced if present), or removed when value is None.""" 98out = list (args ) 99if flag in out : 100i = out .index (flag ) 101del out [i :i + 2 ] 102if value is not None : 103out += [flag ,value ] 104return out 105 106 107def worker_candidates (default :int ,extra = ())-> list [int ]: 108"""The engine's own count, and fewer: two thirds, a half and a quarter (at least 2), plus `extra` (the P-cores 109minus one on a hybrid CPU, one socket's cores minus one on a 2-socket PC), without repeats. Bench #780 #815 110#707 #674: 4 beat 15 by 28.7% on 8P + 16E; 17-18 beat 35 by ~20% on 2-socket Xeons.""" 111c = [default ] 112for w in (round (default * 2 / 3 ),round (default / 2 ),round (default / 4 ),* extra ): 113if 2 <= w < default and w not in c : 114c .append (w ) 115return c 116 117 118def host_worker_extras ()-> list [int ]: 119"""P-cores - 1 (hybrid CPU) and one socket's cores - 1 (several sockets) of this PC: more counts to try.""" 120try : 121import setup 122out = [] 123cores ,sockets = setup .cpu_cores (),setup .cpu_sockets () 124if cores : 125out .append (cores [0 ]- 1 ) 126if sockets and sockets [0 ]>= 2 : 127out .append (sockets [1 ]- 1 ) 128return out 129except Exception : 130return [] 131 132 133def doc_prompt (tok ): 134"""`make(i, n)`: a fresh prompt of about n tokens - the same stretch of the docs' text for every i, after a header 135that differs for every i, so no read reuses an earlier one's cache and the reads differ only in their chunks (where 136experts are streamed, the read speed depends on the text: a different stretch per read measured the text).""" 137text = "\n\n" .join (p .read_text (encoding = "utf-8" ,errors = "replace" )for p in sorted ((ROOT / "docs" ).glob ("*.md" ))) 138body = tok .encode (text ,parse_special = False )or [0 ] 139tail = tok .encode ("<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n" ,parse_special = True ) 140 141def make (i :int ,n :int )-> list [int ]: 142head = tok .encode (f"<|im_start|>user\n[calibration read { i } ] Summarize:\n" ,parse_special = True ) 143return head + (body * (n // len (body )+ 1 ))[:n ]+ tail 144return make 145 146 147def measure_pipe (eng ,make ,say = -> tuple [float ,dict ]: 148"""--prefill-pipe on one running engine (a layer split): the prompt read speed of fresh prompts per value, then the 149best against the default (0) in SWEEP_ROUNDS paired rounds (back to back, the order alternating). It is kept only 150when it is faster in every round and by more than MIN_GAIN in the median: on two RTX 3090 Ti one read can be 20% 151off, and a b/a too small for the rig reads 19-24% slower there. One pass over the values, not `sweep`'s rounds: 152every value reads the same text (`doc_prompt`), and on four GP100 dies one pass already takes about 4 minutes.""" 153reads = [0 ] 154 155def rate (v :float )-> float : 156ms = toks = 0.0 157for n in PIPE_TOKENS : 158reads [0 ]+= 1 159sampling = {"temperature" :0 ,"strata_checkpoint" :False ,"strata_tune" : {"prefill_pipe" :v }} 160for _ in eng .generate (make (reads [0 ],n ),1 ,sampling ,threading .Event ()): 161pass 162last = eng .last or {} 163ms += float (last .get ("prompt_ms" )or 0.0 ) 164toks += float (last .get ("prompt_read" )or (last .get ("prompt_tokens" )or 0 )- (last .get ("reused" )or 0 )) 165return toks / (ms / 1000.0 )if ms > 0 and toks > 0 else 0.0 166 167rate (0 )# the first long read after a start faults the weights in 168by_value = {} 169for v in PIPE_VALUES : 170by_value [v ]= [rate (v )] 171say (f" prompt chunks { 'off' if v == 0 else 'evened out' if v == 1 else f'b/a { v } ' } : { by_value [ v ][ 0 ]:.0f } tok/s" ) 172best = max (by_value ,key = lambda k :by_value [k ][0 ]) 173confirm = {0 : [],best : []} 174chosen = 0 175if best != 0 : 176for r in range (SWEEP_ROUNDS ): 177for k in ((0 ,best )if r % 2 == 0 else (best ,0 )): 178confirm [k ].append (rate (k )) 179gains = [c / d - 1.0 for d ,c in zip (confirm [0 ],confirm [best ])if d > 0 ] 180if len (gains )== SWEEP_ROUNDS and min (gains )> 0.0 and statistics .median (gains )> MIN_GAIN : 181chosen = best 182return chosen , {"pipe_sweep" : {str (k ):v for k ,v in by_value .items ()}, 183"pipe_confirm" : {str (k ):v for k ,v in confirm .items ()}} 184 185 186def pick (measured :dict ,default_key ,min_gain :float = MIN_GAIN ): 187"""The key with the best median tok/s, or `default_key` unless the best beats it by more than min_gain.""" 188med = {k :statistics .median (v )for k ,v in measured .items ()if v } 189if not med or default_key not in med : 190return default_key 191best = max (med ,key = med .get ) 192return best if med [best ]> med [default_key ]* (1.0 + min_gain )else default_key 193 194 195class Session : 196"""One running engine: measure decode tok/s for a setting (the median of the prompts' rates).""" 197 198def __init__ (self ,engine ,ids_list ,cancel_event = None ): 199self .engine = engine 200self .ids_list = ids_list 201self .cancel_event = cancel_event 202 203def rate (self ,tune :dict | None = None ,max_new :int | None = None )-> float : 204rates = [] 205for ids in self .ids_list : 206_check_cancel (self .cancel_event ) 207sampling = {"temperature" :0 } 208if tune : 209sampling ["strata_tune" ]= tune 210n = sum (1 for t in self .engine .generate (ids ,max_new or MAX_NEW ,sampling , 211self .cancel_event or threading .Event ()) 212if t is not None ) 213_check_cancel (self .cancel_event ) 214ms = (self .engine .last or {}).get ("decode_ms" )or 0.0 215if n > 8 and ms > 0 : 216rates .append (n / (ms / 1000.0 )) 217return statistics .median (rates )if rates else 0.0 218 219def warm_up (self ,rounds :int = 2 ): 220for _ in range (rounds ): 221self .rate () 222 223 224def run (cfg :dict ,say = start_engine = None ,* ,progress = None ,cancel_event = None )-> dict : 225"""Measure on the engine `cfg` describes; returns {"settings": {flag: value}, "report": {...}}. 226`start_engine(args)` returns a started engine (serve.server.StrataEngine or a stand-in in tests).""" 227if start_engine is None : 228from serve .server import StrataEngine ,child_env 229 230def start_engine (args ,env = None ): 231e = child_env (cfg ) 232e .update (env or {}) 233return StrataEngine (cfg ["exe" ],args ,cwd = cfg .get ("cwd" ),log = cfg .get ("log" ),env = e ) 234import strata_tokenizer as ST 235tpath = Path (cfg ["tokenizer" ]) 236vocab = json .loads ((tpath / "vocab.json" ).read_text (encoding = "utf-8" )) 237toks = [None ]* len (vocab ) 238for t ,i in vocab .items (): 239toks [i ]= t 240tok = ST .Tokenizer (toks , (tpath / "merges.txt" ).read_text (encoding = "utf-8" ).split ("\n" ), 241json .loads ((tpath / "token_type.json" ).read_text ())) 242ids_list = [chat_ids (tok ,p )for p in PROMPTS ] 243if progress is None and cancel_event is None : 244return measure (engine_args (cfg ),ids_list ,start_engine ,say ,host_worker_extras (),doc_prompt (tok ), 245hip = cfg .get ("backend" )== "hip" ) 246return measure (engine_args (cfg ),ids_list ,start_engine ,say ,host_worker_extras (),doc_prompt (tok ), 247hip = cfg .get ("backend" )== "hip" ,progress = progress ,cancel_event = cancel_event ) 248 249 250def engine_args (cfg :dict )-> list [str ]: 251"""The arguments the server starts this config's engine with (serve.server.engine_args), so the tuning measures 252the engine as it runs. #447: this used to read any "gpu" list as a layer split and add --layer-split auto, which 253broke a one-card config with a helper card for the expert tier ("gpu": [0] + --expert-cache-device1: the engine 254refuses a split that leaves no card without a stage), missed the "0,2" spelling, and ignored split_skip_if_fits. 255#5720: with the engine program, as the server passes it: the drafter pack follows the program (a selector-Q4 pack 256only for one that reads it), so without it the sweep engines started with another pack than the server's.""" 257from serve .server import engine_args as server_args 258return server_args (cfg ,cfg .get ("exe" )) 259 260 261def engine_error (log :str | None ,since :int = 0 )-> str | None : 262"""#447: the engine's own reason for a failed start - the last line of its log written after byte `since` that is 263its own ("strata ..." or "ERR ..."), else the last line there; None without a log or a new line.""" 264if not log : 265return None 266try : 267with open (log ,"rb" )as f : 268f .seek (since ) 269lines = [x .strip ()for x in f .read ()[- 16384 :].decode ("utf-8" ,"replace" ).splitlines ()if x .strip ()] 270except OSError : 271return None 272return next ((x for x in reversed (lines )if x .startswith (("strata" ,"ERR" ))),lines [- 1 ]if lines else None ) 273 274 275def sweep (s ,values :list ,base_tune :dict ,key :str ,label :str ,say , 276progress = None ,stage :str | None = None )-> dict : 277"""Every value, `SWEEP_ROUNDS` times, one round visiting all of them and every other round in reverse order. 278 279A single rate per value cannot order neighbours. #1332 has 0.75 to 0.95 inside each other's noise at 72.7, 28069.0, 71.0 and 71.9, and that box moved 8-28% between engine starts at an unchanged setting; a 5080/Xeon box 281reports +9.57 tok/s between two blocks at an unchanged setting (p = 0.00004), larger than the effect being 282hunted. Rotating the values inside one engine start puts that drift on every value the same number of times, 283and the median over the rounds keeps a single bad sample from deciding. The caller takes the winner from the 284medians, so every value keeps the same chance the others had. 285""" 286out = {v : []for v in values } 287if stage is not None : 288_progress (progress ,stage ,0 ,len (values )* SWEEP_ROUNDS ) 289completed = 0 290for r in range (SWEEP_ROUNDS ): 291for v in (values if r % 2 == 0 else values [::- 1 ]): 292out [v ].append (s .rate ({** base_tune ,key :v })) 293completed += 1 294if stage is not None : 295_progress (progress ,stage ,completed ,len (values )* SWEEP_ROUNDS ) 296say (f" round { r + 1 } / { SWEEP_ROUNDS } { label } : " + 297" " .join (f" { v :g } { out [ v ][ - 1 ]:.1f } " for v in values )) 298med = {v :statistics .median (out [v ])for v in values } 299say (f" { label } , median of { SWEEP_ROUNDS } : " + 300", " .join (f" { v :g } : { med [ v ]:.1f } ( { min ( out [ v ]):.1f } - { max ( out [ v ]):.1f } )" for v in values )+ 301f" -> best { max ( med , key = lambda k : med [ k ]):g } " ) 302return out 303 304 305def measure (base_args :list [str ],ids_list ,start_engine ,say = extra_workers = (),long_prompt = None ,hip :bool = False , 306* ,progress = None ,cancel_event = None )-> dict : 307t0 = time .time () 308report :dict = {} 309_check_cancel (cancel_event ) 310_progress (progress ,"loading" ,0 ,1 ) 311say (" Loading the model for the measurements ..." ) 312base_args = apply (base_args , {})# the product defaults: what the measurements must beat 313eng = start_engine (base_args ) 314try : 315info = dict (getattr (eng ,"info" , {})or {}) 316d_pcie = float (info .get ("pcie_frac" ,0.55 )) 317d_minp = float (info .get ("spec_min_p" ,0.5 )) 318d_workers = int (info .get ("pool_workers" ,0 ))or None 319s = Session (eng ,ids_list ,cancel_event ) 320s .warm_up () 321_progress (progress ,"loading" ,1 ,1 ) 322# 0. a layer split's prompt chunks (prompt read speed; independent of the decode settings below) 323pipe = 0 324# the engine's own count of prompt stages where it reports one (a split can leave one, e.g. 325# --split-skip-if-fits), else the flag 326stages = info .get ("prefill_stages" ) 327split = stages > 1 if isinstance (stages ,int )else "--layer-split" in base_args 328if long_prompt is not None and split : 329say (" Measuring the prompt chunks of the layer split ..." ) 330pipe ,rep_pipe = measure_pipe (eng ,long_prompt ,say ) 331report .update (rep_pipe ) 332# 1. the PCIe share, at the default draft floor 333by_pcie = sweep (s ,sorted (set (PCIE_FRACS )| {round (d_pcie ,2 )}), {"spec_min_p" :d_minp },"pcie_frac" , 334"PCIe share" ,say ,progress ,"pcie_share" ) 335best_pcie = max (by_pcie ,key = lambda k :statistics .median (by_pcie [k ])) 336# 2. the draft floor, at that share 337by_minp = sweep (s ,sorted (set (SPEC_MIN_PS )| {round (d_minp ,2 )}), {"pcie_frac" :best_pcie },"spec_min_p" , 338"draft floor" ,say ,progress ,"draft_floor" ) 339best_minp = max (by_minp ,key = lambda k :statistics .median (by_minp [k ])) 340# 3. the winner against the default, interleaved, the same number of rounds 341dflt ,cand = (round (d_pcie ,2 ),round (d_minp ,2 )), (best_pcie ,best_minp ) 342confirm = {dflt : [],cand : []} 343confirm_total = SWEEP_ROUNDS * 2 if cand != dflt else 1 344_progress (progress ,"confirmation" ,0 ,confirm_total ) 345if cand != dflt : 346for _ in range (SWEEP_ROUNDS ): 347for k in (dflt ,cand ): 348confirm [k ].append (s .rate ({"pcie_frac" :k [0 ],"spec_min_p" :k [1 ]})) 349_progress (progress ,"confirmation" ,sum (map (len ,confirm .values ())),confirm_total ) 350else : 351_progress (progress ,"confirmation" ,1 ,1 ) 352chosen = pick (confirm ,dflt )if cand != dflt else dflt 353report .update (default = {"pcie_frac" :dflt [0 ],"spec_min_p" :dflt [1 ],"pool_workers" :d_workers }, 354pcie_sweep = {str (k ):v for k ,v in by_pcie .items ()}, 355min_p_sweep = {str (k ):v for k ,v in by_minp .items ()}, 356confirm = {f" { k [ 0 ] } / { k [ 1 ] } " :v for k ,v in confirm .items ()}) 357finally : 358close (eng ) 359settings = {} 360if pipe : 361settings ["--prefill-pipe" ]= str (int (pipe )) 362if chosen != dflt : 363settings ["--pcie-frac" ]= f" { chosen [ 0 ]:.2f } " 364settings ["--spec-min-p" ]= f" { chosen [ 1 ]:.2f } " 365base_rate = statistics .median (confirm [chosen ])if confirm .get (chosen )else None 366# 4. fewer CPU workers (a restart each), with the chosen settings. #1337's rule covers a death during a 367# measurement too: an engine that exits mid-rate is that candidate losing; the measurements so far stay. 368if d_workers and len (worker_candidates (d_workers ,extra_workers ))> 1 : 369tuned = with_arg (with_arg (base_args ,"--pcie-frac" ,f" { chosen [ 0 ]:.2f } " ),"--spec-min-p" ,f" { chosen [ 1 ]:.2f } " ) 370by_workers = {} 371workers = worker_candidates (d_workers ,extra_workers ) 372_progress (progress ,"cpu_workers" ,0 ,len (workers )) 373for index ,w in enumerate (workers ,1 ): 374_check_cancel (cancel_event ) 375say (f" Measuring with { w } CPU workers (restarts the engine) ..." ) 376measure_candidate (start_engine ,with_arg (tuned ,"--pool-workers" ,None if w == d_workers else str (w )), 377f" { w } workers" ,say ,report ,by_workers ,w ,ids_list ,cancel_event = cancel_event ) 378_progress (progress ,"cpu_workers" ,index ,len (workers )) 379report ["workers" ]= {str (k ):v for k ,v in by_workers .items ()} 380w_best = pick (by_workers ,d_workers )if by_workers else d_workers 381if w_best != d_workers : 382settings ["--pool-workers" ]= str (w_best ) 383base_rate = statistics .median (by_workers [w_best ]) 384elif by_workers .get (d_workers ): 385base_rate = statistics .median (by_workers [d_workers ]) 386else : 387_progress (progress ,"cpu_workers" ,1 ,1 ) 388# 5. the adaptive expert tier (a restart each), with everything chosen so far. A candidate whose engine dies 389# during its own measurement is dropped like a failed start (#1337); the other candidates and every earlier 390# result survive. 391tuned = apply (base_args ,settings ) 392by_adapt = {} 393_progress (progress ,"expert_tier" ,0 ,len (ADAPT_CANDIDATES )) 394for index ,cand in enumerate (ADAPT_CANDIDATES ,1 ): 395_check_cancel (cancel_event ) 396key = "default" if cand is None else "/" .join (cand ) 397args = tuned 398for flag ,v in zip (ADAPT_FLAGS ,cand or (None ,)* len (ADAPT_FLAGS )): 399args = with_arg (args ,flag ,v ) 400say (f" Measuring the expert tier { '(the engine default)' if cand is None else 'every ' + cand [ 0 ] + ', ' + cand [ 1 ] + ' swaps, decay ' + cand [ 2 ] } (restarts the engine) ..." ) 401measure_candidate (start_engine ,args ,"the expert tier " + key ,say ,report ,by_adapt ,key ,ids_list , 402TIER_MAX_NEW ,cancel_event = cancel_event ) 403_progress (progress ,"expert_tier" ,index ,len (ADAPT_CANDIDATES )) 404a_best = pick (by_adapt ,"default" )if by_adapt else "default" 405report ["adapt" ]= by_adapt 406if a_best != "default" : 407for flag ,v in zip (ADAPT_FLAGS ,a_best .split ("/" )): 408settings [flag ]= v 409base_rate = statistics .median (by_adapt [a_best ]) 410elif by_adapt .get ("default" ): 411base_rate = statistics .median (by_adapt ["default" ]) 412# 6. HIP: the shared-expert stream fork (a restart each), with everything chosen so far. Both values are set 413# explicitly, so a value the config carried before does not decide the baseline. 414env = {} 415tuned = apply (base_args ,settings ) 416if hip and fork_is_unsafe (tuned ): 417# #3895: one Windows RX 6000 PC faulted the engine on the first request with the fork and KV streaming together. The fork is off by 418# default on AMD, so skipping the measurement changes nothing; whoever wants it sets the variable by hand. 419say (" Not measuring the shared expert on its own stream: on Windows with KV streaming (--kv-resident) it made the engine fail on the first " 420f"request on one PC (#3895). To try it anyway, put { SH_STREAM } =1 in the config's env." ) 421report ["sh_stream_skipped" ]= "windows with --kv-resident" 422elif hip : 423by_fork = {} 424for v in ("0" ,"1" ): 425_check_cancel (cancel_event ) 426say (f" Measuring the shared expert { 'on its own stream' if v == '1' else 'on the main stream (the AMD default)' } " 427" (restarts the engine) ..." ) 428measure_candidate (lambda a :start_engine (a , {SH_STREAM :v }),tuned ,f" { SH_STREAM } = { v } " ,say ,report , 429by_fork ,v ,ids_list ,cancel_event = cancel_event ) 430report ["sh_stream" ]= by_fork 431if pick (by_fork ,"0" )== "1" : 432env [SH_STREAM ]= "1" 433base_rate = statistics .median (by_fork ["1" ]) 434elif by_fork .get ("0" ): 435base_rate = statistics .median (by_fork ["0" ]) 436report ["seconds" ]= round (time .time ()- t0 ) 437report ["tok_s" ]= round (base_rate ,1 )if base_rate else None 438_check_cancel (cancel_event ) 439return {"settings" :settings ,"env" :env ,"report" :report } 440 441 442def first_line (exc :Exception )-> str : 443return str (exc ).strip ().splitlines ()[0 ][:300 ]if str (exc ).strip ()else type (exc ).__name__ 444 445def fork_is_unsafe (args )-> bool : 446"""The shared-expert fork (STRATA_SH_STREAM) with KV streaming on Windows: the one combination that has made an engine fail on its first 447request (#3895, an RX 6900 XT). Not measured there; a person can still set the variable.""" 448return sys .platform == "win32" and arg_value (args ,"--kv-resident" )is not None 449 450 451def restart (start_engine ,args ,what ,say ,report ): 452"""#1337: a later step's engine start that fails is a candidate that loses, not a failed run: what the earlier 453steps measured (and the settings they chose) must survive it. Returns the engine, or None after saying why and 454noting it in report["failed_starts"]. (The first start, for steps 1-3, is not covered: with no engine there is 455nothing measured.)""" 456try : 457return start_engine (args ) 458except Exception as e :# noqa: BLE001 - whatever the start raised (RuntimeError, EngineDied, OSError ...) 459why = first_line (e ) 460say (f" the engine did not start for { what } : { why } - this candidate is dropped, the earlier results are kept" ) 461report .setdefault ("failed_starts" , {})[what ]= why 462return None 463 464 465def measure_candidate (start_engine ,args ,what ,say ,report ,by :dict ,key ,ids_list ,max_new :int | None = None , 466cancel_event = None ): 467"""One restart-and-measure candidate (#1337): a start that fails and an engine that exits mid-measurement are 468both that candidate losing - `by[key]` gets its two rates, or report["failed_starts"] its reason. Everything 469measured earlier and the other candidates survive. An operator cancel is not a candidate death: it raises.""" 470e = restart (start_engine ,args ,what ,say ,report ) 471if e is None : 472return 473try : 474s = Session (e ,ids_list ,cancel_event ) 475s .warm_up (1 ) 476by [key ]= [s .rate (max_new = max_new ),s .rate (max_new = max_new )] 477say (f" { what } : { statistics . median ( by [ key ]):.1f } tok/s" ) 478except CalibrationCancelled : 479raise 480except Exception as exc :# noqa: BLE001 - the engine died mid-measurement: this candidate loses (#1337) 481why = first_line (exc ) 482say (f" the engine died while measuring { what } : { why } - this candidate is dropped, " 483"the earlier results are kept" ) 484report .setdefault ("failed_starts" , {})[what ]= why 485finally : 486close (e ) 487 488 489def close (eng ): 490proc = getattr (eng ,"proc" ,None ) 491if proc is None : 492return 493try : 494proc .stdin .write ("QUIT\n" ) 495proc .stdin .flush () 496proc .stdin .close () 497proc .wait (60 ) 498except Exception : 499proc .kill () 500 501 502DEFAULTS = {"--pcie-frac" :None ,"--spec-min-p" :"0.5" ,"--pool-workers" :None ,# None: the engine's own choice 503"--adapt-every" :None ,"--adapt-swaps" :None ,"--adapt-decay" :None ,"--prefill-pipe" :None } 504 505 506def apply (args :list [str ],settings :dict )-> list [str ]: 507"""`args` with the calibrated settings; a setting the calibration did not change goes back to the product 508default (setup's --spec-min-p 0.5, the engine's own PCIe share and worker count), so an older calibration's 509values never linger.""" 510out = list (args ) 511for flag ,default in DEFAULTS .items (): 512out = with_arg (out ,flag ,settings .get (flag ,default )) 513return out 514 515 516ENV_KEYS = (SH_STREAM ,) 517 518 519def apply_env (env :dict | None ,calibrated :dict | None )-> dict : 520"""The config's "env" with a calibration's engine variables: the ones it chose are set, the others in ENV_KEYS are 521removed (back to the engine's default), so an older calibration's choice never lingers.""" 522out = {k :v for k ,v in (env or {}).items ()if k not in ENV_KEYS } 523out .update (calibrated or {}) 524return out 525 526 527if __name__ == "__main__" : 528if len (sys .argv )!= 2 : 529sys .exit ("usage: calibrate.py <strata-*.json>" ) 530res = run (json .loads (Path (sys .argv [1 ]).read_text (encoding = "utf-8-sig" ))) 531json .dumps (res ,indent = 1 ))