okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""The tuner's knowledge, as data: which settings it may try, the bounds, the never-pick list, and what each costs. 2 3Everything here comes from the measured study in ``phaseA-tests/split/TUNING-SPEC.md`` (S5a, draft 1; section numbers 4below are that document's). The rules are tables, not code, so a new measurement changes a row, and the same rows check a 5candidate before it runs and a preset before it is applied. 6 7Rule 1 (6.6): a candidate is a **single-knob change of the user's own configuration**. It never starts at "the first 8value of every dimension" (that is how the old Terminal sweep put ``--expert-cache 0 --kv fp16 --spec-min-p 0.001`` in 9place of the user's settings). Rule 2: a value outside the bounds, or on the never list, is not tried. Rule 3: boolean 10flags are present or absent (``--kv-grow 0`` is an unknown argument). 11 12Answer classes (3.2): ``exact`` (byte-identical to the standard setup), ``placement`` (same math, a different CPU/GPU 13split, so near-ties can flip), ``quality`` (changes the numbers on purpose; never automatic), ``nonrepeatable`` (not 14bit-exact run to run). Only ``exact`` is picked on its own; the others need the user's tick. 15""" 16 17from __future__import annotations 18 19import sys 20from dataclasses import dataclass ,field 21from typing import Any ,Sequence 22 23from strata_control import user_args 24 25ANSWER_ORDER = ("exact" ,"placement" ,"nonrepeatable" ,"quality" ) 26 27#: What the Tune screen says about a preset's answer class (3.4), in plain words. 28ANSWER_NOTICE = { 29"exact" :"Answers are identical to the standard setup." , 30"placement" :"Answers may differ slightly from the standard setup." , 31"nonrepeatable" :"Answers are not repeatable run to run." , 32"quality" :"Includes a quality setting that changes the numbers." , 33} 34 35#: On some cards the standard setup itself is not repeatable run to run (the RTX 3060 in resident-RAM mode and the Arc A750: 36#: 2 and 3 of 10 gate prompts identical between two runs of the default, spec 3.3 note). There "exact" can only mean "no worse 37#: than the default's own variation", so the notice must not promise identical answers. 38ANSWER_NOTICE_UNSTEADY = { 39"exact" :"Answers can differ from run to run on this PC even with the standard setup; this setting does not add to that." , 40} 41 42 43def default_unsteady (ctx :"Context" )-> bool : 44"""True where the setup default is itself not repeatable: the low-RAM resident mode (adaptive tier and draft timing) and SYCL.""" 45return ctx .backend == "sycl" or condition_holds ("resident_ram" ,ctx ) 46 47 48#: Flags that take no value (present = on, absent = off). 49BOOL_FLAGS = frozenset ({"--kv-grow" ,"--trim-stage-weights" ,"--no-host-worker" ,"--no-pool" ,"--mmap-experts" , 50"--resident-experts" ,"--prompt-cache-tail" ,"--vram-elastic" ,"--split-skip-if-fits" , 51"--resident-cpu-experts" ,"--no-hit-poke" ,"--expert-cache-per-layer" ,"--batch-mtp" }) 52 53 54 55# --------------------------------------------------------------------------- the arms 56 57@dataclass( frozen = True ) 58class Arm : 59"""One candidate: a single knob (or one tied group) changed from the user's configuration.""" 60 61id :str 62label :str # plain words, shown in the progress and the result 63answer :str # exact | placement | nonrepeatable | quality 64set_args :dict [str ,Any ]= field (default_factory = dict )# flag -> value | True (present) | None (remove) 65env :dict [str ,str | None ]= field (default_factory = dict ) 66families :tuple [str , ...]= ("flash-next" ,) 67backends :tuple [str , ...]= ("cuda" ,"hip" ) 68classes :tuple [str , ...]= ()# machine classes (6.2) whose list this arm is on 69needs :tuple [str , ...]= ()# machine facts that must hold, see `condition_holds` 70goals :tuple [str , ...]= ("speed" ,"coding" ,"chat" ,"room" ) 71ram_delta_mib :int = 0 # extra memory the engine is predicted to take over the base run 72deep_only :bool = False 73#: what a win is judged on: "decode" (the goal's metric) or "prompt" (long-prompt speed; the knob costs no decode speed) 74metric :str = "decode" 75#: a dynamic value: name of a computed number ("workers-2" ...), filled from the base run's engine log 76dynamic :dict [str ,str ]= field (default_factory = dict ) 77 78def requires_flags (self )-> list [str ]: 79return [f for f in self .set_args if self .set_args [f ]is not None ] 80 81 82ARMS :tuple [Arm , ...]= ( 83# --- long contexts (spec 4.3, 3.3): exact, measured +5.4% decode (5/5) at 128K on the R9700 -------------------------------- 84Arm ("kv_resident_64k" ,"Keep more of the conversation in graphics memory" ,"exact" , {"--kv-resident" :65536 }, 85classes = ("A" ,"B" ,"C" ),backends = ("cuda" ,"hip" ),needs = ("ctx_ge_128k" ,)), 86# --- prompt speed: the chunk size is exact (10/10) and costs no decode speed on a card with VRAM to spare ------------------ 87Arm ("prefill_32k" ,"Larger prompt chunks (faster very long prompts)" ,"exact" , {"--prefill" :"auto:32768" }, 88classes = ("B" ,),goals = ("coding" ,"chat" ),ram_delta_mib = 4096 ,needs = ("vram_ge_24g" ,"long_prompts" ,"discrete_gpu" ),metric = "prompt" ), 89# --- class A: RAM-bound resident mode (RTX 3060 / 46 GB): the one measured gain is adapt-async, behind its own switch ------ 90Arm ("adapt_async" ,"Learn which experts to keep while you chat, in the background" ,"nonrepeatable" , 91 {"--adapt-async" :1 },backends = ("cuda" ,),classes = ("A" ,),needs = ("resident_ram" ,"one_gpu" )), 92# --- placement-dependent (behind the owner's switch for answers that may differ slightly) --------------------------------- 93Arm ("adapt_tier_fast" ,"Re-balance the expert cache faster" ,"placement" , 94 {"--adapt-every" :1 ,"--adapt-swaps" :80 ,"--adapt-decay" :0.97 },classes = ("B" ,"C" )), 95Arm ("adapt_decay_09" ,"Forget old expert use a little faster" ,"placement" , {"--adapt-decay" :0.9 }, 96classes = ("B" ,"C" ,"G" ),backends = ("cuda" ,"hip" ,"sycl" )), 97Arm ("spec3" ,"Shorter speculative window (3 tokens)" ,"placement" , {"--spec" :3 },classes = ("A" ,"B" )), 98# --- class C: mid graphics memory, PCIe-bound ------------------------------------------------------------------------------- 99Arm ("trim_stage" ,"Trim stage weights on two cards" ,"exact" , {"--trim-stage-weights" :True }, 100backends = ("cuda" ,),classes = ("C" ,),needs = ("two_gpus" ,)), 101# --- class G: Intel Arc (SYCL): +5.5% (5/5, twice) ------------------------------------------------------------------------ 102Arm ("pcie_start_02" ,"Start with a smaller PCIe share" ,"placement" , {"--pcie-frac" :0.2 }, 103backends = ("sycl" ,),classes = ("G" ,)), 104# --- Qwen3.6 hybrid (class D): exact while the experts fit the card, placement-dependent when CPU experts take part ------ 105Arm ("q36_workers_explicit" ,"Fix the CPU helper thread count" ,"exact" , {},families = ("qwen36" ,), 106backends = ("cuda" ,"hip" ),classes = ("D" ,),dynamic = {"--pool-workers" :"workers" },needs = ("hybrid_experts" ,)), 107Arm ("q36_mtp1" ,"Shorter draft window (1)" ,"placement" , {"--mtp" :1 },families = ("qwen36" ,), 108backends = ("cuda" ,"hip" ),classes = ("D" ,),needs = ("hybrid_experts" ,)), 109Arm ("q36_prefill_4096" ,"Larger prompt chunks (twice the prompt speed, a little slower answers)" ,"placement" , 110 {"--prefill" :4096 },families = ("qwen36" ,),backends = ("cuda" ,"hip" ),classes = ("D" ,),goals = ("coding" ,), 111needs = ("hybrid_experts" ,)), 112Arm ("q36_hybrid_rows_256" ,"Larger hybrid row blocks" ,"placement" , {"--hybrid-rows" :256 },families = ("qwen36" ,), 113backends = ("cuda" ,"hip" ),classes = ("D" ,),needs = ("hybrid_experts" ,),deep_only = True ), 114# --- thorough only: measured as no effect (spec 4.2-4.4), tried last ------------------------------------------------------ 115Arm ("pin_by_need" ,"Pin memory only when needed" ,"exact" , {}, {"STRATA_PIN_BY_NEED" :"1" }, 116backends = ("cuda" ,),classes = ("C" ,),needs = ("one_gpu" ,),deep_only = True ), 117Arm ("host_core_last" ,"Run the control thread on the last CPU core" ,"exact" , {"--host-core" :"last" }, 118classes = ("B" ,"C" ),deep_only = True ), 119Arm ("workers_minus1" ,"One fewer CPU helper thread" ,"exact" , {},classes = ("F" ,), 120dynamic = {"--pool-workers" :"workers-1" },needs = ("hybrid_cpu" ,),deep_only = True ), 121Arm ("kv_grow" ,"Allocate the conversation memory as it grows" ,"exact" , {"--kv-grow" :True }, 122classes = ("B" ,"C" ),backends = ("cuda" ,"hip" ,"sycl" ),deep_only = True ), 123) 124 125#: The per-request settings (3.1, 4.1). They need no restart, so every one is tried before any restart (5). 126#: `values` are tried against the engine's own choice (absent); a win needs >= 3% in every round. 127PER_REQUEST :tuple [dict [str ,Any ], ...]= ( 128 {"key" :"pcie_frac" ,"values" : (0.2 ,0.35 ,0.0 ),"backends" : ("cuda" ,"hip" ,"sycl" ), 129"label" :"PCIe share" ,"answer" :"placement" }, 130 {"key" :"spec_min_p" ,"values" : (0.7 ,0.5 ),"backends" : ("cuda" ,"hip" ,"sycl" ,"metal" ), 131"label" :"speculative confidence floor" ,"answer" :"exact" }, 132 {"key" :"aux_cpus" ,"values" : (1 ,0 ),"backends" : ("cuda" ,"hip" ),"label" :"spare CPU cores for helper threads" , 133"answer" :"exact" }, 134) 135 136# --------------------------------------------------------------------------- bounds and the never list 137 138#: Safe bounds (6.6, column 3). A value outside them is not tried and is refused in a preset. 139BOUNDS :dict [str ,dict [str ,Any ]]= { 140"--spec" : {"choices" : (3 ,4 )}, 141"--spec-min-p" : {"min" :0.3 ,"max" :0.7 }, 142"--mtp" : {"choices" : (1 ,2 ,3 ),"numeric_only" :True },# Qwen3.6; Flash-Next's --mtp is a path 143"--pcie-frac" : {"min" :0.0 ,"max" :0.55 }, 144"--adapt-every" : {"min" :1 ,"max" :4 }, 145"--adapt-swaps" : {"min" :80 ,"max" :160 }, 146"--adapt-decay" : {"min" :0.7 ,"max" :0.97 }, 147"--hybrid-rows" : {"min" :64 ,"max" :256 }, 148"--host-core" : {"choices" : ("first" ,"last" )}, 149"--kv-resident" : {"choices" : (32768 ,49152 ,65536 )}, 150"--prefill" : {"choices" : ("auto" ,"auto:16384" ,"auto:32768" ,2048 ,4096 )}, 151} 152 153#: The never-pick list (4.5), as rows: ``flag`` (or ``env``), a condition on the machine, the value test and the reason 154#: in plain words. ``when`` names facts from `condition_holds`; empty = always. 155NEVER :tuple [dict [str ,Any ], ...]= ( 156 {"env" :"STRATA_SH_STREAM" ,"when" : ("gfx12" ,),"reason" :"it halves decode speed on this graphics card" }, 157 {"env" :"STRATA_SH_STREAM" ,"when" : ("windows_amd_kv_stream" ,),"reason" :"with KV streaming on Windows it made the engine fail on the first request on one RX 6000 PC (#3895)" }, 158 {"env" :"STRATA_RDNA2_SGEMM" ,"value" :"all" ,"when" : ("gfx12" ,),"reason" :"it makes long prompts five times slower" }, 159 {"env" :"STRATA_SELECT_SIMT" ,"reason" :"its gain is below the 3% margin" }, 160 {"env" :"STRATA_HIP_WMMA" ,"reason" :"it changes the numbers (a quality setting)" }, 161 {"flag" :"--pool-affinity" ,"when" : ("hybrid_cpu" ,),"values" : ("auto" ,"p-cores" ), 162"reason" :"it made answers 47% slower on a CPU with performance and efficiency cores" }, 163 {"flag" :"--pool-workers" ,"test" :"above_engine_default" ,"reason" :"more helper threads than the engine chose made it 36% slower" }, 164 {"flag" :"--ple-io" ,"values" : ("ram" ,"mmap" ),"when" : ("ram_bound" ,), 165"reason" :"it needs the table in memory, which this PC does not have to spare (-61% speed)" }, 166 {"flag" :"--adapt-every" ,"test" :"at_least" ,"limit" :100000 ,"reason" :"turning the expert re-balancing off cost 3% to 44%" }, 167 {"flag" :"--kv-resident" ,"test" :"kv_resident" ,"reason" :"below the context it made answers 22% to 34% slower (and changes them) except at 128K, where only 49152 and 65536 were measured as flat or better" }, 168 {"flag" :"--pcie-frac" ,"test" :"at_least" ,"limit" :0.75 ,"when" : ("pcie_bound" ,), 169"reason" :"a high PCIe share made answers 14% to 37% slower" }, 170 {"flag" :"--prefill" ,"test" :"fixed_below_auto" ,"reason" :"smaller prompt chunks made long prompts 11% to 75% slower" }, 171 {"flag" :"--expert-vram" ,"test" :"without_prefill" ,"families" : ("qwen36" ,), 172"reason" :"without a matching prompt chunk it made prompts 44% slower" }, 173 {"flag" :"--spec" ,"test" :"at_least" ,"limit" :6 ,"reason" :"wider speculative windows were 4% to 16% slower" }, 174 {"flag" :"--spec" ,"test" :"at_most" ,"limit" :2 ,"families" : ("flash-next" ,),"reason" :"a 2-token window was 4% to 11% slower" }, 175 {"flag" :"--lookup-chain" ,"reason" :"it was 3% to 8.5% slower" }, 176 {"flag" :"--vram-reserve-mib" ,"when" : ("vram_le_8g" ,),"reason" :"this card cannot start with a reserve" }, 177 {"flag" :"--expert-cache" ,"test" :"zero_or_small" ,"reason" :"turning the GPU expert cache off or very small costs speed" }, 178 {"flag" :"--mtp" ,"test" :"mtp_extreme" ,"families" : ("qwen36" ,),"reason" :"that draft window was 10% to 28% slower" }, 179) 180 181#: Which flags change answers by themselves, for the notice on a preset (3.4). 182ANSWER_OF_FLAG :dict [str ,str ]= { 183"--expert-cache" :"placement" ,"--vram-reserve-mib" :"placement" ,"--adapt-every" :"placement" , 184"--adapt-swaps" :"placement" ,"--adapt-decay" :"placement" ,"--adapt-min-gain" :"placement" , 185"--pcie-frac" :"placement" ,"--spec" :"placement" ,"--mtp" :"placement" ,"--lookup-chain" :"placement" , 186"--kv" :"quality" ,"--adapt-async" :"nonrepeatable" , 187} 188 189 190# --------------------------------------------------------------------------- the context rules run in 191 192@dataclass 193class Context : 194"""The machine and the choices a candidate plan is made for.""" 195 196backend :str = "cuda" # cuda | hip | sycl | metal | cpu 197family :str = "flash-next" # flash-next | qwen36 198gpu_count :int = 1 199vram_mib :int = 0 # the card the model runs on (smallest if several) 200ram_gib :int = 0 201model_gib :float = 0.0 202hybrid_cpu :bool = False 203logical_threads :int = 0 204arch :str | None = None # e.g. gfx1201 205context_tokens :int = 32768 206goal :str = "speed" # speed | room 207use :str = "chat" # chat | coding 208allow_placement :bool = False 209allow_nonrepeatable :bool = False 210facts :dict [str ,Any ]= field (default_factory = dict )# parsed from the base run's engine log 211engine_flags :Sequence [str ]| None = None 212base_args :list [str ]= field (default_factory = list ) 213 214 215def condition_holds (name :str ,ctx :Context )-> bool : 216f = ctx .facts 217return { 218"resident_ram" :bool (f .get ("resident_ram" ))or "--resident-experts" in ctx .base_args , 219"one_gpu" :ctx .gpu_count <= 1 , 220"two_gpus" :ctx .gpu_count == 2 , 221"hybrid_cpu" :ctx .hybrid_cpu , 222"hybrid_experts" :bool (f .get ("hybrid_experts" )), 223"vram_ge_24g" :ctx .vram_mib >= 24000 , 224"discrete_gpu" :not (ctx .arch and ctx .arch .split (":" )[0 ]in ("gfx1151" ,"gfx1150" ,"gfx1103" )),# an APU's pool is shared with the expert cache 225"vram_le_8g" :0 < ctx .vram_mib <= 8400 , 226"gfx12" :bool (ctx .arch and ctx .arch .startswith ("gfx12" )), 227"windows_amd_kv_stream" :ctx .backend == "hip" and sys .platform == "win32" and "--kv-resident" in ctx .base_args , 228"pcie_bound" :0 < ctx .vram_mib < 24000 , 229"ram_bound" :bool (ctx .ram_gib and ctx .model_gib and ctx .ram_gib - ctx .model_gib < 30 ), 230"ctx_ge_128k" :ctx .context_tokens >= 98304 , 231"long_prompts" :ctx .context_tokens >= 65536 or ctx .use == "coding" , 232 }.get (name ,False ) 233 234 235def machine_classes (ctx :Context )-> list [str ]: 236"""The classes of 6.2 this machine belongs to, in the order their candidate lists are walked.""" 237classes :list [str ]= [] 238if ctx .family == "qwen36" : 239classes .append ("D" if ctx .facts .get ("hybrid_experts" )else "E" ) 240return classes 241if ctx .backend == "sycl" : 242return ["G" ] 243if condition_holds ("resident_ram" ,ctx )or (ctx .ram_gib and ctx .model_gib and ctx .ram_gib - ctx .model_gib < 12 ): 244classes .append ("A" ) 245classes .append ("B" if ctx .vram_mib >= 24000 else "C" ) 246if ctx .hybrid_cpu : 247classes .append ("F" ) 248return classes 249 250 251# --------------------------------------------------------------------------- rule checks 252 253def _as_number (value :Any )-> float | None : 254try : 255return float (value ) 256except (TypeError ,ValueError ): 257return None 258 259 260def _prefill_below_auto (value :Any )-> bool : 261n = _as_number (value ) 262return n is not None and not str (value ).startswith ("auto" ) 263 264 265def check_setting (args :dict [str ,Any ],env :dict [str ,str | None ],ctx :Context )-> list [str ]: 266"""Reasons (plain words) a setting must not be applied; an empty list means it is inside the rules. 267 268``args`` maps flag -> value (True for a present boolean flag); ``env`` maps name -> value. The tuner uses this whole 269list for what it tries; a saved or imported preset uses `check_setting_parts` (see there).""" 270never ,bounds = check_setting_parts (args ,env ,ctx ) 271return never + bounds 272 273 274def check_setting_parts (args :dict [str ,Any ],env :dict [str ,str | None ],ctx :Context )-> tuple [list [str ],list [str ]]: 275"""(never, bounds): `never` are the settings measured to be harmful (the never list: slower, unsafe, or changing the 276numbers); `bounds` are values outside the range the tuner tried (``--spec 5``, ``--pcie-frac 0.6``), which nobody 277measured as bad. A preset keeps a user's setting that is only outside the tested range, with a warning (#3844); the 278tuner itself never tries one.""" 279problems :list [str ]= [] 280ctx_tokens = ctx .context_tokens 281default_workers = ctx .facts .get ("workers" ) 282for rule in NEVER : 283fams = rule .get ("families" ) 284if fams and ctx .family not in fams : 285continue 286if any (not condition_holds (w ,ctx )for w in rule .get ("when" , ())): 287continue 288if "env" in rule : 289if rule ["env" ]in env and env [rule ["env" ]]not in (None ,"" ,"0" )and \ 290 ("value" not in rule or env [rule ["env" ]]== rule ["value" ]): 291problems .append (f" { rule [ 'env' ] } : { rule [ 'reason' ] } " ) 292continue 293flag = rule ["flag" ] 294if flag not in args or args [flag ]is None : 295continue 296value = args [flag ] 297test = rule .get ("test" ) 298hit = False 299if "values" in rule : 300hit = str (value )in rule ["values" ] 301elif test is None : 302hit = True 303elif test == "above_engine_default" : 304n = _as_number (value ) 305hit = n is not None and default_workers is not None and n > float (default_workers ) 306elif test == "at_least" : 307n = _as_number (value ) 308hit = n is not None and n >= rule ["limit" ] 309elif test == "at_most" : 310n = _as_number (value ) 311hit = n is not None and n <= rule ["limit" ]and flag == "--spec" 312elif test == "kv_resident" : 313n = _as_number (value ) 314own = _as_number (_current (ctx .base_args ,"--kv-resident" )) 315# the config's own value is always fine; at a long context 49152 and 65536 were measured; anything else below the context is not 316hit = n is not None and n < ctx_tokens and n != own and not (ctx_tokens >= 98304 and n in (49152 ,65536 )) 317elif test == "fixed_below_auto" : 318hit = _prefill_below_auto (value )and ctx .family == "flash-next" 319if ctx .family == "qwen36" : 320n = _as_number (value ) 321hit = n is not None and n <= 512 322elif test == "without_prefill" : 323hit = "--prefill" not in args and "--prefill" not in _flags_of (ctx .base_args ) 324elif test == "zero_or_small" : 325n = _as_number (value ) 326hit = n is not None and str (value )!= "auto" and n < 0.5 * float (ctx .facts .get ("auto_slots" )or 0 or 1 ) 327elif test == "mtp_extreme" : 328n = _as_number (value ) 329hit = n is not None and (n == 0 or n >= 4 ) 330if hit : 331problems .append (f" { flag } { value } : { rule [ 'reason' ] } " ) 332bound_problems :list [str ]= [] 333for flag ,value in args .items (): 334bound = BOUNDS .get (flag ) 335if not bound or value is None or value is True : 336continue 337if bound .get ("numeric_only" )and _as_number (value )is None : 338continue 339if "choices" in bound and value not in bound ["choices" ]and str (value )not in [str (c )for c in bound ["choices" ]]: 340bound_problems .append (f" { flag } { value } : outside the safe values { list ( bound [ 'choices' ]) } " ) 341n = _as_number (value ) 342if n is not None and "min" in bound and n < bound ["min" ]: 343bound_problems .append (f" { flag } { value } : below the safe minimum { bound [ 'min' ] } " ) 344if n is not None and "max" in bound and n > bound ["max" ]: 345bound_problems .append (f" { flag } { value } : above the safe maximum { bound [ 'max' ] } " ) 346return problems ,bound_problems 347 348 349def keep_warnings (bound_problems :Sequence [str ])-> list [str ]: 350"""The short warning for each setting that is outside the tested range and is kept (#3844): said, never dropped.""" 351return [f" { p . split ( ': ' , 1 )[ 0 ] } : not tried by the tuner, kept because it is your setting" for p in bound_problems ] 352 353 354def _flags_of (argv :Sequence [str ])-> set [str ]: 355return {a for a in argv if isinstance (a ,str )and a .startswith ("--" )} 356 357 358def answer_class (args :dict [str ,Any ],env :dict [str ,str | None ]| None = None , 359base_args :dict [str ,Any ]| None = None )-> tuple [str ,list [str ]]: 360"""The worst answer class among the settings that differ from the base, and which flags cause it.""" 361worst ,fields = "exact" , [] 362base_args = base_args or {} 363for flag ,value in args .items (): 364if base_args .get (flag )== value : 365continue 366cls = ANSWER_OF_FLAG .get (flag ) 367if cls : 368fields .append (flag ) 369if ANSWER_ORDER .index (cls )> ANSWER_ORDER .index (worst ): 370worst = cls 371return worst ,fields 372 373 374def allowed (answer :str ,ctx :Context )-> bool : 375"""May an arm of this answer class be picked on its own? Exact always; the rest need the user's tick; quality never.""" 376return answer == "exact" or (answer == "placement" and ctx .allow_placement )or \ 377 (answer == "nonrepeatable" and ctx .allow_nonrepeatable ) 378 379 380# --------------------------------------------------------------------------- planning 381 382def dynamic_value (spec :str ,ctx :Context )-> Any : 383f = ctx .facts 384workers = f .get ("workers" ) 385if spec == "workers" : 386return int (workers )if workers else None 387if spec .startswith ("workers-" )and workers : 388value = int (workers )- int (spec [len ("workers-" ):]) 389floor = max (2 ,int (workers )- 1 )# one step down at most (6.2 F); never two below (6.2 C) 390return value if value >= floor else None 391return None 392 393 394@dataclass 395class PlannedArm : 396arm :Arm 397args :dict [str ,Any ] 398env :dict [str ,str | None ] 399 400 401def plan_arms (ctx :Context ,* ,mode :str = "quick" ,history_bad :set [str ]| None = None )-> tuple [list [PlannedArm ],list [dict [str ,str ]]]: 402"""The candidates for this machine in the order they are tried, and the ones left out with the reason. 403 404Order: the machine's classes in order (6.2), each class's arms in the table order. Quick keeps the first ones the 405time budget allows; thorough keeps all of them, flat knobs last.""" 406classes = machine_classes (ctx ) 407base_flags = _flags_of (ctx .base_args ) 408chosen :list [PlannedArm ]= [] 409skipped :list [dict [str ,str ]]= [] 410seen :set [str ]= set () 411for cls in classes : 412for arm in ARMS : 413if cls not in arm .classes or arm .id in seen : 414continue 415seen .add (arm .id ) 416 417def skip (reason :str )-> None : 418skipped .append ({"id" :arm .id ,"label" :arm .label ,"reason" :reason }) 419 420if ctx .family not in arm .families : 421continue 422if ctx .backend not in arm .backends : 423skip (f"not a { ctx . backend } setting" ) 424continue 425if arm .deep_only and mode != "thorough" : 426skip ("only tried in the thorough tune (it was measured as flat)" ) 427continue 428if ctx .goal not in arm .goals and ctx .use not in arm .goals : 429skip ("does not serve what you asked for" ) 430continue 431if not allowed (arm .answer ,ctx ): 432skip ({"placement" :"it can change answers slightly; tick 'allow small answer differences' to try it" , 433"nonrepeatable" :"answers would not repeat run to run; tick 'allow settings that are not repeatable' to try it" , 434"quality" :"it is a quality setting, never chosen automatically" }.get (arm .answer ,"not allowed" )) 435continue 436miss = [n for n in arm .needs if not condition_holds (n ,ctx )] 437if miss : 438skip ("this PC does not match: " + ", " .join (miss ).replace ("_" ," " )) 439continue 440args = dict (arm .set_args ) 441bad = False 442for flag ,spec in arm .dynamic .items (): 443v = dynamic_value (spec ,ctx ) 444if v is None : 445skip ("the engine's current value could not be read" ) 446bad = True 447break 448args [flag ]= v 449if bad : 450continue 451if ctx .engine_flags is not None : 452unknown = [f for f in args if f not in ctx .engine_flags ] 453if unknown : 454skip ("this engine does not accept " + ", " .join (unknown )) 455continue 456problems = check_setting (args ,dict (arm .env ),ctx ) 457if problems : 458skip ("; " .join (problems )) 459continue 460if all (_current (ctx .base_args ,f )== _norm (v )for f ,v in args .items ())and not arm .env : 461skip ("already the current setting" ) 462continue 463sig = signature (args ,arm .env ) 464if history_bad and (sig in history_bad or arm .id in history_bad ): 465skip ("did not start on this PC before" ) 466continue 467chosen .append (PlannedArm (arm ,args ,dict (arm .env ))) 468return chosen ,skipped 469 470 471def _norm (value :Any )-> str | None : 472return None if value is None else ("" if value is True else str (value )) 473 474 475def _current (argv :Sequence [str ],flag :str )-> str | None : 476"""The value a flag has in an argv list: '' for a bare flag, None when absent (several values joined by a space).""" 477for i ,a in enumerate (argv ): 478if a == flag : 479if flag in BOOL_FLAGS or i + 1 >= len (argv )or str (argv [i + 1 ]).startswith ("--" ): 480return "" 481return " " .join (str (x )for x in argv [i + 1 :i + 1 + _value_count (argv ,i )]) 482return None 483 484 485def _value_count (argv :Sequence [str ],i :int ,bool_flags :frozenset [str ]= BOOL_FLAGS )-> int : 486"""How many entries after the flag at ``argv[i]`` are its values: none for a bool flag, as many as the option takes 487(``--control-vector-layer-range 4 44`` is two) up to the next ``--option``.""" 488flag = argv [i ] 489if flag in bool_flags : 490return 0 491n = 0 492while n < user_args .MULTI_VALUE_FLAGS .get (flag ,1 )and i + 1 + n < len (argv )and not str (argv [i + 1 + n ]).startswith ("--" ): 493n += 1 494return n 495 496 497def signature (args :dict [str ,Any ],env :dict [str ,str | None ]| None = None )-> str : 498parts = [f" { k } = { _norm ( v ) } " for k ,v in sorted (args .items ())]+ [f" { k } = { v } " for k ,v in sorted ((env or {}).items ())] 499return "|" .join (parts ) 500 501 502def apply_to_argv (argv :Sequence [str ],args :dict [str ,Any ],bool_flags :frozenset [str ]= BOOL_FLAGS )-> list [str ]: 503"""The user's argv with the candidate's settings put on top (Rule 3: a boolean is present or absent). 504`bool_flags`: the engine's flags that take no value.""" 505out = list (argv ) 506for flag ,value in args .items (): 507i = 0 508while i < len (out ): 509if out [i ]== flag : 510del out [i :i + 1 + _value_count (out ,i ,bool_flags )] 511else : 512i += 1 513if value is None or value is False : 514continue 515if value is True or flag in bool_flags : 516out .append (flag ) 517else : 518out .extend ([flag ,* user_args .value_tokens (flag ,value )]) 519return out 520 521 522def apply_to_env (env :dict [str ,str ],changes :dict [str ,str | None ])-> dict [str ,str ]: 523out = dict (env ) 524for k ,v in changes .items (): 525if v is None : 526out .pop (k ,None ) 527else : 528out [k ]= str (v ) 529return out