okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2503b206b
main
1"""Engine tuning: a bounded, evidence-driven search over runtime configuration. 2 3This is **runtime configuration optimization**, not model training. It searches the engine's own 4launch settings, measures each candidate, and produces a *recommendation* — never an automatic 5change. 6 7Why Strata owns this rather than delegating wholesale to HyperCore-Tune 8----------------------------------------------------------------------- 9 10HyperCore-Tune was evaluated as the preferred adapter and is **not sufficient as the optimizer** for 11every backend. The evidence, gathered from the pinned checkout and this machine's engine: 12 13* Its search space is expressed as engine flags: ``--vram-reserve-mib``, ``--pcie-frac``, 14``--pool-workers``, ``--host-core``, ``--pool-affinity``, ``--ple-io``, ``--kv``, ``--kv-grow``, 15``--prompt-cache-tail``, ``--spec-min-p``. Two of those, ``--vram-reserve-mib`` and 16``--pcie-frac``, are NVIDIA/AMD concepts: the Apple Silicon engine does not parse them at all 17(``strata --help`` on the Metal build lists neither). On Metal their "measurements" could only be 18an engine refusal, so a HyperCore sweep there would produce ``FAIL_BOOT`` rows rather than 19evidence. 20* It resolves the engine by walking up from its own directory looking for a Strata checkout, and it 21writes its deliverables next to that root. Neither is acceptable for a packaged application: the 22component registry must name an exact engine build, and the active profile must not be mutated by 23a search. 24* Its README states Linux and Windows support and its tests use stub engines. That is a claim about 25the harness, not a qualification of any GPU. 26 27So the decision, recorded here rather than in a design document alone: **Strata owns the job, the 28lease, the evidence and the apply step; HyperCore-Tune remains a candidate optimizer behind that 29job for the backends whose flags it actually targets.** The dimension table below is the mechanism 30that makes this safe — a dimension whose flag the selected backend cannot accept is *excluded with a 31reason*, so a sweep can never "measure" a configuration the engine would refuse. 32 33What this module deliberately does not do 34----------------------------------------- 35 36* It never writes the active profile. It produces a report; applying is a separate step. 37* It never invents a metric. A candidate that failed to boot, produced no tokens, or whose 38measurement could not be taken is recorded with its failure and excluded from selection. 39* It never claims a winner from fewer than the required repeats, and it always re-measures the 40*baseline* at the end so drift is visible in the report. 41* It never promises a speed-up. The report says what was measured, on what, and how many times. 42 43Stdlib only, like the rest of Strata Control: the tuner is optional and its absence must leave 44serving untouched. 45""" 46 47from __future__import annotations 48 49import json 50import os 51import platform 52from strata_control import sysinfo 53from strata_control .childenv import quiet_crash_env 54import statistics 55import subprocess 56import time 57import uuid 58from dataclasses import asdict ,dataclass ,field 59from pathlib import Path 60from typing import Any ,Callable ,Sequence 61 62from strata_control import atomic 63 64SCHEMA_VERSION = 1 65 66# --------------------------------------------------------------------------- backends 67 68#: The backend families the product targets. The key is what the engine package manifest and the 69#: profile record, not something inferred from a device name. 70BACKENDS = ("metal" ,"cuda" ,"hip" ,"sycl" ,"cpu" ) 71 72 73@dataclass( frozen = True ) 74class Dimension : 75"""One searchable engine setting. 76 77``flags`` lists the engine flags this dimension drives, and ``backends`` the backends on which 78those flags are meaningful. A dimension is offered only when *every* flag it drives is supported 79by the selected backend — a partial lever would produce a configuration the engine cannot run. 80""" 81 82id :str 83flags :tuple [str , ...] 84values :tuple [Any , ...] 85backends :tuple [str , ...] 86help :str 87#: Benchmark-only levers that must be stripped from the exported production args. 88benchmark_only :bool = False 89 90 91#: The searchable dimensions. Only entries whose flags a backend actually accepts are offered, and 92#: which those are is *checked against the engine binary*, not assumed — see `validate_dimensions`. 93DIMENSIONS :tuple [Dimension , ...]= ( 94Dimension ("ple_io" , ("--ple-io" ,), ("direct" ,"mmap" ,"ram" ), 95 ("metal" ,"cuda" ,"hip" ,"sycl" ,"cpu" ), 96"How the n-gram table is read: unbuffered SSD reads, mmap, or locked in RAM." ), 97Dimension ("kv" , ("--kv" ,), ("fp16" ,"int8" ,"q4_0" ,"k8v4" ), 98 ("metal" ,"cuda" ,"hip" ,"sycl" ,"cpu" ), 99"KV storage format. Lower precision is cheaper and slightly less exact." ), 100Dimension ("kv_grow" , ("--kv-grow" ,), (False ,True ), 101 ("metal" ,"cuda" ,"hip" ,"sycl" ,"cpu" ), 102"Allocate KV only for the cells actually reached, returning VRAM to the expert cache." ), 103Dimension ("expert_cache" , ("--expert-cache" ,), (0 ,1024 ,2048 ,4096 ,8192 ,12288 ,16384 ), 104 ("cuda" ,"hip" ,"sycl" ),"MiB of device memory for the expert cache." ), 105Dimension ("host_core" , ("--host-core" ,), ("first" ,"last" ), 106 ("cuda" ,"hip" ),"Which cores run the host-side work." ), 107Dimension ("pool_affinity" , ("--pool-affinity" ,), ("all" ,"p-cores" ,"auto" ), 108 ("cuda" ,"hip" ),"CPU pool affinity for the expert I/O threads." ), 109Dimension ("pool_workers" , ("--pool-workers" ,), (0 ,2 ,4 ,8 ,12 ,16 ), 110 ("cuda" ,"hip" ),"I/O workers; 0 means every physical core except the host's." ), 111Dimension ("spec_min_p" , ("--spec-min-p" ,), (0.001 ,0.1 ,0.5 ,0.9 ), 112 ("metal" ,"cuda" ,"hip" ,"sycl" ,"cpu" ), 113"Draft-acceptance floor: how confident a speculative token must be to be proposed." ), 114Dimension ("vram_reserve" , ("--vram-reserve-mib" ,), (256 ,512 ,768 ,1024 ,1280 ,1536 ), 115 ("cuda" ,"hip" ), 116"Device memory left free for other programs. NVIDIA/AMD only." ), 117Dimension ("pcie_frac" , ("--pcie-frac" ,), (0.0 ,0.25 ,0.5 ,0.75 ,0.95 ), 118 ("cuda" ,"hip" ),"Share of PCIe bandwidth the expert streamer may use. NVIDIA/AMD only." ), 119Dimension ("prompt_cache_tail" , ("--prompt-cache-tail" ,), (False ,True ), 120 ("cuda" ,"hip" ,"sycl" ), 121"Prompt-cache tail retention. BENCHMARK ONLY: measured, never exported." , 122benchmark_only = True ), 123) 124 125#: Flags that take no value: on when present, off when absent. A candidate records them as "1" / "0". 126BOOLEAN_FLAGS = frozenset (flag for _d in DIMENSIONS if all (isinstance (v ,bool )for v in _d .values )for flag in _d .flags ) 127 128 129def flag_argv (flag :str ,value :Any )-> list [str ]: 130"""One candidate setting as engine argv. A boolean flag is `--flag` when on and nothing when off; it never 131gets a value ("--kv-grow 0" is "unknown argument: 0" to the engine, and a bare "--kv-grow" meaning off enabled it).""" 132if flag in BOOLEAN_FLAGS or isinstance (value ,bool ): 133return [flag ]if value in (True ,"1" ,"true" ,"True" )else [] 134if value is None or value == "" : 135return [flag ] 136return [flag ,str (value )] 137 138 139#: Dimensions a backend must never be offered, with the reason kept for the report. 140def _why_excluded (dim :Dimension ,backend :str )-> str | None : 141if backend in dim .backends : 142return None 143if backend == "metal" : 144if dim .id in ("vram_reserve" ,"pcie_frac" ,"expert_cache" ): 145return ("the Apple Silicon engine does not parse this flag; it is an NVIDIA/AMD device " 146"concept, so a sweep could only record a boot failure" ) 147if dim .id in ("host_core" ,"pool_affinity" ,"pool_workers" ): 148return ("the Metal build's CPU-side pool is not exposed; the flag parses but its " 149"entry point is one of the unported kernels (metal/src/engine/stubs.cpp)" ) 150return f"not a { backend } setting" 151 152 153def validate_dimensions (backend :str , 154engine_flags :Sequence [str ]| None = None )-> tuple [list [Dimension ],list [dict [str ,str ]]]: 155"""Return the dimensions this backend may search, and why the rest were excluded. 156 157When ``engine_flags`` is supplied — the flags the actual engine binary reports — a dimension is 158additionally required to name only flags in that list. That is the check that keeps a sweep from 159measuring a configuration the engine would refuse: if the binary does not accept a flag, the 160dimension is excluded with the flag named, no matter what the static table says. 161""" 162offered :list [Dimension ]= [] 163excluded :list [dict [str ,str ]]= [] 164known = set (engine_flags )if engine_flags is not None else None 165for dim in DIMENSIONS : 166reason = _why_excluded (dim ,backend ) 167if reason is None and known is not None : 168missing = [f for f in dim .flags if f not in known ] 169if missing : 170reason = ("the engine binary does not accept " + ", " .join (missing )+ 171", so a candidate using this dimension could not start" ) 172if reason is None : 173offered .append (dim ) 174else : 175excluded .append ({"id" :dim .id ,"reason" :reason }) 176return offered ,excluded 177 178 179def engine_command (engine :Path | str )-> list [str ]: 180"""The argv prefix that runs an engine: the binary itself, or ``[sys.executable, script.py]``. 181 182A ``.py`` file stands in for the engine in tests and demos (the same READY/PP/T/DONE protocol, 183no weights). Running it through the current interpreter is what works on every OS: a ``#!`` line 184is ignored by Windows, which answers WinError 193. 185""" 186import sys 187path = str (engine ) 188return [sys .executable ,path ]if path .lower ().endswith (".py" )else [path ] 189 190 191def engine_env (engine :Path | str )-> dict [str ,str ]| None : 192"""The environment to run an engine with, or None for the caller's own. 193 194An engine package (`engine-component.json` beside the binary) carries its GPU runtime libraries in its own 195folder, and `serve` puts that folder first on the library path. A tuning run that starts the same binary must 196too, or it cannot even print `--help` ("error while loading shared libraries").""" 197folder = Path (engine ).resolve ().parent 198if not (folder / "engine-component.json" ).is_file (): 199return None 200var = "PATH" if os .name == "nt" else "LD_LIBRARY_PATH" 201env = quiet_crash_env (dict (os .environ )) 202from strata_control import engine_component 203env [var ]= os .pathsep .join (engine_component .package_lib_dirs (folder )+ ([env [var ]]if env .get (var )else [])) 204return env 205 206 207def engine_flag_inventory (engine :Path )-> list [str ]| None : 208"""Read the flags an engine binary documents, or None when it cannot be run here. 209 210Both output streams are read. The Strata engine writes its usage to **stderr**, which is easy to 211miss: a stdout-only read reports "no flags" for a perfectly good engine, and because every 212dimension is then excluded the sweep silently searches nothing. That failure is safe but 213useless, so the parser reads stderr too and only reports None when the binary could not be run 214at all. 215""" 216try : 217proc = subprocess .run ([* engine_command (engine ),"--help" ],capture_output = True ,text = True ,errors = "replace" ,timeout = 20 , 218env = engine_env (engine )) 219except (OSError ,subprocess .SubprocessError ): 220return None 221import re 222text = f" { proc . stdout or '' } \n { proc . stderr or '' } " 223flags = sorted (set (re .findall (r"^\s+(--[a-z0-9-]+)" ,text ,re .MULTILINE ))) 224# `--help` on this engine exits 0 but writes to stderr; exit codes are not a reliable signal, so 225# the presence of a usable flag list is. 226return flags or None 227 228 229# --------------------------------------------------------------------------- the job 230 231@dataclass 232class Candidate : 233"""One configuration and everything that was observed about it.""" 234 235index :int 236settings :dict [str ,Any ] 237args :dict [str ,str ]= field (default_factory = dict ) 238status :str = "pending" # PASS | FAIL_BOOT | NO_TOKENS | TIMEOUT | UNMEASURED | INVALID 239reason :str = "" 240metrics :list [dict [str ,float ]]= field (default_factory = list ) 241# `baseline` is the reference measurement; `recheck` is the same configuration measured again 242# after the sweep so machine drift is visible; `trial` is a candidate. 243kind :str = "trial" # baseline | recheck | trial 244 245@property 246def is_baseline (self )-> bool : 247return self .kind == "baseline" 248 249@property 250def ok (self )-> bool : 251return self .status == "PASS" and bool (self .metrics ) 252 253def median (self ,metric :str )-> float | None : 254vals = [m [metric ]for m in self .metrics if isinstance (m .get (metric ), (int ,float ))] 255return statistics .median (vals )if vals else None 256 257def worst (self ,metric :str )-> float | None : 258vals = [m [metric ]for m in self .metrics if isinstance (m .get (metric ), (int ,float ))] 259return min (vals )if vals else None 260 261def to_dict (self )-> dict [str ,Any ]: 262data = asdict (self ) 263data .pop ("is_baseline" ,None )# derived from `kind` 264metric = "tokens_per_s" 265data ["median" ]= self .median (metric ) 266data ["worst" ]= self .worst (metric ) 267data ["measured" ]= len (self .metrics ) 268return data 269 270 271@dataclass 272class TuningPlan : 273"""What a sweep would do, before it does anything. 274 275A plan is the review surface: it names the exact engine, model and profile revisions, the 276dimensions and their searched values, what is held fixed, the workload, the objective, the 277limits, and the resources it needs exclusively. 278""" 279 280id :str 281backend :str 282engine :str 283engine_flags_known :bool 284model :str 285profile_revision :str | None 286objective :str 287workload :dict [str ,Any ] 288dimensions :list [dict [str ,Any ]] 289excluded :list [dict [str ,str ]] 290fixed :dict [str ,Any ] 291max_trials :int 292total_time_s :float 293repeats :int 294devices :list [str ] 295needs_exclusive :bool = True 296created_at :float = field (default_factory = time .time ) 297#: What was measured, by content rather than by name. Two sweeps are comparable only when these 298#: match — see `tune_history.incomparable_reasons`. 299identity :dict [str ,Any ]= field (default_factory = dict ) 300context :int | None = None 301 302def to_dict (self )-> dict [str ,Any ]: 303return asdict (self ) 304 305 306class Tuner : 307"""A bounded search with durable progress. 308 309The measurements come from an injected ``measure`` callable, so the control flow, the selection 310rule and the retest are testable without a GPU — and, more importantly, so the module cannot 311accidentally contain a hardcoded benchmark result. 312 313``measure(candidate) -> dict`` must return a dict with at least ``tokens_per_s`` and may carry 314``ttft_ms``, ``prefill_tokens_per_s``, ``decode_tokens_per_s``, ``memory_mib``, ``power_w`` and 315``correct`` (a correctness check the caller performs). Raising means the candidate could not be 316measured; the exception's message becomes the candidate's status. 317""" 318 319def __init__ (self ,root :Path ,plan :TuningPlan , 320measure :Callable [[Candidate ],dict [str ,float ]], 321clock :Callable [[],float ]= time .time )-> None : 322self .id = plan .id 323self .root = Path (root )/ plan .id 324self .plan = plan 325self .measure = measure 326self .clock = clock 327self .candidates :list [Candidate ]= [] 328self .trials_run = 0 329self .history :dict [str ,Any ]= {} 330self .state = "queued" 331self .started_at = self .clock () 332self .finished_at :float | None = None 333self .events :list [dict [str ,Any ]]= [] 334self .error :str | None = None 335self ._cancel = False 336self ._lease :Path | None = None 337self .root .mkdir (parents = True ,exist_ok = True ) 338 339# ---- persistence ----------------------------------------------------- 340 341@property 342def state_file (self )-> Path : 343return self .root / "job.json" 344 345def to_dict (self )-> dict [str ,Any ]: 346return { 347"schema_version" :SCHEMA_VERSION , 348"id" :self .id , 349"state" :self .state , 350"plan" :self .plan .to_dict (), 351"candidates" : [asdict (c )for c in self .candidates ], 352"started_at" :self .started_at , 353"finished_at" :self .finished_at , 354"events" :self .events , 355"error" :self .error , 356# A job that cannot compose its own report must still be persistable, or the failure 357# path would recurse and lose the reason it failed. 358"report" :self ._report_or_none (), 359 } 360 361def save (self )-> None : 362tmp = self .state_file .with_suffix (".tmp" ) 363tmp .write_text (json .dumps (self .to_dict (),indent = 2 ),encoding = "utf-8" ) 364atomic .replace (tmp ,self .state_file ) 365 366def _report_or_none (self )-> dict [str ,Any ]| None : 367if self .state not in ("completed" ,"cancelled" ,"failed" ): 368return None 369try : 370return self .report () 371except Exception as e :# noqa: BLE001 - never lose the job record over a report bug 372return {"unavailable" :f" { type ( e ). __name__ } : { e } " } 373 374def _enter (self ,state :str ,** extra :Any )-> None : 375self .state = state 376self .events .append ({"seq" :len (self .events ),"at" :self .clock (),"state" :state ,** extra }) 377self .save () 378 379def request_cancel (self )-> None : 380"""Ask the sweep to stop at the next trial boundary. 381 382A trial already booting is allowed to finish or be killed by the measurement function; the 383point is that the sweep stops *starting* new ones, and the evidence collected so far is 384kept. Nothing is reported as a winner from a cancelled sweep. 385""" 386self ._cancel = True 387self .save () 388 389# ---- the exclusive lease -------------------------------------------- 390 391def _acquire_lease (self )-> None : 392"""Take the exclusive tuning lease for the selected devices. 393 394Tuning and serving must not share a device: a load beside a measurement changes what is 395measured, and the reviewed calibration's broad exclusive lease is preserved here until 396per-device leases are proven. The lease is an ``O_EXCL`` marker, so a crashed sweep leaves a 397stale one that a later run reports rather than silently ignoring. 398""" 399if not self .plan .needs_exclusive : 400return 401lease = self .root / "tuning.lease" 402try : 403fd = os .open (lease ,os .O_CREAT | os .O_EXCL | os .O_WRONLY ,0o600 ) 404except FileExistsError : 405other = json .loads (lease .read_text (encoding = "utf-8" ))if lease .exists ()else {} 406raise RuntimeError ( 407"another tuning job holds the exclusive device lease " 408f"( { other . get ( 'id' , 'unknown' ) } , pid { other . get ( 'pid' , '?' ) } ); " 409"finish or cancel it, or remove the lease if that job is gone" )from None 410with os .fdopen (fd ,"w" )as fh : 411json .dump ({"id" :self .id ,"pid" :os .getpid (),"at" :self .clock (), 412"devices" :self .plan .devices },fh ) 413self ._lease = lease 414 415def _release_lease (self )-> None : 416if self ._lease is not None : 417try : 418self ._lease .unlink () 419except OSError : 420pass 421self ._lease = None 422 423# ---- the sweep ------------------------------------------------------- 424 425def run (self )-> dict [str ,Any ]: 426try : 427self ._acquire_lease () 428self ._enter ("measuring_baseline" ) 429baseline = Candidate (index = 0 ,settings = dict (self .plan .fixed ),kind = "baseline" , 430args = self ._args_for (dict (self .plan .fixed ))) 431self ._measure_candidate (baseline ) 432self .candidates .append (baseline ) 433self .save () 434 435grid = self ._grid () 436if baseline .ok and not grid : 437self .events .append ({"seq" :len (self .events ),"at" :self .clock (), 438"state" :"no_dimensions" , 439"reason" :"this backend offers no searchable dimension; " 440"the baseline was measured and nothing was compared" }) 441if baseline .ok : 442self ._enter ("searching" ,trials = min (len (grid ),self .plan .max_trials )) 443started = self .clock () 444for index ,settings in enumerate (grid ,start = 1 ): 445if self ._cancel : 446break 447if index > self .plan .max_trials : 448break 449if self .clock ()- started > self .plan .total_time_s : 450self .events .append ({"seq" :len (self .events ),"at" :self .clock (), 451"state" :"time_limit" ,"after" :index - 1 }) 452break 453candidate = Candidate (index = index ,settings = settings , 454args = self ._args_for (settings )) 455self ._measure_candidate (candidate ) 456self .candidates .append (candidate ) 457self .trials_run += 1 458self .save () 459else : 460self .events .append ({"seq" :len (self .events ),"at" :self .clock (), 461"state" :"baseline_failed" , 462"reason" :baseline .reason or baseline .status }) 463 464# Always re-measure the baseline last, so drift is visible in the report rather than 465# hidden inside the comparison. 466if baseline .ok and not self ._cancel : 467self ._enter ("rechecking_baseline" ) 468again = Candidate (index =- 1 ,settings = dict (self .plan .fixed ),kind = "recheck" , 469args = self ._args_for (dict (self .plan .fixed ))) 470self ._measure_candidate (again ) 471again .index = len (self .candidates ) 472self .candidates .append (again ) 473 474self ._enter ("cancelled" if self ._cancel else "completed" ) 475self .finished_at = self .clock () 476self ._record_history () 477self .save () 478return self .to_dict () 479except Exception as e :# noqa: BLE001 - a failed job is a recorded outcome 480self .error = f" { type ( e ). __name__ } : { e } " 481self ._enter ("failed" ,error = self .error ) 482self .finished_at = self .clock () 483self .save () 484return self .to_dict () 485finally : 486self ._release_lease () 487 488def _measure_candidate (self ,candidate :Candidate )-> None : 489"""Take the required repeats, and record why a candidate could not be measured.""" 490try : 491warm = self .measure (Candidate (index = candidate .index ,settings = candidate .settings , 492args = candidate .args ,kind = candidate .kind )) 493if not isinstance (warm ,dict ): 494raise TypeError ("the measurement function must return a dict" ) 495except Exception as e :# noqa: BLE001 496message = str (e ) 497lowered = message .lower () 498candidate .status = ("TIMEOUT" if "timeout" in lowered or "timed out" in lowered else 499"FAIL_BOOT" if "boot" in lowered or "start" in lowered else 500"UNMEASURED" ) 501candidate .reason = message [:400 ] 502return 503 504for _ in range (max (1 ,self .plan .repeats )): 505try : 506m = self .measure (Candidate (index = candidate .index ,settings = candidate .settings , 507args = candidate .args ,kind = candidate .kind )) 508except Exception as e :# noqa: BLE001 509candidate .status = "TIMEOUT" if "timeout" in str (e ).lower ()else "UNMEASURED" 510candidate .reason = str (e )[:400 ] 511return 512# Order matters: these two rejections must happen *before* the measurement is recorded, 513# otherwise a fast but incorrect configuration accumulates passing metrics and its 514# reason gets overwritten with PASS. 515if not isinstance (m .get ("tokens_per_s" ), (int ,float ))or not m ["tokens_per_s" ]: 516# A configuration that produced no tokens is not a slow configuration; it failed. 517candidate .status = "NO_TOKENS" 518candidate .reason = "the engine produced no tokens" 519return 520if m .get ("correct" )is False : 521candidate .status = "INVALID" 522candidate .reason = "a correctness check failed for this configuration" 523return 524candidate .metrics .append ({k :v for k ,v in m .items ()if isinstance (v , (int ,float ))}) 525candidate .status = "PASS" 526 527def _grid (self )-> list [dict [str ,Any ]]: 528"""A bounded, deterministic grid over the offered dimensions. 529 530Deterministic on purpose: a fixed seed and a fixed enumeration mean two sweeps are 531comparable, and a reviewer can reproduce any candidate from its index. An adaptive search 532(TPE) can be layered behind the same job contract later; it must log every suggestion and 533every outcome, which this structure already records. 534""" 535# The plan is authoritative for *which* dimensions are searched; the static table supplies 536# the values and the flags. Reading the values from the plan as well (when it carries them) 537# keeps a caller able to narrow a dimension without editing the table. 538planned = {x .get ("id" ):x for x in self .plan .dimensions } 539offered :list [Dimension ]= [] 540for dim in DIMENSIONS : 541spec = planned .get (dim .id ) 542if spec is None : 543continue 544values = tuple (spec .get ("values" )or dim .values ) 545offered .append (dim if values == dim .values else 546Dimension (dim .id ,dim .flags ,values ,dim .backends ,dim .help , 547dim .benchmark_only )) 548if not offered : 549return [] 550combos :list [dict [str ,Any ]]= [{}] 551for dim in offered : 552grown :list [dict [str ,Any ]]= [] 553for base in combos : 554for value in dim .values : 555grown .append ({** base ,dim .id :value }) 556combos = grown 557return combos 558 559def _args_for (self ,settings :dict [str ,Any ])-> dict [str ,str ]: 560"""Render settings as engine flags, dropping benchmark-only levers. 561 562`prompt_cache_tail` is the worked example the handoff calls out: it can be measured, but the 563production interface does not accept it, so a winner that depended on it would not survive 564export. It is dropped here and the report says so. 565""" 566by_id = {d .id :d for d in DIMENSIONS } 567args :dict [str ,str ]= {} 568for key ,value in settings .items (): 569dim = by_id .get (key ) 570if dim is None or dim .benchmark_only : 571continue 572flag = dim .flags [0 ] 573if isinstance (value ,bool ): 574args [flag ]= "1" if value else "0" 575else : 576args [flag ]= str (value ) 577return args 578 579# ---- the report ------------------------------------------------------ 580 581def report (self )-> dict [str ,Any ]: 582"""What was measured, what is recommended, and what is still unknown. 583 584Selection rule, in order: 5851. the candidate must have passed at least ``repeats`` measurements; 5862. it must not be worse than the baseline's *worst* measurement — comparing a candidate's 587best run against the baseline's best run is how noise gets promoted to an improvement; 5883. among those, the best median on the objective wins. 589 590When nothing satisfies that, the report recommends **no change**. That is a real result, not 591a failed run. 592""" 593baselines = [c for c in self .candidates if c .kind == "baseline" and c .ok ] 594rechecks = [c for c in self .candidates if c .kind == "recheck" and c .ok ] 595trials = [c for c in self .candidates if c .kind == "trial" ] 596metric = self ._objective_metric () 597higher_is_better = self .plan .objective in ("generation" ,"prefill" ) 598 599recommendation :dict [str ,Any ]| None = None 600baseline_ref = baselines [0 ]if baselines else None 601if baseline_ref is not None : 602base_worst = baseline_ref .worst (metric ) 603base_median = baseline_ref .median (metric ) 604eligible = [] 605for c in trials : 606if not c .ok or len (c .metrics )< self .plan .repeats : 607continue 608worst = c .worst (metric ) 609median = c .median (metric ) 610if worst is None or median is None : 611continue 612# Rule 2: the candidate's worst run must not be worse than the baseline's worst. 613if base_worst is not None and higher_is_better and worst < base_worst : 614continue 615if base_worst is not None and not higher_is_better and worst > base_worst : 616continue 617eligible .append ((median ,c )) 618if eligible : 619eligible .sort (key = lambda p :p [0 ],reverse = higher_is_better ) 620best_median ,best = eligible [0 ] 621if base_median is not None and ( 622 (higher_is_better and best_median > base_median )or 623 (not higher_is_better and best_median < base_median )): 624recommendation = { 625"candidate_index" :best .index , 626"settings" :best .settings , 627"args" :best .args , 628"median" :best_median , 629"baseline_median" :base_median , 630 } 631 632drift = None 633if baselines and rechecks : 634first ,last = baselines [0 ].median (metric ),rechecks [- 1 ].median (metric ) 635if first is not None and last is not None and first : 636drift = {"metric" :metric ,"first" :first ,"last" :last , 637"relative" : (last - first )/ first , 638"note" : ("the baseline was measured again after the sweep; a large " 639"relative change means the machine drifted and the comparison is " 640"weaker than the repeat count suggests" )} 641 642return { 643"objective" :self .plan .objective , 644"metric" :metric , 645"higher_is_better" :higher_is_better , 646"repeats" :self .plan .repeats , 647"baseline" :baseline_ref .to_dict ()if baseline_ref else None , 648"recheck" :rechecks [- 1 ].to_dict ()if rechecks else None , 649"recommendation" :None if self .state == "cancelled" else recommendation , 650"recommendation_available" :recommendation is not None and self .state != "cancelled" , 651"reason" : ("the sweep was cancelled, so no comparison was completed and nothing is " 652"recommended" if self .state == "cancelled" else 653"no candidate beat the baseline outside its own spread; keeping the current " 654"configuration" if recommendation is None and baseline_ref else 655"the baseline could not be measured, so nothing could be compared" 656if baseline_ref is None else "" ), 657"candidates" : [c .to_dict ()for c in self .candidates ], 658"trials_run" :self .trials_run , 659# The grid is enumerated deterministically; a bounded sweep evaluates a *prefix* of it. 660# Reporting only "4 trials" would let a reader conclude that four was the whole space, 661# which is exactly how a partial search gets mistaken for a complete one. 662"combinations_total" :self ._grid_size (), 663"trials_are_a_prefix" :self .trials_run < self ._grid_size (), 664"failures" : [{"index" :c .index ,"status" :c .status ,"reason" :c .reason } 665for c in self .candidates if not c .ok ], 666"drift" :drift , 667"drift_material" :bool (drift and abs (drift ["relative" ])>= 0.02 ), 668"excluded_dimensions" :self .plan .excluded , 669"identity" :dict (self .plan .identity ), 670"history" :self .history , 671"excluded_from_export" :sorted (d .id for d in DIMENSIONS if d .benchmark_only ), 672 } 673 674def _grid_size (self )-> int : 675"""How many combinations the offered dimensions describe, before any bound.""" 676offered = {x .get ("id" )for x in self .plan .dimensions } 677total = 1 678for dim in DIMENSIONS : 679if dim .id in offered : 680spec = next (x for x in self .plan .dimensions if x .get ("id" )== dim .id ) 681total *= len (spec .get ("values" )or dim .values ) 682return total if offered else 0 683 684def _record_history (self )-> None : 685"""Store this sweep and report what it is comparable to. 686 687Recording *and* comparing in one place is deliberate: a store that only wrote would let a 688report present a recommendation next to incomparable earlier numbers without saying so. 689""" 690try : 691from strata_control import tune_history 692except ImportError :# history is optional 693self .history = {"note" :"the history store is unavailable" } 694return 695try : 696store = tune_history .HistoryStore (self .root .parent / "history" ) 697key = self .plan .identity or {} 698self .history = tune_history .summarise_history (store ,key )if key else { 699"note" :"this plan carries no artifact identity, so nothing can be compared to it" } 700report = self .report () 701rec = report .get ("recommendation" ) 702store .record ( 703key = key , 704outcome = (report .get ("recommendation" )or {}).get ("outcome" ) 705or ("cancelled" if self .state == "cancelled" else 706"accepted" if report .get ("recommendation_available" )else "inconclusive" ), 707recommendation_args = (rec or {}).get ("args" )or {}, 708median = (rec or {}).get ("median" ), 709baseline_median = (rec or {}).get ("baseline_median" ), 710metric = report .get ("metric" ,"tokens_per_s" ), 711trials_run = report .get ("trials_run" ,0 ), 712combinations_total = report .get ("combinations_total" ,0 ), 713engine_path = self .plan .engine ,model_path = self .plan .model , 714note = self .state ) 715except Exception as e :# noqa: BLE001 - history must never break a sweep 716self .history = {"note" :f"the history store could not be used: { type ( e ). __name__ } : { e } " } 717 718def _objective_metric (self )-> str : 719return {"generation" :"tokens_per_s" ,"prefill" :"prefill_tokens_per_s" , 720"latency" :"ttft_ms" }.get (self .plan .objective ,"tokens_per_s" ) 721 722 723# --------------------------------------------------------------------------- plan + apply 724 725def plan_tuning (engine :Path ,backend :str ,model :str ,objective :str , 726workload :dict [str ,Any ],profile_revision :str | None = None , 727hold :Sequence [str ]= (),max_trials :int = 16 ,total_time_s :float = 1800.0 , 728repeats :int = 3 ,devices :Sequence [str ]= (), 729model_path :Path | None = None ,context :int | None = None , 730full_digests :bool = False )-> TuningPlan : 731"""Build the reviewable plan. Nothing is measured here; the plan is what a user approves. 732 733The default ``max_trials`` is the specification's short sweep. ``total_time_s`` is a displayed 734bound: a sweep stops starting new trials when it is reached, and the report says how many ran. 735""" 736flags = engine_flag_inventory (engine ) 737offered ,excluded = validate_dimensions (backend ,flags ) 738held = set (hold ) 739dimensions = [{"id" :d .id ,"values" :list (d .values ),"flags" :list (d .flags ),"help" :d .help , 740"benchmark_only" :d .benchmark_only }for d in offered if d .id not in held ] 741fixed = {d .id : ("held at the engine's own default" if d .benchmark_only else None ) 742for d in offered if d .id in held } 743for dim_id in held : 744if dim_id not in {d .id for d in offered }: 745excluded .append ({"id" :dim_id ,"reason" :"held constant, or not a dimension of this backend" }) 746if flags is not None and not dimensions : 747# Every dimension was excluded. If the reason is that the binary lacks all of them, the 748# declared backend and the engine probably disagree, which the caller should see rather 749# than discover from an empty sweep. 750excluded .append ({ 751"id" :"(plan)" , 752"reason" : ("every dimension for this backend was excluded against this engine binary; " 753"check that --backend matches the engine package you are measuring" ), 754 }) 755# Identity by content, so a later sweep can tell whether these numbers still apply. `model_path` 756# is optional: when the caller does not know where the weights are, the model's digest is 757# `None`, which makes the record incomparable to everything rather than falsely comparable. 758from strata_control import tune_history 759identity = tune_history .comparison_key ( 760engine = tune_history .file_identity (engine ,full = full_digests ), 761model = (tune_history .file_identity (model_path ,full = full_digests )if model_path 762else {"path" :None ,"exists" :False ,"method" :None ,"digest" :None ,"bytes" :None }), 763backend = backend ,workload = workload ,context = context ) 764return TuningPlan ( 765id = uuid .uuid4 ().hex ,backend = backend ,engine = str (engine ),identity = identity ,context = context , 766engine_flags_known = flags is not None ,model = model ,profile_revision = profile_revision , 767objective = objective ,workload = dict (workload ),dimensions = dimensions ,excluded = excluded , 768fixed = fixed ,max_trials = max (0 ,int (max_trials )),total_time_s = float (total_time_s ), 769repeats = max (1 ,int (repeats )),devices = list (devices ), 770 ) 771 772 773def verify_exported (engine :Path ,args :dict [str ,str ],measure :Callable [[dict [str ,str ]],dict [str ,float ]], 774* ,repeats :int = 3 )-> dict [str ,Any ]: 775"""Re-measure the configuration *as it will actually be exported*. 776 777This is the step that makes a recommendation honest. A sweep may measure a lever that is stripped 778from the exported args (``prompt_cache_tail`` is the documented example), so the winner must be 779measured again with exactly the flags that would be written into the profile. If the retest does 780not reproduce the result, the recommendation is withdrawn. 781""" 782results :list [dict [str ,float ]]= [] 783for _ in range (max (1 ,repeats )): 784try : 785m = measure (args ) 786except Exception as e :# noqa: BLE001 787return {"verified" :False ,"reason" :f"the exported configuration failed to run: { e } " , 788"measurements" :results } 789if not isinstance (m .get ("tokens_per_s" ), (int ,float ))or not m ["tokens_per_s" ]: 790return {"verified" :False ,"reason" :"the exported configuration produced no tokens" , 791"measurements" :results } 792if m .get ("correct" )is False : 793return {"verified" :False ,"reason" :"a correctness check failed for the exported configuration" , 794"measurements" :results } 795results .append (m ) 796metric = "tokens_per_s" 797return {"verified" :True ,"metric" :metric ,"median" :statistics .median (r [metric ]for r in results ), 798"measurements" :results ,"args" :dict (args ),"repeats" :len (results )} 799 800 801def machine_identity ()-> dict [str ,Any ]: 802"""The machine the measurements belong to. 803 804Tuning history is invalidated by a change here, because a different machine's numbers are not 805comparable — which is why this is recorded with every report rather than assumed stable. 806""" 807return { 808"platform" :sysinfo .platform_string (), 809"machine" :sysinfo .machine (), 810"processor" :sysinfo .processor (), 811"python" :platform .python_version (), 812"cpu_count" :os .cpu_count (), 813 }