okami.mom/strata

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

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

main
26.5 KiB511 linesraw
1"""The auto-tuner's decisions, tested with a stub engine whose speed is computed from the flags it is given."""
2
3from __future__ import annotations
4
5import threading
6import unittest
7
8from strata_control import autotune, tune_knobs
9from strata_control.tune_session import StartFailed
10
11from tests.tuning.stub_session import FakeClock, StubSession, flag
12
13BASE = ["--pack", "P", "--native", "m.gguf", "--expert-cache", "auto", "--prefill", "auto", "--spec", "4",
14        "--spec-min-p", "0.5", "--mtp", "D", "--max-context", "131072", "--kv", "int8", "--kv-resident", "32768",
15        "--vram-reserve-mib", "1536"]
16
17
18def make_ctx(**kw):
19    ctx = tune_knobs.Context(backend="cuda", family="flash-next", gpu_count=1, vram_mib=12000, ram_gib=64, model_gib=60.0,
20                             context_tokens=131072, base_args=list(BASE), logical_threads=12, **kw)
21    ctx.facts = {"workers": 6, "slots": 3000}
22    return ctx
23
24
25def speed_with(gains: dict[str, float], base=60.0):
26    """tok/s as a function of the flags: each (flag, value) in `gains` multiplies the speed."""
27    def model(args, env, tune=None):
28        v = base
29        for (f, val), g in gains.items():
30            if f.startswith("STRATA_"):
31                if env.get(f) == val:
32                    v *= g
33            elif flag(args, f) == val:
34                v *= g
35        if tune:
36            for k, g in (gains.get(("tune", None)) or {}).items() if False else []:
37                pass
38        return v
39    return model
40
41
42def make_ctx_small():
43    c = make_ctx()
44    c.context_tokens = 16384
45    c.base_args = ["--max-context", "16384"]
46    return c
47
48
49def run_tuner(model, *, opts=None, ctx=None, clock=None, session_kw=None, cancel=None, progress=None, **kw):
50    clock = clock or FakeClock()
51    session = StubSession(model=model, clock=clock, **(session_kw or {}))
52    t = autotune.Tuner(session, BASE, {}, ctx or make_ctx(), opts or autotune.Options(), clock=clock, sleep=clock.sleep,
53                       system=session.system, total_ram_mib=64000, total_vram_mib=12000, quiet=lambda: None,
54                       cancel=cancel, progress=progress, **kw)
55    return t, session, t.run()
56
57
58class RulesTest(unittest.TestCase):
59    def test_never_list(self):
60        ctx = make_ctx(arch="gfx1201")
61        bad = [({"--expert-cache": 0}, {}), ({"--kv-resident": 20480}, {}), ({"--pcie-frac": 0.75}, {}),
62               ({"--spec": 6}, {}), ({"--spec": 2}, {}), ({"--lookup-chain": 4}, {}), ({"--adapt-every": 100000}, {}),
63               ({"--spec": 5}, {}),   # outside the tuner's values: still not tried (a saved preset may keep it, #3844)
64               ({"--prefill": 512}, {}), ({"--ple-io": "ram"}, {}), ({}, {"STRATA_SH_STREAM": "1"}),
65               ({}, {"STRATA_RDNA2_SGEMM": "all"}), ({}, {"STRATA_HIP_WMMA": "1"}), ({"--pool-workers": 8}, {})]
66        for args, env in bad:
67            self.assertTrue(tune_knobs.check_setting(args, env, ctx), (args, env))
68        ok = [({"--spec": 3}, {}), ({"--kv-resident": 65536}, {}), ({"--pool-workers": 4}, {}), ({"--prefill": "auto:32768"}, {}),
69              ({"--adapt-every": 1, "--adapt-swaps": 80, "--adapt-decay": 0.97}, {}), ({"--pcie-frac": 0.2}, {})]
70        for args, env in ok:
71            self.assertEqual(tune_knobs.check_setting(args, env, ctx), [], (args, env))
72
73    def test_kv_resident_rules_follow_the_context(self):
74        long = make_ctx()                               # 128K, the config's own --kv-resident is 32768
75        self.assertEqual(tune_knobs.check_setting({"--kv-resident": 65536}, {}, long), [])
76        self.assertEqual(tune_knobs.check_setting({"--kv-resident": 49152}, {}, long), [])
77        self.assertTrue(tune_knobs.check_setting({"--kv-resident": 20480}, {}, long))      # below the context and not measured
78        short = make_ctx()
79        short.context_tokens = 32768
80        short.base_args = ["--max-context", "32768"]
81        self.assertTrue(tune_knobs.check_setting({"--kv-resident": 20480}, {}, short))     # -29.5% at 32K
82        self.assertEqual(tune_knobs.check_setting({"--kv-resident": 65536}, {}, make_ctx_small()), [])   # above the context: no streaming at all
83
84    def test_long_context_candidates_exist_and_are_exact(self):
85        ctx = make_ctx()
86        ctx.vram_mib = 32624                            # the R9700: class B
87        ctx.facts = {"workers": 31}
88        arms, _ = tune_knobs.plan_arms(ctx, mode="quick")
89        ids = [p.arm.id for p in arms]
90        self.assertEqual(ids[:2], ["kv_resident_64k", "prefill_32k"])
91        self.assertTrue(all(p.arm.answer == "exact" for p in arms))
92        short = make_ctx()
93        short.vram_mib = 32624
94        short.context_tokens = 32768
95        short.base_args = ["--max-context", "32768"]
96        self.assertNotIn("kv_resident_64k", [p.arm.id for p in tune_knobs.plan_arms(short, mode="quick")[0]])
97
98    def test_the_larger_chunk_is_not_tried_on_an_apu(self):
99        # round0212: on a Strix Halo the prompt buffers share the pool with the expert cache; a 32768 chunk on UD-Q4_K_XL ends the engine at the start
100        ctx = make_ctx()
101        ctx.vram_mib = 90000                            # an APU's pool reads large
102        ctx.facts = {"workers": 31}
103        ctx.arch = "gfx1151"
104        self.assertNotIn("prefill_32k", [p.arm.id for p in tune_knobs.plan_arms(ctx, mode="quick")[0]])
105        ctx.arch = "gfx1201"
106        self.assertIn("prefill_32k", [p.arm.id for p in tune_knobs.plan_arms(ctx, mode="quick")[0]])
107
108    def test_a_prompt_knob_is_judged_on_prompt_speed_and_may_not_cost_decode(self):
109        ctx = make_ctx()
110        ctx.vram_mib = 32624
111        def pp(args, env):
112            return 1500.0 * (1.06 if flag(args, "--prefill") == "auto:32768" else 1.0)
113        # decode unchanged, long prompt +6%: wins on the prompt metric
114        clock = FakeClock()
115        sess = StubSession(model=lambda a, e, tune=None: 60.0, pp=pp, clock=clock, noise=0.001)
116        t = autotune.Tuner(sess, BASE, {}, ctx, autotune.Options(budget_s=3600), clock=clock, sleep=clock.sleep, system=sess.system,
117                           total_ram_mib=64000, total_vram_mib=32000, quiet=lambda: None)
118        r = t.run()
119        self.assertEqual(r.settings["args"], {"--prefill": "auto:32768"}, r.notes)
120        # the same prompt gain with a 6% decode loss does not
121        sess2 = StubSession(model=lambda a, e, tune=None: 60.0 * (0.94 if flag(a, "--prefill") == "auto:32768" else 1.0), pp=pp, clock=FakeClock(), noise=0.001)
122        c2 = sess2.clock
123        t2 = autotune.Tuner(sess2, BASE, {}, ctx, autotune.Options(budget_s=3600), clock=c2, sleep=c2.sleep, system=sess2.system,
124                            total_ram_mib=64000, total_vram_mib=32000, quiet=lambda: None)
125        self.assertEqual(t2.run().settings["args"], {})
126
127    def test_only_the_best_single_knob_is_kept(self):
128        ctx = make_ctx()
129        ctx.vram_mib = 32624
130        model = speed_with({("--kv-resident", "65536"): 1.06})
131        pp = lambda a, e: 1500.0 * (1.07 if flag(a, "--prefill") == "auto:32768" else 1.0)
132        clock = FakeClock()
133        sess = StubSession(model=model, pp=pp, clock=clock, noise=0.001)
134        t = autotune.Tuner(sess, BASE, {}, ctx, autotune.Options(budget_s=3600), clock=clock, sleep=clock.sleep, system=sess.system,
135                           total_ram_mib=64000, total_vram_mib=32000, quiet=lambda: None)
136        r = t.run()
137        self.assertEqual(len(r.settings["args"]), 1)
138        self.assertTrue(any("only the best one" in n for n in r.notes))
139
140    def test_a_box_whose_default_is_not_repeatable_says_so(self):
141        ctx = make_ctx()
142        self.assertFalse(tune_knobs.default_unsteady(ctx))
143        ctx.facts = {"workers": 6, "resident_ram": True}            # the RTX 3060 in resident-RAM mode
144        self.assertTrue(tune_knobs.default_unsteady(ctx))
145        sy = make_ctx()
146        sy.backend = "sycl"
147        self.assertTrue(tune_knobs.default_unsteady(sy))
148        from strata_control import presets
149        steady = {"answers": {"class": "exact", "default_repeatable": True}}
150        unsteady = {"answers": {"class": "exact", "default_repeatable": False}}
151        self.assertIn("identical", presets.notice(steady))
152        self.assertIn("even with the standard setup", presets.notice(unsteady))
153        # the class of the knob does not change: exact knobs are still auto-picked there, nonrepeatable ones stay behind their switch
154        ids = [p.arm.id for p in tune_knobs.plan_arms(ctx, mode="quick")[0]]
155        self.assertNotIn("adapt_async", ids)
156
157    def test_hybrid_cpu_affinity_never(self):
158        ctx = make_ctx()
159        ctx.hybrid_cpu = True
160        self.assertTrue(tune_knobs.check_setting({"--pool-affinity": "auto"}, {}, ctx))
161        ctx.hybrid_cpu = False
162        self.assertEqual(tune_knobs.check_setting({"--pool-affinity": "auto"}, {}, ctx), [])
163
164    def test_boolean_flags_are_present_or_absent(self):
165        self.assertEqual(tune_knobs.apply_to_argv(["--a", "1"], {"--kv-grow": True}), ["--a", "1", "--kv-grow"])
166        self.assertEqual(tune_knobs.apply_to_argv(["--kv-grow", "--a", "1"], {"--kv-grow": None}), ["--a", "1"])
167        self.assertNotIn("0", tune_knobs.apply_to_argv(["--kv-grow"], {"--kv-grow": False}))
168
169    def test_candidates_are_single_knob_changes_of_the_users_config(self):
170        ctx = make_ctx(allow_placement=True)
171        arms, skipped = tune_knobs.plan_arms(ctx, mode="thorough")
172        self.assertTrue(arms)
173        for p in arms:
174            argv = tune_knobs.apply_to_argv(BASE, p.args)
175            # everything the user had that the arm does not name is untouched (Rule 1)
176            for f in ("--expert-cache", "--kv", "--spec-min-p", "--vram-reserve-mib", "--max-context"):
177                if f not in p.args:
178                    self.assertEqual(flag(argv, f), flag(BASE, f), (p.arm.id, f))
179            self.assertEqual(tune_knobs.check_setting(p.args, p.env, ctx), [])
180
181    def test_answer_changing_arms_need_the_users_tick(self):
182        ctx = make_ctx()
183        ids = {p.arm.id for p in tune_knobs.plan_arms(ctx, mode="thorough")[0]}
184        self.assertNotIn("spec3", ids)
185        self.assertNotIn("adapt_async", ids)
186        ctx2 = make_ctx(allow_placement=True)
187        self.assertIn("spec3", {p.arm.id for p in tune_knobs.plan_arms(ctx2, mode="thorough")[0]})
188        ctx3 = make_ctx(allow_nonrepeatable=True)
189        ctx3.facts = {"workers": 6, "resident_ram": True}
190        self.assertIn("adapt_async", {p.arm.id for p in tune_knobs.plan_arms(ctx3, mode="thorough")[0]})
191
192    def test_engine_without_a_flag_drops_the_arm_with_a_reason(self):
193        ctx = make_ctx()
194        ctx.engine_flags = ["--spec"]
195        arms, skipped = tune_knobs.plan_arms(ctx, mode="thorough")
196        self.assertFalse(any(p.arm.id == "kv_resident_64k" for p in arms))
197        self.assertTrue(any("does not accept" in s["reason"] for s in skipped))
198
199    def test_qwen36_and_sycl_lists(self):
200        q = make_ctx()
201        q.family = "qwen36"
202        q.facts = {"workers": 6, "hybrid_experts": True}
203        ids = [p.arm.id for p in tune_knobs.plan_arms(q, mode="thorough")[0]]
204        self.assertIn("q36_workers_explicit", ids)
205        self.assertNotIn("kv_resident_64k", ids)
206        s = make_ctx(allow_placement=True)
207        s.backend = "sycl"
208        ids = [p.arm.id for p in tune_knobs.plan_arms(s, mode="thorough")[0]]
209        self.assertEqual(set(ids) - {"adapt_decay_09", "pcie_start_02"}, set())
210
211    def test_workers_arm_never_goes_below_a_quarter(self):
212        c = make_ctx()
213        c.facts = {"workers": 4}
214        self.assertEqual(tune_knobs.dynamic_value("workers-1", c), 3)       # one step down at most
215        self.assertIsNone(tune_knobs.dynamic_value("workers-2", c))          # never two below (spec 6.2 C)
216        c.facts = {"workers": 2}
217        self.assertIsNone(tune_knobs.dynamic_value("workers-1", c))
218
219
220class TunerTest(unittest.TestCase):
221    def test_finds_a_real_gain_and_changes_one_knob(self):
222        model = speed_with({("--kv-resident", "65536"): 1.08})
223        t, s, r = run_tuner(model, ctx=make_ctx())
224        self.assertEqual(r.outcome, "improved", r.notes)
225        self.assertEqual(r.settings["args"], {"--kv-resident": 65536})
226        self.assertAlmostEqual(r.gain_pct, 8.0, delta=2.0)
227        self.assertEqual(r.answers["class"], "exact")
228        for args, env in s.runs:                           # every run kept the user's own flags
229            self.assertEqual(flag(args, "--expert-cache"), "auto")
230            self.assertEqual(flag(args, "--kv"), "int8")
231        self.assertLessEqual(r.seconds, 1200 + 90 * 2)
232
233    def test_no_gain_keeps_the_default(self):
234        t, s, r = run_tuner(lambda a, e, tune=None: 60.0, session_kw={"noise": 0.02})
235        self.assertEqual(r.outcome, "default_confirmed")
236        self.assertEqual(r.settings, {"args": {}, "env": {}, "per_request": {}})
237        self.assertIn("already the fastest", r.message)
238
239    def test_a_gain_below_the_margin_is_not_taken(self):
240        model = speed_with({("--kv-resident", "65536"): 1.02})
241        t, s, r = run_tuner(model, session_kw={"noise": 0.001})
242        self.assertEqual(r.settings["args"], {})
243
244    def test_losing_candidates_are_dropped_after_one_loss(self):
245        model = speed_with({("--kv-resident", "65536"): 0.85})
246        t, s, r = run_tuner(model, session_kw={"noise": 0.001})
247        arm = [a for a in r.arms if a["id"] == "kv_resident_64k"][0]
248        self.assertEqual(arm["status"], "dropped")
249        self.assertEqual(sum(1 for args, _ in s.runs if flag(args, "--kv-resident") == "65536"), 1)
250
251    def test_machine_drift_is_not_mistaken_for_a_gain(self):
252        clock = FakeClock()
253        counter = {"n": 0}
254
255        def model(args, env, tune=None):                    # the machine slows 1.2% per engine start
256            return 60.0 * (1.0 - 0.012 * len(session.runs)) * (1.03 if flag(args, "--kv-resident") == "65536" else 1.0)
257        session = StubSession(model=model, clock=clock, noise=0.0005)
258        t = autotune.Tuner(session, BASE, {}, make_ctx(), autotune.Options(), clock=clock, sleep=clock.sleep, system=session.system,
259                           total_ram_mib=64000, quiet=lambda: None)
260        r = t.run()
261        self.assertEqual(r.settings["args"], {}, r.notes)
262
263    def test_candidate_that_does_not_fit_is_never_started(self):
264        model = speed_with({("--kv-resident", "65536"): 1.10})
265        clock = FakeClock()
266        session = StubSession(model=model, clock=clock, avail=9000, rss=lambda a, e: 12000.0)
267        calls = {"n": 0}
268        real = session.system
269
270        def system():
271            out = real()
272            out["memory"]["available_mib"] = 40000 if not session.runs else 9000     # after the base run only 9 GB is free
273            return out
274        t = autotune.Tuner(session, BASE, {}, make_ctx(), autotune.Options(wait_ram_s=30), clock=clock, sleep=clock.sleep,
275                           system=system, total_ram_mib=64000, quiet=lambda: None)
276        r = t.run()
277        self.assertEqual(len(session.runs), 1, "only the base was started")
278        self.assertEqual(r.outcome, "default_confirmed")
279        self.assertTrue(any(a["status"] == "skipped" and "memory" in a["reason"] for a in r.arms))
280
281    def test_memory_wait_gives_up_when_nothing_is_freed(self):
282        # #3490: a loaded model keeps the memory; ten minutes of waiting per candidate made a tuning last for hours
283        model = speed_with({})
284        clock = FakeClock()
285        session = StubSession(model=model, clock=clock)
286
287        def system():
288            out = session.system()
289            out["memory"]["available_mib"] = 40000 if not session.runs else 3000
290            return out
291        t = autotune.Tuner(session, BASE, {}, make_ctx(), autotune.Options(per_request=False), clock=clock,
292                           sleep=clock.sleep, system=system, total_ram_mib=64000, quiet=lambda: None)
293        before = clock()
294        t.run()
295        self.assertLess(clock() - before, 600.0, "waited for the whole ten minutes per candidate")
296
297    def test_a_wait_that_found_nothing_freed_is_not_repeated_for_a_candidate_that_needs_less(self):
298        # #4895: "Waiting for memory to be freed ..." came up again and again: each later candidate waited its own minute, although the minute before had shown
299        # that nothing is freed (29.0 GiB free, 30.0 needed; the next candidate needed 29.5)
300        model = speed_with({})
301        clock = FakeClock()
302        session = StubSession(model=model, clock=clock)
303
304        def system():
305            out = session.system()
306            out["memory"]["available_mib"] = 3000
307            return out
308        t = autotune.Tuner(session, BASE, {}, make_ctx(), autotune.Options(min_free_ram_mib=1000, wait_ram_s=300), clock=clock,
309                           sleep=clock.sleep, system=system, total_ram_mib=64000, quiet=lambda: None)
310        first_started = clock()
311        self.assertIn("not enough free memory", t._ram_guard(5000, "a big one"))
312        waited = clock() - first_started
313        self.assertGreaterEqual(waited, autotune.STAGNANT_WAIT_S)
314        second_started = clock()
315        self.assertIn("not enough free memory", t._ram_guard(3000, "a smaller one"))          # needs 4000: still more than the 3000 that is free
316        self.assertEqual(clock() - second_started, 0, "waited a second time for memory that was not being freed")
317
318        def grown():
319            out = session.system()
320            out["memory"]["available_mib"] = 9000
321            return out
322        t.system = grown
323        self.assertIsNone(t._ram_guard(3000, "now it fits"))
324
325    def test_nothing_compared_is_inconclusive_not_default_confirmed(self):
326        model = speed_with({})
327        clock = FakeClock()
328        session = StubSession(model=model, clock=clock)
329
330        def system():
331            out = session.system()
332            out["memory"]["available_mib"] = 40000 if not session.runs else 3000
333            return out
334        t = autotune.Tuner(session, BASE, {}, make_ctx(), autotune.Options(wait_ram_s=30, per_request=False), clock=clock,
335                           sleep=clock.sleep, system=system, total_ram_mib=64000, quiet=lambda: None)
336        r = t.run()
337        self.assertEqual(r.outcome, "inconclusive")
338        self.assertIn("could not be tried", r.message)
339
340    def test_first_oom_stops_the_search(self):
341        def fail(args, env):
342            return StartFailed("OOM", "out of memory") if flag(args, "--kv-resident") == "65536" else None
343        t, s, r = run_tuner(speed_with({}), session_kw={"fail": fail})
344        self.assertTrue(any("ran out of memory" in n for n in r.notes))
345        self.assertEqual(sum(1 for a, _ in s.runs if flag(a, "--kv-resident") == "65536"), 1)
346        self.assertEqual(r.settings["args"], {})
347
348    def test_unsupported_candidate_fails_alone(self):
349        def fail(args, env):
350            return StartFailed("UNSUPPORTED", "unknown argument: --kv-resident") if flag(args, "--kv-resident") == "65536" else None
351        ctx = make_ctx()
352        ctx.facts = {"workers": 6}
353        t, s, r = run_tuner(speed_with({}), ctx=ctx, session_kw={"fail": fail})
354        failed = [a for a in r.arms if a["status"] == "failed"]
355        self.assertTrue(failed and "UNSUPPORTED" in failed[0]["reason"])
356        self.assertEqual(r.settings["args"], {})
357
358    def test_room_goal_refuses_a_faster_candidate_that_takes_more_memory(self):
359        model = speed_with({("--kv-resident", "65536"): 1.1})
360        rss = lambda a, e: 20000.0 if flag(a, "--kv-resident") == "65536" else 12000.0
361        t, s, r = run_tuner(model, opts=autotune.Options(goal="room", ram_wish_pct=20, reserve_mib=1536), session_kw={"rss": rss})
362        self.assertEqual(r.settings["args"], {})
363        self.assertTrue(any("more memory" in a["reason"] for a in r.arms))
364        t, s, r = run_tuner(model, opts=autotune.Options(goal="speed"), session_kw={"rss": rss})
365        self.assertEqual(r.settings["args"], {"--kv-resident": 65536})
366
367    def test_cancel_changes_nothing(self):
368        cancel = threading.Event()
369        model = speed_with({("--kv-resident", "65536"): 1.1})
370        n = {"i": 0}
371
372        def progress(p):
373            if p["stage"] == "rounds":
374                cancel.set()
375        t, s, r = run_tuner(model, cancel=cancel, progress=progress)
376        self.assertEqual(r.outcome, "cancelled")
377        self.assertEqual(r.settings["args"], {})
378
379    def test_the_time_chosen_bounds_the_number_of_restarts(self):
380        model = speed_with({})
381        t, s, r = run_tuner(model, session_kw={"run_s": 300.0}, opts=autotune.Options(budget_s=1200))
382        self.assertLessEqual(len(s.runs), 1200 / 300 + 1)
383        t, s, r = run_tuner(model, session_kw={"run_s": 60.0}, opts=autotune.Options(budget_s=1200))
384        self.assertGreater(len(s.runs), 4)
385
386    def test_progress_reports_stage_and_time_left(self):
387        seen = []
388        t, s, r = run_tuner(speed_with({}), progress=seen.append)
389        self.assertTrue(any(p["stage"] == "base" for p in seen))
390        etas = [p["eta_s"] for p in seen if p.get("eta_s") is not None]
391        self.assertTrue(etas)
392        self.assertLessEqual(etas[-1], etas[0])
393        self.assertEqual(seen[-1]["stage"], "done")
394
395    def test_progress_carries_the_speed_of_every_measurement_so_far(self):
396        seen = []
397        t, s, r = run_tuner(speed_with({("--spec", "6"): 1.2}), progress=seen.append)
398        last = [p for p in seen if p.get("speeds")][-1]["speeds"]
399        self.assertEqual(last[0]["label"], "base")
400        self.assertAlmostEqual(last[0]["tok_s"], 60.0, places=1)
401        self.assertTrue(all(isinstance(x["tok_s"], float) and x["tok_s"] > 0 for x in last))
402        self.assertGreater(len(last), 1, "the candidates' speeds follow the base")
403
404    def test_per_request_value_needs_every_round(self):
405        wins = {"n": 0}
406
407        def model(args, env, tune=None):
408            if tune and tune.get("spec_min_p") == 0.7:
409                return 60.0 * 1.06
410            return 60.0
411        t, s, r = run_tuner(model, session_kw={"noise": 0.002})
412        self.assertEqual(r.settings["per_request"].get("spec_min_p"), 0.7)
413        self.assertEqual(r.outcome, "improved")
414
415        calls = {"n": 0}
416
417        def noisy(args, env, tune=None):
418            if tune and tune.get("spec_min_p") == 0.7:
419                calls["n"] += 1
420                return 60.0 * (1.06 if calls["n"] % 3 else 0.99)      # one round in three it does not win
421            return 60.0
422        t, s2, r = run_tuner(noisy, session_kw={"noise": 0.0})
423        self.assertNotIn("spec_min_p", r.settings["per_request"])
424
425    def test_sending_any_setting_is_not_a_gain(self):
426        # the p620 artifact: every request that carried a setting read ~10% faster than the plain default, even a setting equal
427        # to what the engine already uses. The control point catches it.
428        def model(args, env, tune=None):
429            return 60.0 * (1.10 if tune else 1.0)
430        t, s, r = run_tuner(model, session_kw={"noise": 0.002})
431        self.assertEqual(r.settings["per_request"], {})
432        self.assertNotEqual(r.outcome, "improved")
433
434    def test_a_real_per_request_gain_is_confirmed_in_a_fresh_engine(self):
435        def model(args, env, tune=None):
436            return 60.0 * (1.06 if tune and tune.get("spec_min_p") == 0.7 else 1.0)
437        t, s, r = run_tuner(model, session_kw={"noise": 0.002})
438        self.assertEqual(r.settings["per_request"], {"spec_min_p": 0.7})
439        self.assertEqual(r.per_request_confirm["status"], "PASS")
440        self.assertGreaterEqual(sum(1 for x in r.per_request_confirm["ratios"] if x > 1.0), 4)
441        self.assertAlmostEqual(r.gain_pct, 6.0, delta=1.5)
442
443    def test_thorough_confirms_with_five_pairs(self):
444        model = speed_with({("--kv-resident", "65536"): 1.06})
445        t, s, r = run_tuner(model, opts=autotune.Options(mode="thorough", budget_s=7200), session_kw={"noise": 0.003})
446        self.assertEqual(r.outcome, "improved")
447        self.assertEqual(r.pairs, 5)
448        self.assertGreaterEqual(r.faster_pairs, 4)
449
450    def test_prompt_regression_blocks_a_decode_win(self):
451        model = speed_with({("--kv-resident", "65536"): 1.08})
452        pp = lambda a, e: 1500.0 * (0.8 if flag(a, "--kv-resident") == "65536" else 1.0)
453        t, s, r = run_tuner(model, session_kw={"pp": pp, "noise": 0.001})
454        self.assertEqual(r.settings["args"], {})
455
456    def test_base_that_cannot_start_is_reported(self):
457        t, s, r = run_tuner(speed_with({}), session_kw={"fail": lambda a, e: StartFailed("FAIL_BOOT", "x")})
458        self.assertEqual(r.outcome, "base_failed")
459        self.assertEqual(len(s.runs), 1)
460
461    def test_coding_metric_uses_prompt_speed(self):
462        m = autotune.metric({"decode_tok_s": 100.0, "pp_tok_s": 400.0}, "coding")
463        self.assertAlmostEqual(m, 200.0)
464        self.assertEqual(autotune.metric({"decode_tok_s": 100.0, "pp_tok_s": 400.0}, "chat"), 100.0)
465
466
467class DecisionRulesTest(unittest.TestCase):
468    def test_threshold_follows_the_noise(self):
469        self.assertAlmostEqual(autotune.accept_threshold(0.03, 0.0, 0.0), 1.03)
470        self.assertAlmostEqual(autotune.accept_threshold(0.03, 0.025, 0.0), 1.05)
471        self.assertAlmostEqual(autotune.accept_threshold(0.03, 0.0, 0.04), 1.08)
472
473    def test_is_win(self):
474        self.assertTrue(autotune.is_win([1.05, 1.06], [1.0], threshold=1.03))
475        self.assertFalse(autotune.is_win([1.05, 0.99], [1.0], threshold=1.03))
476        self.assertFalse(autotune.is_win([1.04, 1.04], [0.9], threshold=1.03))
477        self.assertTrue(autotune.is_win([1.05, 1.06, 1.04, 1.05, 0.99], [1.0], threshold=1.03, need=4))
478
479
480class RecheckTest(unittest.TestCase):
481    def _preset(self):
482        return {"settings": {"args": {"--host-core": "last"}, "env": {}, "per_request": {}},
483                "measured": {"decode_tok_s": 60.0, "pp4k_tok_s": 1500.0, "rss_peak_mib": 12000.0, "vram_peak_mib": 10000.0}}
484
485    def test_keep_when_as_fast(self):
486        s = StubSession(model=lambda a, e, tune=None: 59.0, noise=0.0)
487        out = autotune.recheck(s, BASE, self._preset(), ctx=make_ctx())
488        self.assertEqual(out["verdict"], "keep")
489        self.assertEqual(len(s.runs), 1)
490        self.assertEqual(flag(s.runs[0][0], "--host-core"), "last")
491
492    def test_retune_suggested_when_slower(self):
493        s = StubSession(model=lambda a, e, tune=None: 50.0, noise=0.0)
494        out = autotune.recheck(s, BASE, self._preset(), ctx=make_ctx())
495        self.assertEqual(out["verdict"], "retune")
496        self.assertIn("slower", out["reason"])
497
498    def test_engine_update_adds_a_baseline_start(self):
499        s = StubSession(model=lambda a, e, tune=None: 60.0 if flag(a, "--host-core") else 62.0, noise=0.0)
500        out = autotune.recheck(s, BASE, self._preset(), ctx=make_ctx(), engine_changed=True)
501        self.assertEqual(len(s.runs), 2)
502        self.assertEqual(out["verdict"], "retune")
503
504    def test_a_start_that_fails_suggests_retune(self):
505        s = StubSession(model=lambda a, e, tune=None: 60.0, fail=lambda a, e: StartFailed("UNSUPPORTED", "unknown argument"))
506        out = autotune.recheck(s, BASE, self._preset(), ctx=make_ctx())
507        self.assertEqual(out["verdict"], "retune")
508
509
510if __name__ == "__main__":
511    unittest.main()