okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
66331f9bc
main
1"""The auto-tuner: find the fastest settings for this PC, for this model, for what the user asked for. 2 3What it does (TUNING-SPEC.md sections 5-6, measured on five machines): 4 51. **Starts from the user's own configuration** (the "base") and changes one knob at a time (`tune_knobs`). It never starts 6a candidate at "the first value of every dimension". 72. Measures with the real worker over HTTP, on the engine's own clock (`tune_session`), the same fixed request set every 8time. Restart knobs are tried as **interleaved rounds**: every round runs the base and each candidate once, in a 9rotating order, so machine drift cannot favour one of them. Per-request knobs need no restart and are tried first, in 10one engine. 113. Accepts a candidate only if the **median of its per-round ratios** to the base beats the noise: at least +3%, and twice 12the drift and twice the A/A gap measured on the base runs, in every round (quick) or at least 4 of 5 (thorough 13confirm), without losing more than 2% elsewhere (prompt speed). A gain the noise can explain is not a gain: the result 14is then "your current settings are already the fastest" and nothing changes. 154. Guards before every start: free RAM, free graphics memory, other engines running, the CPU busy with something else. 16A candidate that does not fit is skipped, never started. A candidate must not use more memory than the base the user 17asked for (so "leave 20% for my work" is respected). The first crash stops the stage. 185. Only knobs whose answers are byte-identical (class exact) are chosen on their own; the others need the user's tick. 19 20Progress and time left are reported through a callback; a cancel stops at the next run and keeps nothing half-measured. 21""" 22 23from __future__import annotations 24 25import math 26import statistics 27import threading 28import time 29from dataclasses import dataclass ,field 30from typing import Any ,Callable 31 32from strata_control import engine_component ,tune_knobs ,tune_machine 33from strata_control .tune_session import RequestSet ,RunResult ,Session ,StartFailed 34 35MIN_FREE_RAM_MIB = 3584 # 3.5 GiB left for the system at every start (6.5) 36EARLY_DROP = 0.05 # a candidate this much slower than its own round's base is dropped after one round (run-to-run noise is 2-8%) 37STAGE_GAP_NOISY = 0.04 # an A/A gap above this: the machine is noisy (6.5) 38 39 40STAGNANT_WAIT_S = 60.0 # free memory that has not grown by STAGNANT_MIB after this long is not going to 41STAGNANT_MIB = 512 42 43 44class Cancelled (Exception ): 45"""The user stopped the tune; what was measured so far is kept in the result.""" 46 47 48# --------------------------------------------------------------------------- options and result 49 50@dataclass 51class Options : 52mode :str = "quick" # quick | thorough 53goal :str = "speed" # speed | room 54reserve_mib :int = 0 # graphics memory to leave free (goal room) 55ram_wish_pct :int = 0 # system memory to leave free, in percent (goal room, e.g. 20) 56use :str = "chat" # chat | coding 57allow_placement :bool = False 58allow_nonrepeatable :bool = False 59budget_s :float | None = None # quick 20 min, thorough 2 h 60margin :float = 0.03 61rounds :int | None = None # quick 2, thorough 3 (screen); confirm 5 in thorough 62confirm_pairs :int | None = None # thorough: 5 63per_request :bool = True 64min_free_ram_mib :int = MIN_FREE_RAM_MIB 65wait_ram_s :float = 600.0 66busy_pct :float = 25.0 67wait_busy_s :float = 300.0 68check_busy :bool = True 69 70def resolved (self )-> "Options" : 71o = Options (** self .__dict__ ) 72thorough = o .mode == "thorough" 73o .budget_s = o .budget_s or (7200.0 if thorough else 1200.0 ) 74o .rounds = o .rounds or (3 if thorough else 2 ) 75o .confirm_pairs = o .confirm_pairs if o .confirm_pairs is not None else (5 if thorough else 0 ) 76return o 77 78 79@dataclass 80class ArmReport : 81id :str 82label :str 83settings :dict [str ,Any ] 84env :dict [str ,Any ] 85answer :str 86status :str = "pending" # pending | tested | dropped | failed | skipped 87reason :str = "" 88runs :list [dict [str ,Any ]]= field (default_factory = list )# per round: ratios vs that round's base 89ratio_decode :float | None = None 90ratio_pp :float | None = None 91pairs :int = 0 92faster :int = 0 93won :bool = False 94 95def to_dict (self )-> dict [str ,Any ]: 96return dict (self .__dict__ ) 97 98 99@dataclass 100class TuneResult : 101outcome :str = "default_confirmed" # improved | default_confirmed | inconclusive | base_failed | cancelled 102#: what a screen shows, one of: faster | already_fastest | busy_pc | failed | stopped (see `finalize`) 103code :str = "already_fastest" 104#: why, for busy_pc: noisy | drift | not_tried (no memory or time to compare anything); for failed: start_failed | no_engine 105reason_code :str = "" 106#: the numbers a screen puts in its sentence, all plain numbers: gain_pct, base_tok_s, tuned_tok_s, noise_pct, drift_pct, 107#: minutes, pairs, faster_pairs, preset_name 108values :dict [str ,Any ]= field (default_factory = dict ) 109message :str = "" 110not_tried :int = 0 # candidates skipped for lack of free memory in a result that otherwise confirms the current settings (#5122) 111mode :str = "quick" 112seconds :float = 0.0 113waited_s :float = 0.0 # of those seconds, spent waiting (box lock, busy PC, memory) 114runs :int = 0 115base :dict [str ,Any ]= field (default_factory = dict ) 116chosen :dict [str ,Any ]= field (default_factory = dict ) 117gain_pct :float = 0.0 118gain_decode_pct :float = 0.0 119gain_pp_pct :float = 0.0 120settings :dict [str ,Any ]= field (default_factory = lambda : {"args" : {},"env" : {},"per_request" : {}}) 121answers :dict [str ,Any ]= field (default_factory = lambda : {"class" :"exact" ,"fields" : []}) 122arms :list [dict [str ,Any ]]= field (default_factory = list ) 123skipped :list [dict [str ,str ]]= field (default_factory = list ) 124noise :dict [str ,Any ]= field (default_factory = dict ) 125pairs :int = 0 126faster_pairs :int = 0 127per_request :list [dict [str ,Any ]]= field (default_factory = list ) 128per_request_confirm :dict [str ,Any ]| None = None 129notes :list [str ]= field (default_factory = list ) 130classes :list [str ]= field (default_factory = list ) 131facts :dict [str ,Any ]= field (default_factory = dict ) 132trials :list [dict [str ,Any ]]= field (default_factory = list )# every engine run, for the history store 133 134def to_dict (self )-> dict [str ,Any ]: 135return dict (self .__dict__ ) 136 137 138# --------------------------------------------------------------------------- pure decision rules 139 140def metric (run :dict [str ,Any ]| RunResult ,use :str )-> float | None : 141"""The number a configuration is judged on (6.1): decode speed for chat; for coding the geometric mean of decode 142speed and long-prompt speed (the 4K prompt when no long one was measured).""" 143get = (lambda k :run .get (k ))if isinstance (run ,dict )else (lambda k :getattr (run ,k ,None )) 144if use == "prompt" :# a prompt-only knob (the chunk size): long-prompt speed, the 4K prompt otherwise 145p = get ("pp_long_tok_s" )or get ("pp_tok_s" ) 146return float (p )if p else None 147d = get ("decode_tok_s" ) 148if not d : 149return None 150if use == "coding" : 151p = get ("pp_long_tok_s" )or get ("pp_tok_s" ) 152if p : 153return math .sqrt (d * p ) 154return float (d ) 155 156 157def median_ratio (ratios :list [float ])-> float | None : 158return statistics .median (ratios )if ratios else None 159 160 161def accept_threshold (margin :float ,aa_gap :float ,drift :float )-> float : 162"""How far above 1.0 a median ratio has to be: the margin, or twice the noise the base runs showed (6.7 rule 3).""" 163return 1.0 + max (margin ,2.0 * aa_gap ,2.0 * drift ) 164 165 166def is_win (ratios :list [float ],pp_ratios :list [float ],* ,threshold :float ,need :int | None = None )-> bool : 167"""A win: the median ratio beats the threshold, enough rounds were faster, and the prompt speed lost at most 2%.""" 168if not ratios : 169return False 170need = len (ratios )if need is None else need 171faster = sum (1 for r in ratios if r > 1.0 ) 172if faster < need or statistics .median (ratios )< threshold : 173return False 174if pp_ratios and statistics .median (pp_ratios )< 0.98 : 175return False 176return True 177 178 179def rotate (items :list [Any ],r :int )-> list [Any ]: 180k = r % len (items )if items else 0 181return items [k :]+ items [:k ] 182 183 184# --------------------------------------------------------------------------- the tuner 185 186class Tuner : 187def __init__ (self ,session :Session ,base_args :list [str ],base_env :dict [str ,str ],ctx :tune_knobs .Context , 188options :Options ,* ,progress :Callable [[dict [str ,Any ]],None ]| None = None , 189cancel :threading .Event | None = None ,history_bad :set [str ]| None = None , 190clock :Callable [[],float ]= time .monotonic ,sleep :Callable [[float ],None ]= time .sleep , 191system :Callable [[],dict [str ,Any ]]| None = None ,total_ram_mib :int | None = None , 192total_vram_mib :int | None = None ,quiet :Callable [[],str | None ]| None = None )-> None : 193self .session = session 194self .base_args = list (base_args ) 195self .base_env = dict (base_env ) 196self .ctx = ctx 197self .o = options .resolved () 198self .progress = progress or (lambda p :None ) 199self .cancel = cancel or threading .Event () 200self .history_bad = history_bad or set () 201self ._ram_gave_up :tuple [float ,float ]| None = None 202self ._base_start_avail :float | None = None # free memory (MiB) the base run was allowed to start with: what a candidate that adds nothing needs again (#5122) 203self .clock = clock 204self .sleep = sleep 205self .system = system or session .system 206self .result = TuneResult (mode = self .o .mode ) 207self .started = 0.0 208self .run_times :list [float ]= [] 209self .planned_runs = 0 210self .done_runs = 0 211self .base_runs :list [RunResult ]= [] 212self .total_ram = total_ram_mib or (tune_machine .memory ().get ("total_mib" )or 0 ) 213self .total_vram = total_vram_mib 214self .quiet = quiet 215self .storm = False 216self .speeds :list [dict [str ,Any ]]= [] 217self .waited_s = 0.0 # time spent waiting for the box lock, the PC to be quiet or memory: not the user's budget 218 219# ---- bookkeeping 220def _elapsed (self )-> float : 221return self .clock ()- self .started - self .waited_s 222 223def _say (self ,stage :str ,message :str ,** extra :Any )-> None : 224elapsed = self ._elapsed () 225avg = statistics .mean (self .run_times )if self .run_times else 150.0 226remaining = max (0 ,self .planned_runs - self .done_runs ) 227eta = min (max (0.0 ,self .o .budget_s - elapsed ),remaining * avg )if self .planned_runs else None 228self .progress ({"stage" :stage ,"message" :message ,"elapsed_s" :round (elapsed ),"runs_done" :self .done_runs , 229"runs_planned" :self .planned_runs ,"eta_s" :None if eta is None else round (eta ), 230# what each measurement so far came to, for the live readout (label, decode tok/s as the goal judges it) 231"speeds" :list (self .speeds ),** extra }) 232 233def _check_cancel (self )-> None : 234if self .cancel .is_set (): 235raise Cancelled () 236 237def _over_budget (self ,reserve_s :float = 0.0 )-> bool : 238return self ._elapsed ()+ reserve_s > self .o .budget_s 239 240def _avg_run (self )-> float : 241return statistics .mean (self .run_times )if self .run_times else 150.0 242 243# ---- guards 244def _wait_for_quiet (self )-> None : 245"""Pause while another engine runs or the CPU is busy with something else (6.5, 6.7 rule 5).""" 246if not self .o .check_busy : 247return 248waited = 0.0 249while True : 250why = self .quiet ()if self .quiet else self ._machine_busy () 251if not why : 252return 253if waited >= self .o .wait_busy_s : 254self .result .notes .append (f"measured while the machine was busy ( { why } )" ) 255return 256self ._say ("waiting" ,f"Waiting for the PC to be quiet ( { why } )" ) 257self ._check_cancel () 258self .sleep (10.0 ) 259waited += 10.0 260 261def _machine_busy (self )-> str | None : 262eng = tune_machine .other_engines () 263if eng : 264return "another Strata engine is running" 265busy = tune_machine .cpu_busy_percent (1.0 ) 266if busy is not None and busy > self .o .busy_pct : 267return f"the CPU is { busy :.0f } % busy" 268return None 269 270def _ram_guard (self ,delta_mib :int ,label :str ,wait_s :float | None = None )-> str | None : 271"""None when a start fits; otherwise the plain reason it does not. Waiting ends early when the free memory does not 272grow (a loaded model keeps it): ten minutes per candidate made a tuning run last for hours (#3490).""" 273waited = 0.0 274first_avail :float | None = None 275while True : 276mem = self .system ().get ("memory" , {}) 277avail = mem .get ("available_mib" ) 278if avail is None : 279return None # unreadable: the engine's own guard decides 280need = self .o .min_free_ram_mib + delta_mib 281base_rss = self .base_runs [0 ].rss_peak_mib if self .base_runs else None 282if base_rss : 283need += base_rss 284elif self .total_ram : 285need = max (need ,self .o .min_free_ram_mib ) 286if self .base_runs and self ._base_start_avail and self .base_runs [0 ].status == "PASS" : 287# like for like (#5122): the base run started with this much free and ran; its peak RSS counts file pages the kernel can take back, so 288# "peak + floor" can ask for more than the PC had at the base start. A candidate needs what the base had plus what it adds. 289need = min (need ,max (self ._base_start_avail + delta_mib ,self .o .min_free_ram_mib + delta_mib )) 290if avail >= need : 291if not self .base_runs : 292self ._base_start_avail = float (avail ) 293return None 294reason = (f"not enough free memory to start it safely ( { avail / 1024 :.1f } GiB free, " 295f" { need / 1024 :.1f } GiB needed)" ) 296prior = self ._ram_gave_up 297if prior is not None and avail <= prior [1 ]+ STAGNANT_MIB : 298return reason # an earlier wait found nothing freed: waiting again for a candidate that needs less, but still more than is free, repeats it (#4895) 299if first_avail is None : 300first_avail = avail 301stagnant = waited >= STAGNANT_WAIT_S and avail <= first_avail + STAGNANT_MIB 302if stagnant or waited >= (self .o .wait_ram_s if wait_s is None else wait_s ): 303self ._ram_gave_up = (need ,avail ) 304return reason 305self ._say ("waiting" ,f"Waiting for memory to be freed before trying { label } " 306f"( { avail / 1024 :.1f } GiB free, { need / 1024 :.1f } GiB needed)" ) 307self ._check_cancel () 308self .sleep (10.0 ) 309waited += 10.0 310 311# ---- one engine run 312def _run (self ,args :list [str ],env :dict [str ,str | None ],spec :RequestSet ,label :str , 313points :Callable [[Any ],None ]| None = None ,delta_mib :int = 0 )-> RunResult : 314self ._check_cancel () 315t0 = self .clock () 316 317entered :list [float ]= [] 318 319def pre_start ()-> None : 320# checked again once the box lock is ours: another stream's engine may have come and gone while we waited 321lock_got = self .clock () 322self .waited_s += lock_got - t0 323self ._wait_for_quiet () 324why = self ._ram_guard (delta_mib ,label ,wait_s = 60.0 ) 325self .waited_s += self .clock ()- lock_got 326if why : 327raise StartFailed ("SKIPPED" ,why ) 328entered .append (self .clock ()) 329 330try : 331with self .session .engine (args ,env ,pre_start = pre_start )as eng : 332res = eng .measure (spec ) 333if points is not None and res .status == "PASS" : 334points (eng ) 335except StartFailed as e : 336res = RunResult (status = e .status ,reason = e .reason ) 337dt = self .clock ()- (entered [0 ]if entered else t0 )# the run itself, not the waiting before it 338if res .status != "SKIPPED" : 339self .run_times .append (dt ) 340self .done_runs += 1 341self .result .runs += 1 342res .wall_s = round (dt ,1 ) 343self .result .trials .append ({"label" :label ,"args" :args ,"env" :env ,"status" :res .status ,"reason" :res .reason , 344"decode_tok_s" :res .decode_tok_s ,"pp_tok_s" :res .pp_tok_s , 345"rss_peak_mib" :res .rss_peak_mib ,"load_s" :res .load_s ,"at" :time .time ()}) 346return res 347 348# ---- the whole job 349def run (self )-> TuneResult : 350self .started = self .clock () 351r = self .result 352try : 353self ._run_stages () 354except Cancelled : 355r .outcome ,r .message = "cancelled" ,"Stopped. Your settings were not changed." 356r .seconds = round (self .clock ()- self .started ,1 ) 357r .waited_s = round (self .waited_s ,1 ) 358self .finalize (r ) 359return r 360 361@staticmethod 362def finalize (r :"TuneResult" )-> None : 363"""The structured outcome a screen shows inside the tune dialog (owner feedback, item 13): a code and plain numbers, so no 364screen has to read a sentence. faster / already_fastest / busy_pc (noisy, drifting, or nothing could be compared) / 365failed / stopped. `busy_pc` is a result, not an error: nothing was changed and trying again later is the answer.""" 366r .code = {"improved" :"faster" ,"default_confirmed" :"already_fastest" ,"inconclusive" :"busy_pc" , 367"base_failed" :"failed" ,"cancelled" :"stopped" }.get (r .outcome ,"failed" ) 368if r .outcome == "default_confirmed" and r .noise .get ("noisy" ): 369r .reason_code = r .reason_code or "noisy_but_nothing_better" 370base = (r .base or {}).get ("decode_tok_s" ) 371tuned = (r .chosen or {}).get ("decode_tok_s" ) 372r .values = {"gain_pct" :r .gain_pct ,"gain_decode_pct" :r .gain_decode_pct ,"base_tok_s" :base ,"tuned_tok_s" :tuned , 373"noise_pct" :round (100 * (r .noise or {}).get ("spread" ,0.0 ),1 )if r .noise else None , 374"drift_pct" :round (100 * (r .noise or {}).get ("drift" ,0.0 ),1 )if r .noise else None , 375"minutes" :round (r .seconds / 60.0 - r .waited_s / 60.0 ,1 ),"pairs" :r .pairs ,"faster_pairs" :r .faster_pairs , 376"not_tried" :r .not_tried } 377 378def _spec (self )-> RequestSet : 379long_tokens = 0 380if self .ctx .context_tokens >= 65536 : 381# long contexts mean long prompts: the chunk size (spec 4.3) only shows on a long one 382long_tokens = min (98304 ,int (0.75 * self .ctx .context_tokens )) 383elif self .o .use == "coding" and self .o .mode == "thorough" : 384long_tokens = min (28000 ,int (0.8 * self .ctx .context_tokens )) 385return RequestSet (warmups = 2 if self .o .mode == "thorough" else 1 ,decodes = 5 ,decode_tokens = 200 , 386pp_tokens = 4096 if self .ctx .context_tokens >= 6000 else 1024 ,long_tokens = long_tokens ) 387 388def _run_stages (self )-> None : 389r ,o = self .result ,self .o 390spec = self ._spec () 391self .planned_runs = 6 # corrected once the candidates are known 392self ._say ("start" ,"Checking your PC before the first measurement" ) 393 394# ---- stage 1: the base run (the user's configuration, untouched), with the per-request guard in the same engine 395why = self ._ram_guard (0 ,"your current settings" ) 396if why : 397r .outcome ,r .message = "base_failed" ,"Not tuned: " + why 398r .reason_code = "no_memory" 399return 400pr_rows :list [dict [str ,Any ]]= [] 401 402def per_request_points (eng :Any )-> None : 403if o .per_request : 404pr_rows .extend (self ._per_request_stage (eng )) 405 406self ._say ("base" ,"Measuring your current settings" ) 407base1 = self ._run (self .base_args , {},spec ,"base" ,points = per_request_points ) 408self .base_runs .append (base1 ) 409if base1 .status == "PASS" and metric (base1 ,o .use ): 410self .speeds .append ({"label" :"base" ,"tok_s" :round (float (metric (base1 ,o .use )),1 )}) 411self ._say ("base" ,"Measured your current settings" ) 412if base1 .status != "PASS" or not metric (base1 ,o .use ): 413r .outcome = "base_failed" 414r .reason_code = "start_failed" 415r .message = "Your current settings could not be measured: " + (base1 .reason or base1 .status ) 416return 417r .base = base1 .to_dict () 418r .facts = dict (base1 .facts ) 419self .ctx .facts = dict (base1 .facts ) 420if base1 .vram_used_mib is not None and self .total_vram is None : 421cards = [g for g in self .system ().get ("gpus" , [])if g .get ("vram_total_mib" )] 422self .total_vram = sum (g ["vram_total_mib" ]for g in cards )if cards else None 423r .per_request = pr_rows 424r .classes = tune_knobs .machine_classes (self .ctx ) 425 426# ---- stage 2: plan the candidates for this machine; how many depends on the time chosen 427planned ,skipped = tune_knobs .plan_arms (self .ctx ,mode = o .mode ,history_bad = self .history_bad ) 428r .skipped = skipped 429per_arm = o .rounds or 2 430if o .mode == "thorough" : 431n_arms = len (planned ) 432else : 433left = int ((o .budget_s - self ._elapsed ())/ max (1.0 ,self ._avg_run ())) 434fixed = (per_arm - 1 )+ 1 # extra base rounds, the final base 435n_arms = min (len (planned ),max (0 , (left - fixed )// per_arm )) 436for p in planned [n_arms :]: 437skipped .append ({"id" :p .arm .id ,"label" :p .arm .label ,"reason" :"left out to stay inside the time you chose" }) 438planned = planned [:n_arms ] 439arms = [ArmReport (p .arm .id ,p .arm .label ,dict (p .args ),dict (p .env ),p .arm .answer )for p in planned ] 440by_id = {a .id :a for a in arms } 441by_use = {p .arm .id : ("prompt" if p .arm .metric == "prompt" else o .use )for p in planned } 442self .planned_runs = self .done_runs + per_arm * (len (planned )+ 1 )- 1 + 1 + (o .confirm_pairs or 0 )* 2 443if not planned : 444self ._say ("plan" ,"No other setting is worth trying on this PC" ) 445 446# ---- stage 3: interleaved rounds. Every round runs the base and each live candidate once, in a rotating order. 447round_runs :list [dict [str ,RunResult ]]= [{}for _ in range (per_arm )] 448round_runs [0 ]["base" ]= base1 449alive = list (planned ) 450stop = False 451for rnd in range (per_arm ): 452if stop or self .storm or (rnd > 0 and not alive ): 453break 454for item in rotate (["base" ]+ alive ,rnd ): 455self ._check_cancel () 456if self ._over_budget (reserve_s = 2 * self ._avg_run ()): 457r .notes .append ("the time you chose ran out before every round finished" ) 458stop = True 459break 460if item == "base" : 461if rnd == 0 : 462continue # round 1's base is the run above 463if self ._ram_guard (0 ,"your current settings" ): 464r .notes .append ("not enough free memory for another measurement of your current settings; the search stopped" ) 465stop = True 466break 467self ._say ("rounds" ,f"Measuring your current settings again (round { rnd + 1 } of { per_arm } )" ) 468b = self ._run (self .base_args , {},spec ,f"base r { rnd + 1 } " ) 469if b .status == "SKIPPED" : 470r .notes .append ("not enough free memory for another measurement of your current settings; the search stopped" ) 471self .storm = stop = True 472break 473if b .status != "PASS" : 474r .notes .append ("your current settings failed to start a second time; the search stopped" ) 475self .storm = stop = True 476break 477self .base_runs .append (b ) 478round_runs [rnd ]["base" ]= b 479continue 480p = item 481rep = by_id [p .arm .id ] 482why = self ._ram_guard (p .arm .ram_delta_mib ,p .arm .label ) 483if why : 484rep .status ,rep .reason = "skipped" ,why 485alive = [x for x in alive if x .arm .id != p .arm .id ] 486continue 487self ._say ("rounds" ,f"Trying: { p . arm . label } (round { rnd + 1 } of { per_arm } )" ,arm = p .arm .id ) 488res = self ._run (tune_knobs .apply_to_argv (self .base_args ,p .args ),dict (p .env ),spec ,p .arm .id , 489delta_mib = p .arm .ram_delta_mib ) 490if res .status == "SKIPPED" : 491rep .status ,rep .reason = "skipped" ,res .reason 492alive = [x for x in alive if x .arm .id != p .arm .id ] 493continue 494if res .status != "PASS" : 495rep .status ,rep .reason = "failed" ,f" { res . status } : { res . reason } " 496alive = [x for x in alive if x .arm .id != p .arm .id ] 497if res .status == "OOM" : 498self .storm = stop = True 499r .notes .append ("an engine ran out of memory; the search stopped (nothing was retried)" ) 500break 501continue 502if metric (res ,o .use ): 503self .speeds .append ({"label" :p .arm .label ,"tok_s" :round (float (metric (res ,o .use )),1 )}) 504over = self ._memory_overrun (res ,base1 ) 505if over : 506rep .status ,rep .reason = "failed" ,over 507alive = [x for x in alive if x .arm .id != p .arm .id ] 508continue 509round_runs [rnd ][p .arm .id ]= res 510# a candidate that lost by more than the margin against its own round's base is dropped from later rounds 511for p in list (alive ): 512b ,c = round_runs [rnd ].get ("base" ),round_runs [rnd ].get (p .arm .id ) 513um = by_use [p .arm .id ] 514m_b ,m_c = (metric (b ,um )if b else None ), (metric (c ,um )if c else None ) 515if m_b and m_c and m_c / m_b < 1.0 - max (o .margin ,EARLY_DROP ): 516by_id [p .arm .id ].status = "dropped" 517by_id [p .arm .id ].reason = f"slower by { 100 * ( 1 - m_c / m_b ):.1f } % in round { rnd + 1 } " 518alive = [x for x in alive if x .arm .id != p .arm .id ] 519data :dict [str ,list [tuple [RunResult ,RunResult ]]]= { 520a .id : [(rr ["base" ],rr [a .id ])for rr in round_runs if a .id in rr and "base" in rr ]for a in arms } 521 522# ---- noise: the A/A gap between base runs, the drift against a final base run 523end_base :RunResult | None = None 524ran_any = any (len (v )for v in data .values ()) 525if not self .storm and not self .cancel .is_set ()and ran_any and not self ._over_budget ()and not self ._ram_guard (0 ,"your current settings" ): 526self ._say ("drift" ,"Measuring your current settings once more to check the PC did not drift" ) 527end_base = self ._run (self .base_args , {},spec ,"base end" ) 528if end_base .status == "PASS" : 529self .base_runs .append (end_base ) 530mb = [metric (b ,o .use )for b in self .base_runs if metric (b ,o .use )] 531aa = abs (mb [1 ]/ mb [0 ]- 1.0 )if len (mb )>= 2 else 0.0 532drift = abs (mb [- 1 ]/ mb [0 ]- 1.0 )if len (mb )>= 3 else (aa if len (mb )== 2 else 0.0 ) 533spread = (max (mb )/ min (mb )- 1.0 )if len (mb )>= 2 else 0.0 534r .noise = {"aa_gap" :round (aa ,4 ),"drift" :round (drift ,4 ),"spread" :round (spread ,4 ), 535"base_runs" : [round (x ,2 )for x in mb ],"noisy" :spread > STAGE_GAP_NOISY } 536threshold = accept_threshold (o .margin ,aa ,drift ) 537 538# ---- evaluate the candidates 539winners :list [ArmReport ]= [] 540for p in planned : 541rep = by_id [p .arm .id ] 542rows = data [p .arm .id ] 543if rep .status in ("failed" ,"skipped" )or not rows : 544continue 545ratios ,pps = [], [] 546um = by_use [p .arm .id ] 547for b ,c in rows : 548mc ,mbb = metric (c ,um ),metric (b ,um ) 549if mc and mbb : 550ratios .append (mc / mbb ) 551# the other side of the trade: prompt speed for a decode knob, decode speed for a prompt knob 552if um == "prompt" : 553if c .decode_tok_s and b .decode_tok_s : 554pps .append (c .decode_tok_s / b .decode_tok_s ) 555elif c .pp_tok_s and b .pp_tok_s : 556pps .append (c .pp_tok_s / b .pp_tok_s ) 557rep .pairs = len (ratios ) 558rep .faster = sum (1 for x in ratios if x > 1.0 ) 559rep .ratio_decode = round (statistics .median (ratios ),4 )if ratios else None 560rep .ratio_pp = round (statistics .median (pps ),4 )if pps else None 561rep .runs = [{"ratio" :round (x ,4 )}for x in ratios ] 562if rep .status == "dropped" : 563continue 564rep .status = "tested" 565if len (ratios )>= per_arm and is_win (ratios ,pps ,threshold = threshold ): 566rep .won = True 567winners .append (rep ) 568r .arms = [a .to_dict ()for a in arms ] 569 570if r .noise ["noisy" ]and not winners : 571r .notes .append (f"the PC was noisy ( { spread * 100 :.1f } % between identical runs)" ) 572 573# ---- stage 4: stack the winners, then (thorough) confirm against the base with more pairs 574fu = o .use 575chosen_args :dict [str ,Any ]= {} 576chosen_env :dict [str ,str | None ]= {} 577final_pairs :list [tuple [RunResult ,RunResult ]]= [] 578if winners : 579winners .sort (key = lambda a :a .ratio_decode or 0.0 ,reverse = True ) 580incumbent = [winners [0 ]]# gains did not stack in three stacking runs (spec 1.10): the best single knob 581if len (winners )> 1 : 582r .notes .append ("more than one setting helped; only the best one is kept because gains did not add up in the study" ) 583for w in incumbent : 584chosen_args .update (w .settings ) 585chosen_env .update (w .env ) 586fu = by_use [incumbent [0 ].id ] 587need_confirm = (o .confirm_pairs or 0 )> 0 588if need_confirm and not self ._over_budget (reserve_s = 2 * self ._avg_run ()): 589n = o .confirm_pairs or 2 590self ._say ("confirm" ,"Confirming the combined result against your current settings" ) 591final_pairs = self ._confirm (chosen_args ,chosen_env ,spec ,n ,fu ) 592ratios = [metric (c ,fu )/ metric (b ,fu )for b ,c in final_pairs if metric (c ,fu )and metric (b ,fu )] 593pps = [c .decode_tok_s / b .decode_tok_s for b ,c in final_pairs if c .decode_tok_s and b .decode_tok_s ]if fu == "prompt" \ 594else [c .pp_tok_s / b .pp_tok_s for b ,c in final_pairs if c .pp_tok_s and b .pp_tok_s ] 595need = max (2 ,int (math .ceil (0.8 * len (ratios ))))if len (ratios )>= 5 else len (ratios ) 596if not (ratios and is_win (ratios ,pps ,threshold = threshold ,need = need )): 597# the stack did not hold; fall back to the best single winner, which already won its own pairs 598if len (incumbent )> 1 : 599r .notes .append ("the combination did not beat the best single change; keeping the best single change" ) 600best = incumbent [0 ] 601chosen_args ,chosen_env = dict (best .settings ),dict (best .env ) 602final_pairs = [(b ,c )for b ,c in data [best .id ]] 603else : 604winners ,chosen_args ,chosen_env ,final_pairs = [], {}, {}, [] 605r .notes .append ("the gain did not hold up in the confirmation, so nothing was changed" ) 606else : 607pass 608else : 609best = incumbent [0 ] 610chosen_args ,chosen_env = dict (best .settings ),dict (best .env ) 611final_pairs = list (data [best .id ]) 612if not final_pairs and winners : 613final_pairs = list (data [winners [0 ].id ]) 614 615fu_final = fu 616# ---- per-request winners (found in the base engine): keep only the ones that won every round 617per_request_chosen = {row ["key" ]:row ["value" ]for row in r .per_request if row .get ("won" )} 618if per_request_chosen and not self .storm and not self .cancel .is_set ()and not self ._over_budget (reserve_s = self ._avg_run ()): 619# a per-request win from one engine's quick points is only a candidate: confirm it in a fresh engine, 5 interleaved rounds 620self ._say ("confirm" ,"Confirming the settings that need no restart" ) 621r .per_request_confirm = self ._confirm_per_request (per_request_chosen ,spec ,threshold ) 622if not r .per_request_confirm ["ok" ]: 623r .notes .append ("a per-request setting looked faster in the first test but did not hold in the confirmation, so it was not kept" ) 624per_request_chosen = {} 625elif per_request_chosen : 626r .notes .append ("a per-request setting looked faster but could not be confirmed in the time left, so it was not kept" ) 627per_request_chosen = {} 628 629# ---- result 630if end_base is not None and end_base .status == "PASS" and drift > 0.03 and winners : 631gain_guess = statistics .median ([metric (c ,fu )/ metric (b ,fu )for b ,c in final_pairs ])- 1.0 if final_pairs else 0.0 632if gain_guess < 2 * drift : 633chosen_args ,chosen_env ,winners ,final_pairs = {}, {}, [], [] 634per_request_chosen = {} 635r .outcome = "inconclusive" 636r .reason_code = "drift" 637r .message = ("The PC changed speed while measuring (about %.0f%%), more than the gain found, so nothing " 638"was changed. Try again when nothing else is running." % (drift * 100 )) 639if r .outcome != "inconclusive" : 640if chosen_args or chosen_env or per_request_chosen : 641r .outcome = "improved" 642elif r .noise ["noisy" ]and (spread > 2 * STAGE_GAP_NOISY ): 643r .outcome = "inconclusive" 644r .reason_code = "noisy" 645r .message = "The PC was too noisy to tell settings apart, so nothing was changed. Try again when it is idle." 646elif arms and not any (a .status in ("tested" ,"dropped" ,"failed" )for a in arms )and not r .per_request : 647# candidates were planned but none could be measured (no free memory, no time): that is not "already the fastest" 648r .outcome = "inconclusive" 649r .reason_code = "not_tried" 650r .message = ("Other settings could not be tried (not enough free memory or time), so nothing was compared and nothing was " 651"changed. Try again when the PC is quiet." ) 652else : 653r .outcome = "default_confirmed" 654r .not_tried = sum (1 for a in arms if a .status == "skipped" and "memory" in (a .reason or "" )) 655if r .not_tried :# "already the fastest" would claim a comparison that never happened (#5122) 656r .reason_code = r .reason_code or "some_not_tried" 657r .message = f" { r . not_tried } setting { 's' if r . not_tried != 1 else '' } could not be tried: not enough free memory" 658else : 659r .message = "Your current settings are already the fastest we found. Nothing was changed." 660if r .noise .get ("noisy" )and not r .not_tried : 661r .message += " (The PC was busy while measuring, so a small gain could be hidden.)" 662r .settings = {"args" :chosen_args ,"env" :chosen_env ,"per_request" :per_request_chosen } 663cls ,fields = "exact" , [] 664for rep in arms : 665if rep .won and any (k in chosen_args for k in rep .settings )or (rep .won and any (k in chosen_env for k in rep .env )): 666if tune_knobs .ANSWER_ORDER .index (rep .answer )> tune_knobs .ANSWER_ORDER .index (cls ): 667cls = rep .answer 668if rep .answer != "exact" : 669fields += list (rep .settings )+ list (rep .env ) 670for key in per_request_chosen : 671for row in tune_knobs .PER_REQUEST : 672if row ["key" ]== key and tune_knobs .ANSWER_ORDER .index (row ["answer" ])> tune_knobs .ANSWER_ORDER .index (cls ): 673cls = row ["answer" ] 674if row ["key" ]== key and row ["answer" ]!= "exact" : 675fields .append (key ) 676r .answers = {"class" :cls ,"fields" :sorted (set (fields )),"default_repeatable" :not tune_knobs .default_unsteady (self .ctx )} 677if final_pairs : 678fu = fu_final 679ratios = [metric (c ,fu )/ metric (b ,fu )for b ,c in final_pairs if metric (c ,fu )and metric (b ,fu )] 680pps = [c .pp_tok_s / b .pp_tok_s for b ,c in final_pairs if c .pp_tok_s and b .pp_tok_s ] 681r .pairs = len (ratios ) 682r .faster_pairs = sum (1 for x in ratios if x > 1.0 ) 683r .gain_pct = round (100 * (statistics .median (ratios )- 1.0 ),1 )if ratios else 0.0 684r .gain_pp_pct = round (100 * (statistics .median (pps )- 1.0 ),1 )if pps else 0.0 685dec = [c .decode_tok_s / b .decode_tok_s for b ,c in final_pairs if c .decode_tok_s and b .decode_tok_s ] 686r .gain_decode_pct = round (100 * (statistics .median (dec )- 1.0 ),1 )if dec else 0.0 687c_runs = [c for _ ,c in final_pairs ] 688r .chosen = {"decode_tok_s" :round (statistics .median ([c .decode_tok_s for c in c_runs if c .decode_tok_s ]),2 ) 689if any (c .decode_tok_s for c in c_runs )else None , 690"pp_tok_s" :round (statistics .median ([c .pp_long_tok_s or c .pp_tok_s for c in c_runs if c .pp_long_tok_s or c .pp_tok_s ]),1 ) 691if any (c .pp_tok_s for c in c_runs )else None , 692"rss_peak_mib" :max ([c .rss_peak_mib for c in c_runs if c .rss_peak_mib ]or [None ])if any (c .rss_peak_mib for c in c_runs )else None , 693"vram_used_mib" :max ([c .vram_used_mib for c in c_runs if c .vram_used_mib ]or [None ])if any (c .vram_used_mib for c in c_runs )else None } 694elif r .outcome == "improved" and per_request_chosen : 695r .gain_pct = r .gain_decode_pct = round (100 * ((r .per_request_confirm or {}).get ("ratio" ,1.0 )- 1.0 ),1 ) 696r .pairs = len ((r .per_request_confirm or {}).get ("ratios" , [])) 697r .faster_pairs = sum (1 for x in (r .per_request_confirm or {}).get ("ratios" , [])if x > 1.0 ) 698r .chosen = dict (r .base ) 699else : 700r .chosen = {k :r .base .get (k )for k in ("decode_tok_s" ,"pp_tok_s" ,"rss_peak_mib" ,"vram_used_mib" )} 701if r .outcome == "improved" : 702r .message = "+%.0f%% faster answers" % r .gain_pct if r .gain_pct >= 0.5 else "slightly faster" 703self ._say ("done" ,r .message or "Done" ) 704 705# ---- helpers 706def _memory_overrun (self ,res :RunResult ,base :RunResult )-> str | None : 707"""A candidate that takes more memory than the base the user asked for is not a candidate (their wish, 20% left 708for work, is a promise about memory).""" 709if res .rss_peak_mib and base .rss_peak_mib and res .rss_peak_mib > base .rss_peak_mib * 1.05 + 512 and self .o .goal == "room" : 710return "it needs more memory than your current settings, which would eat into the memory you wanted left free" 711if res .min_avail_mib is not None and res .min_avail_mib < self .o .min_free_ram_mib and ( 712base .min_avail_mib is None or res .min_avail_mib < base .min_avail_mib - 512 ):# a RAM-bound base can sit below the floor itself 713return "it left the PC with too little free memory" 714if self .o .goal == "room" and self .o .ram_wish_pct and self .total_ram and res .min_avail_mib is not None and \ 715base .min_avail_mib is not None : 716if res .min_avail_mib < base .min_avail_mib - max (512 ,0.03 * self .total_ram ): 717return "it left less memory free than your current settings" 718if self .o .goal == "room" and res .vram_used_mib is not None and base .vram_used_mib is not None and \ 719res .vram_used_mib > base .vram_used_mib + 256 : 720return "it uses more graphics memory than your current settings" 721if self .o .goal == "room" and self .o .reserve_mib and self .total_vram and res .vram_used_mib is not None and \ 722base .vram_used_mib is not None and self .total_vram - base .vram_used_mib >= self .o .reserve_mib - 128 and \ 723self .total_vram - res .vram_used_mib < self .o .reserve_mib - 128 : 724return "it would not leave the graphics memory you wanted free" 725return None 726 727def _confirm (self ,args :dict [str ,Any ],env :dict [str ,str | None ],spec :RequestSet ,pairs :int ,use :str | None = None )-> list [tuple [RunResult ,RunResult ]]: 728"""Interleaved pairs of the combined settings against the base (the order alternates).""" 729out :list [tuple [RunResult ,RunResult ]]= [] 730cand_args = tune_knobs .apply_to_argv (self .base_args ,args ) 731for i in range (pairs ): 732self ._check_cancel () 733if self ._over_budget (reserve_s = 2 * self ._avg_run ()): 734self .result .notes .append ("confirmation stopped early: the time you chose ran out" ) 735break 736first = "cand" if i % 2 == 0 else "base" 737runs :dict [str ,RunResult ]= {} 738for who in (first ,"base" if first == "cand" else "cand" ): 739self ._say ("confirm" ,f"Confirming (pair { i + 1 } of { pairs } )" ) 740runs [who ]= self ._run (cand_args if who == "cand" else self .base_args ,env if who == "cand" else {},spec , 741f"confirm { who } { i + 1 } " ) 742if runs ["cand" ].status == "PASS" and runs ["base" ].status == "PASS" : 743use = use or self .o .use 744if metric (runs ["cand" ],use )and metric (runs ["base" ],use ): 745out .append ((runs ["base" ],runs ["cand" ])) 746self .base_runs .append (runs ["base" ]) 747else : 748break 749return out 750 751def _per_request_stage (self ,eng :Any )-> list [dict [str ,Any ]]: 752"""Per-request settings against the engine's own choice, in this one engine, 3 interleaved rounds (6.3 step 2). 753 754A **control** point sends a per-request value equal to what the engine already uses (the configuration's own 755`--spec-min-p`), so it changes nothing: whatever it "gains" is the bias of sending a setting at all (the first run 756after an idle gap, the order). A value must beat the default by the margin AND beat the control by the margin in every 757round. A win here is only a candidate: the tuner confirms it afterwards in a fresh engine. One value per key can win.""" 758points :list [tuple [str ,Any ]]= [] 759for spec in tune_knobs .PER_REQUEST : 760if self .ctx .backend not in spec ["backends" ]: 761continue 762if spec ["answer" ]!= "exact" and not tune_knobs .allowed (spec ["answer" ],self .ctx ): 763continue 764for v in spec ["values" ]: 765points .append ((spec ["key" ],v )) 766if not points : 767return [] 768own = tune_knobs ._current (self .ctx .base_args ,"--spec-min-p" ) 769control = ("control" ,float (own ))if own not in (None ,"" )and self .ctx .backend != "metal" else None 770rounds = 3 771default :dict [int ,list [float ]]= {} 772vals :dict [tuple [str ,Any ],dict [int ,float ]]= {pt : {}for pt in points + ([control ]if control else [])} 773self ._say ("per_request" ,"Trying settings that need no restart" ) 774for rnd in range (rounds ): 775order = rotate ([None ]+ points + ([control ]if control else [])+ [None ],rnd ) 776for item in order : 777self ._check_cancel () 778if item is None : 779d = eng .decode_once (None ,200 ) 780if d : 781default .setdefault (rnd , []).append (d ) 782else : 783key = "spec_min_p" if item [0 ]== "control" else item [0 ] 784d = eng .decode_once ({key :item [1 ]},200 ) 785if d : 786vals [item ][rnd ]= d 787ref = {i :statistics .mean (v )for i ,v in default .items ()if v } 788ctl = [vals [control ][i ]/ ref [i ]for i in range (rounds )if control and i in vals [control ]and i in ref ]if control else [] 789rows :list [dict [str ,Any ]]= [] 790for pt in points : 791ratios = [vals [pt ][i ]/ ref [i ]for i in range (rounds )if i in vals [pt ]and i in ref ] 792adj = [ratios [j ]/ ctl [j ]for j in range (min (len (ratios ),len (ctl )))]if ctl else ratios 793won = len (ratios )== rounds and len (adj )== rounds and all (x >= 1.0 + self .o .margin for x in adj ) \ 794and all (x >= 1.0 + self .o .margin for x in ratios ) 795rows .append ({"key" :pt [0 ],"value" :pt [1 ],"ratios" : [round (x ,4 )for x in ratios ],"control_ratios" : [round (x ,4 )for x in ctl ], 796"ratio" :round (statistics .median (adj ),4 )if adj else None ,"won" :won }) 797best :dict [str ,dict [str ,Any ]]= {} 798for row in rows : 799if row ["won" ]and (row ["key" ]not in best or row ["ratio" ]> best [row ["key" ]]["ratio" ]): 800best [row ["key" ]]= row 801for row in rows : 802row ["won" ]= best .get (row ["key" ])is row 803return rows 804 805def _confirm_per_request (self ,chosen :dict [str ,Any ],spec :RequestSet ,threshold :float )-> dict [str ,Any ]: 806"""5 interleaved rounds in a fresh engine of the chosen per-request settings against the engine's own choice (two decodes 807each, the order alternating). Kept only if the median ratio beats the threshold in at least 4 of 5 rounds.""" 808ratios :list [float ]= [] 809 810def points (eng :Any )-> None : 811for i in range (5 ): 812self ._check_cancel () 813got :dict [str ,list [float ]]= {"d" : [],"t" : []} 814for who in (("d" ,"t" )if i % 2 == 0 else ("t" ,"d" )): 815for _ in range (2 ): 816v = eng .decode_once (chosen if who == "t" else None ,200 ) 817if v : 818got [who ].append (v ) 819if got ["d" ]and got ["t" ]: 820ratios .append (statistics .mean (got ["t" ])/ statistics .mean (got ["d" ])) 821 822res = self ._run (self .base_args , {},spec ,"confirm per-request" ,points = points ) 823ok = res .status == "PASS" and len (ratios )== 5 and sum (1 for x in ratios if x > 1.0 )>= 4 \ 824and statistics .median (ratios )>= threshold 825return {"ok" :ok ,"ratios" : [round (x ,4 )for x in ratios ],"ratio" :round (statistics .median (ratios ),4 )if ratios else None , 826"status" :res .status } 827 828 829# --------------------------------------------------------------------------- building a tuner from a run configuration 830 831def split_args (argv :list [str ])-> list [str ]: 832return [str (a )for a in argv ] 833 834 835def detect_family (args :list [str ])-> str : 836for i ,a in enumerate (args ): 837if a == "--mtp" and i + 1 < len (args ): 838return "qwen36" if str (args [i + 1 ]).isdigit ()else "flash-next" 839if "--pack" in args or "--native" in args : 840return "flash-next" 841return "flash-next" 842 843 844def model_gib_of (args :list [str ])-> float : 845"""Total size of the model files a configuration names, shards included.""" 846from pathlib import Path 847import re 848total = 0 849seen :set [str ]= set () 850for i ,a in enumerate (args ): 851if a in ("--native" ,"--model" ,"--ple-gguf" )and i + 1 < len (args ): 852p = Path (str (args [i + 1 ])) 853if not p .is_file ()or str (p )in seen : 854continue 855m = re .match (r"(.*)-(\d{5})-of-(\d{5})\.gguf$" ,p .name ) 856group = sorted (p .parent .glob (f" { m . group ( 1 ) } -*-of- { m . group ( 3 ) } .gguf" ))if m else [p ] 857for f in group : 858if str (f )not in seen : 859seen .add (str (f )) 860total += f .stat ().st_size 861return round (total / 1024 ** 3 ,1 ) 862 863 864def context_from_config (cfg :dict [str ,Any ],* ,engine_backend :str | None ,opts :Options , 865engine_flags :list [str ]| None = None ,system :dict [str ,Any ]| None = None , 866family :str | None = None )-> tune_knobs .Context : 867args = split_args (cfg .get ("args" )or []) 868system = system or {"memory" :tune_machine .memory (),"gpus" :tune_machine .gpus (),"cpu" :tune_machine .cpu ()} 869gpu_cfg = cfg .get ("gpu" ) 870wanted = gpu_cfg if isinstance (gpu_cfg ,list )else ([gpu_cfg ]if isinstance (gpu_cfg ,int )else None ) 871cards = system .get ("gpus" )or [] 872used = [g for g in cards if not wanted or g .get ("index" )in wanted ]or cards 873ctx_tokens = 32768 874for i ,a in enumerate (args ): 875if a == "--max-context" and i + 1 < len (args )and str (args [i + 1 ]).isdigit (): 876ctx_tokens = int (args [i + 1 ]) 877mem = system .get ("memory" )or {} 878cpu = system .get ("cpu" )or {} 879backend = engine_backend or ("cuda" if any (g .get ("vendor" )== "nvidia" for g in cards )else 880"hip" if any (g .get ("vendor" )== "amd" for g in cards )else "cpu" ) 881arch = None 882if backend == "hip" : 883try : 884archs = engine_component .hip_archs_present () 885arch = archs [0 ]if archs else None 886except Exception :# noqa: BLE001 887arch = None 888return tune_knobs .Context ( 889backend = backend ,family = family or detect_family (args ),gpu_count = max (1 ,len (used )), 890vram_mib = min ((g ["vram_total_mib" ]for g in used if g .get ("vram_total_mib" )),default = 0 ), 891ram_gib = int ((mem .get ("total_mib" )or 0 )// 1024 ),model_gib = model_gib_of (args ), 892hybrid_cpu = bool (cpu .get ("hybrid" )),logical_threads = int (cpu .get ("logical" )or 0 ),arch = arch , 893context_tokens = ctx_tokens ,goal = opts .goal ,use = opts .use ,allow_placement = opts .allow_placement , 894allow_nonrepeatable = opts .allow_nonrepeatable ,engine_flags = engine_flags ,base_args = args ) 895 896 897# --------------------------------------------------------------------------- the short "still good?" re-check (8.3) 898 899def recheck (session :Session ,base_args :list [str ],preset :dict [str ,Any ],* ,ctx :tune_knobs .Context , 900engine_changed :bool = False ,progress :Callable [[dict [str ,Any ]],None ]| None = None , 901cancel :threading .Event | None = None ,clock :Callable [[],float ]= time .monotonic )-> dict [str ,Any ]: 902"""Is a saved preset still as fast as when it was made? One restart with the preset's settings and 30-45 s of requests. 903 904Pass rule (against the stored numbers, not a fresh baseline): decode and the 4K prompt at least 95% of what was stored, 905memory within the stored +5%. A failing prompt rate is measured once more with a second start before it counts (the 906prompt rate of some cards is bimodal between engine starts). When the engine changed in a way that can move speed 907(``tuning_epoch``) a baseline start is added and the preset must be at least as fast as doing nothing. 908The result is ``keep``, ``retune`` (suggested, never forced) or ``inconclusive`` (noise or a competing process).""" 909progress = progress or (lambda p :None ) 910cancel = cancel or threading .Event () 911t0 = clock () 912s = preset .get ("settings" )or {} 913stored = preset .get ("measured" )or {} 914args = tune_knobs .apply_to_argv (base_args ,s .get ("args" )or {}) 915env = dict (s .get ("env" )or {}) 916spec = RequestSet (warmups = 1 ,decodes = 3 ,decode_tokens = 200 ,pp_tokens = 4096 if ctx .context_tokens >= 6000 else 1024 ,long_tokens = 0 ) 917if ctx .backend == "sycl" : 918spec .pp_tokens = 0 # the A750's 4K prompt takes a minute: decode only (8.3) 919out :dict [str ,Any ]= {"verdict" :"inconclusive" ,"request_set" :RECHECK_SET_NAME ,"notes" : []} 920 921def one (a :list [str ],e :dict [str ,str | None ],label :str )-> RunResult : 922if cancel .is_set (): 923raise Cancelled () 924progress ({"stage" :"recheck" ,"message" :label ,"elapsed_s" :round (clock ()- t0 )}) 925try : 926with session .engine (a ,e )as eng : 927r = eng .measure (spec ) 928except StartFailed as ex : 929return RunResult (status = ex .status ,reason = ex .reason ) 930return r 931 932try : 933run = one (args ,env ,"Checking your saved settings" ) 934if run .status != "PASS" : 935out .update (verdict = "retune" ,reason = f"the saved settings did not start now: { run . status } { run . reason } " ) 936out ["seconds" ]= round (clock ()- t0 ,1 ) 937return out 938out ["measured" ]= {"decode_tok_s" :run .decode_tok_s ,"pp4k_tok_s" :run .pp_tok_s ,"rss_peak_mib" :run .rss_peak_mib , 939"vram_peak_mib" :run .vram_used_mib } 940sd ,sp = stored .get ("decode_tok_s" ),stored .get ("pp4k_tok_s" ) 941problems :list [str ]= [] 942if sd and run .decode_tok_s and run .decode_tok_s < 0.95 * sd : 943problems .append (f"answers are { 100 * ( 1 - run . decode_tok_s / sd ):.0f } % slower than when it was saved" ) 944if sp and run .pp_tok_s and run .pp_tok_s < 0.95 * sp : 945again = one (args ,env ,"Checking prompt speed once more" ) 946if again .status == "PASS" and again .pp_tok_s and again .pp_tok_s >= 0.95 * sp : 947out ["notes" ].append ("prompt speed varied between starts; the second start was fine" ) 948else : 949problems .append ("long prompts are slower than when it was saved" ) 950for key ,got in (("rss_peak_mib" ,run .rss_peak_mib ), ("vram_peak_mib" ,run .vram_used_mib )): 951ref = stored .get (key ) 952if ref and got and got > 1.05 * ref : 953problems .append ("it now uses more memory than when it was saved" ) 954break 955if engine_changed : 956base = one (base_args , {},"Checking against the standard settings after the engine update" ) 957if base .status == "PASS" and base .decode_tok_s and run .decode_tok_s and run .decode_tok_s < base .decode_tok_s : 958problems .append ("the standard settings are now faster than the saved ones" ) 959out ["baseline" ]= {"decode_tok_s" :base .decode_tok_s ,"pp4k_tok_s" :base .pp_tok_s } 960out ["problems" ]= problems 961out ["verdict" ]= "retune" if problems else "keep" 962out ["reason" ]= ("Still as fast as when it was saved." if not problems else "; " .join (problems )) 963except Cancelled : 964out .update (verdict = "inconclusive" ,reason = "Stopped." ) 965out ["seconds" ]= round (clock ()- t0 ,1 ) 966return out 967 968 969RECHECK_SET_NAME = "recheck/1"