okami.mom/strata

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

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
28.0 KiB531 linesraw
1"""Tune the engine's hardware-dependent settings on this PC (setup's --calibrate).
2
3Three settings depend on the machine more than on the model, and the defaults are right for the PC they were
4measured on (a Ryzen 5 7600 + RTX 5070 on PCIe 5):
5  --pcie-frac     the share of the experts missing from VRAM that are copied over PCIe and run on the GPU instead of
6                  on the CPU.  A fast PCIe link and a slow CPU want more; a laptop's x8 link or a fast CPU want less.
7  --spec-min-p    how sure the draft layer must be to extend a verify window by another guess.  A slower CPU pays more
8                  per extra window row (more experts per window), so it wants a higher floor.
9  --pool-workers  the CPU threads that compute experts.  Every physical core is not always best: on hybrid CPUs the
10                  efficiency cores can make the whole window wait for them.
11  --adapt-every / --adapt-swaps / --adapt-decay
12                  how the VRAM expert tier follows the conversation: how often, how many experts it swaps in, how fast
13                  its use counts fade.  A PC whose CPU reads the missed experts slowly (DDR3, ~24 GB/s) gains from
14                  swapping more: 160 swaps every window measured +7.9% over the default tier on a Xeon E5-2673 v3 (DDR3) with an
15                  RTX 4060 Ti on PCIe 3.0 x8 (Q2_0; with the swaps taking effect a window later, #764).
16  --prefill-pipe  a layer split only: the prompt chunks that keep the stages reading at once.  The best chunk count
17                  depends on b/a, the fixed cost of a chunk over that of a token, which differs by an order of
18                  magnitude between rigs (about 700 tokens on four GP100 dies, 5000 on two RTX 3090 Ti) and costs
19                  when it is wrong (a fixed 1024 read 22-36% slower on two RTX 4090) - so it is measured here, once,
20                  as the prompt read speed of fresh prompts, rather than guessed or learned while the PC serves.
21  STRATA_SH_STREAM (AMD only)
22                  the shared expert on its own stream.  Off by default on HIP (#816: an RX 6800 on Windows and 4x R9700
23                  decode 12-45% faster without it), but the same card family on another PC goes the other way (#1272:
24                  2x RX 6900 XT on Linux, 6-11% faster with it), so it is measured here, per PC, and written into the
25                  config's "env" only when it wins.  The output is identical either way (same token ids).
26
27The first two and the prompt chunks are measured through one engine (per-request `strata_tune` keys); the worker
28count, the adaptive tier and the shared-expert stream need a restart per value.  Those are decode speed: the prompt
29path streams every expert whatever they say.
30
31A setting is kept only when it beats the default by more than MIN_GAIN in an interleaved re-measurement - the
32adaptive expert tier and the OS make single measurements noisy by a few percent.
33
34    python tools/calibrate.py strata-q2_0.json        # measure and print; setup.py --calibrate also saves it
35"""
36from __future__ import annotations
37
38import json
39import statistics
40import sys
41import threading
42import time
43from pathlib import Path
44
45ROOT = Path(__file__).resolve().parents[1]
46sys.path.insert(0, str(ROOT / "tools"))
47sys.path.insert(0, str(ROOT))
48
49MIN_GAIN = 0.03                    # a setting must beat the default by this much to be kept
50PCIE_FRACS = (0.0, 0.2, 0.35, 0.55, 0.75, 0.9, 1.0)   # 1.0: every miss over PCIe, the CPU pool gets no expert
51SPEC_MIN_PS = (0.3, 0.5, 0.7)
52SWEEP_ROUNDS = 3                   # how many times the sweep visits each value (see `sweep`)
53# the adaptive tier's candidates (every, swaps, decay) against the engine's own (None): swapping more and remembering
54# longer, the rest of the set as the engine has it
55# HIP: the shared-expert stream fork, off (the HIP default) against on; an engine environment variable, not an argument
56SH_STREAM = "STRATA_SH_STREAM"
57ADAPT_CANDIDATES = (None, ("1", "80", "0.97"), ("1", "160", "0.97"))
58ADAPT_FLAGS = ("--adapt-every", "--adapt-swaps", "--adapt-decay")
59MAX_NEW = 128
60# the expert tier follows a text over some windows: 128-token answers end before it shows (on a Xeon E5-2673 v3 with
61# DDR3, every 1 / 160 / 0.97 measured +0.7% with 128 tokens and +7.9% with 512-token answers), so its step uses these
62TIER_MAX_NEW = 512
63# --prefill-pipe's values: 0 the buffers' chunks (the engine default), 1 their count evened out, then b/a in tokens
64PIPE_VALUES = (0, 1, 768, 1536, 3072, 6144)
65PIPE_TOKENS = (2048, 8192)        # fresh prompts read per value (their text: the install's docs/*.md)
66PROMPTS = (
67    "Write a Python function that merges two sorted lists into one sorted list, with a docstring and two tests.",
68    "Explain in two paragraphs how a refrigerator moves heat from inside to outside.",
69    "List twelve European capitals with one sentence about each.",
70)
71
72
73class CalibrationCancelled(RuntimeError):
74    """An operator requested a stop; no partial sample may enter the report."""
75
76
77def _check_cancel(cancel_event):
78    if cancel_event is not None and cancel_event.is_set():
79        raise CalibrationCancelled("calibration cancelled")
80
81
82def _progress(callback, stage: str, completed: int, total: int):
83    if callback is not None:
84        callback(stage, completed, total)
85
86
87def chat_ids(tok, text: str) -> list[int]:
88    return tok.encode(f"<|im_start|>user\n{text}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
89                      parse_special=True)
90
91
92def arg_value(args: list[str], flag: str) -> str | None:
93    return args[args.index(flag) + 1] if flag in args and args.index(flag) + 1 < len(args) else None
94
95
96def with_arg(args: list[str], flag: str, value: str | None) -> list[str]:
97    """`args` with `flag value` set (replaced if present), or removed when value is None."""
98    out = list(args)
99    if flag in out:
100        i = out.index(flag)
101        del out[i:i + 2]
102    if value is not None:
103        out += [flag, value]
104    return out
105
106
107def worker_candidates(default: int, extra=()) -> list[int]:
108    """The engine's own count, and fewer: two thirds, a half and a quarter (at least 2), plus `extra` (the P-cores
109    minus one on a hybrid CPU, one socket's cores minus one on a 2-socket PC), without repeats.  Bench #780 #815
110    #707 #674: 4 beat 15 by 28.7% on 8P + 16E; 17-18 beat 35 by ~20% on 2-socket Xeons."""
111    c = [default]
112    for w in (round(default * 2 / 3), round(default / 2), round(default / 4), *extra):
113        if 2 <= w < default and w not in c:
114            c.append(w)
115    return c
116
117
118def host_worker_extras() -> list[int]:
119    """P-cores - 1 (hybrid CPU) and one socket's cores - 1 (several sockets) of this PC: more counts to try."""
120    try:
121        import setup
122        out = []
123        cores, sockets = setup.cpu_cores(), setup.cpu_sockets()
124        if cores:
125            out.append(cores[0] - 1)
126        if sockets and sockets[0] >= 2:
127            out.append(sockets[1] - 1)
128        return out
129    except Exception:
130        return []
131
132
133def doc_prompt(tok):
134    """`make(i, n)`: a fresh prompt of about n tokens - the same stretch of the docs' text for every i, after a header
135    that differs for every i, so no read reuses an earlier one's cache and the reads differ only in their chunks (where
136    experts are streamed, the read speed depends on the text: a different stretch per read measured the text)."""
137    text = "\n\n".join(p.read_text(encoding="utf-8", errors="replace") for p in sorted((ROOT / "docs").glob("*.md")))
138    body = tok.encode(text, parse_special=False) or [0]
139    tail = tok.encode("<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n", parse_special=True)
140
141    def make(i: int, n: int) -> list[int]:
142        head = tok.encode(f"<|im_start|>user\n[calibration read {i}] Summarize:\n", parse_special=True)
143        return head + (body * (n // len(body) + 1))[:n] + tail
144    return make
145
146
147def measure_pipe(eng, make, say=print) -> tuple[float, dict]:
148    """--prefill-pipe on one running engine (a layer split): the prompt read speed of fresh prompts per value, then the
149    best against the default (0) in SWEEP_ROUNDS paired rounds (back to back, the order alternating).  It is kept only
150    when it is faster in every round and by more than MIN_GAIN in the median: on two RTX 3090 Ti one read can be 20%
151    off, and a b/a too small for the rig reads 19-24% slower there.  One pass over the values, not `sweep`'s rounds:
152    every value reads the same text (`doc_prompt`), and on four GP100 dies one pass already takes about 4 minutes."""
153    reads = [0]
154
155    def rate(v: float) -> float:
156        ms = toks = 0.0
157        for n in PIPE_TOKENS:
158            reads[0] += 1
159            sampling = {"temperature": 0, "strata_checkpoint": False, "strata_tune": {"prefill_pipe": v}}
160            for _ in eng.generate(make(reads[0], n), 1, sampling, threading.Event()):
161                pass
162            last = eng.last or {}
163            ms += float(last.get("prompt_ms") or 0.0)
164            toks += float(last.get("prompt_read") or (last.get("prompt_tokens") or 0) - (last.get("reused") or 0))
165        return toks / (ms / 1000.0) if ms > 0 and toks > 0 else 0.0
166
167    rate(0)                                            # the first long read after a start faults the weights in
168    by_value = {}
169    for v in PIPE_VALUES:
170        by_value[v] = [rate(v)]
171        say(f"    prompt chunks {'off' if v == 0 else 'evened out' if v == 1 else f'b/a {v}'}: {by_value[v][0]:.0f} tok/s")
172    best = max(by_value, key=lambda k: by_value[k][0])
173    confirm = {0: [], best: []}
174    chosen = 0
175    if best != 0:
176        for r in range(SWEEP_ROUNDS):
177            for k in ((0, best) if r % 2 == 0 else (best, 0)):
178                confirm[k].append(rate(k))
179        gains = [c / d - 1.0 for d, c in zip(confirm[0], confirm[best]) if d > 0]
180        if len(gains) == SWEEP_ROUNDS and min(gains) > 0.0 and statistics.median(gains) > MIN_GAIN:
181            chosen = best
182    return chosen, {"pipe_sweep": {str(k): v for k, v in by_value.items()},
183                    "pipe_confirm": {str(k): v for k, v in confirm.items()}}
184
185
186def pick(measured: dict, default_key, min_gain: float = MIN_GAIN):
187    """The key with the best median tok/s, or `default_key` unless the best beats it by more than min_gain."""
188    med = {k: statistics.median(v) for k, v in measured.items() if v}
189    if not med or default_key not in med:
190        return default_key
191    best = max(med, key=med.get)
192    return best if med[best] > med[default_key] * (1.0 + min_gain) else default_key
193
194
195class Session:
196    """One running engine: measure decode tok/s for a setting (the median of the prompts' rates)."""
197
198    def __init__(self, engine, ids_list, cancel_event=None):
199        self.engine = engine
200        self.ids_list = ids_list
201        self.cancel_event = cancel_event
202
203    def rate(self, tune: dict | None = None, max_new: int | None = None) -> float:
204        rates = []
205        for ids in self.ids_list:
206            _check_cancel(self.cancel_event)
207            sampling = {"temperature": 0}
208            if tune:
209                sampling["strata_tune"] = tune
210            n = sum(1 for t in self.engine.generate(ids, max_new or MAX_NEW, sampling,
211                                                   self.cancel_event or threading.Event())
212                    if t is not None)
213            _check_cancel(self.cancel_event)
214            ms = (self.engine.last or {}).get("decode_ms") or 0.0
215            if n > 8 and ms > 0:
216                rates.append(n / (ms / 1000.0))
217        return statistics.median(rates) if rates else 0.0
218
219    def warm_up(self, rounds: int = 2):
220        for _ in range(rounds):
221            self.rate()
222
223
224def run(cfg: dict, say=print, start_engine=None, *, progress=None, cancel_event=None) -> dict:
225    """Measure on the engine `cfg` describes; returns {"settings": {flag: value}, "report": {...}}.
226    `start_engine(args)` returns a started engine (serve.server.StrataEngine or a stand-in in tests)."""
227    if start_engine is None:
228        from serve.server import StrataEngine, child_env
229
230        def start_engine(args, env=None):
231            e = child_env(cfg)
232            e.update(env or {})
233            return StrataEngine(cfg["exe"], args, cwd=cfg.get("cwd"), log=cfg.get("log"), env=e)
234    import strata_tokenizer as ST
235    tpath = Path(cfg["tokenizer"])
236    vocab = json.loads((tpath / "vocab.json").read_text(encoding="utf-8"))
237    toks = [None] * len(vocab)
238    for t, i in vocab.items():
239        toks[i] = t
240    tok = ST.Tokenizer(toks, (tpath / "merges.txt").read_text(encoding="utf-8").split("\n"),
241                       json.loads((tpath / "token_type.json").read_text()))
242    ids_list = [chat_ids(tok, p) for p in PROMPTS]
243    if progress is None and cancel_event is None:
244        return measure(engine_args(cfg), ids_list, start_engine, say, host_worker_extras(), doc_prompt(tok),
245                       hip=cfg.get("backend") == "hip")
246    return measure(engine_args(cfg), ids_list, start_engine, say, host_worker_extras(), doc_prompt(tok),
247                   hip=cfg.get("backend") == "hip", progress=progress, cancel_event=cancel_event)
248
249
250def engine_args(cfg: dict) -> list[str]:
251    """The arguments the server starts this config's engine with (serve.server.engine_args), so the tuning measures
252    the engine as it runs.  #447: this used to read any "gpu" list as a layer split and add --layer-split auto, which
253    broke a one-card config with a helper card for the expert tier ("gpu": [0] + --expert-cache-device1: the engine
254    refuses a split that leaves no card without a stage), missed the "0,2" spelling, and ignored split_skip_if_fits.
255    #5720: with the engine program, as the server passes it: the drafter pack follows the program (a selector-Q4 pack
256    only for one that reads it), so without it the sweep engines started with another pack than the server's."""
257    from serve.server import engine_args as server_args
258    return server_args(cfg, cfg.get("exe"))
259
260
261def engine_error(log: str | None, since: int = 0) -> str | None:
262    """#447: the engine's own reason for a failed start - the last line of its log written after byte `since` that is
263    its own ("strata ..." or "ERR ..."), else the last line there; None without a log or a new line."""
264    if not log:
265        return None
266    try:
267        with open(log, "rb") as f:
268            f.seek(since)
269            lines = [x.strip() for x in f.read()[-16384:].decode("utf-8", "replace").splitlines() if x.strip()]
270    except OSError:
271        return None
272    return next((x for x in reversed(lines) if x.startswith(("strata", "ERR"))), lines[-1] if lines else None)
273
274
275def sweep(s, values: list, base_tune: dict, key: str, label: str, say,
276          progress=None, stage: str | None = None) -> dict:
277    """Every value, `SWEEP_ROUNDS` times, one round visiting all of them and every other round in reverse order.
278
279    A single rate per value cannot order neighbours.  #1332 has 0.75 to 0.95 inside each other's noise at 72.7,
280    69.0, 71.0 and 71.9, and that box moved 8-28% between engine starts at an unchanged setting; a 5080/Xeon box
281    reports +9.57 tok/s between two blocks at an unchanged setting (p = 0.00004), larger than the effect being
282    hunted.  Rotating the values inside one engine start puts that drift on every value the same number of times,
283    and the median over the rounds keeps a single bad sample from deciding.  The caller takes the winner from the
284    medians, so every value keeps the same chance the others had.
285    """
286    out = {v: [] for v in values}
287    if stage is not None:
288        _progress(progress, stage, 0, len(values) * SWEEP_ROUNDS)
289    completed = 0
290    for r in range(SWEEP_ROUNDS):
291        for v in (values if r % 2 == 0 else values[::-1]):
292            out[v].append(s.rate({**base_tune, key: v}))
293            completed += 1
294            if stage is not None:
295                _progress(progress, stage, completed, len(values) * SWEEP_ROUNDS)
296        say(f"    round {r + 1}/{SWEEP_ROUNDS} {label}: " +
297            "  ".join(f"{v:g} {out[v][-1]:.1f}" for v in values))
298    med = {v: statistics.median(out[v]) for v in values}
299    say(f"    {label}, median of {SWEEP_ROUNDS}: " +
300        ", ".join(f"{v:g}: {med[v]:.1f} ({min(out[v]):.1f}-{max(out[v]):.1f})" for v in values) +
301        f" -> best {max(med, key=lambda k: med[k]):g}")
302    return out
303
304
305def measure(base_args: list[str], ids_list, start_engine, say=print, extra_workers=(), long_prompt=None, hip: bool = False,
306            *, progress=None, cancel_event=None) -> dict:
307    t0 = time.time()
308    report: dict = {}
309    _check_cancel(cancel_event)
310    _progress(progress, "loading", 0, 1)
311    say("  Loading the model for the measurements ...")
312    base_args = apply(base_args, {})                   # the product defaults: what the measurements must beat
313    eng = start_engine(base_args)
314    try:
315        info = dict(getattr(eng, "info", {}) or {})
316        d_pcie = float(info.get("pcie_frac", 0.55))
317        d_minp = float(info.get("spec_min_p", 0.5))
318        d_workers = int(info.get("pool_workers", 0)) or None
319        s = Session(eng, ids_list, cancel_event)
320        s.warm_up()
321        _progress(progress, "loading", 1, 1)
322        # 0. a layer split's prompt chunks (prompt read speed; independent of the decode settings below)
323        pipe = 0
324        # the engine's own count of prompt stages where it reports one (a split can leave one, e.g.
325        # --split-skip-if-fits), else the flag
326        stages = info.get("prefill_stages")
327        split = stages > 1 if isinstance(stages, int) else "--layer-split" in base_args
328        if long_prompt is not None and split:
329            say("  Measuring the prompt chunks of the layer split ...")
330            pipe, rep_pipe = measure_pipe(eng, long_prompt, say)
331            report.update(rep_pipe)
332        # 1. the PCIe share, at the default draft floor
333        by_pcie = sweep(s, sorted(set(PCIE_FRACS) | {round(d_pcie, 2)}), {"spec_min_p": d_minp}, "pcie_frac",
334                        "PCIe share", say, progress, "pcie_share")
335        best_pcie = max(by_pcie, key=lambda k: statistics.median(by_pcie[k]))
336        # 2. the draft floor, at that share
337        by_minp = sweep(s, sorted(set(SPEC_MIN_PS) | {round(d_minp, 2)}), {"pcie_frac": best_pcie}, "spec_min_p",
338                        "draft floor", say, progress, "draft_floor")
339        best_minp = max(by_minp, key=lambda k: statistics.median(by_minp[k]))
340        # 3. the winner against the default, interleaved, the same number of rounds
341        dflt, cand = (round(d_pcie, 2), round(d_minp, 2)), (best_pcie, best_minp)
342        confirm = {dflt: [], cand: []}
343        confirm_total = SWEEP_ROUNDS * 2 if cand != dflt else 1
344        _progress(progress, "confirmation", 0, confirm_total)
345        if cand != dflt:
346            for _ in range(SWEEP_ROUNDS):
347                for k in (dflt, cand):
348                    confirm[k].append(s.rate({"pcie_frac": k[0], "spec_min_p": k[1]}))
349                    _progress(progress, "confirmation", sum(map(len, confirm.values())), confirm_total)
350        else:
351            _progress(progress, "confirmation", 1, 1)
352        chosen = pick(confirm, dflt) if cand != dflt else dflt
353        report.update(default={"pcie_frac": dflt[0], "spec_min_p": dflt[1], "pool_workers": d_workers},
354                      pcie_sweep={str(k): v for k, v in by_pcie.items()},
355                      min_p_sweep={str(k): v for k, v in by_minp.items()},
356                      confirm={f"{k[0]}/{k[1]}": v for k, v in confirm.items()})
357    finally:
358        close(eng)
359    settings = {}
360    if pipe:
361        settings["--prefill-pipe"] = str(int(pipe))
362    if chosen != dflt:
363        settings["--pcie-frac"] = f"{chosen[0]:.2f}"
364        settings["--spec-min-p"] = f"{chosen[1]:.2f}"
365    base_rate = statistics.median(confirm[chosen]) if confirm.get(chosen) else None
366    # 4. fewer CPU workers (a restart each), with the chosen settings.  #1337's rule covers a death during a
367    # measurement too: an engine that exits mid-rate is that candidate losing; the measurements so far stay.
368    if d_workers and len(worker_candidates(d_workers, extra_workers)) > 1:
369        tuned = with_arg(with_arg(base_args, "--pcie-frac", f"{chosen[0]:.2f}"), "--spec-min-p", f"{chosen[1]:.2f}")
370        by_workers = {}
371        workers = worker_candidates(d_workers, extra_workers)
372        _progress(progress, "cpu_workers", 0, len(workers))
373        for index, w in enumerate(workers, 1):
374            _check_cancel(cancel_event)
375            say(f"  Measuring with {w} CPU workers (restarts the engine) ...")
376            measure_candidate(start_engine, with_arg(tuned, "--pool-workers", None if w == d_workers else str(w)),
377                              f"{w} workers", say, report, by_workers, w, ids_list, cancel_event=cancel_event)
378            _progress(progress, "cpu_workers", index, len(workers))
379        report["workers"] = {str(k): v for k, v in by_workers.items()}
380        w_best = pick(by_workers, d_workers) if by_workers else d_workers
381        if w_best != d_workers:
382            settings["--pool-workers"] = str(w_best)
383            base_rate = statistics.median(by_workers[w_best])
384        elif by_workers.get(d_workers):
385            base_rate = statistics.median(by_workers[d_workers])
386    else:
387        _progress(progress, "cpu_workers", 1, 1)
388    # 5. the adaptive expert tier (a restart each), with everything chosen so far.  A candidate whose engine dies
389    # during its own measurement is dropped like a failed start (#1337); the other candidates and every earlier
390    # result survive.
391    tuned = apply(base_args, settings)
392    by_adapt = {}
393    _progress(progress, "expert_tier", 0, len(ADAPT_CANDIDATES))
394    for index, cand in enumerate(ADAPT_CANDIDATES, 1):
395        _check_cancel(cancel_event)
396        key = "default" if cand is None else "/".join(cand)
397        args = tuned
398        for flag, v in zip(ADAPT_FLAGS, cand or (None,) * len(ADAPT_FLAGS)):
399            args = with_arg(args, flag, v)
400        say(f"  Measuring the expert tier {'(the engine default)' if cand is None else 'every ' + cand[0] + ', ' + cand[1] + ' swaps, decay ' + cand[2]} (restarts the engine) ...")
401        measure_candidate(start_engine, args, "the expert tier " + key, say, report, by_adapt, key, ids_list,
402                          TIER_MAX_NEW, cancel_event=cancel_event)
403        _progress(progress, "expert_tier", index, len(ADAPT_CANDIDATES))
404    a_best = pick(by_adapt, "default") if by_adapt else "default"
405    report["adapt"] = by_adapt
406    if a_best != "default":
407        for flag, v in zip(ADAPT_FLAGS, a_best.split("/")):
408            settings[flag] = v
409        base_rate = statistics.median(by_adapt[a_best])
410    elif by_adapt.get("default"):
411        base_rate = statistics.median(by_adapt["default"])
412    # 6. HIP: the shared-expert stream fork (a restart each), with everything chosen so far.  Both values are set
413    # explicitly, so a value the config carried before does not decide the baseline.
414    env = {}
415    tuned = apply(base_args, settings)
416    if hip and fork_is_unsafe(tuned):
417        # #3895: one Windows RX 6000 PC faulted the engine on the first request with the fork and KV streaming together. The fork is off by
418        # default on AMD, so skipping the measurement changes nothing; whoever wants it sets the variable by hand.
419        say("  Not measuring the shared expert on its own stream: on Windows with KV streaming (--kv-resident) it made the engine fail on the first "
420            f"request on one PC (#3895). To try it anyway, put {SH_STREAM}=1 in the config's env.")
421        report["sh_stream_skipped"] = "windows with --kv-resident"
422    elif hip:
423        by_fork = {}
424        for v in ("0", "1"):
425            _check_cancel(cancel_event)
426            say(f"  Measuring the shared expert {'on its own stream' if v == '1' else 'on the main stream (the AMD default)'}"
427                " (restarts the engine) ...")
428            measure_candidate(lambda a: start_engine(a, {SH_STREAM: v}), tuned, f"{SH_STREAM}={v}", say, report,
429                              by_fork, v, ids_list, cancel_event=cancel_event)
430        report["sh_stream"] = by_fork
431        if pick(by_fork, "0") == "1":
432            env[SH_STREAM] = "1"
433            base_rate = statistics.median(by_fork["1"])
434        elif by_fork.get("0"):
435            base_rate = statistics.median(by_fork["0"])
436    report["seconds"] = round(time.time() - t0)
437    report["tok_s"] = round(base_rate, 1) if base_rate else None
438    _check_cancel(cancel_event)
439    return {"settings": settings, "env": env, "report": report}
440
441
442def first_line(exc: Exception) -> str:
443    return str(exc).strip().splitlines()[0][:300] if str(exc).strip() else type(exc).__name__
444
445def fork_is_unsafe(args) -> bool:
446    """The shared-expert fork (STRATA_SH_STREAM) with KV streaming on Windows: the one combination that has made an engine fail on its first
447    request (#3895, an RX 6900 XT). Not measured there; a person can still set the variable."""
448    return sys.platform == "win32" and arg_value(args, "--kv-resident") is not None
449
450
451def restart(start_engine, args, what, say, report):
452    """#1337: a later step's engine start that fails is a candidate that loses, not a failed run: what the earlier
453    steps measured (and the settings they chose) must survive it.  Returns the engine, or None after saying why and
454    noting it in report["failed_starts"].  (The first start, for steps 1-3, is not covered: with no engine there is
455    nothing measured.)"""
456    try:
457        return start_engine(args)
458    except Exception as e:  # noqa: BLE001 - whatever the start raised (RuntimeError, EngineDied, OSError ...)
459        why = first_line(e)
460        say(f"    the engine did not start for {what}: {why} - this candidate is dropped, the earlier results are kept")
461        report.setdefault("failed_starts", {})[what] = why
462        return None
463
464
465def measure_candidate(start_engine, args, what, say, report, by: dict, key, ids_list, max_new: int | None = None,
466                      cancel_event=None):
467    """One restart-and-measure candidate (#1337): a start that fails and an engine that exits mid-measurement are
468    both that candidate losing - `by[key]` gets its two rates, or report["failed_starts"] its reason.  Everything
469    measured earlier and the other candidates survive.  An operator cancel is not a candidate death: it raises."""
470    e = restart(start_engine, args, what, say, report)
471    if e is None:
472        return
473    try:
474        s = Session(e, ids_list, cancel_event)
475        s.warm_up(1)
476        by[key] = [s.rate(max_new=max_new), s.rate(max_new=max_new)]
477        say(f"    {what}: {statistics.median(by[key]):.1f} tok/s")
478    except CalibrationCancelled:
479        raise
480    except Exception as exc:  # noqa: BLE001 - the engine died mid-measurement: this candidate loses (#1337)
481        why = first_line(exc)
482        say(f"    the engine died while measuring {what}: {why} - this candidate is dropped, "
483            "the earlier results are kept")
484        report.setdefault("failed_starts", {})[what] = why
485    finally:
486        close(e)
487
488
489def close(eng):
490    proc = getattr(eng, "proc", None)
491    if proc is None:
492        return
493    try:
494        proc.stdin.write("QUIT\n")
495        proc.stdin.flush()
496        proc.stdin.close()
497        proc.wait(60)
498    except Exception:
499        proc.kill()
500
501
502DEFAULTS = {"--pcie-frac": None, "--spec-min-p": "0.5", "--pool-workers": None,   # None: the engine's own choice
503            "--adapt-every": None, "--adapt-swaps": None, "--adapt-decay": None, "--prefill-pipe": None}
504
505
506def apply(args: list[str], settings: dict) -> list[str]:
507    """`args` with the calibrated settings; a setting the calibration did not change goes back to the product
508    default (setup's --spec-min-p 0.5, the engine's own PCIe share and worker count), so an older calibration's
509    values never linger."""
510    out = list(args)
511    for flag, default in DEFAULTS.items():
512        out = with_arg(out, flag, settings.get(flag, default))
513    return out
514
515
516ENV_KEYS = (SH_STREAM,)
517
518
519def apply_env(env: dict | None, calibrated: dict | None) -> dict:
520    """The config's "env" with a calibration's engine variables: the ones it chose are set, the others in ENV_KEYS are
521    removed (back to the engine's default), so an older calibration's choice never lingers."""
522    out = {k: v for k, v in (env or {}).items() if k not in ENV_KEYS}
523    out.update(calibrated or {})
524    return out
525
526
527if __name__ == "__main__":
528    if len(sys.argv) != 2:
529        sys.exit("usage: calibrate.py <strata-*.json>")
530    res = run(json.loads(Path(sys.argv[1]).read_text(encoding="utf-8-sig")))
531    print(json.dumps(res, indent=1))