okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
1"""`strata tune auto` (the real tuner) and `strata presets` (the saved results), for the Terminal and, through JSON output 2and a status file, for the desktop app. The same code and the same store serve both.""" 3 4from __future__import annotations 5 6import argparse 7import atexit 8import json 9import os 10import shutil 11import sys 12import tempfile 13import threading 14from strata_control import atomic as _atomic_mod 15from pathlib import Path 16from typing import Any 17 18 19# --------------------------------------------------------------------------- parsers 20 21def add_tune_auto (tune_sp :argparse ._SubParsersAction )-> None : 22p = tune_sp .add_parser ( 23"auto" ,help = "find the fastest settings for this PC and save them as a preset (quick: about 20 minutes)" , 24description = "Measures your configuration, tries single-knob changes in interleaved rounds against it, keeps only gains " 25"above the noise, and saves the result as a named preset that is applied at every start. " 26"Nothing changes if the current settings are already the fastest." ) 27p .add_argument ("target" ,help = "a saved profile name or a run configuration (JSON) to tune" ) 28p .add_argument ("--mode" ,choices = ("quick" ,"thorough" ),default = "quick" , 29help = "quick: about 20 minutes. thorough: up to 2 hours, 5-pair confirmation (default quick)" ) 30p .add_argument ("--goal" ,default = "speed" ,help = "speed (full performance), room (leave memory free), or room:MiB " 31"(leave that much graphics memory free)" ) 32p .add_argument ("--leave-ram" ,type = int ,default = 0 ,metavar = "PERCENT" ,help = "leave this share of system memory free (0-50)" ) 33p .add_argument ("--use" ,choices = ("chat" ,"coding" ),default = "chat" ,help = "coding judges long-prompt speed as well" ) 34p .add_argument ("--allow-small-differences" ,action = "store_true" , 35help = "also try settings that can change answers slightly (expert cache split, speculative window)" ) 36p .add_argument ("--allow-not-repeatable" ,action = "store_true" ,help = "also try settings whose answers are not repeatable" ) 37p .add_argument ("--name" ,default = None ,help = "the preset's name (default: model, context and your wish)" ) 38p .add_argument ("--time" ,dest = "minutes" ,type = float ,default = None ,help = "time to spend, in minutes" ) 39p .add_argument ("--no-save" ,action = "store_true" ,help = "measure and report, but do not save a preset" ) 40p .add_argument ("--gpu-lock" ,default = os .environ .get ("STRATA_TUNE_GPU_LOCK" ), 41help = "a lock file held around every engine run (shared boxes)" ) 42p .add_argument ("--no-quiet-check" ,action = "store_true" ,help = "do not wait for other engines or a busy CPU" ) 43p .add_argument ("--serve-dir" ,default = None ,help = "the folder that holds serve/ (default: this installation)" ) 44p .add_argument ("--work-dir" ,default = None ,help = "where the run's configs and logs go (default: a temp folder)" ) 45p .add_argument ("--status-file" ,default = None ,help = "progress as JSON, rewritten at every step (for the desktop app)" ) 46p .add_argument ("--boot-timeout" ,type = float ,default = 900.0 ) 47p .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 48 49 50def add_presets (sp :argparse ._SubParsersAction )-> None : 51pr = sp .add_parser ("presets" ,help = "saved tuning presets: list, apply, rename, delete, undo, re-check" ) 52psp = pr .add_subparsers (dest = "presets_command" ,required = True ) 53 54def common (x :argparse .ArgumentParser )-> argparse .ArgumentParser : 55x .add_argument ("--output" ,choices = ("human" ,"json" ),default = "human" ) 56return x 57 58l = common (psp .add_parser ("list" ,help = "every saved preset (or those for one model/configuration)" )) 59l .add_argument ("--model" ,default = None ,help = "only presets whose model or quant contains this text" ) 60s = common (psp .add_parser ("status" ,help = "which preset a configuration would start with, and whether it is still valid" )) 61s .add_argument ("target" ,help = "a saved profile name or a run configuration (JSON)" ) 62sh = common (psp .add_parser ("show" ,help = "one preset in full" )) 63sh .add_argument ("preset" ) 64ap = common (psp .add_parser ("apply" ,help = "make a preset the active one for its choices (the previous one is kept for undo)" )) 65ap .add_argument ("preset" ) 66rn = common (psp .add_parser ("rename" ,help = "give a preset another name" )) 67rn .add_argument ("preset" ) 68rn .add_argument ("name" ) 69de = common (psp .add_parser ("delete" ,help = "delete a preset" )) 70de .add_argument ("preset" ) 71un = common (psp .add_parser ("undo" ,help = "go back to the preset that was active before (or the standard settings)" )) 72un .add_argument ("preset" ,help = "a preset, or a configuration target with --config" ) 73un .add_argument ("--config" ,default = None ,help = "a profile name or run configuration whose slot to undo" ) 74ex = common (psp .add_parser ("export" ,help = "write a preset to a file (or print it)" )) 75ex .add_argument ("preset" ) 76ex .add_argument ("--file" ,default = None ) 77im = common (psp .add_parser ("import" ,help = "read a preset from a file" )) 78im .add_argument ("file" ) 79ef = common (psp .add_parser ("effective" ,help = "what a start with these choices will actually run: the saved tuning's values on top of the configuration" )) 80ef .add_argument ("target" ,help = "a saved profile name or a run configuration (JSON)" ) 81of = common (psp .add_parser ("off" ,help = "switch the saved tuning off for these choices (back to the standard settings; it is kept and can be switched on again)" )) 82of .add_argument ("target" ,help = "a saved profile name or a run configuration (JSON)" ) 83rc = common (psp .add_parser ("recheck" ,help = "a short check (about 2 minutes) that a preset is still as fast" )) 84rc .add_argument ("preset" ) 85rc .add_argument ("target" ,help = "the profile name or run configuration the preset belongs to" ) 86rc .add_argument ("--gpu-lock" ,default = os .environ .get ("STRATA_TUNE_GPU_LOCK" )) 87rc .add_argument ("--serve-dir" ,default = None ) 88rc .add_argument ("--work-dir" ,default = None ) 89rc .add_argument ("--status-file" ,default = None ) 90rc .add_argument ("--boot-timeout" ,type = float ,default = 900.0 ) 91rc .add_argument ("--no-quiet-check" ,action = "store_true" ) 92 93 94# --------------------------------------------------------------------------- helpers 95 96def _print (payload :dict [str ,Any ],machine :bool ,human :str )-> int : 97if machine : 98json .dumps ({"schema_version" :1 ,"ok" :True ,** payload },ensure_ascii = False ,default = str )) 99else : 100human ) 101return 0 102 103 104def _fail (message :str ,code :int ,machine :bool )-> int : 105if machine : 106json .dumps ({"schema_version" :1 ,"ok" :False ,"error" : {"code" :code ,"message" :message }})) 107else : 108f"strata: { message } " ,file = sys .stderr ) 109return code 110 111 112def _load_target (target :str )-> tuple [Path ,dict [str ,Any ]]: 113from strata_control import profiles 114path ,_profile ,_rev = profiles .resolve (target ) 115return path ,profiles .read_run_config (path ) 116 117 118def _engine_exe (cfg :dict [str ,Any ])-> str : 119from strata_control import engine_component 120ref = cfg .get ("exe" ) 121if engine_component .is_reference (ref ): 122return engine_component .expand (ref ,cfg ,full = False ) 123p = Path (ref ) 124return str (p if p .is_absolute ()else Path (cfg .get ("cwd" )or "." )/ p ) 125 126 127def _serve_dir (a :argparse .Namespace )-> Path : 128if getattr (a ,"serve_dir" ,None ): 129return Path (a .serve_dir ) 130return Path (__file__ ).resolve ().parent .parent 131 132 133def _lock_factory (a :argparse .Namespace ,log ): 134if not getattr (a ,"gpu_lock" ,None ): 135return None 136from strata_control .tune_session import FileLock 137return lambda :FileLock (a .gpu_lock ,log = log ) 138 139 140def _parse_goal (text :str )-> tuple [str ,int ]: 141if text in ("speed" ,"full" ): 142return "speed" ,0 143if text == "room" : 144return "room" ,0 145if text .startswith ("room:" ): 146return "room" ,max (0 ,int (text [5 :])) 147raise ValueError ("goal is speed, room or room:MiB" ) 148 149 150def _write_status (path :str | None ,payload :dict [str ,Any ])-> None : 151if not path : 152return 153try : 154tmp = path + ".tmp" 155Path (tmp ).write_text (json .dumps (payload ,ensure_ascii = False ,default = str ),encoding = "utf-8" ) 156_atomic_mod .replace (tmp ,path ) 157except OSError : 158pass 159 160 161def minutes_text (seconds :float | None )-> str : 162if seconds is None : 163return "" 164m = max (1 ,int (round (seconds / 60.0 ))) 165return f"about { m } min left" 166 167 168def _hw_hash (identity :dict [str ,Any ])-> str : 169from strata_control import tune_machine 170return tune_machine .stable_hash ((identity .get ("hardware" )or {}).get ("hard" )) 171 172 173# --------------------------------------------------------------------------- tune auto 174 175def auto (a :argparse .Namespace )-> int : 176from strata_control import autotune ,engine_component ,presets ,tuning 177from strata_control .tune_session import WorkerSession 178 179machine = a .output == "json" 180try : 181goal ,reserve = _parse_goal (a .goal ) 182cfg_path ,cfg = _load_target (a .target ) 183except Exception as e :# noqa: BLE001 184return _fail (str (e ),getattr (e ,"exit_code" ,2 ),machine ) 185if not 0 <= a .leave_ram <= 50 : 186return _fail ("--leave-ram is a percentage from 0 to 50" ,2 ,machine ) 187if a .leave_ram and goal == "speed" : 188goal = "room" 189exe = _engine_exe (cfg ) 190if not Path (exe ).exists (): 191return _fail (f"no engine was found at { exe } " ,5 ,machine ) 192identity = presets .current_identity (cfg ,exe = exe ) 193backend = (identity .get ("engine" )or {}).get ("backend" )or engine_component .detect_backend ()[0 ]or "cpu" 194flags = tuning .engine_flag_inventory (Path (exe )) 195opts = autotune .Options (mode = a .mode ,goal = goal ,reserve_mib = reserve ,ram_wish_pct = a .leave_ram ,use = a .use , 196allow_placement = a .allow_small_differences ,allow_nonrepeatable = a .allow_not_repeatable , 197budget_s = (a .minutes * 60.0 if a .minutes else None ),check_busy =not a .no_quiet_check ) 198ctx = autotune .context_from_config (cfg ,engine_backend = backend ,opts = opts ,engine_flags = flags ) 199hw = _hw_hash (identity ) 200digest = (identity .get ("model" )or {}).get ("sha256_shard1" ) 201bad = presets .bad_signatures (hw_hash = hw ,model_digest = digest ,engine_sha = (identity .get ("engine" )or {}).get ("sha256" )) 202 203cancel = threading .Event () 204state :dict [str ,Any ]= {"stage" :"start" ,"message" :"Starting" ,"state" :"running" } 205 206def say (line :str )-> None : 207if not machine : 208line ,file = sys .stderr ,flush = True ) 209 210def progress (p :dict [str ,Any ])-> None : 211state .update (p ) 212state ["minutes_left" ]= None if p .get ("eta_s" )is None else max (1 ,int (round (p ["eta_s" ]/ 60.0 ))) 213state ["text" ]= (f"Finding the fastest settings for your PC… { minutes_text ( p . get ( 'eta_s' )) } " 214if p .get ("eta_s" )is not None else "Finding the fastest settings for your PC…" ) 215_write_status (a .status_file ,state ) 216say (f"[ { p . get ( 'elapsed_s' , 0 ) // 60 :>3d } m] { p [ 'message' ] } " + (f" ( { minutes_text ( p [ 'eta_s' ]) } )" if p .get ("eta_s" )else "" )) 217 218workdir = Path (a .work_dir )if a .work_dir else Path (tempfile .mkdtemp (prefix = "strata-tune-" )) 219if not a .work_dir : 220atexit .register (shutil .rmtree ,workdir ,True )# its own scratch folder goes with the run (--work-dir keeps the logs) 221session = WorkerSession (base_config = cfg ,python = sys .executable ,serve_dir = _serve_dir (a ),workdir = workdir , 222boot_timeout_s = a .boot_timeout ,lock = _lock_factory (a ,say ),log = say ) 223base_args = [str (x )for x in cfg .get ("args" )or []] 224# the wish becomes part of the base: leave-room asks the engine for the reserve if the configuration has none yet 225if goal == "room" and reserve and "--vram-reserve-mib" not in base_args and ctx .family == "flash-next" \ 226and backend in ("cuda" ,"hip" )and (flags is None or "--vram-reserve-mib" in flags ): 227base_args += ["--vram-reserve-mib" ,str (reserve )] 228ctx .base_args = list (base_args ) 229tuner = autotune .Tuner (session ,base_args ,dict (cfg .get ("env" )or {}),ctx ,opts ,progress = progress ,cancel = cancel , 230history_bad = bad ,quiet = None ) 231say (f"Tuning { presets . choices_from_config ( cfg ). get ( 'model' ) } ( { a . mode } ); engine { exe } " ) 232try : 233result = tuner .run () 234except KeyboardInterrupt : 235cancel .set () 236result = tuner .result 237result .outcome ,result .message = "cancelled" ,"Stopped. Your settings were not changed." 238out = result .to_dict () 239choices = presets .choices_from_config (cfg ,use = a .use ) 240choices ["goal" ],choices ["reserve_mib" ]= goal ,reserve 241if a .leave_ram : 242choices ["leave_ram_pct" ]= a .leave_ram 243saved = None 244try : 245presets .record_trials (result .trials ,hw_hash = hw ,model_digest = digest , 246engine_sha = (identity .get ("engine" )or {}).get ("sha256" )) 247except OSError : 248pass 249if result .outcome in ("improved" ,"default_confirmed" )and not a .no_save : 250try : 251saved = presets .create (out ,choices = choices ,identity = identity ,name = a .name ,mode = a .mode ) 252except presets .PresetError as e : 253result .notes .append (str (e )) 254out ["preset" ]= ({"id" :saved ["id" ],"name" :saved ["name" ]}if saved else None ) 255autotune .Tuner .finalize (result ) 256out .update ({"code" :result .code ,"reason_code" :result .reason_code ,"values" :result .values }) 257out ["values" ]["preset_name" ]= saved ["name" ]if saved else None 258state .update ({"state" :"done" ,"result" :out ,"stage" :"done" }) 259_write_status (a .status_file ,state ) 260if machine : 261json .dumps ({"schema_version" :1 ,"ok" :True ,"result" :out },ensure_ascii = False ,default = str )) 262else : 263_human_result (out ,saved )) 264return {"improved" :0 ,"default_confirmed" :0 ,"cancelled" :130 }.get (result .outcome ,6 ) 265 266 267def _human_result (r :dict [str ,Any ],saved :dict [str ,Any ]| None )-> str : 268lines = ["" ] 269if r ["outcome" ]== "improved" : 270lines .append (f"Done in { r [ 'seconds' ] / 60 :.0f } min: + { r [ 'gain_pct' ]:.0f } % faster answers" 271+ (f", saved as ' { saved [ 'name' ] } '." if saved else "." )) 272s = r ["settings" ] 273shown = {** {k :v for k ,v in s ["args" ].items ()},** s ["env" ],** {f"per request { k } " :v for k ,v in s ["per_request" ].items ()}} 274lines .append (" Changed: " + ", " .join (f" { k } { v } " for k ,v in shown .items ())) 275lines .append (f" Measured: { r [ 'base' ]. get ( 'decode_tok_s' ) } -> { r [ 'chosen' ]. get ( 'decode_tok_s' ) } tok/s " 276f"( { r [ 'faster_pairs' ] } of { r [ 'pairs' ] } pairs faster)" ) 277from strata_control .tune_knobs import ANSWER_NOTICE 278from strata_control .tune_knobs import ANSWER_NOTICE_UNSTEADY 279unsteady = r ["answers" ].get ("default_repeatable" )is False and r ["answers" ]["class" ]in ANSWER_NOTICE_UNSTEADY 280lines .append (" " + (ANSWER_NOTICE_UNSTEADY if unsteady else ANSWER_NOTICE ).get (r ["answers" ]["class" ],"" )) 281else : 282lines .append (r ["message" ]or r ["outcome" ]) 283if saved : 284lines .append (f" Saved as ' { saved [ 'name' ] } ' so it is not tuned again on reopen." ) 285for n in r .get ("notes" )or []: 286lines .append (f" note: { n } " ) 287return "\n" .join (lines ) 288 289 290# --------------------------------------------------------------------------- presets 291 292def presets_command (a :argparse .Namespace )-> int : 293from strata_control import presets 294 295machine = a .output == "json" 296cmd = a .presets_command 297try : 298if cmd == "list" : 299items = presets .list_presets (model = a .model ) 300human = "\n" .join (f" { '*' if p [ 'active' ] else ' ' } { p [ 'id' ][: 8 ] } { p [ 'name' ] } " 301f" { ( p . get ( 'measured' ) or {}). get ( 'gain_pct' ) or 0 :+.0f } % { p [ 'answers' ][ 'class' ] } " 302for p in items )or "No saved presets yet. Run: strata tune auto <profile>" 303return _print ({"presets" : [_summary (p )for p in items ]},machine ,human ) 304if cmd == "status" : 305return _status (a ,machine ) 306if cmd == "effective" : 307return _effective (a ,machine ) 308if cmd == "off" : 309return _off (a ,machine ) 310if cmd == "show" : 311p = presets .find (a .preset ) 312return _print ({"preset" :p },machine ,json .dumps (p ,indent = 2 ,ensure_ascii = False )) 313if cmd == "apply" : 314p = presets .activate_preset (a .preset ) 315return _print ({"preset" :_summary (p ),"notice" :presets .notice (p )},machine , 316f"' { p [ 'name' ] } ' is now active. It is used the next time the model starts. Undo: strata presets undo { p [ 'id' ][: 8 ] } " ) 317if cmd == "rename" : 318p = presets .rename (a .preset ,a .name ) 319return _print ({"preset" :_summary (p )},machine ,f"Renamed to ' { p [ 'name' ] } '." ) 320if cmd == "delete" : 321p = presets .find (a .preset ) 322presets .delete (a .preset ) 323return _print ({"deleted" :p ["id" ]},machine ,f"Deleted ' { p [ 'name' ] } '." ) 324if cmd == "undo" : 325if a .config : 326_path ,cfg = _load_target (a .config ) 327ident = presets .current_identity (cfg ) 328slot = presets .slot_key (presets .choices_from_config (cfg ), (ident .get ("model" )or {}).get ("sha256_shard1" )) 329else : 330slot = a .preset 331back = presets .undo (slot ) 332return _print ({"active" :_summary (back )if back else None },machine , 333f"Back to ' { back [ 'name' ] } '." if back else "Back to the standard settings." ) 334if cmd == "export" : 335data = presets .export_preset (a .preset ) 336if a .file : 337Path (a .file ).write_text (json .dumps (data ,indent = 2 ,ensure_ascii = False ),encoding = "utf-8" ) 338return _print ({"file" :a .file },machine ,f"Wrote { a . file } " ) 339json .dumps (data ,indent = 2 ,ensure_ascii = False )) 340return 0 341if cmd == "import" : 342data = json .loads (Path (a .file ).read_text (encoding = "utf-8-sig" )) 343p = presets .import_preset (data ) 344return _print ({"preset" :_summary (p )},machine ,f"Imported ' { p [ 'name' ] } '. Apply it with: strata presets apply { p [ 'id' ][: 8 ] } " ) 345if cmd == "recheck" : 346return _recheck (a ,machine ) 347except presets .PresetError as e : 348return _fail (str (e ),5 ,machine ) 349except (OSError ,ValueError )as e : 350return _fail (str (e ),getattr (e ,"exit_code" ,2 ),machine ) 351return _fail ("unknown presets command" ,2 ,machine ) 352 353 354def _summary (p :dict [str ,Any ])-> dict [str ,Any ]: 355from strata_control import presets 356m = p .get ("measured" )or {} 357return {"id" :p ["id" ],"name" :p ["name" ],"active" :bool (p .get ("active" )),"created" :p .get ("created" ), 358"choices" :p .get ("choices" ),"settings" :p .get ("settings" ),"answers" :p .get ("answers" ), 359"notice" :presets .notice (p ),"gain_pct" :m .get ("gain_pct" ),"decode_tok_s" :m .get ("decode_tok_s" ), 360"baseline_decode_tok_s" : (p .get ("baseline" )or {}).get ("decode_tok_s" ),"tuner" :p .get ("tuner" ), 361"recheck" :p .get ("recheck" ),"slot" :p .get ("slot" )} 362 363 364def _effective (a :argparse .Namespace ,machine :bool )-> int : 365"""The values a start will really use (owner feedback, item 11): the configuration with the active saved tuning put on top, 366plus the list of what the tuning changed, so Expert mode can show the tuned numbers and not the untuned ones.""" 367from strata_control import presets ,tune_knobs 368_path ,cfg = _load_target (a .target ) 369merged ,info = presets .overlay (cfg ) 370before = [str (x )for x in cfg .get ("args" )or []] 371after = [str (x )for x in merged .get ("args" )or []] 372changed = [] 373for flag in sorted ({x for x in before + after if x .startswith ("--" )}): 374was ,now = tune_knobs ._current (before ,flag ),tune_knobs ._current (after ,flag ) 375if was != now : 376changed .append ({"flag" :flag ,"was" :was ,"now" :now }) 377payload = {"applied" :bool (info .get ("applied" )),"preset" :info .get ("preset" ),"state" :info .get ("state" ),"reasons" :info .get ("reasons" , []), 378"why_not" :info .get ("why_not" ),"warnings" :info .get ("warnings" )or [],"notice" :info .get ("notice" ), 379"args" :merged .get ("args" ),"env" :merged .get ("env" )or {}, 380"sampling" :merged .get ("sampling" )or {},"changed" :changed ,"per_request" :info .get ("per_request" )or {}} 381human = (f"Using your tuning ' { info [ 'preset' ][ 'name' ] } '" if info .get ("applied" )else "No saved tuning is applied; the standard settings run." ) 382return _print (payload ,machine ,human ) 383 384 385def _off (a :argparse .Namespace ,machine :bool )-> int : 386"""Switch the saved tuning off for these choices. It is kept (and listed), so switching it back on is one step.""" 387from strata_control import presets 388_path ,cfg = _load_target (a .target ) 389ident = presets .current_identity (cfg ) 390slot = presets .slot_key (presets .choices_from_config (cfg ), (ident .get ("model" )or {}).get ("sha256_shard1" )) 391presets .deactivate_slot (slot ) 392return _print ({"active" :None },machine ,"Back to the standard settings. Your tuning is kept and can be switched on again." ) 393 394 395def _status (a :argparse .Namespace ,machine :bool )-> int : 396from strata_control import presets 397_path ,cfg = _load_target (a .target ) 398ident = presets .current_identity (cfg ) 399choices = presets .choices_from_config (cfg ) 400slot = presets .slot_key (choices , (ident .get ("model" )or {}).get ("sha256_shard1" )) 401idx = presets ._index ().get (slot )or {} 402items = [p for p in presets .list_presets ()if p .get ("slot" )== slot ] 403active = next ((p for p in items if p ["id" ]== idx .get ("active" )),None ) 404stale = presets .staleness (active ,ident )if active else None 405default = presets .default_name (choices ) 406return _print ({"slot" :slot ,"suggested_name" :default ,"choices" :choices , 407"active" :_summary (active )if active else None ,"state" :stale ["state" ]if stale else None , 408"reasons" :stale ["reasons" ]if stale else [],"presets" : [_summary (p )for p in items ], 409"can_undo" :bool (idx .get ("history" ))or bool (active ), 410"switched_off" :bool (not active and idx .get ("history" )), 411"last_active" :next ((_summary (p )for p in items if p ["id" ]== (idx .get ("history" )or [None ])[- 1 ]),None )if not active else None }, 412machine , (f"Active: ' { active [ 'name' ] } ' ( { stale [ 'state' ] } )" if active else "No saved tuning for these choices yet." )) 413 414 415def _recheck (a :argparse .Namespace ,machine :bool )-> int : 416from strata_control import autotune ,presets ,tuning 417from strata_control .tune_session import WorkerSession 418preset = presets .find (a .preset ) 419_path ,cfg = _load_target (a .target ) 420exe = _engine_exe (cfg ) 421ident = presets .current_identity (cfg ,exe = exe ) 422stale = presets .staleness (preset ,ident ) 423if stale ["state" ]== "hard" : 424return _fail ("this PC changed too much for a re-check (" + "; " .join (stale ["reasons" ])+ "): tune again with strata tune auto" ,5 ,machine ) 425engine_changed = int ((preset .get ("identity" , {}).get ("engine" )or {}).get ("tuning_epoch" )or 0 )!= \ 426int ((ident .get ("engine" )or {}).get ("tuning_epoch" )or 0 ) 427opts = autotune .Options (use = (preset .get ("choices" )or {}).get ("use" ,"chat" )) 428ctx = autotune .context_from_config (cfg ,engine_backend = (ident .get ("engine" )or {}).get ("backend" ),opts = opts , 429engine_flags = tuning .engine_flag_inventory (Path (exe ))) 430say = (lambda s :None )if machine else (lambda s :s ,file = sys .stderr ,flush = True )) 431workdir = Path (a .work_dir )if a .work_dir else Path (tempfile .mkdtemp (prefix = "strata-recheck-" )) 432if not a .work_dir : 433atexit .register (shutil .rmtree ,workdir ,True )# its own scratch folder goes with the run (--work-dir keeps the logs) 434session = WorkerSession (base_config = cfg ,python = sys .executable ,serve_dir = _serve_dir (a ),workdir = workdir , 435boot_timeout_s = a .boot_timeout ,lock = _lock_factory (a ,say ),log = say ) 436state :dict [str ,Any ]= {"state" :"running" } 437 438def progress (p :dict [str ,Any ])-> None : 439state .update (p ) 440_write_status (a .status_file ,state ) 441say (p ["message" ]) 442 443out = autotune .recheck (session , [str (x )for x in cfg .get ("args" )or []],preset ,ctx = ctx ,engine_changed = engine_changed , 444progress = progress ) 445out ["identity" ]= ident 446updated = presets .record_recheck (preset ["id" ],out ) 447state .update ({"state" :"done" ,"result" : {k :v for k ,v in out .items ()if k != "identity" }}) 448_write_status (a .status_file ,state ) 449human = {"keep" :"Still as fast as when it was saved. Kept." , 450"retune" :"Not as fast as before: " + str (out .get ("reason" ))+ "\nYou can tune again with: strata tune auto" , 451"inconclusive" :"Could not tell (the PC was busy). Kept; try again later." }[out ["verdict" ]] 452return _print ({"verdict" :out ["verdict" ],"reason" :out .get ("reason" ),"result" : {k :v for k ,v in out .items ()if k != "identity" }, 453"preset" :_summary (updated )},machine ,human )