okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
1"""Saved tuning presets: tune once, keep it. 2 3One store for the Terminal and the desktop app: a folder of small JSON files (``presets/`` beside the profiles), so tuning in 4one place covers the other. A preset holds 5 6* the settings the tuner found (``settings``: engine arguments, environment, per-request defaults), 7* what was measured (speeds and the baseline they were compared to), 8* the user's choices it was made for (model, context, KV format, "leave room" or "full performance", chat or coding), and 9* the identity it is valid for: the PC (graphics card and driver, memory, processor), the engine build and the model file. 10 11On every start the **active** preset for the model's choices is applied with no measurement (`overlay`, called by the 12server before it starts the engine). When the identity changed the preset says how much: a new graphics card or model file 13is a *hard* change (settings may not even start, so they are not applied on their own); a new driver or an engine build 14with a new ``tuning_epoch`` is a *soft* change (the preset still applies, and a 2-minute re-check is offered, never forced). 15 16Several named presets per model; activating one keeps the one it replaced, so **undo** restores it exactly. Nothing here 17starts an engine or changes anything but its own folder. 18""" 19 20from __future__import annotations 21 22import json 23import os 24import re 25import tempfile 26import time 27import uuid 28from pathlib import Path 29from typing import Any 30 31from strata_control import tune_knobs ,tune_machine 32from strata_control import atomic as _atomic_mod 33 34SCHEMA = "strata.preset/1" 35RECHECK_SET = "recheck/1" 36DEFAULT_LAST_OK_DAYS = 90 37 38 39class PresetError (ValueError ): 40"""A preset is missing or invalid; the message is for the user.""" 41 42 43# --------------------------------------------------------------------------- the folder 44 45def preset_dir ()-> Path : 46explicit = os .environ .get ("STRATA_PRESET_DIR" ) 47if explicit : 48return Path (explicit ).expanduser () 49from strata_control import profiles 50return profiles .profile_dir ().parent / "presets" 51 52 53def _atomic (path :Path ,payload :bytes )-> None : 54path .parent .mkdir (parents = True ,exist_ok = True ) 55fd ,tmp = tempfile .mkstemp (prefix = f". { path . name } -" ,suffix = ".tmp" ,dir = path .parent ) 56try : 57with os .fdopen (fd ,"wb" )as fh : 58fh .write (payload ) 59fh .flush () 60os .fsync (fh .fileno ()) 61_atomic_mod .replace (tmp ,path ) 62finally : 63if os .path .exists (tmp ): 64os .unlink (tmp ) 65 66 67def _write_json (path :Path ,obj :Any )-> None : 68_atomic (path , (json .dumps (obj ,indent = 2 ,ensure_ascii = False ,sort_keys = True )+ "\n" ).encode ("utf-8" )) 69 70 71def _read_json (path :Path ,default :Any )-> Any : 72try : 73return json .loads (path .read_text (encoding = "utf-8-sig" )) 74except (OSError ,ValueError ): 75return default 76 77 78def _path (pid :str )-> Path : 79if not re .fullmatch (r"[0-9a-f]{32}" ,pid ): 80raise PresetError ("that is not a preset id" ) 81return preset_dir ()/ f" { pid } .json" 82 83 84# --------------------------------------------------------------------------- the choices a preset belongs to 85 86_QUANT = re .compile (r"(UD-Q\d_K_\w+|IQ\d_[A-Z]+|Q\d_K_[A-Z]+|Q\d_K|Q\d_\d|Q\d|BF16|F16)" ,re .I ) 87 88 89def choices_from_config (cfg :dict [str ,Any ],* ,use :str = "chat" )-> dict [str ,Any ]: 90"""What the user chose, read from a run configuration: model, context, KV format, pictures, and whether they asked to 91leave room for other work. The slot a preset is active in is made from these.""" 92args = [str (a )for a in cfg .get ("args" )or []] 93 94def val (flag :str )-> str | None : 95for i ,a in enumerate (args ): 96if a == flag and i + 1 < len (args )and not args [i + 1 ].startswith ("--" ): 97return args [i + 1 ] 98return None 99 100ctx = val ("--max-context" ) 101native = val ("--native" )or val ("--model" )or "" 102quant = (_QUANT .search (Path (native ).name )or _QUANT .search (str (cfg .get ("model_name" )or "" ))) 103profile = cfg .get ("ui_resource_profile" ) 104reserve = cfg .get ("vram_reserve_mib" ) 105room = profile == "work" 106return { 107"model" :str (cfg .get ("model_name" )or Path (native ).stem or "model" ), 108"quant" :quant .group (1 ).upper ()if quant else None , 109"model_file" :native , 110"context" :int (ctx )if ctx and ctx .isdigit ()else None , 111"kv" :val ("--kv" )or "int8" , 112"vision" :bool (cfg .get ("ui_vision_enabled" ))or "--vision" in args , 113"goal" :"room" if room else "speed" , 114"reserve_mib" :int (reserve )if isinstance (reserve , (int ,float ))else 0 , 115"use" :use , 116"family" :"qwen36" if (val ("--mtp" )or "" ).isdigit ()else "flash-next" , 117 } 118 119 120def default_name (choices :dict [str ,Any ])-> str : 121ctx = choices .get ("context" ) 122ctx_s = f" { ctx // 1024 } K" if ctx else "?" 123label = choices .get ("quant" )or choices .get ("model" )or "Model" 124wish = "Work" if choices .get ("goal" )== "room" else "Full speed" 125return f" { label } { ctx_s } – { wish } " 126 127 128def slot_key (choices :dict [str ,Any ],model_digest :str | None )-> str : 129"""Presets of the same model file, context, KV format, pictures and wish compete for the active place.""" 130return tune_machine .stable_hash ({"m" :model_digest ,"ctx" :choices .get ("context" ),"kv" :choices .get ("kv" ), 131"v" :bool (choices .get ("vision" )),"g" :choices .get ("goal" )}) 132 133 134# --------------------------------------------------------------------------- identity and staleness 135 136def current_identity (cfg :dict [str ,Any ],* ,exe :str | None = None ,pcie :str | None = None )-> dict [str ,Any ]: 137"""The identity this PC, engine and model file have now.""" 138from strata_control import engine_component 139args = [str (a )for a in cfg .get ("args" )or []] 140files = [a for a in args if a .lower ().endswith (".gguf" )] 141native = None 142for i ,a in enumerate (args ): 143if a == "--native" and i + 1 < len (args ): 144native = args [i + 1 ] 145first = native or (files [0 ]if files else None ) 146engine_path = exe 147if engine_path is None : 148try : 149ref = cfg .get ("exe" ) 150engine_path = engine_component .expand (ref ,cfg ,full = False )if ref else None 151except Exception :# noqa: BLE001 152engine_path = cfg .get ("exe" ) 153return {"hardware" :tune_machine .hardware_identity (pcie = pcie ), 154"engine" :tune_machine .engine_identity (engine_path )if engine_path else {}, 155"model" :tune_machine .model_identity ([first ])if first and Path (first ).is_file ()else {}} 156 157 158def staleness (preset :dict [str ,Any ],now :dict [str ,Any ],* ,today :float | None = None )-> dict [str ,Any ]: 159"""Compare a preset's identity with the current one: ``state`` is fresh, soft (re-check offered) or hard (settings 160are not applied on their own; re-tune offered). ``reasons`` are plain words.""" 161old = preset .get ("identity" )or {} 162hard :list [str ]= [] 163soft :list [str ]= [] 164oh ,nh = (old .get ("hardware" )or {}).get ("hard" )or {}, (now .get ("hardware" )or {}).get ("hard" )or {} 165if oh and nh : 166if oh .get ("gpus" )!= nh .get ("gpus" ): 167hard .append ("the graphics card changed" ) 168if oh .get ("cpu" )!= nh .get ("cpu" )or oh .get ("logical" )!= nh .get ("logical" ): 169hard .append ("the processor changed" ) 170a ,b = oh .get ("ram_gib" ),nh .get ("ram_gib" ) 171if a and b and abs (a - b )/ max (a ,b )> 0.10 : 172hard .append ("the amount of memory changed" ) 173if oh .get ("pcie" )and nh .get ("pcie" )and oh ["pcie" ]!= nh ["pcie" ]: 174hard .append ("the PCIe link changed" ) 175om ,nm = (old .get ("model" )or {}), (now .get ("model" )or {}) 176if om .get ("sha256_shard1" )and nm .get ("sha256_shard1" )and om ["sha256_shard1" ]!= nm ["sha256_shard1" ]: 177hard .append ("the model file changed" ) 178oe ,ne = (old .get ("engine" )or {}), (now .get ("engine" )or {}) 179if oe .get ("backend" )and ne .get ("backend" )and oe ["backend" ]!= ne ["backend" ]: 180hard .append ("the engine's graphics backend changed" ) 181if oe and ne and int (oe .get ("tuning_epoch" )or 0 )!= int (ne .get ("tuning_epoch" )or 0 ): 182soft .append ("the engine was updated in a way that can change speed" ) 183elif oe .get ("version" )and ne .get ("version" )and oe ["version" ]!= ne ["version" ]and \ 184oe .get ("sha256" )and ne .get ("sha256" )and oe ["sha256" ]!= ne ["sha256" ]and \ 185int (oe .get ("tuning_epoch" )or 0 )!= int (ne .get ("tuning_epoch" )or 0 ): 186soft .append ("the engine was updated" ) 187os_ ,ns = (old .get ("hardware" )or {}).get ("soft" )or {}, (now .get ("hardware" )or {}).get ("soft" )or {} 188if os_ .get ("driver" )and ns .get ("driver" )and os_ ["driver" ]!= ns ["driver" ]: 189soft .append ("the graphics driver changed" ) 190last_ok = ((preset .get ("recheck" )or {}).get ("last_ok_epoch" ))or preset .get ("created_epoch" ) 191if last_ok and (today or time .time ())- last_ok > DEFAULT_LAST_OK_DAYS * 86400 : 192soft .append ("it has not been checked for a while" ) 193if hard : 194return {"state" :"hard" ,"reasons" :hard + soft } 195if soft : 196return {"state" :"soft" ,"reasons" :soft } 197return {"state" :"fresh" ,"reasons" : []} 198 199 200# --------------------------------------------------------------------------- the store 201 202def _index ()-> dict [str ,Any ]: 203idx = _read_json (preset_dir ()/ "active.json" , {}) 204return idx if isinstance (idx ,dict )else {} 205 206 207def _save_index (idx :dict [str ,Any ])-> None : 208_write_json (preset_dir ()/ "active.json" ,idx ) 209 210 211def load (pid :str )-> dict [str ,Any ]: 212data = _read_json (_path (pid ),None ) 213if not isinstance (data ,dict )or data .get ("schema" )!= SCHEMA : 214raise PresetError ("that preset does not exist" ) 215return data 216 217 218def find (ref :str )-> dict [str ,Any ]: 219"""A preset by id, id prefix or exact name (case-insensitive); an ambiguous name is refused.""" 220items = list_presets () 221exact = [p for p in items if p ["id" ]== ref ] 222if exact : 223return exact [0 ] 224by_prefix = [p for p in items if len (ref )>= 4 and p ["id" ].startswith (ref )] 225by_name = [p for p in items if p ["name" ].lower ()== ref .lower ()] 226found = by_name or by_prefix 227if not found : 228raise PresetError (f"no preset called ' { ref } '" ) 229if len (found )> 1 : 230raise PresetError (f"' { ref } ' matches { len ( found ) } presets; use the id" ) 231return found [0 ] 232 233 234def list_presets (* ,model :str | None = None )-> list [dict [str ,Any ]]: 235out :list [dict [str ,Any ]]= [] 236d = preset_dir () 237if not d .is_dir (): 238return out 239idx = _index () 240active_ids = {v .get ("active" )for v in idx .values ()if isinstance (v ,dict )} 241for f in sorted (d .glob ("*.json" )): 242if f .name == "active.json" : 243continue 244data = _read_json (f ,None ) 245if not isinstance (data ,dict )or data .get ("schema" )!= SCHEMA : 246continue 247if model and model .lower ()not in json .dumps (data .get ("choices" , {})).lower (): 248continue 249data ["active" ]= data .get ("id" )in active_ids 250out .append (data ) 251out .sort (key = lambda p :p .get ("created_epoch" ,0 ),reverse = True ) 252return out 253 254 255def _name_taken (name :str ,exclude :str | None = None )-> bool : 256return any (p ["name" ].lower ()== name .lower ()and p ["id" ]!= exclude for p in list_presets ()) 257 258 259def _unique_name (name :str )-> str : 260if not _name_taken (name ): 261return name 262n = 2 263while _name_taken (f" { name } ( { n } )" ): 264n += 1 265return f" { name } ( { n } )" 266 267 268def create (result :dict [str ,Any ],* ,choices :dict [str ,Any ],identity :dict [str ,Any ],name :str | None = None , 269mode :str = "quick" ,activate :bool = True ,base_args :dict [str ,Any ]| None = None )-> dict [str ,Any ]: 270"""Save a tune result as a named preset (active at once unless ``activate`` is False).""" 271settings = result .get ("settings" )or {"args" : {},"env" : {},"per_request" : {}} 272# (a value only outside the tuner's tested range is kept, #3844; the never list still refuses) 273problems ,_outside = tune_knobs .check_setting_parts (settings .get ("args" )or {},settings .get ("env" )or {}, 274tune_knobs .Context (context_tokens = choices .get ("context" )or 32768 , 275family = choices .get ("family" )or "flash-next" )) 276if problems : 277raise PresetError ("these settings are outside the safe rules and cannot be saved: " + "; " .join (problems )) 278base = result .get ("base" )or {} 279chosen = result .get ("chosen" )or {} 280pid = uuid .uuid4 ().hex 281now = time .time () 282digest = (identity .get ("model" )or {}).get ("sha256_shard1" ) 283preset = { 284"schema" :SCHEMA ,"id" :pid ,"name" :_unique_name (name or default_name (choices )), 285"created" :time .strftime ("%Y-%m-%dT%H:%M:%S%z" ,time .localtime (now )),"created_epoch" :now , 286"tuner" : {"mode" :mode ,"version" :"1" ,"seconds" :result .get ("seconds" ),"outcome" :result .get ("outcome" )}, 287"choices" :choices ,"identity" :identity ,"slot" :slot_key (choices ,digest ), 288"settings" : {"args" :settings .get ("args" )or {},"env" :settings .get ("env" )or {}, 289"per_request" :settings .get ("per_request" )or {}}, 290"answers" :result .get ("answers" )or {"class" :"exact" ,"fields" : []}, 291"baseline" : {"args" :base_args or {},"decode_tok_s" :base .get ("decode_tok_s" ),"pp4k_tok_s" :base .get ("pp_tok_s" ), 292"pairs" :result .get ("pairs" ),"noise_aa_decode" : (result .get ("noise" )or {}).get ("aa_gap" )}, 293"measured" : {"decode_tok_s" :chosen .get ("decode_tok_s" ),"pp4k_tok_s" :chosen .get ("pp_tok_s" ), 294"vram_peak_mib" :chosen .get ("vram_used_mib" ),"rss_peak_mib" :chosen .get ("rss_peak_mib" ), 295"pairs" :result .get ("pairs" ),"faster_pairs" :result .get ("faster_pairs" ), 296"gain_pct" :result .get ("gain_pct" ),"gain_decode_pct" :result .get ("gain_decode_pct" ), 297"gain_pp_pct" :result .get ("gain_pp_pct" )}, 298"noise" :result .get ("noise" )or {}, 299"evidence" : {"arms" :result .get ("arms" ),"per_request" :result .get ("per_request" ),"notes" :result .get ("notes" ), 300"classes" :result .get ("classes" )}, 301"recheck" : {"request_set" :RECHECK_SET ,"last_ok" :None ,"last_ok_epoch" :None ,"last_result" :None }, 302"previous" :None , 303 } 304_write_json (_path (pid ),preset ) 305if activate : 306activate_preset (pid ) 307preset = load (pid ) 308return preset 309 310 311def activate_preset (ref :str )-> dict [str ,Any ]: 312"""Make a preset the active one for its slot; the one it replaces is kept for undo.""" 313p = find (ref ) 314idx = _index () 315entry = idx .get (p ["slot" ])if isinstance (idx .get (p ["slot" ]),dict )else {"active" :None ,"history" : []} 316if entry .get ("active" )== p ["id" ]: 317return p 318if entry .get ("active" ): 319entry .setdefault ("history" , []).append (entry ["active" ]) 320entry ["history" ]= entry ["history" ][- 20 :] 321p ["previous" ]= entry .get ("active" ) 322entry ["active" ]= p ["id" ] 323idx [p ["slot" ]]= entry 324_write_json (_path (p ["id" ]), {k :v for k ,v in p .items ()if k != "active" }) 325_save_index (idx ) 326p ["active" ]= True 327return p 328 329 330def deactivate_slot (slot :str )-> None : 331"""Back to the standard setup for this slot (the active preset is kept for undo).""" 332idx = _index () 333entry = idx .get (slot ) 334if isinstance (entry ,dict )and entry .get ("active" ): 335entry .setdefault ("history" , []).append (entry ["active" ]) 336entry ["active" ]= None 337_save_index (idx ) 338 339 340def undo (slot_or_ref :str )-> dict [str ,Any ]| None : 341"""Restore the preset that was active before the current one (None = the standard setup). ``slot_or_ref`` is a slot 342key or any preset of the slot.""" 343idx = _index () 344slot = slot_or_ref if slot_or_ref in idx else None 345if slot is None : 346slot = find (slot_or_ref )["slot" ] 347entry = idx .get (slot ) 348if not isinstance (entry ,dict )or not entry .get ("history" )and entry .get ("active" )is None : 349raise PresetError ("there is nothing to undo" ) 350hist = entry .get ("history" )or [] 351if not hist : 352entry ["active" ]= None 353_save_index (idx ) 354return None 355prev = hist .pop () 356entry ["history" ]= hist 357entry ["active" ]= prev if _path (prev ).exists ()else None 358_save_index (idx ) 359return load (entry ["active" ])if entry ["active" ]else None 360 361 362def rename (ref :str ,name :str )-> dict [str ,Any ]: 363name = name .strip () 364if not name or len (name )> 80 or re .search (r"[\r\n\0]" ,name ): 365raise PresetError ("choose a name of 1 to 80 characters" ) 366p = find (ref ) 367if _name_taken (name ,p ["id" ]): 368raise PresetError ("another preset already has that name" ) 369p ["name" ]= name 370p .pop ("active" ,None ) 371_write_json (_path (p ["id" ]),p ) 372return find (p ["id" ]) 373 374 375def delete (ref :str )-> None : 376p = find (ref ) 377idx = _index () 378for slot ,entry in list (idx .items ()): 379if not isinstance (entry ,dict ): 380continue 381entry ["history" ]= [h for h in entry .get ("history" , [])if h != p ["id" ]] 382if entry .get ("active" )== p ["id" ]: 383entry ["active" ]= entry ["history" ].pop ()if entry ["history" ]else None 384_save_index (idx ) 385try : 386_path (p ["id" ]).unlink () 387except OSError : 388pass 389 390 391def export_preset (ref :str )-> dict [str ,Any ]: 392p = find (ref ) 393p .pop ("active" ,None ) 394return p 395 396 397def import_preset (data :dict [str ,Any ])-> dict [str ,Any ]: 398if not isinstance (data ,dict )or data .get ("schema" )!= SCHEMA : 399raise PresetError ("that file is not a Strata preset" ) 400# (a value only outside the tuner's tested range is kept, #3844; the never list still refuses) 401problems ,_outside = tune_knobs .check_setting_parts ((data .get ("settings" )or {}).get ("args" )or {}, 402 (data .get ("settings" )or {}).get ("env" )or {}, 403tune_knobs .Context (context_tokens = (data .get ("choices" )or {}).get ("context" )or 32768 )) 404if problems : 405raise PresetError ("the preset has settings outside the safe rules: " + "; " .join (problems )) 406data = dict (data ) 407data ["id" ]= uuid .uuid4 ().hex 408data ["name" ]= _unique_name (str (data .get ("name" )or "Imported preset" )) 409data ["previous" ]= None 410data .pop ("active" ,None ) 411_write_json (_path (data ["id" ]),data ) 412return find (data ["id" ]) 413 414 415def record_recheck (ref :str ,outcome :dict [str ,Any ])-> dict [str ,Any ]: 416p = find (ref ) 417p .pop ("active" ,None ) 418rc = dict (p .get ("recheck" )or {}) 419rc ["last_result" ]= outcome 420if outcome .get ("verdict" )== "keep" : 421rc ["last_ok" ]= time .strftime ("%Y-%m-%dT%H:%M:%S%z" ) 422rc ["last_ok_epoch" ]= time .time () 423# an identity that was soft-stale is refreshed once the settings were checked on this PC 424if outcome .get ("identity" ): 425p ["identity" ]= outcome ["identity" ] 426better = outcome .get ("measured" ) 427if better and p .get ("measured" , {}).get ("decode_tok_s" )and better .get ("decode_tok_s" )and \ 428better ["decode_tok_s" ]> 1.03 * p ["measured" ]["decode_tok_s" ]: 429p ["measured" ].update ({k :v for k ,v in better .items ()if v is not None }) 430p ["recheck" ]= rc 431_write_json (_path (p ["id" ]),p ) 432return find (p ["id" ]) 433 434 435# --------------------------------------------------------------------------- applying the active preset at every start 436 437def notice (preset :dict [str ,Any ])-> str : 438a = preset .get ("answers" )or {} 439if a .get ("default_repeatable" )is False and a .get ("class" ,"exact" )in tune_knobs .ANSWER_NOTICE_UNSTEADY : 440return tune_knobs .ANSWER_NOTICE_UNSTEADY [a .get ("class" ,"exact" )] 441return tune_knobs .ANSWER_NOTICE .get (a .get ("class" ,"exact" ),"" ) 442 443 444def overlay (cfg :dict [str ,Any ],* ,now :dict [str ,Any ]| None = None ,use :str = "chat" )-> tuple [dict [str ,Any ],dict [str ,Any ]]: 445"""The run configuration with the active preset for its choices put on top, and what was done. 446 447No measurement happens here. A preset whose identity changed in a *hard* way is not applied (it says why); a *soft* change 448applies it and marks it for a re-check. A setting on the never list (measured harmful) is left out, never applied; one 449that is only outside the range the tuner tries is kept and listed in ``info["warnings"]``. Never raises: 450a store that cannot be read means "no preset", and the engine starts with the configuration as it is.""" 451info :dict [str ,Any ]= {"applied" :False } 452try : 453if not preset_dir ().is_dir (): 454return cfg ,info 455choices = choices_from_config (cfg ,use = use ) 456now = now or current_identity (cfg ) 457digest = (now .get ("model" )or {}).get ("sha256_shard1" ) 458entry = _index ().get (slot_key (choices ,digest )) 459if not isinstance (entry ,dict )or not entry .get ("active" ): 460return cfg ,info 461preset = load (entry ["active" ]) 462stale = staleness (preset ,now ) 463info .update ({"preset" : {"id" :preset ["id" ],"name" :preset ["name" ]},"state" :stale ["state" ],"reasons" :stale ["reasons" ]}) 464if stale ["state" ]== "hard" : 465info ["why_not" ]= "not applied: " + "; " .join (stale ["reasons" ]) 466return cfg ,info 467s = preset .get ("settings" )or {} 468ctx = tune_knobs .Context (context_tokens = choices .get ("context" )or 32768 ,family = choices .get ("family" )or "flash-next" ) 469problems ,outside = tune_knobs .check_setting_parts (s .get ("args" )or {},s .get ("env" )or {},ctx ) 470if problems : 471info ["why_not" ]= "not applied: " + "; " .join (problems ) 472return cfg ,info 473if outside :# #3844: a value outside the range the tuner tries was chosen by the user: kept, with a warning 474info ["warnings" ]= tune_knobs .keep_warnings (outside ) 475out = json .loads (json .dumps (cfg )) 476out ["args" ]= tune_knobs .apply_to_argv ([str (a )for a in out .get ("args" )or []],s .get ("args" )or {}) 477if s .get ("env" ): 478out ["env" ]= tune_knobs .apply_to_env (dict (out .get ("env" )or {}),s ["env" ]) 479if s .get ("per_request" ): 480sampling = dict (out .get ("sampling" )or {}) 481sampling .setdefault ("strata_tune" , {k :v for k ,v in s ["per_request" ].items ()if v is not None }) 482out ["sampling" ]= sampling 483info .update ({"applied" :True ,"args" :s .get ("args" ),"env" :s .get ("env" ),"per_request" :s .get ("per_request" ), 484"answers" :preset .get ("answers" ),"notice" :notice (preset )}) 485return out ,info 486except Exception as e :# noqa: BLE001 - serving must never fail because of the preset store 487info ["error" ]= f" { type ( e ). __name__ } : { e } " 488return cfg ,info 489 490 491# --------------------------------------------------------------------------- history of every trial 492 493def history_path ()-> Path : 494return preset_dir ()/ "history.jsonl" 495 496 497def record_trials (trials :list [dict [str ,Any ]],* ,hw_hash :str ,model_digest :str | None ,engine_sha :str | None )-> None : 498rows = [] 499for t in trials : 500args = {} 501a = t .get ("args" )or [] 502rows .append ({"at" :t .get ("at" ),"hw" :hw_hash ,"model" :model_digest ,"engine" :engine_sha ,"label" :t .get ("label" ), 503"sig" :" " .join (str (x )for x in a )+ "|" + json .dumps (t .get ("env" )or {},sort_keys = True ), 504"status" :t .get ("status" ),"reason" :t .get ("reason" ),"decode_tok_s" :t .get ("decode_tok_s" ), 505"pp_tok_s" :t .get ("pp_tok_s" ),"rss_peak_mib" :t .get ("rss_peak_mib" )}) 506if not rows : 507return 508p = history_path () 509p .parent .mkdir (parents = True ,exist_ok = True ) 510with open (p ,"a" ,encoding = "utf-8" )as fh : 511for r in rows : 512fh .write (json .dumps (r ,sort_keys = True )+ "\n" ) 513 514 515def bad_signatures (* ,hw_hash :str ,model_digest :str | None ,engine_sha :str | None )-> set [str ]: 516"""Candidates that did not start on this PC with this engine and model before (UNSUPPORTED or OOM): never retried. 517A candidate that also has a PASS row for the same command here is not listed: one busy-card failure after it 518worked must not switch it off for good (#3502).""" 519bad :set [str ]= set () 520passed :set [str ]= set () 521try : 522for line in history_path ().read_text (encoding = "utf-8" ).splitlines (): 523r = json .loads (line ) 524if r .get ("hw" )== hw_hash and r .get ("model" )== model_digest and r .get ("engine" )== engine_sha : 525if r .get ("status" )in ("UNSUPPORTED" ,"OOM" ): 526bad .add (r .get ("label" )or "" ) 527elif r .get ("status" )== "PASS" : 528passed .add (r .get ("label" )or "" ) 529except (OSError ,ValueError ): 530pass 531return bad - passed