okami.mom/strata

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

Niko1221Merge f-0213-life (final 576d06553) into f-0213-int66331f9bc

main
54.1 KiB969 linesraw
1"""The auto-tuner: find the fastest settings for this PC, for this model, for what the user asked for.
2
3What it does (TUNING-SPEC.md sections 5-6, measured on five machines):
4
51. **Starts from the user's own configuration** (the "base") and changes one knob at a time (`tune_knobs`). It never starts
6   a candidate at "the first value of every dimension".
72. Measures with the real worker over HTTP, on the engine's own clock (`tune_session`), the same fixed request set every
8   time. Restart knobs are tried as **interleaved rounds**: every round runs the base and each candidate once, in a
9   rotating order, so machine drift cannot favour one of them. Per-request knobs need no restart and are tried first, in
10   one engine.
113. Accepts a candidate only if the **median of its per-round ratios** to the base beats the noise: at least +3%, and twice
12   the drift and twice the A/A gap measured on the base runs, in every round (quick) or at least 4 of 5 (thorough
13   confirm), without losing more than 2% elsewhere (prompt speed). A gain the noise can explain is not a gain: the result
14   is then "your current settings are already the fastest" and nothing changes.
154. Guards before every start: free RAM, free graphics memory, other engines running, the CPU busy with something else.
16   A candidate that does not fit is skipped, never started. A candidate must not use more memory than the base the user
17   asked for (so "leave 20% for my work" is respected). The first crash stops the stage.
185. Only knobs whose answers are byte-identical (class exact) are chosen on their own; the others need the user's tick.
19
20Progress and time left are reported through a callback; a cancel stops at the next run and keeps nothing half-measured.
21"""
22
23from __future__ import annotations
24
25import math
26import statistics
27import threading
28import time
29from dataclasses import dataclass, field
30from typing import Any, Callable
31
32from strata_control import engine_component, tune_knobs, tune_machine
33from strata_control.tune_session import RequestSet, RunResult, Session, StartFailed
34
35MIN_FREE_RAM_MIB = 3584            # 3.5 GiB left for the system at every start (6.5)
36EARLY_DROP = 0.05                  # a candidate this much slower than its own round's base is dropped after one round (run-to-run noise is 2-8%)
37STAGE_GAP_NOISY = 0.04             # an A/A gap above this: the machine is noisy (6.5)
38
39
40STAGNANT_WAIT_S = 60.0          # free memory that has not grown by STAGNANT_MIB after this long is not going to
41STAGNANT_MIB = 512
42
43
44class Cancelled(Exception):
45    """The user stopped the tune; what was measured so far is kept in the result."""
46
47
48# --------------------------------------------------------------------------- options and result
49
50@dataclass
51class Options:
52    mode: str = "quick"                       # quick | thorough
53    goal: str = "speed"                       # speed | room
54    reserve_mib: int = 0                      # graphics memory to leave free (goal room)
55    ram_wish_pct: int = 0                     # system memory to leave free, in percent (goal room, e.g. 20)
56    use: str = "chat"                         # chat | coding
57    allow_placement: bool = False
58    allow_nonrepeatable: bool = False
59    budget_s: float | None = None             # quick 20 min, thorough 2 h
60    margin: float = 0.03
61    rounds: int | None = None                 # quick 2, thorough 3 (screen); confirm 5 in thorough
62    confirm_pairs: int | None = None          # thorough: 5
63    per_request: bool = True
64    min_free_ram_mib: int = MIN_FREE_RAM_MIB
65    wait_ram_s: float = 600.0
66    busy_pct: float = 25.0
67    wait_busy_s: float = 300.0
68    check_busy: bool = True
69
70    def resolved(self) -> "Options":
71        o = Options(**self.__dict__)
72        thorough = o.mode == "thorough"
73        o.budget_s = o.budget_s or (7200.0 if thorough else 1200.0)
74        o.rounds = o.rounds or (3 if thorough else 2)
75        o.confirm_pairs = o.confirm_pairs if o.confirm_pairs is not None else (5 if thorough else 0)
76        return o
77
78
79@dataclass
80class ArmReport:
81    id: str
82    label: str
83    settings: dict[str, Any]
84    env: dict[str, Any]
85    answer: str
86    status: str = "pending"        # pending | tested | dropped | failed | skipped
87    reason: str = ""
88    runs: list[dict[str, Any]] = field(default_factory=list)       # per round: ratios vs that round's base
89    ratio_decode: float | None = None
90    ratio_pp: float | None = None
91    pairs: int = 0
92    faster: int = 0
93    won: bool = False
94
95    def to_dict(self) -> dict[str, Any]:
96        return dict(self.__dict__)
97
98
99@dataclass
100class TuneResult:
101    outcome: str = "default_confirmed"   # improved | default_confirmed | inconclusive | base_failed | cancelled
102    #: what a screen shows, one of: faster | already_fastest | busy_pc | failed | stopped  (see `finalize`)
103    code: str = "already_fastest"
104    #: why, for busy_pc: noisy | drift | not_tried (no memory or time to compare anything); for failed: start_failed | no_engine
105    reason_code: str = ""
106    #: the numbers a screen puts in its sentence, all plain numbers: gain_pct, base_tok_s, tuned_tok_s, noise_pct, drift_pct,
107    #: minutes, pairs, faster_pairs, preset_name
108    values: dict[str, Any] = field(default_factory=dict)
109    message: str = ""
110    not_tried: int = 0                 # candidates skipped for lack of free memory in a result that otherwise confirms the current settings (#5122)
111    mode: str = "quick"
112    seconds: float = 0.0
113    waited_s: float = 0.0              # of those seconds, spent waiting (box lock, busy PC, memory)
114    runs: int = 0
115    base: dict[str, Any] = field(default_factory=dict)
116    chosen: dict[str, Any] = field(default_factory=dict)
117    gain_pct: float = 0.0
118    gain_decode_pct: float = 0.0
119    gain_pp_pct: float = 0.0
120    settings: dict[str, Any] = field(default_factory=lambda: {"args": {}, "env": {}, "per_request": {}})
121    answers: dict[str, Any] = field(default_factory=lambda: {"class": "exact", "fields": []})
122    arms: list[dict[str, Any]] = field(default_factory=list)
123    skipped: list[dict[str, str]] = field(default_factory=list)
124    noise: dict[str, Any] = field(default_factory=dict)
125    pairs: int = 0
126    faster_pairs: int = 0
127    per_request: list[dict[str, Any]] = field(default_factory=list)
128    per_request_confirm: dict[str, Any] | None = None
129    notes: list[str] = field(default_factory=list)
130    classes: list[str] = field(default_factory=list)
131    facts: dict[str, Any] = field(default_factory=dict)
132    trials: list[dict[str, Any]] = field(default_factory=list)       # every engine run, for the history store
133
134    def to_dict(self) -> dict[str, Any]:
135        return dict(self.__dict__)
136
137
138# --------------------------------------------------------------------------- pure decision rules
139
140def metric(run: dict[str, Any] | RunResult, use: str) -> float | None:
141    """The number a configuration is judged on (6.1): decode speed for chat; for coding the geometric mean of decode
142    speed and long-prompt speed (the 4K prompt when no long one was measured)."""
143    get = (lambda k: run.get(k)) if isinstance(run, dict) else (lambda k: getattr(run, k, None))
144    if use == "prompt":                       # a prompt-only knob (the chunk size): long-prompt speed, the 4K prompt otherwise
145        p = get("pp_long_tok_s") or get("pp_tok_s")
146        return float(p) if p else None
147    d = get("decode_tok_s")
148    if not d:
149        return None
150    if use == "coding":
151        p = get("pp_long_tok_s") or get("pp_tok_s")
152        if p:
153            return math.sqrt(d * p)
154    return float(d)
155
156
157def median_ratio(ratios: list[float]) -> float | None:
158    return statistics.median(ratios) if ratios else None
159
160
161def accept_threshold(margin: float, aa_gap: float, drift: float) -> float:
162    """How far above 1.0 a median ratio has to be: the margin, or twice the noise the base runs showed (6.7 rule 3)."""
163    return 1.0 + max(margin, 2.0 * aa_gap, 2.0 * drift)
164
165
166def is_win(ratios: list[float], pp_ratios: list[float], *, threshold: float, need: int | None = None) -> bool:
167    """A win: the median ratio beats the threshold, enough rounds were faster, and the prompt speed lost at most 2%."""
168    if not ratios:
169        return False
170    need = len(ratios) if need is None else need
171    faster = sum(1 for r in ratios if r > 1.0)
172    if faster < need or statistics.median(ratios) < threshold:
173        return False
174    if pp_ratios and statistics.median(pp_ratios) < 0.98:
175        return False
176    return True
177
178
179def rotate(items: list[Any], r: int) -> list[Any]:
180    k = r % len(items) if items else 0
181    return items[k:] + items[:k]
182
183
184# --------------------------------------------------------------------------- the tuner
185
186class Tuner:
187    def __init__(self, session: Session, base_args: list[str], base_env: dict[str, str], ctx: tune_knobs.Context,
188                 options: Options, *, progress: Callable[[dict[str, Any]], None] | None = None,
189                 cancel: threading.Event | None = None, history_bad: set[str] | None = None,
190                 clock: Callable[[], float] = time.monotonic, sleep: Callable[[float], None] = time.sleep,
191                 system: Callable[[], dict[str, Any]] | None = None, total_ram_mib: int | None = None,
192                 total_vram_mib: int | None = None, quiet: Callable[[], str | None] | None = None) -> None:
193        self.session = session
194        self.base_args = list(base_args)
195        self.base_env = dict(base_env)
196        self.ctx = ctx
197        self.o = options.resolved()
198        self.progress = progress or (lambda p: None)
199        self.cancel = cancel or threading.Event()
200        self.history_bad = history_bad or set()
201        self._ram_gave_up: tuple[float, float] | None = None
202        self._base_start_avail: float | None = None     # free memory (MiB) the base run was allowed to start with: what a candidate that adds nothing needs again (#5122)
203        self.clock = clock
204        self.sleep = sleep
205        self.system = system or session.system
206        self.result = TuneResult(mode=self.o.mode)
207        self.started = 0.0
208        self.run_times: list[float] = []
209        self.planned_runs = 0
210        self.done_runs = 0
211        self.base_runs: list[RunResult] = []
212        self.total_ram = total_ram_mib or (tune_machine.memory().get("total_mib") or 0)
213        self.total_vram = total_vram_mib
214        self.quiet = quiet
215        self.storm = False
216        self.speeds: list[dict[str, Any]] = []
217        self.waited_s = 0.0                # time spent waiting for the box lock, the PC to be quiet or memory: not the user's budget
218
219    # ---- bookkeeping
220    def _elapsed(self) -> float:
221        return self.clock() - self.started - self.waited_s
222
223    def _say(self, stage: str, message: str, **extra: Any) -> None:
224        elapsed = self._elapsed()
225        avg = statistics.mean(self.run_times) if self.run_times else 150.0
226        remaining = max(0, self.planned_runs - self.done_runs)
227        eta = min(max(0.0, self.o.budget_s - elapsed), remaining * avg) if self.planned_runs else None
228        self.progress({"stage": stage, "message": message, "elapsed_s": round(elapsed), "runs_done": self.done_runs,
229                       "runs_planned": self.planned_runs, "eta_s": None if eta is None else round(eta),
230                       # what each measurement so far came to, for the live readout (label, decode tok/s as the goal judges it)
231                       "speeds": list(self.speeds), **extra})
232
233    def _check_cancel(self) -> None:
234        if self.cancel.is_set():
235            raise Cancelled()
236
237    def _over_budget(self, reserve_s: float = 0.0) -> bool:
238        return self._elapsed() + reserve_s > self.o.budget_s
239
240    def _avg_run(self) -> float:
241        return statistics.mean(self.run_times) if self.run_times else 150.0
242
243    # ---- guards
244    def _wait_for_quiet(self) -> None:
245        """Pause while another engine runs or the CPU is busy with something else (6.5, 6.7 rule 5)."""
246        if not self.o.check_busy:
247            return
248        waited = 0.0
249        while True:
250            why = self.quiet() if self.quiet else self._machine_busy()
251            if not why:
252                return
253            if waited >= self.o.wait_busy_s:
254                self.result.notes.append(f"measured while the machine was busy ({why})")
255                return
256            self._say("waiting", f"Waiting for the PC to be quiet ({why})")
257            self._check_cancel()
258            self.sleep(10.0)
259            waited += 10.0
260
261    def _machine_busy(self) -> str | None:
262        eng = tune_machine.other_engines()
263        if eng:
264            return "another Strata engine is running"
265        busy = tune_machine.cpu_busy_percent(1.0)
266        if busy is not None and busy > self.o.busy_pct:
267            return f"the CPU is {busy:.0f}% busy"
268        return None
269
270    def _ram_guard(self, delta_mib: int, label: str, wait_s: float | None = None) -> str | None:
271        """None when a start fits; otherwise the plain reason it does not. Waiting ends early when the free memory does not
272        grow (a loaded model keeps it): ten minutes per candidate made a tuning run last for hours (#3490)."""
273        waited = 0.0
274        first_avail: float | None = None
275        while True:
276            mem = self.system().get("memory", {})
277            avail = mem.get("available_mib")
278            if avail is None:
279                return None                       # unreadable: the engine's own guard decides
280            need = self.o.min_free_ram_mib + delta_mib
281            base_rss = self.base_runs[0].rss_peak_mib if self.base_runs else None
282            if base_rss:
283                need += base_rss
284            elif self.total_ram:
285                need = max(need, self.o.min_free_ram_mib)
286            if self.base_runs and self._base_start_avail and self.base_runs[0].status == "PASS":
287                # like for like (#5122): the base run started with this much free and ran; its peak RSS counts file pages the kernel can take back, so
288                # "peak + floor" can ask for more than the PC had at the base start. A candidate needs what the base had plus what it adds.
289                need = min(need, max(self._base_start_avail + delta_mib, self.o.min_free_ram_mib + delta_mib))
290            if avail >= need:
291                if not self.base_runs:
292                    self._base_start_avail = float(avail)
293                return None
294            reason = (f"not enough free memory to start it safely ({avail / 1024:.1f} GiB free, "
295                      f"{need / 1024:.1f} GiB needed)")
296            prior = self._ram_gave_up
297            if prior is not None and avail <= prior[1] + STAGNANT_MIB:
298                return reason                     # an earlier wait found nothing freed: waiting again for a candidate that needs less, but still more than is free, repeats it (#4895)
299            if first_avail is None:
300                first_avail = avail
301            stagnant = waited >= STAGNANT_WAIT_S and avail <= first_avail + STAGNANT_MIB
302            if stagnant or waited >= (self.o.wait_ram_s if wait_s is None else wait_s):
303                self._ram_gave_up = (need, avail)
304                return reason
305            self._say("waiting", f"Waiting for memory to be freed before trying {label} "
306                                 f"({avail / 1024:.1f} GiB free, {need / 1024:.1f} GiB needed)")
307            self._check_cancel()
308            self.sleep(10.0)
309            waited += 10.0
310
311    # ---- one engine run
312    def _run(self, args: list[str], env: dict[str, str | None], spec: RequestSet, label: str,
313             points: Callable[[Any], None] | None = None, delta_mib: int = 0) -> RunResult:
314        self._check_cancel()
315        t0 = self.clock()
316
317        entered: list[float] = []
318
319        def pre_start() -> None:
320            # checked again once the box lock is ours: another stream's engine may have come and gone while we waited
321            lock_got = self.clock()
322            self.waited_s += lock_got - t0
323            self._wait_for_quiet()
324            why = self._ram_guard(delta_mib, label, wait_s=60.0)
325            self.waited_s += self.clock() - lock_got
326            if why:
327                raise StartFailed("SKIPPED", why)
328            entered.append(self.clock())
329
330        try:
331            with self.session.engine(args, env, pre_start=pre_start) as eng:
332                res = eng.measure(spec)
333                if points is not None and res.status == "PASS":
334                    points(eng)
335        except StartFailed as e:
336            res = RunResult(status=e.status, reason=e.reason)
337        dt = self.clock() - (entered[0] if entered else t0)          # the run itself, not the waiting before it
338        if res.status != "SKIPPED":
339            self.run_times.append(dt)
340            self.done_runs += 1
341            self.result.runs += 1
342        res.wall_s = round(dt, 1)
343        self.result.trials.append({"label": label, "args": args, "env": env, "status": res.status, "reason": res.reason,
344                                   "decode_tok_s": res.decode_tok_s, "pp_tok_s": res.pp_tok_s,
345                                   "rss_peak_mib": res.rss_peak_mib, "load_s": res.load_s, "at": time.time()})
346        return res
347
348    # ---- the whole job
349    def run(self) -> TuneResult:
350        self.started = self.clock()
351        r = self.result
352        try:
353            self._run_stages()
354        except Cancelled:
355            r.outcome, r.message = "cancelled", "Stopped. Your settings were not changed."
356        r.seconds = round(self.clock() - self.started, 1)
357        r.waited_s = round(self.waited_s, 1)
358        self.finalize(r)
359        return r
360
361    @staticmethod
362    def finalize(r: "TuneResult") -> None:
363        """The structured outcome a screen shows inside the tune dialog (owner feedback, item 13): a code and plain numbers, so no
364        screen has to read a sentence. faster / already_fastest / busy_pc (noisy, drifting, or nothing could be compared) /
365        failed / stopped. `busy_pc` is a result, not an error: nothing was changed and trying again later is the answer."""
366        r.code = {"improved": "faster", "default_confirmed": "already_fastest", "inconclusive": "busy_pc",
367                  "base_failed": "failed", "cancelled": "stopped"}.get(r.outcome, "failed")
368        if r.outcome == "default_confirmed" and r.noise.get("noisy"):
369            r.reason_code = r.reason_code or "noisy_but_nothing_better"
370        base = (r.base or {}).get("decode_tok_s")
371        tuned = (r.chosen or {}).get("decode_tok_s")
372        r.values = {"gain_pct": r.gain_pct, "gain_decode_pct": r.gain_decode_pct, "base_tok_s": base, "tuned_tok_s": tuned,
373                    "noise_pct": round(100 * (r.noise or {}).get("spread", 0.0), 1) if r.noise else None,
374                    "drift_pct": round(100 * (r.noise or {}).get("drift", 0.0), 1) if r.noise else None,
375                    "minutes": round(r.seconds / 60.0 - r.waited_s / 60.0, 1), "pairs": r.pairs, "faster_pairs": r.faster_pairs,
376                    "not_tried": r.not_tried}
377
378    def _spec(self) -> RequestSet:
379        long_tokens = 0
380        if self.ctx.context_tokens >= 65536:
381            # long contexts mean long prompts: the chunk size (spec 4.3) only shows on a long one
382            long_tokens = min(98304, int(0.75 * self.ctx.context_tokens))
383        elif self.o.use == "coding" and self.o.mode == "thorough":
384            long_tokens = min(28000, int(0.8 * self.ctx.context_tokens))
385        return RequestSet(warmups=2 if self.o.mode == "thorough" else 1, decodes=5, decode_tokens=200,
386                          pp_tokens=4096 if self.ctx.context_tokens >= 6000 else 1024, long_tokens=long_tokens)
387
388    def _run_stages(self) -> None:
389        r, o = self.result, self.o
390        spec = self._spec()
391        self.planned_runs = 6                              # corrected once the candidates are known
392        self._say("start", "Checking your PC before the first measurement")
393
394        # ---- stage 1: the base run (the user's configuration, untouched), with the per-request guard in the same engine
395        why = self._ram_guard(0, "your current settings")
396        if why:
397            r.outcome, r.message = "base_failed", "Not tuned: " + why
398            r.reason_code = "no_memory"
399            return
400        pr_rows: list[dict[str, Any]] = []
401
402        def per_request_points(eng: Any) -> None:
403            if o.per_request:
404                pr_rows.extend(self._per_request_stage(eng))
405
406        self._say("base", "Measuring your current settings")
407        base1 = self._run(self.base_args, {}, spec, "base", points=per_request_points)
408        self.base_runs.append(base1)
409        if base1.status == "PASS" and metric(base1, o.use):
410            self.speeds.append({"label": "base", "tok_s": round(float(metric(base1, o.use)), 1)})
411            self._say("base", "Measured your current settings")
412        if base1.status != "PASS" or not metric(base1, o.use):
413            r.outcome = "base_failed"
414            r.reason_code = "start_failed"
415            r.message = "Your current settings could not be measured: " + (base1.reason or base1.status)
416            return
417        r.base = base1.to_dict()
418        r.facts = dict(base1.facts)
419        self.ctx.facts = dict(base1.facts)
420        if base1.vram_used_mib is not None and self.total_vram is None:
421            cards = [g for g in self.system().get("gpus", []) if g.get("vram_total_mib")]
422            self.total_vram = sum(g["vram_total_mib"] for g in cards) if cards else None
423        r.per_request = pr_rows
424        r.classes = tune_knobs.machine_classes(self.ctx)
425
426        # ---- stage 2: plan the candidates for this machine; how many depends on the time chosen
427        planned, skipped = tune_knobs.plan_arms(self.ctx, mode=o.mode, history_bad=self.history_bad)
428        r.skipped = skipped
429        per_arm = o.rounds or 2
430        if o.mode == "thorough":
431            n_arms = len(planned)
432        else:
433            left = int((o.budget_s - self._elapsed()) / max(1.0, self._avg_run()))
434            fixed = (per_arm - 1) + 1                      # extra base rounds, the final base
435            n_arms = min(len(planned), max(0, (left - fixed) // per_arm))
436        for p in planned[n_arms:]:
437            skipped.append({"id": p.arm.id, "label": p.arm.label, "reason": "left out to stay inside the time you chose"})
438        planned = planned[:n_arms]
439        arms = [ArmReport(p.arm.id, p.arm.label, dict(p.args), dict(p.env), p.arm.answer) for p in planned]
440        by_id = {a.id: a for a in arms}
441        by_use = {p.arm.id: ("prompt" if p.arm.metric == "prompt" else o.use) for p in planned}
442        self.planned_runs = self.done_runs + per_arm * (len(planned) + 1) - 1 + 1 + (o.confirm_pairs or 0) * 2
443        if not planned:
444            self._say("plan", "No other setting is worth trying on this PC")
445
446        # ---- stage 3: interleaved rounds. Every round runs the base and each live candidate once, in a rotating order.
447        round_runs: list[dict[str, RunResult]] = [{} for _ in range(per_arm)]
448        round_runs[0]["base"] = base1
449        alive = list(planned)
450        stop = False
451        for rnd in range(per_arm):
452            if stop or self.storm or (rnd > 0 and not alive):
453                break
454            for item in rotate(["base"] + alive, rnd):
455                self._check_cancel()
456                if self._over_budget(reserve_s=2 * self._avg_run()):
457                    r.notes.append("the time you chose ran out before every round finished")
458                    stop = True
459                    break
460                if item == "base":
461                    if rnd == 0:
462                        continue                         # round 1's base is the run above
463                    if self._ram_guard(0, "your current settings"):
464                        r.notes.append("not enough free memory for another measurement of your current settings; the search stopped")
465                        stop = True
466                        break
467                    self._say("rounds", f"Measuring your current settings again (round {rnd + 1} of {per_arm})")
468                    b = self._run(self.base_args, {}, spec, f"base r{rnd + 1}")
469                    if b.status == "SKIPPED":
470                        r.notes.append("not enough free memory for another measurement of your current settings; the search stopped")
471                        self.storm = stop = True
472                        break
473                    if b.status != "PASS":
474                        r.notes.append("your current settings failed to start a second time; the search stopped")
475                        self.storm = stop = True
476                        break
477                    self.base_runs.append(b)
478                    round_runs[rnd]["base"] = b
479                    continue
480                p = item
481                rep = by_id[p.arm.id]
482                why = self._ram_guard(p.arm.ram_delta_mib, p.arm.label)
483                if why:
484                    rep.status, rep.reason = "skipped", why
485                    alive = [x for x in alive if x.arm.id != p.arm.id]
486                    continue
487                self._say("rounds", f"Trying: {p.arm.label} (round {rnd + 1} of {per_arm})", arm=p.arm.id)
488                res = self._run(tune_knobs.apply_to_argv(self.base_args, p.args), dict(p.env), spec, p.arm.id,
489                                delta_mib=p.arm.ram_delta_mib)
490                if res.status == "SKIPPED":
491                    rep.status, rep.reason = "skipped", res.reason
492                    alive = [x for x in alive if x.arm.id != p.arm.id]
493                    continue
494                if res.status != "PASS":
495                    rep.status, rep.reason = "failed", f"{res.status}: {res.reason}"
496                    alive = [x for x in alive if x.arm.id != p.arm.id]
497                    if res.status == "OOM":
498                        self.storm = stop = True
499                        r.notes.append("an engine ran out of memory; the search stopped (nothing was retried)")
500                        break
501                    continue
502                if metric(res, o.use):
503                    self.speeds.append({"label": p.arm.label, "tok_s": round(float(metric(res, o.use)), 1)})
504                over = self._memory_overrun(res, base1)
505                if over:
506                    rep.status, rep.reason = "failed", over
507                    alive = [x for x in alive if x.arm.id != p.arm.id]
508                    continue
509                round_runs[rnd][p.arm.id] = res
510            # a candidate that lost by more than the margin against its own round's base is dropped from later rounds
511            for p in list(alive):
512                b, c = round_runs[rnd].get("base"), round_runs[rnd].get(p.arm.id)
513                um = by_use[p.arm.id]
514                m_b, m_c = (metric(b, um) if b else None), (metric(c, um) if c else None)
515                if m_b and m_c and m_c / m_b < 1.0 - max(o.margin, EARLY_DROP):
516                    by_id[p.arm.id].status = "dropped"
517                    by_id[p.arm.id].reason = f"slower by {100 * (1 - m_c / m_b):.1f}% in round {rnd + 1}"
518                    alive = [x for x in alive if x.arm.id != p.arm.id]
519        data: dict[str, list[tuple[RunResult, RunResult]]] = {
520            a.id: [(rr["base"], rr[a.id]) for rr in round_runs if a.id in rr and "base" in rr] for a in arms}
521
522        # ---- noise: the A/A gap between base runs, the drift against a final base run
523        end_base: RunResult | None = None
524        ran_any = any(len(v) for v in data.values())
525        if not self.storm and not self.cancel.is_set() and ran_any and not self._over_budget()                 and not self._ram_guard(0, "your current settings"):
526            self._say("drift", "Measuring your current settings once more to check the PC did not drift")
527            end_base = self._run(self.base_args, {}, spec, "base end")
528            if end_base.status == "PASS":
529                self.base_runs.append(end_base)
530        mb = [metric(b, o.use) for b in self.base_runs if metric(b, o.use)]
531        aa = abs(mb[1] / mb[0] - 1.0) if len(mb) >= 2 else 0.0
532        drift = abs(mb[-1] / mb[0] - 1.0) if len(mb) >= 3 else (aa if len(mb) == 2 else 0.0)
533        spread = (max(mb) / min(mb) - 1.0) if len(mb) >= 2 else 0.0
534        r.noise = {"aa_gap": round(aa, 4), "drift": round(drift, 4), "spread": round(spread, 4),
535                   "base_runs": [round(x, 2) for x in mb], "noisy": spread > STAGE_GAP_NOISY}
536        threshold = accept_threshold(o.margin, aa, drift)
537
538        # ---- evaluate the candidates
539        winners: list[ArmReport] = []
540        for p in planned:
541            rep = by_id[p.arm.id]
542            rows = data[p.arm.id]
543            if rep.status in ("failed", "skipped") or not rows:
544                continue
545            ratios, pps = [], []
546            um = by_use[p.arm.id]
547            for b, c in rows:
548                mc, mbb = metric(c, um), metric(b, um)
549                if mc and mbb:
550                    ratios.append(mc / mbb)
551                # the other side of the trade: prompt speed for a decode knob, decode speed for a prompt knob
552                if um == "prompt":
553                    if c.decode_tok_s and b.decode_tok_s:
554                        pps.append(c.decode_tok_s / b.decode_tok_s)
555                elif c.pp_tok_s and b.pp_tok_s:
556                    pps.append(c.pp_tok_s / b.pp_tok_s)
557            rep.pairs = len(ratios)
558            rep.faster = sum(1 for x in ratios if x > 1.0)
559            rep.ratio_decode = round(statistics.median(ratios), 4) if ratios else None
560            rep.ratio_pp = round(statistics.median(pps), 4) if pps else None
561            rep.runs = [{"ratio": round(x, 4)} for x in ratios]
562            if rep.status == "dropped":
563                continue
564            rep.status = "tested"
565            if len(ratios) >= per_arm and is_win(ratios, pps, threshold=threshold):
566                rep.won = True
567                winners.append(rep)
568        r.arms = [a.to_dict() for a in arms]
569
570        if r.noise["noisy"] and not winners:
571            r.notes.append(f"the PC was noisy ({spread * 100:.1f}% between identical runs)")
572
573        # ---- stage 4: stack the winners, then (thorough) confirm against the base with more pairs
574        fu = o.use
575        chosen_args: dict[str, Any] = {}
576        chosen_env: dict[str, str | None] = {}
577        final_pairs: list[tuple[RunResult, RunResult]] = []
578        if winners:
579            winners.sort(key=lambda a: a.ratio_decode or 0.0, reverse=True)
580            incumbent = [winners[0]]            # gains did not stack in three stacking runs (spec 1.10): the best single knob
581            if len(winners) > 1:
582                r.notes.append("more than one setting helped; only the best one is kept because gains did not add up in the study")
583            for w in incumbent:
584                chosen_args.update(w.settings)
585                chosen_env.update(w.env)
586            fu = by_use[incumbent[0].id]
587            need_confirm = (o.confirm_pairs or 0) > 0
588            if need_confirm and not self._over_budget(reserve_s=2 * self._avg_run()):
589                n = o.confirm_pairs or 2
590                self._say("confirm", "Confirming the combined result against your current settings")
591                final_pairs = self._confirm(chosen_args, chosen_env, spec, n, fu)
592                ratios = [metric(c, fu) / metric(b, fu) for b, c in final_pairs if metric(c, fu) and metric(b, fu)]
593                pps = [c.decode_tok_s / b.decode_tok_s for b, c in final_pairs if c.decode_tok_s and b.decode_tok_s] if fu == "prompt" \
594                    else [c.pp_tok_s / b.pp_tok_s for b, c in final_pairs if c.pp_tok_s and b.pp_tok_s]
595                need = max(2, int(math.ceil(0.8 * len(ratios)))) if len(ratios) >= 5 else len(ratios)
596                if not (ratios and is_win(ratios, pps, threshold=threshold, need=need)):
597                    # the stack did not hold; fall back to the best single winner, which already won its own pairs
598                    if len(incumbent) > 1:
599                        r.notes.append("the combination did not beat the best single change; keeping the best single change")
600                        best = incumbent[0]
601                        chosen_args, chosen_env = dict(best.settings), dict(best.env)
602                        final_pairs = [(b, c) for b, c in data[best.id]]
603                    else:
604                        winners, chosen_args, chosen_env, final_pairs = [], {}, {}, []
605                        r.notes.append("the gain did not hold up in the confirmation, so nothing was changed")
606                else:
607                    pass
608            else:
609                best = incumbent[0]
610                chosen_args, chosen_env = dict(best.settings), dict(best.env)
611                final_pairs = list(data[best.id])
612            if not final_pairs and winners:
613                final_pairs = list(data[winners[0].id])
614
615        fu_final = fu
616        # ---- per-request winners (found in the base engine): keep only the ones that won every round
617        per_request_chosen = {row["key"]: row["value"] for row in r.per_request if row.get("won")}
618        if per_request_chosen and not self.storm and not self.cancel.is_set() and not self._over_budget(reserve_s=self._avg_run()):
619            # a per-request win from one engine's quick points is only a candidate: confirm it in a fresh engine, 5 interleaved rounds
620            self._say("confirm", "Confirming the settings that need no restart")
621            r.per_request_confirm = self._confirm_per_request(per_request_chosen, spec, threshold)
622            if not r.per_request_confirm["ok"]:
623                r.notes.append("a per-request setting looked faster in the first test but did not hold in the confirmation, so it was not kept")
624                per_request_chosen = {}
625        elif per_request_chosen:
626            r.notes.append("a per-request setting looked faster but could not be confirmed in the time left, so it was not kept")
627            per_request_chosen = {}
628
629        # ---- result
630        if end_base is not None and end_base.status == "PASS" and drift > 0.03 and winners:
631            gain_guess = statistics.median([metric(c, fu) / metric(b, fu) for b, c in final_pairs]) - 1.0 if final_pairs else 0.0
632            if gain_guess < 2 * drift:
633                chosen_args, chosen_env, winners, final_pairs = {}, {}, [], []
634                per_request_chosen = {}
635                r.outcome = "inconclusive"
636                r.reason_code = "drift"
637                r.message = ("The PC changed speed while measuring (about %.0f%%), more than the gain found, so nothing "
638                             "was changed. Try again when nothing else is running." % (drift * 100))
639        if r.outcome != "inconclusive":
640            if chosen_args or chosen_env or per_request_chosen:
641                r.outcome = "improved"
642            elif r.noise["noisy"] and (spread > 2 * STAGE_GAP_NOISY):
643                r.outcome = "inconclusive"
644                r.reason_code = "noisy"
645                r.message = "The PC was too noisy to tell settings apart, so nothing was changed. Try again when it is idle."
646            elif arms and not any(a.status in ("tested", "dropped", "failed") for a in arms) and not r.per_request:
647                # candidates were planned but none could be measured (no free memory, no time): that is not "already the fastest"
648                r.outcome = "inconclusive"
649                r.reason_code = "not_tried"
650                r.message = ("Other settings could not be tried (not enough free memory or time), so nothing was compared and nothing was "
651                             "changed. Try again when the PC is quiet.")
652            else:
653                r.outcome = "default_confirmed"
654                r.not_tried = sum(1 for a in arms if a.status == "skipped" and "memory" in (a.reason or ""))
655                if r.not_tried:                  # "already the fastest" would claim a comparison that never happened (#5122)
656                    r.reason_code = r.reason_code or "some_not_tried"
657                    r.message = f"{r.not_tried} setting{'s' if r.not_tried != 1 else ''} could not be tried: not enough free memory"
658                else:
659                    r.message = "Your current settings are already the fastest we found. Nothing was changed."
660                if r.noise.get("noisy") and not r.not_tried:
661                    r.message += " (The PC was busy while measuring, so a small gain could be hidden.)"
662        r.settings = {"args": chosen_args, "env": chosen_env, "per_request": per_request_chosen}
663        cls, fields = "exact", []
664        for rep in arms:
665            if rep.won and any(k in chosen_args for k in rep.settings) or (rep.won and any(k in chosen_env for k in rep.env)):
666                if tune_knobs.ANSWER_ORDER.index(rep.answer) > tune_knobs.ANSWER_ORDER.index(cls):
667                    cls = rep.answer
668                if rep.answer != "exact":
669                    fields += list(rep.settings) + list(rep.env)
670        for key in per_request_chosen:
671            for row in tune_knobs.PER_REQUEST:
672                if row["key"] == key and tune_knobs.ANSWER_ORDER.index(row["answer"]) > tune_knobs.ANSWER_ORDER.index(cls):
673                    cls = row["answer"]
674                if row["key"] == key and row["answer"] != "exact":
675                    fields.append(key)
676        r.answers = {"class": cls, "fields": sorted(set(fields)), "default_repeatable": not tune_knobs.default_unsteady(self.ctx)}
677        if final_pairs:
678            fu = fu_final
679            ratios = [metric(c, fu) / metric(b, fu) for b, c in final_pairs if metric(c, fu) and metric(b, fu)]
680            pps = [c.pp_tok_s / b.pp_tok_s for b, c in final_pairs if c.pp_tok_s and b.pp_tok_s]
681            r.pairs = len(ratios)
682            r.faster_pairs = sum(1 for x in ratios if x > 1.0)
683            r.gain_pct = round(100 * (statistics.median(ratios) - 1.0), 1) if ratios else 0.0
684            r.gain_pp_pct = round(100 * (statistics.median(pps) - 1.0), 1) if pps else 0.0
685            dec = [c.decode_tok_s / b.decode_tok_s for b, c in final_pairs if c.decode_tok_s and b.decode_tok_s]
686            r.gain_decode_pct = round(100 * (statistics.median(dec) - 1.0), 1) if dec else 0.0
687            c_runs = [c for _, c in final_pairs]
688            r.chosen = {"decode_tok_s": round(statistics.median([c.decode_tok_s for c in c_runs if c.decode_tok_s]), 2)
689                        if any(c.decode_tok_s for c in c_runs) else None,
690                        "pp_tok_s": round(statistics.median([c.pp_long_tok_s or c.pp_tok_s for c in c_runs if c.pp_long_tok_s or c.pp_tok_s]), 1)
691                        if any(c.pp_tok_s for c in c_runs) else None,
692                        "rss_peak_mib": max([c.rss_peak_mib for c in c_runs if c.rss_peak_mib] or [None]) if any(c.rss_peak_mib for c in c_runs) else None,
693                        "vram_used_mib": max([c.vram_used_mib for c in c_runs if c.vram_used_mib] or [None]) if any(c.vram_used_mib for c in c_runs) else None}
694        elif r.outcome == "improved" and per_request_chosen:
695            r.gain_pct = r.gain_decode_pct = round(100 * ((r.per_request_confirm or {}).get("ratio", 1.0) - 1.0), 1)
696            r.pairs = len((r.per_request_confirm or {}).get("ratios", []))
697            r.faster_pairs = sum(1 for x in (r.per_request_confirm or {}).get("ratios", []) if x > 1.0)
698            r.chosen = dict(r.base)
699        else:
700            r.chosen = {k: r.base.get(k) for k in ("decode_tok_s", "pp_tok_s", "rss_peak_mib", "vram_used_mib")}
701        if r.outcome == "improved":
702            r.message = "+%.0f%% faster answers" % r.gain_pct if r.gain_pct >= 0.5 else "slightly faster"
703        self._say("done", r.message or "Done")
704
705    # ---- helpers
706    def _memory_overrun(self, res: RunResult, base: RunResult) -> str | None:
707        """A candidate that takes more memory than the base the user asked for is not a candidate (their wish, 20% left
708        for work, is a promise about memory)."""
709        if res.rss_peak_mib and base.rss_peak_mib and res.rss_peak_mib > base.rss_peak_mib * 1.05 + 512 and self.o.goal == "room":
710            return "it needs more memory than your current settings, which would eat into the memory you wanted left free"
711        if res.min_avail_mib is not None and res.min_avail_mib < self.o.min_free_ram_mib and (
712                base.min_avail_mib is None or res.min_avail_mib < base.min_avail_mib - 512):   # a RAM-bound base can sit below the floor itself
713            return "it left the PC with too little free memory"
714        if self.o.goal == "room" and self.o.ram_wish_pct and self.total_ram and res.min_avail_mib is not None and \
715                base.min_avail_mib is not None:
716            if res.min_avail_mib < base.min_avail_mib - max(512, 0.03 * self.total_ram):
717                return "it left less memory free than your current settings"
718        if self.o.goal == "room" and res.vram_used_mib is not None and base.vram_used_mib is not None and \
719                res.vram_used_mib > base.vram_used_mib + 256:
720            return "it uses more graphics memory than your current settings"
721        if self.o.goal == "room" and self.o.reserve_mib and self.total_vram and res.vram_used_mib is not None and \
722                base.vram_used_mib is not None and self.total_vram - base.vram_used_mib >= self.o.reserve_mib - 128 and \
723                self.total_vram - res.vram_used_mib < self.o.reserve_mib - 128:
724            return "it would not leave the graphics memory you wanted free"
725        return None
726
727    def _confirm(self, args: dict[str, Any], env: dict[str, str | None], spec: RequestSet, pairs: int, use: str | None = None) -> list[tuple[RunResult, RunResult]]:
728        """Interleaved pairs of the combined settings against the base (the order alternates)."""
729        out: list[tuple[RunResult, RunResult]] = []
730        cand_args = tune_knobs.apply_to_argv(self.base_args, args)
731        for i in range(pairs):
732            self._check_cancel()
733            if self._over_budget(reserve_s=2 * self._avg_run()):
734                self.result.notes.append("confirmation stopped early: the time you chose ran out")
735                break
736            first = "cand" if i % 2 == 0 else "base"
737            runs: dict[str, RunResult] = {}
738            for who in (first, "base" if first == "cand" else "cand"):
739                self._say("confirm", f"Confirming (pair {i + 1} of {pairs})")
740                runs[who] = self._run(cand_args if who == "cand" else self.base_args, env if who == "cand" else {}, spec,
741                                      f"confirm {who} {i + 1}")
742            if runs["cand"].status == "PASS" and runs["base"].status == "PASS":
743                use = use or self.o.use
744                if metric(runs["cand"], use) and metric(runs["base"], use):
745                    out.append((runs["base"], runs["cand"]))
746                    self.base_runs.append(runs["base"])
747            else:
748                break
749        return out
750
751    def _per_request_stage(self, eng: Any) -> list[dict[str, Any]]:
752        """Per-request settings against the engine's own choice, in this one engine, 3 interleaved rounds (6.3 step 2).
753
754        A **control** point sends a per-request value equal to what the engine already uses (the configuration's own
755        `--spec-min-p`), so it changes nothing: whatever it "gains" is the bias of sending a setting at all (the first run
756        after an idle gap, the order). A value must beat the default by the margin AND beat the control by the margin in every
757        round. A win here is only a candidate: the tuner confirms it afterwards in a fresh engine. One value per key can win."""
758        points: list[tuple[str, Any]] = []
759        for spec in tune_knobs.PER_REQUEST:
760            if self.ctx.backend not in spec["backends"]:
761                continue
762            if spec["answer"] != "exact" and not tune_knobs.allowed(spec["answer"], self.ctx):
763                continue
764            for v in spec["values"]:
765                points.append((spec["key"], v))
766        if not points:
767            return []
768        own = tune_knobs._current(self.ctx.base_args, "--spec-min-p")
769        control = ("control", float(own)) if own not in (None, "") and self.ctx.backend != "metal" else None
770        rounds = 3
771        default: dict[int, list[float]] = {}
772        vals: dict[tuple[str, Any], dict[int, float]] = {pt: {} for pt in points + ([control] if control else [])}
773        self._say("per_request", "Trying settings that need no restart")
774        for rnd in range(rounds):
775            order = rotate([None] + points + ([control] if control else []) + [None], rnd)
776            for item in order:
777                self._check_cancel()
778                if item is None:
779                    d = eng.decode_once(None, 200)
780                    if d:
781                        default.setdefault(rnd, []).append(d)
782                else:
783                    key = "spec_min_p" if item[0] == "control" else item[0]
784                    d = eng.decode_once({key: item[1]}, 200)
785                    if d:
786                        vals[item][rnd] = d
787        ref = {i: statistics.mean(v) for i, v in default.items() if v}
788        ctl = [vals[control][i] / ref[i] for i in range(rounds) if control and i in vals[control] and i in ref] if control else []
789        rows: list[dict[str, Any]] = []
790        for pt in points:
791            ratios = [vals[pt][i] / ref[i] for i in range(rounds) if i in vals[pt] and i in ref]
792            adj = [ratios[j] / ctl[j] for j in range(min(len(ratios), len(ctl)))] if ctl else ratios
793            won = len(ratios) == rounds and len(adj) == rounds and all(x >= 1.0 + self.o.margin for x in adj) \
794                and all(x >= 1.0 + self.o.margin for x in ratios)
795            rows.append({"key": pt[0], "value": pt[1], "ratios": [round(x, 4) for x in ratios], "control_ratios": [round(x, 4) for x in ctl],
796                         "ratio": round(statistics.median(adj), 4) if adj else None, "won": won})
797        best: dict[str, dict[str, Any]] = {}
798        for row in rows:
799            if row["won"] and (row["key"] not in best or row["ratio"] > best[row["key"]]["ratio"]):
800                best[row["key"]] = row
801        for row in rows:
802            row["won"] = best.get(row["key"]) is row
803        return rows
804
805    def _confirm_per_request(self, chosen: dict[str, Any], spec: RequestSet, threshold: float) -> dict[str, Any]:
806        """5 interleaved rounds in a fresh engine of the chosen per-request settings against the engine's own choice (two decodes
807        each, the order alternating). Kept only if the median ratio beats the threshold in at least 4 of 5 rounds."""
808        ratios: list[float] = []
809
810        def points(eng: Any) -> None:
811            for i in range(5):
812                self._check_cancel()
813                got: dict[str, list[float]] = {"d": [], "t": []}
814                for who in (("d", "t") if i % 2 == 0 else ("t", "d")):
815                    for _ in range(2):
816                        v = eng.decode_once(chosen if who == "t" else None, 200)
817                        if v:
818                            got[who].append(v)
819                if got["d"] and got["t"]:
820                    ratios.append(statistics.mean(got["t"]) / statistics.mean(got["d"]))
821
822        res = self._run(self.base_args, {}, spec, "confirm per-request", points=points)
823        ok = res.status == "PASS" and len(ratios) == 5 and sum(1 for x in ratios if x > 1.0) >= 4 \
824            and statistics.median(ratios) >= threshold
825        return {"ok": ok, "ratios": [round(x, 4) for x in ratios], "ratio": round(statistics.median(ratios), 4) if ratios else None,
826                "status": res.status}
827
828
829# --------------------------------------------------------------------------- building a tuner from a run configuration
830
831def split_args(argv: list[str]) -> list[str]:
832    return [str(a) for a in argv]
833
834
835def detect_family(args: list[str]) -> str:
836    for i, a in enumerate(args):
837        if a == "--mtp" and i + 1 < len(args):
838            return "qwen36" if str(args[i + 1]).isdigit() else "flash-next"
839    if "--pack" in args or "--native" in args:
840        return "flash-next"
841    return "flash-next"
842
843
844def model_gib_of(args: list[str]) -> float:
845    """Total size of the model files a configuration names, shards included."""
846    from pathlib import Path
847    import re
848    total = 0
849    seen: set[str] = set()
850    for i, a in enumerate(args):
851        if a in ("--native", "--model", "--ple-gguf") and i + 1 < len(args):
852            p = Path(str(args[i + 1]))
853            if not p.is_file() or str(p) in seen:
854                continue
855            m = re.match(r"(.*)-(\d{5})-of-(\d{5})\.gguf$", p.name)
856            group = sorted(p.parent.glob(f"{m.group(1)}-*-of-{m.group(3)}.gguf")) if m else [p]
857            for f in group:
858                if str(f) not in seen:
859                    seen.add(str(f))
860                    total += f.stat().st_size
861    return round(total / 1024 ** 3, 1)
862
863
864def context_from_config(cfg: dict[str, Any], *, engine_backend: str | None, opts: Options,
865                        engine_flags: list[str] | None = None, system: dict[str, Any] | None = None,
866                        family: str | None = None) -> tune_knobs.Context:
867    args = split_args(cfg.get("args") or [])
868    system = system or {"memory": tune_machine.memory(), "gpus": tune_machine.gpus(), "cpu": tune_machine.cpu()}
869    gpu_cfg = cfg.get("gpu")
870    wanted = gpu_cfg if isinstance(gpu_cfg, list) else ([gpu_cfg] if isinstance(gpu_cfg, int) else None)
871    cards = system.get("gpus") or []
872    used = [g for g in cards if not wanted or g.get("index") in wanted] or cards
873    ctx_tokens = 32768
874    for i, a in enumerate(args):
875        if a == "--max-context" and i + 1 < len(args) and str(args[i + 1]).isdigit():
876            ctx_tokens = int(args[i + 1])
877    mem = system.get("memory") or {}
878    cpu = system.get("cpu") or {}
879    backend = engine_backend or ("cuda" if any(g.get("vendor") == "nvidia" for g in cards) else
880                                 "hip" if any(g.get("vendor") == "amd" for g in cards) else "cpu")
881    arch = None
882    if backend == "hip":
883        try:
884            archs = engine_component.hip_archs_present()
885            arch = archs[0] if archs else None
886        except Exception:  # noqa: BLE001
887            arch = None
888    return tune_knobs.Context(
889        backend=backend, family=family or detect_family(args), gpu_count=max(1, len(used)),
890        vram_mib=min((g["vram_total_mib"] for g in used if g.get("vram_total_mib")), default=0),
891        ram_gib=int((mem.get("total_mib") or 0) // 1024), model_gib=model_gib_of(args),
892        hybrid_cpu=bool(cpu.get("hybrid")), logical_threads=int(cpu.get("logical") or 0), arch=arch,
893        context_tokens=ctx_tokens, goal=opts.goal, use=opts.use, allow_placement=opts.allow_placement,
894        allow_nonrepeatable=opts.allow_nonrepeatable, engine_flags=engine_flags, base_args=args)
895
896
897# --------------------------------------------------------------------------- the short "still good?" re-check (8.3)
898
899def recheck(session: Session, base_args: list[str], preset: dict[str, Any], *, ctx: tune_knobs.Context,
900            engine_changed: bool = False, progress: Callable[[dict[str, Any]], None] | None = None,
901            cancel: threading.Event | None = None, clock: Callable[[], float] = time.monotonic) -> dict[str, Any]:
902    """Is a saved preset still as fast as when it was made? One restart with the preset's settings and 30-45 s of requests.
903
904    Pass rule (against the stored numbers, not a fresh baseline): decode and the 4K prompt at least 95% of what was stored,
905    memory within the stored +5%. A failing prompt rate is measured once more with a second start before it counts (the
906    prompt rate of some cards is bimodal between engine starts). When the engine changed in a way that can move speed
907    (``tuning_epoch``) a baseline start is added and the preset must be at least as fast as doing nothing.
908    The result is ``keep``, ``retune`` (suggested, never forced) or ``inconclusive`` (noise or a competing process)."""
909    progress = progress or (lambda p: None)
910    cancel = cancel or threading.Event()
911    t0 = clock()
912    s = preset.get("settings") or {}
913    stored = preset.get("measured") or {}
914    args = tune_knobs.apply_to_argv(base_args, s.get("args") or {})
915    env = dict(s.get("env") or {})
916    spec = RequestSet(warmups=1, decodes=3, decode_tokens=200, pp_tokens=4096 if ctx.context_tokens >= 6000 else 1024, long_tokens=0)
917    if ctx.backend == "sycl":
918        spec.pp_tokens = 0                         # the A750's 4K prompt takes a minute: decode only (8.3)
919    out: dict[str, Any] = {"verdict": "inconclusive", "request_set": RECHECK_SET_NAME, "notes": []}
920
921    def one(a: list[str], e: dict[str, str | None], label: str) -> RunResult:
922        if cancel.is_set():
923            raise Cancelled()
924        progress({"stage": "recheck", "message": label, "elapsed_s": round(clock() - t0)})
925        try:
926            with session.engine(a, e) as eng:
927                r = eng.measure(spec)
928        except StartFailed as ex:
929            return RunResult(status=ex.status, reason=ex.reason)
930        return r
931
932    try:
933        run = one(args, env, "Checking your saved settings")
934        if run.status != "PASS":
935            out.update(verdict="retune", reason=f"the saved settings did not start now: {run.status} {run.reason}")
936            out["seconds"] = round(clock() - t0, 1)
937            return out
938        out["measured"] = {"decode_tok_s": run.decode_tok_s, "pp4k_tok_s": run.pp_tok_s, "rss_peak_mib": run.rss_peak_mib,
939                           "vram_peak_mib": run.vram_used_mib}
940        sd, sp = stored.get("decode_tok_s"), stored.get("pp4k_tok_s")
941        problems: list[str] = []
942        if sd and run.decode_tok_s and run.decode_tok_s < 0.95 * sd:
943            problems.append(f"answers are {100 * (1 - run.decode_tok_s / sd):.0f}% slower than when it was saved")
944        if sp and run.pp_tok_s and run.pp_tok_s < 0.95 * sp:
945            again = one(args, env, "Checking prompt speed once more")
946            if again.status == "PASS" and again.pp_tok_s and again.pp_tok_s >= 0.95 * sp:
947                out["notes"].append("prompt speed varied between starts; the second start was fine")
948            else:
949                problems.append("long prompts are slower than when it was saved")
950        for key, got in (("rss_peak_mib", run.rss_peak_mib), ("vram_peak_mib", run.vram_used_mib)):
951            ref = stored.get(key)
952            if ref and got and got > 1.05 * ref:
953                problems.append("it now uses more memory than when it was saved")
954                break
955        if engine_changed:
956            base = one(base_args, {}, "Checking against the standard settings after the engine update")
957            if base.status == "PASS" and base.decode_tok_s and run.decode_tok_s and run.decode_tok_s < base.decode_tok_s:
958                problems.append("the standard settings are now faster than the saved ones")
959            out["baseline"] = {"decode_tok_s": base.decode_tok_s, "pp4k_tok_s": base.pp_tok_s}
960        out["problems"] = problems
961        out["verdict"] = "retune" if problems else "keep"
962        out["reason"] = ("Still as fast as when it was saved." if not problems else "; ".join(problems))
963    except Cancelled:
964        out.update(verdict="inconclusive", reason="Stopped.")
965    out["seconds"] = round(clock() - t0, 1)
966    return out
967
968
969RECHECK_SET_NAME = "recheck/1"