okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main dbb2d168c (picture-reader fix, GGML_NO_BACKTRACE) into f-own-int2503b206b

main
39.8 KiB813 linesraw
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
18  an engine refusal, so a HyperCore sweep there would produce ``FAIL_BOOT`` rows rather than
19  evidence.
20* It resolves the engine by walking up from its own directory looking for a Strata checkout, and it
21  writes its deliverables next to that root. Neither is acceptable for a packaged application: the
22  component registry must name an exact engine build, and the active profile must not be mutated by
23  a search.
24* Its README states Linux and Windows support and its tests use stub engines. That is a claim about
25  the 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
38  measurement 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
78    those flags are meaningful. A dimension is offered only when *every* flag it drives is supported
79    by the selected backend — a partial lever would produce a configuration the engine cannot run.
80    """
81
82    id: str
83    flags: tuple[str, ...]
84    values: tuple[Any, ...]
85    backends: tuple[str, ...]
86    help: str
87    #: Benchmark-only levers that must be stripped from the exported production args.
88    benchmark_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, ...] = (
94    Dimension("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."),
97    Dimension("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."),
100    Dimension("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."),
103    Dimension("expert_cache", ("--expert-cache",), (0, 1024, 2048, 4096, 8192, 12288, 16384),
104              ("cuda", "hip", "sycl"), "MiB of device memory for the expert cache."),
105    Dimension("host_core", ("--host-core",), ("first", "last"),
106              ("cuda", "hip"), "Which cores run the host-side work."),
107    Dimension("pool_affinity", ("--pool-affinity",), ("all", "p-cores", "auto"),
108              ("cuda", "hip"), "CPU pool affinity for the expert I/O threads."),
109    Dimension("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."),
111    Dimension("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."),
114    Dimension("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."),
117    Dimension("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."),
119    Dimension("prompt_cache_tail", ("--prompt-cache-tail",), (False, True),
120              ("cuda", "hip", "sycl"),
121              "Prompt-cache tail retention. BENCHMARK ONLY: measured, never exported.",
122              benchmark_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
131    gets a value ("--kv-grow 0" is "unknown argument: 0" to the engine, and a bare "--kv-grow" meaning off enabled it)."""
132    if flag in BOOLEAN_FLAGS or isinstance(value, bool):
133        return [flag] if value in (True, "1", "true", "True") else []
134    if value is None or value == "":
135        return [flag]
136    return [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:
141    if backend in dim.backends:
142        return None
143    if backend == "metal":
144        if dim.id in ("vram_reserve", "pcie_frac", "expert_cache"):
145            return ("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")
147        if dim.id in ("host_core", "pool_affinity", "pool_workers"):
148            return ("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)")
150    return f"not a {backend} setting"
151
152
153def validate_dimensions(backend: str,
154                        engine_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
157    When ``engine_flags`` is supplied — the flags the actual engine binary reports — a dimension is
158    additionally required to name only flags in that list. That is the check that keeps a sweep from
159    measuring a configuration the engine would refuse: if the binary does not accept a flag, the
160    dimension is excluded with the flag named, no matter what the static table says.
161    """
162    offered: list[Dimension] = []
163    excluded: list[dict[str, str]] = []
164    known = set(engine_flags) if engine_flags is not None else None
165    for dim in DIMENSIONS:
166        reason = _why_excluded(dim, backend)
167        if reason is None and known is not None:
168            missing = [f for f in dim.flags if f not in known]
169            if missing:
170                reason = ("the engine binary does not accept " + ", ".join(missing) +
171                          ", so a candidate using this dimension could not start")
172        if reason is None:
173            offered.append(dim)
174        else:
175            excluded.append({"id": dim.id, "reason": reason})
176    return 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
182    A ``.py`` file stands in for the engine in tests and demos (the same READY/PP/T/DONE protocol,
183    no weights). Running it through the current interpreter is what works on every OS: a ``#!`` line
184    is ignored by Windows, which answers WinError 193.
185    """
186    import sys
187    path = str(engine)
188    return [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
194    An engine package (`engine-component.json` beside the binary) carries its GPU runtime libraries in its own
195    folder, and `serve` puts that folder first on the library path. A tuning run that starts the same binary must
196    too, or it cannot even print `--help` ("error while loading shared libraries")."""
197    folder = Path(engine).resolve().parent
198    if not (folder / "engine-component.json").is_file():
199        return None
200    var = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH"
201    env = quiet_crash_env(dict(os.environ))
202    from strata_control import engine_component
203    env[var] = os.pathsep.join(engine_component.package_lib_dirs(folder) + ([env[var]] if env.get(var) else []))
204    return 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
210    Both output streams are read. The Strata engine writes its usage to **stderr**, which is easy to
211    miss: a stdout-only read reports "no flags" for a perfectly good engine, and because every
212    dimension is then excluded the sweep silently searches nothing. That failure is safe but
213    useless, so the parser reads stderr too and only reports None when the binary could not be run
214    at all.
215    """
216    try:
217        proc = subprocess.run([*engine_command(engine), "--help"], capture_output=True, text=True, errors="replace", timeout=20,
218                              env=engine_env(engine))
219    except (OSError, subprocess.SubprocessError):
220        return None
221    import re
222    text = f"{proc.stdout or ''}\n{proc.stderr or ''}"
223    flags = 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.
226    return flags or None
227
228
229# --------------------------------------------------------------------------- the job
230
231@dataclass
232class Candidate:
233    """One configuration and everything that was observed about it."""
234
235    index: int
236    settings: dict[str, Any]
237    args: dict[str, str] = field(default_factory=dict)
238    status: str = "pending"          # PASS | FAIL_BOOT | NO_TOKENS | TIMEOUT | UNMEASURED | INVALID
239    reason: str = ""
240    metrics: 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.
243    kind: str = "trial"              # baseline | recheck | trial
244
245    @property
246    def is_baseline(self) -> bool:
247        return self.kind == "baseline"
248
249    @property
250    def ok(self) -> bool:
251        return self.status == "PASS" and bool(self.metrics)
252
253    def median(self, metric: str) -> float | None:
254        vals = [m[metric] for m in self.metrics if isinstance(m.get(metric), (int, float))]
255        return statistics.median(vals) if vals else None
256
257    def worst(self, metric: str) -> float | None:
258        vals = [m[metric] for m in self.metrics if isinstance(m.get(metric), (int, float))]
259        return min(vals) if vals else None
260
261    def to_dict(self) -> dict[str, Any]:
262        data = asdict(self)
263        data.pop("is_baseline", None)          # derived from `kind`
264        metric = "tokens_per_s"
265        data["median"] = self.median(metric)
266        data["worst"] = self.worst(metric)
267        data["measured"] = len(self.metrics)
268        return data
269
270
271@dataclass
272class TuningPlan:
273    """What a sweep would do, before it does anything.
274
275    A plan is the review surface: it names the exact engine, model and profile revisions, the
276    dimensions and their searched values, what is held fixed, the workload, the objective, the
277    limits, and the resources it needs exclusively.
278    """
279
280    id: str
281    backend: str
282    engine: str
283    engine_flags_known: bool
284    model: str
285    profile_revision: str | None
286    objective: str
287    workload: dict[str, Any]
288    dimensions: list[dict[str, Any]]
289    excluded: list[dict[str, str]]
290    fixed: dict[str, Any]
291    max_trials: int
292    total_time_s: float
293    repeats: int
294    devices: list[str]
295    needs_exclusive: bool = True
296    created_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`.
299    identity: dict[str, Any] = field(default_factory=dict)
300    context: int | None = None
301
302    def to_dict(self) -> dict[str, Any]:
303        return asdict(self)
304
305
306class Tuner:
307    """A bounded search with durable progress.
308
309    The measurements come from an injected ``measure`` callable, so the control flow, the selection
310    rule and the retest are testable without a GPU — and, more importantly, so the module cannot
311    accidentally 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
316    measured; the exception's message becomes the candidate's status.
317    """
318
319    def __init__(self, root: Path, plan: TuningPlan,
320                 measure: Callable[[Candidate], dict[str, float]],
321                 clock: Callable[[], float] = time.time) -> None:
322        self.id = plan.id
323        self.root = Path(root) / plan.id
324        self.plan = plan
325        self.measure = measure
326        self.clock = clock
327        self.candidates: list[Candidate] = []
328        self.trials_run = 0
329        self.history: dict[str, Any] = {}
330        self.state = "queued"
331        self.started_at = self.clock()
332        self.finished_at: float | None = None
333        self.events: list[dict[str, Any]] = []
334        self.error: str | None = None
335        self._cancel = False
336        self._lease: Path | None = None
337        self.root.mkdir(parents=True, exist_ok=True)
338
339    # ---- persistence -----------------------------------------------------
340
341    @property
342    def state_file(self) -> Path:
343        return self.root / "job.json"
344
345    def to_dict(self) -> dict[str, Any]:
346        return {
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
361    def save(self) -> None:
362        tmp = self.state_file.with_suffix(".tmp")
363        tmp.write_text(json.dumps(self.to_dict(), indent=2), encoding="utf-8")
364        atomic.replace(tmp, self.state_file)
365
366    def _report_or_none(self) -> dict[str, Any] | None:
367        if self.state not in ("completed", "cancelled", "failed"):
368            return None
369        try:
370            return self.report()
371        except Exception as e:  # noqa: BLE001 - never lose the job record over a report bug
372            return {"unavailable": f"{type(e).__name__}: {e}"}
373
374    def _enter(self, state: str, **extra: Any) -> None:
375        self.state = state
376        self.events.append({"seq": len(self.events), "at": self.clock(), "state": state, **extra})
377        self.save()
378
379    def request_cancel(self) -> None:
380        """Ask the sweep to stop at the next trial boundary.
381
382        A trial already booting is allowed to finish or be killed by the measurement function; the
383        point is that the sweep stops *starting* new ones, and the evidence collected so far is
384        kept. Nothing is reported as a winner from a cancelled sweep.
385        """
386        self._cancel = True
387        self.save()
388
389    # ---- the exclusive lease --------------------------------------------
390
391    def _acquire_lease(self) -> None:
392        """Take the exclusive tuning lease for the selected devices.
393
394        Tuning and serving must not share a device: a load beside a measurement changes what is
395        measured, and the reviewed calibration's broad exclusive lease is preserved here until
396        per-device leases are proven. The lease is an ``O_EXCL`` marker, so a crashed sweep leaves a
397        stale one that a later run reports rather than silently ignoring.
398        """
399        if not self.plan.needs_exclusive:
400            return
401        lease = self.root / "tuning.lease"
402        try:
403            fd = os.open(lease, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
404        except FileExistsError:
405            other = json.loads(lease.read_text(encoding="utf-8")) if lease.exists() else {}
406            raise RuntimeError(
407                "another tuning job holds the exclusive device lease "
408                f"({other.get('id', 'unknown')}, pid {other.get('pid', '?')}); "
409                "finish or cancel it, or remove the lease if that job is gone") from None
410        with os.fdopen(fd, "w") as fh:
411            json.dump({"id": self.id, "pid": os.getpid(), "at": self.clock(),
412                       "devices": self.plan.devices}, fh)
413        self._lease = lease
414
415    def _release_lease(self) -> None:
416        if self._lease is not None:
417            try:
418                self._lease.unlink()
419            except OSError:
420                pass
421            self._lease = None
422
423    # ---- the sweep -------------------------------------------------------
424
425    def run(self) -> dict[str, Any]:
426        try:
427            self._acquire_lease()
428            self._enter("measuring_baseline")
429            baseline = Candidate(index=0, settings=dict(self.plan.fixed), kind="baseline",
430                                 args=self._args_for(dict(self.plan.fixed)))
431            self._measure_candidate(baseline)
432            self.candidates.append(baseline)
433            self.save()
434
435            grid = self._grid()
436            if baseline.ok and not grid:
437                self.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"})
441            if baseline.ok:
442                self._enter("searching", trials=min(len(grid), self.plan.max_trials))
443                started = self.clock()
444                for index, settings in enumerate(grid, start=1):
445                    if self._cancel:
446                        break
447                    if index > self.plan.max_trials:
448                        break
449                    if self.clock() - started > self.plan.total_time_s:
450                        self.events.append({"seq": len(self.events), "at": self.clock(),
451                                            "state": "time_limit", "after": index - 1})
452                        break
453                    candidate = Candidate(index=index, settings=settings,
454                                          args=self._args_for(settings))
455                    self._measure_candidate(candidate)
456                    self.candidates.append(candidate)
457                    self.trials_run += 1
458                    self.save()
459            else:
460                self.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.
466            if baseline.ok and not self._cancel:
467                self._enter("rechecking_baseline")
468                again = Candidate(index=-1, settings=dict(self.plan.fixed), kind="recheck",
469                                  args=self._args_for(dict(self.plan.fixed)))
470                self._measure_candidate(again)
471                again.index = len(self.candidates)
472                self.candidates.append(again)
473
474            self._enter("cancelled" if self._cancel else "completed")
475            self.finished_at = self.clock()
476            self._record_history()
477            self.save()
478            return self.to_dict()
479        except Exception as e:  # noqa: BLE001 - a failed job is a recorded outcome
480            self.error = f"{type(e).__name__}: {e}"
481            self._enter("failed", error=self.error)
482            self.finished_at = self.clock()
483            self.save()
484            return self.to_dict()
485        finally:
486            self._release_lease()
487
488    def _measure_candidate(self, candidate: Candidate) -> None:
489        """Take the required repeats, and record why a candidate could not be measured."""
490        try:
491            warm = self.measure(Candidate(index=candidate.index, settings=candidate.settings,
492                                          args=candidate.args, kind=candidate.kind))
493            if not isinstance(warm, dict):
494                raise TypeError("the measurement function must return a dict")
495        except Exception as e:  # noqa: BLE001
496            message = str(e)
497            lowered = message.lower()
498            candidate.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")
501            candidate.reason = message[:400]
502            return
503
504        for _ in range(max(1, self.plan.repeats)):
505            try:
506                m = self.measure(Candidate(index=candidate.index, settings=candidate.settings,
507                                           args=candidate.args, kind=candidate.kind))
508            except Exception as e:  # noqa: BLE001
509                candidate.status = "TIMEOUT" if "timeout" in str(e).lower() else "UNMEASURED"
510                candidate.reason = str(e)[:400]
511                return
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.
515            if 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.
517                candidate.status = "NO_TOKENS"
518                candidate.reason = "the engine produced no tokens"
519                return
520            if m.get("correct") is False:
521                candidate.status = "INVALID"
522                candidate.reason = "a correctness check failed for this configuration"
523                return
524            candidate.metrics.append({k: v for k, v in m.items() if isinstance(v, (int, float))})
525        candidate.status = "PASS"
526
527    def _grid(self) -> list[dict[str, Any]]:
528        """A bounded, deterministic grid over the offered dimensions.
529
530        Deterministic on purpose: a fixed seed and a fixed enumeration mean two sweeps are
531        comparable, 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
533        every 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.
538        planned = {x.get("id"): x for x in self.plan.dimensions}
539        offered: list[Dimension] = []
540        for dim in DIMENSIONS:
541            spec = planned.get(dim.id)
542            if spec is None:
543                continue
544            values = tuple(spec.get("values") or dim.values)
545            offered.append(dim if values == dim.values else
546                           Dimension(dim.id, dim.flags, values, dim.backends, dim.help,
547                                     dim.benchmark_only))
548        if not offered:
549            return []
550        combos: list[dict[str, Any]] = [{}]
551        for dim in offered:
552            grown: list[dict[str, Any]] = []
553            for base in combos:
554                for value in dim.values:
555                    grown.append({**base, dim.id: value})
556            combos = grown
557        return combos
558
559    def _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
563        production interface does not accept it, so a winner that depended on it would not survive
564        export. It is dropped here and the report says so.
565        """
566        by_id = {d.id: d for d in DIMENSIONS}
567        args: dict[str, str] = {}
568        for key, value in settings.items():
569            dim = by_id.get(key)
570            if dim is None or dim.benchmark_only:
571                continue
572            flag = dim.flags[0]
573            if isinstance(value, bool):
574                args[flag] = "1" if value else "0"
575            else:
576                args[flag] = str(value)
577        return args
578
579    # ---- the report ------------------------------------------------------
580
581    def report(self) -> dict[str, Any]:
582        """What was measured, what is recommended, and what is still unknown.
583
584        Selection rule, in order:
585          1. the candidate must have passed at least ``repeats`` measurements;
586          2. it must not be worse than the baseline's *worst* measurement — comparing a candidate's
587             best run against the baseline's best run is how noise gets promoted to an improvement;
588          3. among those, the best median on the objective wins.
589
590        When nothing satisfies that, the report recommends **no change**. That is a real result, not
591        a failed run.
592        """
593        baselines = [c for c in self.candidates if c.kind == "baseline" and c.ok]
594        rechecks = [c for c in self.candidates if c.kind == "recheck" and c.ok]
595        trials = [c for c in self.candidates if c.kind == "trial"]
596        metric = self._objective_metric()
597        higher_is_better = self.plan.objective in ("generation", "prefill")
598
599        recommendation: dict[str, Any] | None = None
600        baseline_ref = baselines[0] if baselines else None
601        if baseline_ref is not None:
602            base_worst = baseline_ref.worst(metric)
603            base_median = baseline_ref.median(metric)
604            eligible = []
605            for c in trials:
606                if not c.ok or len(c.metrics) < self.plan.repeats:
607                    continue
608                worst = c.worst(metric)
609                median = c.median(metric)
610                if worst is None or median is None:
611                    continue
612                # Rule 2: the candidate's worst run must not be worse than the baseline's worst.
613                if base_worst is not None and higher_is_better and worst < base_worst:
614                    continue
615                if base_worst is not None and not higher_is_better and worst > base_worst:
616                    continue
617                eligible.append((median, c))
618            if eligible:
619                eligible.sort(key=lambda p: p[0], reverse=higher_is_better)
620                best_median, best = eligible[0]
621                if 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)):
624                    recommendation = {
625                        "candidate_index": best.index,
626                        "settings": best.settings,
627                        "args": best.args,
628                        "median": best_median,
629                        "baseline_median": base_median,
630                    }
631
632        drift = None
633        if baselines and rechecks:
634            first, last = baselines[0].median(metric), rechecks[-1].median(metric)
635            if first is not None and last is not None and first:
636                drift = {"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
642        return {
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"
656                       if 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}
665                         for 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
674    def _grid_size(self) -> int:
675        """How many combinations the offered dimensions describe, before any bound."""
676        offered = {x.get("id") for x in self.plan.dimensions}
677        total = 1
678        for dim in DIMENSIONS:
679            if dim.id in offered:
680                spec = next(x for x in self.plan.dimensions if x.get("id") == dim.id)
681                total *= len(spec.get("values") or dim.values)
682        return total if offered else 0
683
684    def _record_history(self) -> None:
685        """Store this sweep and report what it is comparable to.
686
687        Recording *and* comparing in one place is deliberate: a store that only wrote would let a
688        report present a recommendation next to incomparable earlier numbers without saying so.
689        """
690        try:
691            from strata_control import tune_history
692        except ImportError:                                  # history is optional
693            self.history = {"note": "the history store is unavailable"}
694            return
695        try:
696            store = tune_history.HistoryStore(self.root.parent / "history")
697            key = self.plan.identity or {}
698            self.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"}
700            report = self.report()
701            rec = report.get("recommendation")
702            store.record(
703                key=key,
704                outcome=(report.get("recommendation") or {}).get("outcome")
705                        or ("cancelled" if self.state == "cancelled" else
706                            "accepted" if report.get("recommendation_available") else "inconclusive"),
707                recommendation_args=(rec or {}).get("args") or {},
708                median=(rec or {}).get("median"),
709                baseline_median=(rec or {}).get("baseline_median"),
710                metric=report.get("metric", "tokens_per_s"),
711                trials_run=report.get("trials_run", 0),
712                combinations_total=report.get("combinations_total", 0),
713                engine_path=self.plan.engine, model_path=self.plan.model,
714                note=self.state)
715        except Exception as e:  # noqa: BLE001 - history must never break a sweep
716            self.history = {"note": f"the history store could not be used: {type(e).__name__}: {e}"}
717
718    def _objective_metric(self) -> str:
719        return {"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,
726                workload: dict[str, Any], profile_revision: str | None = None,
727                hold: Sequence[str] = (), max_trials: int = 16, total_time_s: float = 1800.0,
728                repeats: int = 3, devices: Sequence[str] = (),
729                model_path: Path | None = None, context: int | None = None,
730                full_digests: bool = False) -> TuningPlan:
731    """Build the reviewable plan. Nothing is measured here; the plan is what a user approves.
732
733    The default ``max_trials`` is the specification's short sweep. ``total_time_s`` is a displayed
734    bound: a sweep stops starting new trials when it is reached, and the report says how many ran.
735    """
736    flags = engine_flag_inventory(engine)
737    offered, excluded = validate_dimensions(backend, flags)
738    held = set(hold)
739    dimensions = [{"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]
741    fixed = {d.id: ("held at the engine's own default" if d.benchmark_only else None)
742             for d in offered if d.id in held}
743    for dim_id in held:
744        if dim_id not in {d.id for d in offered}:
745            excluded.append({"id": dim_id, "reason": "held constant, or not a dimension of this backend"})
746    if 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.
750        excluded.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.
758    from strata_control import tune_history
759    identity = tune_history.comparison_key(
760        engine=tune_history.file_identity(engine, full=full_digests),
761        model=(tune_history.file_identity(model_path, full=full_digests) if model_path
762               else {"path": None, "exists": False, "method": None, "digest": None, "bytes": None}),
763        backend=backend, workload=workload, context=context)
764    return TuningPlan(
765        id=uuid.uuid4().hex, backend=backend, engine=str(engine), identity=identity, context=context,
766        engine_flags_known=flags is not None, model=model, profile_revision=profile_revision,
767        objective=objective, workload=dict(workload), dimensions=dimensions, excluded=excluded,
768        fixed=fixed, max_trials=max(0, int(max_trials)), total_time_s=float(total_time_s),
769        repeats=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
777    This is the step that makes a recommendation honest. A sweep may measure a lever that is stripped
778    from the exported args (``prompt_cache_tail`` is the documented example), so the winner must be
779    measured again with exactly the flags that would be written into the profile. If the retest does
780    not reproduce the result, the recommendation is withdrawn.
781    """
782    results: list[dict[str, float]] = []
783    for _ in range(max(1, repeats)):
784        try:
785            m = measure(args)
786        except Exception as e:  # noqa: BLE001
787            return {"verified": False, "reason": f"the exported configuration failed to run: {e}",
788                    "measurements": results}
789        if not isinstance(m.get("tokens_per_s"), (int, float)) or not m["tokens_per_s"]:
790            return {"verified": False, "reason": "the exported configuration produced no tokens",
791                    "measurements": results}
792        if m.get("correct") is False:
793            return {"verified": False, "reason": "a correctness check failed for the exported configuration",
794                    "measurements": results}
795        results.append(m)
796    metric = "tokens_per_s"
797    return {"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
804    Tuning history is invalidated by a change here, because a different machine's numbers are not
805    comparable — which is why this is recorded with every report rather than assumed stable.
806    """
807    return {
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    }