okami.mom/strata

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

Niko1221tuning tests: a Python stub engine (READY/PP/T/DONE) started as [sys.executable, stub.py] replaces the .sh stubs on every OSf7e12d23c

main
21.8 KiB463 linesraw
1"""Tuning job contract tests.
2
3The measurements are injected, which is the point: these tests are about the *contract* — which
4dimensions a backend may search, what happens to a candidate that fails, how a winner is chosen,
5and what the job refuses to do. A GPU is not needed and, more importantly, a hardcoded benchmark
6number can never leak into the module under test.
7
8The negative cases carry the weight: a sweep must never promote a candidate the engine could not
9run, never pick a winner from a machine that drifted, and never recommend a change on evidence it
10does not have.
11"""
12
13from __future__ import annotations
14
15import json
16import shutil
17import sys
18import tempfile
19import unittest
20from pathlib import Path
21
22sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
23
24from strata_control import tuning  # noqa: E402
25
26
27class TuningCase(unittest.TestCase):
28    def setUp(self):
29        self.tmp = Path(tempfile.mkdtemp(prefix="strata-tune-"))
30
31    def tearDown(self):
32        shutil.rmtree(self.tmp, ignore_errors=True)
33
34    def plan(self, backend="cuda", objective="generation", hold=(), max_trials=16, repeats=3,
35             flags=None, dimensions=()):
36        return tuning.TuningPlan(
37            id="job1", backend=backend, engine="/nonexistent/strata",
38            engine_flags_known=flags is not None, model="qwen3.8-flash-next",
39            profile_revision="abc123", objective=objective,
40            workload={"prompt_tokens": 512, "max_new": 200, "seed": 1},
41            dimensions=[{"id": d} for d in dimensions], excluded=[], fixed={},
42            max_trials=max_trials, total_time_s=60.0,
43            repeats=repeats, devices=["0"],
44        )
45
46    def run_job(self, plan, measure):
47        tuner = tuning.Tuner(self.tmp / "runs", plan, measure)
48        return tuner, tuner.run()
49
50
51class TestDimensionValidation(TuningCase):
52    """A backend is offered only the levers its engine can actually accept."""
53
54    def test_metal_is_not_offered_nvidia_only_dimensions(self):
55        offered, excluded = tuning.validate_dimensions("metal")
56        ids = {d.id for d in offered}
57        self.assertNotIn("vram_reserve", ids)
58        self.assertNotIn("pcie_frac", ids)
59        reasons = {e["id"]: e["reason"] for e in excluded}
60        self.assertIn("vram_reserve", reasons)
61        self.assertIn("NVIDIA/AMD", reasons["vram_reserve"])
62
63    def test_cuda_is_offered_the_nvidia_dimensions(self):
64        offered, _ = tuning.validate_dimensions("cuda")
65        ids = {d.id for d in offered}
66        self.assertTrue({"vram_reserve", "pcie_frac", "expert_cache"} <= ids)
67
68    def test_a_flag_the_binary_does_not_accept_excludes_the_dimension(self):
69        """The static table is not trusted: the actual binary's flag list decides."""
70        offered, excluded = tuning.validate_dimensions("cuda", engine_flags=["--kv", "--ple-io"])
71        ids = {d.id for d in offered}
72        self.assertNotIn("vram_reserve", ids, "a dimension whose flag the binary lacks must be excluded")
73        reasons = {e["id"]: e["reason"] for e in excluded}
74        self.assertIn("does not accept --vram-reserve-mib", reasons["vram_reserve"])
75
76    def test_a_flag_the_binary_does_accept_keeps_the_dimension(self):
77        offered, _ = tuning.validate_dimensions("cuda", engine_flags=["--kv", "--vram-reserve-mib"])
78        self.assertIn("vram_reserve", {d.id for d in offered})
79
80    def test_benchmark_only_dimension_is_never_exported(self):
81        tuner = tuning.Tuner(self.tmp / "runs", self.plan(), lambda c: {"tokens_per_s": 1.0})
82        args = tuner._args_for({"prompt_cache_tail": True, "kv": "int8"})
83        self.assertNotIn("--prompt-cache-tail", args,
84                         "a flag the production interface does not accept must not be exported")
85        self.assertEqual(args["--kv"], "int8")
86
87    def test_flag_inventory_returns_none_for_a_missing_engine(self):
88        self.assertIsNone(tuning.engine_flag_inventory(Path("/nonexistent/strata")))
89
90    def test_flag_inventory_reads_stderr_as_well_as_stdout(self):
91        """The Strata engine writes its usage to stderr.
92
93        A stdout-only read reports "no flags" for a working engine, and because every dimension is
94        then excluded the sweep silently searches nothing — safe, but useless and very hard to
95        notice. This test uses a stand-in that prints usage to stderr only.
96        """
97        fake = self.tmp / "fake-engine.py"      # run as [sys.executable, fake]: works on every OS
98        fake.write_text("import sys\nfor line in ('usage:', '  --kv KV', '  --ple-io MODE'):\n    print(line, file=sys.stderr)\n")
99        flags = tuning.engine_flag_inventory(fake)
100        self.assertIsNotNone(flags, "usage on stderr must still be read")
101        self.assertIn("--kv", flags)
102        self.assertIn("--ple-io", flags)
103
104    def test_flag_inventory_reads_stdout_too(self):
105        fake = self.tmp / "fake-engine-stdout.py"
106        fake.write_text("print('  --vram-reserve-mib MIB')\n")
107        self.assertIn("--vram-reserve-mib", tuning.engine_flag_inventory(fake))
108
109    def test_a_backend_with_dimensions_that_all_need_missing_flags_searches_nothing(self):
110        """The safe outcome, asserted so it cannot silently become an unsafe one.
111
112        Every dimension has *some* reason: either its flags are not this backend's concept, or the
113        binary does not accept them. What must never happen is a dimension with no reason being
114        dropped silently.
115        """
116        offered, excluded = tuning.validate_dimensions("metal", engine_flags=["--unrelated"])
117        self.assertEqual(offered, [])
118        self.assertEqual(len(excluded), len(tuning.DIMENSIONS))
119        for e in excluded:
120            self.assertTrue(e["reason"].strip(), f"{e['id']} was excluded with no reason given")
121        # The dimensions that ARE Metal concepts are excluded specifically because the binary lacks
122        # their flags, which is the check that matters.
123        by_id = {e["id"]: e["reason"] for e in excluded}
124        for dim_id in ("kv", "ple_io", "kv_grow", "spec_min_p"):
125            self.assertIn("does not accept", by_id[dim_id])
126
127
128class TestBaselineAndSelection(TuningCase):
129    def test_a_clear_winner_is_recommended(self):
130        calls = {"n": 0}
131
132        def measure(candidate):
133            calls["n"] += 1
134            # The baseline (no settings) is slow; any candidate is faster.
135            return {"tokens_per_s": 50.0 if not candidate.settings else 80.0, "correct": True}
136
137        plan = self.plan(max_trials=2, dimensions=("kv",))
138        tuner, result = self.run_job(plan, measure)
139        rep = result["report"]
140        self.assertTrue(rep["recommendation_available"], rep)
141        self.assertEqual(rep["baseline"]["median"], 50.0)
142        self.assertEqual(rep["recommendation"]["median"], 80.0)
143
144    def test_a_faster_candidate_inside_the_baseline_spread_is_not_recommended(self):
145        """Promoting noise is the classic tuning failure, so the gate compares worst-against-worst."""
146        state = {"phase": 0}
147
148        def measure(candidate):
149            if candidate.is_baseline:
150                # A wide baseline spread: worst 40, best 90.
151                state["phase"] += 1
152                return {"tokens_per_s": [40.0, 90.0, 65.0][state["phase"] % 3]}
153            # The candidate's median is higher but its worst run is below the baseline's worst.
154            return {"tokens_per_s": [45.0, 60.0, 60.0][state["phase"] % 3]}
155
156        plan = self.plan(max_trials=1, repeats=3, dimensions=("kv",))
157        _, result = self.run_job(plan, measure)
158        rep = result["report"]
159        self.assertFalse(rep["recommendation_available"],
160                         "a candidate whose worst run is below the baseline's worst must not win")
161        self.assertIn("spread", rep["reason"])
162
163    def test_no_candidate_better_means_recommend_no_change(self):
164        def measure(candidate):
165            return {"tokens_per_s": 60.0 if not candidate.settings else 55.0}
166
167        _, result = self.run_job(self.plan(max_trials=2, dimensions=("kv",)), measure)
168        rep = result["report"]
169        self.assertFalse(rep["recommendation_available"])
170        self.assertIn("keeping the current configuration", rep["reason"])
171
172    def test_drift_is_reported(self):
173        """The baseline is re-measured last, so a drifting machine is visible instead of silent.
174
175        The baseline is measured once as a warmup plus `repeats` times, and then again after the
176        sweep. This case makes the measured value a function of *which* baseline measurement it is,
177        rather than of the call count, so the expectation does not depend on how repeats are
178        scheduled.
179        """
180        state = {"baseline_measurements": 0}
181
182        def measure(candidate):
183            if candidate.kind == "baseline":
184                state["baseline_measurements"] += 1
185                # The first measurement is the warmup; the three counted repeats are 50, and the
186                # recheck afterwards is 40 (below), simulating a machine that got slower.
187                return {"tokens_per_s": 50.0}
188            if candidate.kind == "recheck":
189                return {"tokens_per_s": 40.0}
190            return {"tokens_per_s": 45.0}
191
192        _, result = self.run_job(self.plan(max_trials=1, dimensions=("kv",)), measure)
193        rep = result["report"]
194        self.assertEqual(rep["baseline"]["median"], 50.0)
195        self.assertIsNotNone(rep["recheck"], "the baseline must be re-measured after the sweep")
196        self.assertEqual(rep["recheck"]["median"], 40.0)
197        self.assertIsNotNone(rep["drift"], "the drift between the two baseline measurements is reported")
198        self.assertLess(rep["drift"]["relative"], 0,
199                        "the report must show that the machine slowed, not hide it")
200
201    def test_fewer_repeats_than_required_disqualifies_a_candidate(self):
202        def measure(candidate):
203            return {"tokens_per_s": 90.0 if candidate.settings else 50.0}
204
205        plan = self.plan(max_trials=1, repeats=5, dimensions=("kv",))
206        _, result = self.run_job(plan, measure)
207        best = [c for c in result["report"]["candidates"] if c["kind"] == "trial"][0]
208        self.assertGreaterEqual(len(best["metrics"]), 5)
209
210
211class TestFailuresAreRecorded(TuningCase):
212    """A candidate that could not run is evidence about the configuration, never a slow winner."""
213
214    def test_a_boot_failure_is_recorded_and_excluded(self):
215        def measure(candidate):
216            if candidate.settings:
217                raise RuntimeError("the engine failed to boot with these flags")
218            return {"tokens_per_s": 50.0}
219
220        _, result = self.run_job(self.plan(max_trials=2, dimensions=("kv",)), measure)
221        rep = result["report"]
222        self.assertEqual(rep["recommendation_available"], False)
223        self.assertTrue(rep["failures"])
224        self.assertEqual(rep["failures"][0]["status"], "FAIL_BOOT")
225        self.assertIn("failed to boot", rep["failures"][0]["reason"])
226
227    def test_a_timeout_is_recorded_as_a_timeout(self):
228        def measure(candidate):
229            if candidate.settings:
230                raise RuntimeError("the measurement timed out after 120s")
231            return {"tokens_per_s": 50.0}
232
233        _, result = self.run_job(self.plan(max_trials=1, dimensions=("kv",)), measure)
234        self.assertEqual(result["report"]["failures"][0]["status"], "TIMEOUT")
235
236    def test_no_tokens_is_not_a_slow_configuration(self):
237        def measure(candidate):
238            return {"tokens_per_s": 0.0}
239
240        _, result = self.run_job(self.plan(max_trials=1, dimensions=("kv",)), measure)
241        rep = result["report"]
242        self.assertFalse(rep["recommendation_available"])
243        statuses = [c["status"] for c in rep["candidates"]]
244        self.assertIn("NO_TOKENS", statuses)
245
246    def test_a_correctness_failure_disqualifies_a_fast_candidate(self):
247        """tokens/s alone is not acceptance."""
248        def measure(candidate):
249            if candidate.settings:
250                return {"tokens_per_s": 500.0, "correct": False}
251            return {"tokens_per_s": 50.0, "correct": True}
252
253        _, result = self.run_job(self.plan(max_trials=1, dimensions=("kv",)), measure)
254        rep = result["report"]
255        self.assertFalse(rep["recommendation_available"],
256                         "a fast but incorrect configuration must never be recommended")
257        self.assertTrue(any(f["status"] == "INVALID" for f in rep["failures"]), rep["failures"])
258
259    def test_a_baseline_that_cannot_be_measured_stops_the_sweep(self):
260        def measure(candidate):
261            raise RuntimeError("no engine here")
262
263        _, result = self.run_job(self.plan(max_trials=5, dimensions=("kv",)), measure)
264        rep = result["report"]
265        self.assertFalse(rep["recommendation_available"])
266        self.assertIsNone(rep["baseline"])
267        self.assertIn("could not be measured", rep["reason"])
268
269
270class TestBounds(TuningCase):
271    def test_the_trial_limit_is_respected(self):
272        # Count *trials*, not measurement calls: each candidate is measured once as a warmup plus
273        # `repeats` times, so counting calls would measure the wrong thing entirely.
274        plan = self.plan(max_trials=3, dimensions=("ple_io", "kv"))
275        _, result = self.run_job(plan, lambda c: {"tokens_per_s": 60.0})
276        self.assertEqual(result["report"]["trials_run"], 3)
277        self.assertEqual(len([c for c in result["report"]["candidates"]
278                              if c["kind"] == "trial"]), 3)
279        self.assertLessEqual(result["report"]["baseline"] is not None, True)
280
281    def test_the_time_bound_stops_new_trials(self):
282        clock = {"t": 0.0}
283
284        def measure(candidate):
285            clock["t"] += 30.0
286            return {"tokens_per_s": 60.0}
287
288        plan = self.plan(max_trials=100, dimensions=("kv",))
289        plan.total_time_s = 45.0
290        tuner = tuning.Tuner(self.tmp / "runs", plan, measure, clock=lambda: clock["t"])
291        result = tuner.run()
292        self.assertTrue(any(e["state"] == "time_limit" for e in result["events"]),
293                        "the displayed time bound must actually stop the sweep")
294
295    def test_cancellation_keeps_evidence_and_recommends_nothing(self):
296        def measure(candidate):
297            if candidate.settings:
298                tuner.request_cancel()
299            return {"tokens_per_s": 90.0 if candidate.settings else 50.0}
300
301        plan = self.plan(max_trials=10, dimensions=("kv",))
302        tuner = tuning.Tuner(self.tmp / "runs", plan, measure)
303        result = tuner.run()
304        self.assertEqual(result["state"], "cancelled")
305        self.assertFalse(result["report"]["recommendation_available"],
306                         "a cancelled sweep must not produce a winner")
307        self.assertTrue(result["report"]["candidates"], "evidence collected before the cancel is kept")
308
309
310class TestSearchSpaceIsDisclosed(TuningCase):
311    """A bounded sweep must not look like a complete one.
312
313    This is the honesty property that decides whether "no candidate beat the baseline" can be read
314    as a conclusion. With four trials out of ninety-six combinations, it cannot — and the report has
315    to say so, or a reader will take a partial search for a full one.
316    """
317
318    def test_a_bounded_sweep_reports_the_size_of_the_space_it_sampled(self):
319        plan = self.plan(max_trials=2, dimensions=("kv",))
320        _, result = self.run_job(plan, lambda c: {"tokens_per_s": 60.0})
321        rep = result["report"]
322        self.assertEqual(rep["trials_run"], 2)
323        # `kv` has four values, so the space is four and two trials is a prefix of it.
324        self.assertEqual(rep["combinations_total"], 4)
325        self.assertTrue(rep["trials_are_a_prefix"])
326
327    def test_a_complete_sweep_is_not_labelled_a_prefix(self):
328        plan = self.plan(max_trials=10, dimensions=("kv",))
329        _, result = self.run_job(plan, lambda c: {"tokens_per_s": 60.0})
330        rep = result["report"]
331        self.assertEqual(rep["combinations_total"], 4)
332        self.assertEqual(rep["trials_run"], 4, "the whole four-value space is enumerated")
333        self.assertFalse(rep["trials_are_a_prefix"])
334
335    def test_the_space_size_accounts_for_every_offered_dimension(self):
336        plan = self.plan(max_trials=1, dimensions=("kv", "kv_grow"))
337        _, result = self.run_job(plan, lambda c: {"tokens_per_s": 60.0})
338        # kv has 4 values, kv_grow has 2 -> 8 combinations.
339        self.assertEqual(result["report"]["combinations_total"], 8)
340
341    def test_a_plan_with_no_dimensions_reports_no_space(self):
342        _, result = self.run_job(self.plan(max_trials=1), lambda c: {"tokens_per_s": 60.0})
343        self.assertEqual(result["report"]["combinations_total"], 0)
344
345
346class TestDriftIsGraded(TuningCase):
347    """A drift note is only warranted when the drift is material.
348
349    Printing "the comparison is weaker than the repeat count suggests" at +0.0% trains the reader to
350    ignore the warning, which is worse than not printing it.
351    """
352
353    def test_negligible_drift_is_not_flagged_as_material(self):
354        def measure(candidate):
355            return {"tokens_per_s": 50.0}
356
357        _, result = self.run_job(self.plan(max_trials=1, dimensions=("kv",)), measure)
358        rep = result["report"]
359        self.assertIsNotNone(rep["drift"])
360        self.assertAlmostEqual(rep["drift"]["relative"], 0.0)
361        self.assertFalse(rep["drift_material"])
362
363    def test_material_drift_is_flagged(self):
364        def measure(candidate):
365            return {"tokens_per_s": 40.0 if candidate.kind == "recheck" else 50.0}
366
367        _, result = self.run_job(self.plan(max_trials=1, dimensions=("kv",)), measure)
368        rep = result["report"]
369        self.assertAlmostEqual(rep["drift"]["relative"], -0.2)
370        self.assertTrue(rep["drift_material"])
371
372
373class TestExclusiveLease(TuningCase):
374    """Tuning must own its devices: a second job, or a serving load, must not share them."""
375
376    def test_a_second_job_is_refused_while_the_lease_is_held(self):
377        first = tuning.Tuner(self.tmp / "runs", self.plan(), lambda c: {"tokens_per_s": 50.0})
378        first._acquire_lease()
379        try:
380            second = tuning.Tuner(self.tmp / "runs", self.plan(), lambda c: {"tokens_per_s": 50.0})
381            with self.assertRaises(RuntimeError) as ctx:
382                second._acquire_lease()
383            self.assertIn("exclusive device lease", str(ctx.exception))
384        finally:
385            first._release_lease()
386
387    def test_the_lease_is_released_even_when_the_job_fails(self):
388        plan = self.plan()
389        tuner = tuning.Tuner(self.tmp / "runs", plan, lambda c: (_ for _ in ()).throw(RuntimeError("boom")))
390        tuner.run()
391        self.assertFalse((tuner.root / "tuning.lease").exists(),
392                         "a failed job must not leave the devices leased")
393
394    def test_a_stale_lease_is_reported_rather_than_ignored(self):
395        stale = self.tmp / "runs" / "job1"
396        stale.mkdir(parents=True)
397        (stale / "tuning.lease").write_text(json.dumps({"id": "dead", "pid": 1}))
398        tuner = tuning.Tuner(self.tmp / "runs", self.plan(), lambda c: {"tokens_per_s": 50.0})
399        with self.assertRaises(RuntimeError) as ctx:
400            tuner._acquire_lease()
401        self.assertIn("dead", str(ctx.exception))
402
403
404class TestExportedRetest(TuningCase):
405    """A winner is not qualified until the *exported* configuration is measured again."""
406
407    def test_a_configuration_that_loses_its_advantage_on_export_is_withdrawn(self):
408        def measure(args):
409            # The benchmark-only lever carried the gain; without it the engine is at the baseline.
410            return {"tokens_per_s": 90.0 if "--prompt-cache-tail" in args else 50.0}
411
412        outcome = tuning.verify_exported(Path("/engine"), {"--kv": "int8"}, measure)
413        self.assertTrue(outcome["verified"])
414        self.assertEqual(outcome["median"], 50.0)
415
416    def test_an_exported_configuration_that_fails_to_boot_is_not_verified(self):
417        def measure(args):
418            raise RuntimeError("the engine failed to boot")
419
420        outcome = tuning.verify_exported(Path("/engine"), {}, measure)
421        self.assertFalse(outcome["verified"])
422        self.assertIn("failed to run", outcome["reason"])
423
424    def test_an_incorrect_exported_configuration_is_not_verified(self):
425        outcome = tuning.verify_exported(Path("/engine"), {}, lambda a: {"tokens_per_s": 100.0,
426                                                                        "correct": False})
427        self.assertFalse(outcome["verified"])
428        self.assertIn("correctness", outcome["reason"])
429
430
431class TestPersistenceAndReporting(TuningCase):
432    def test_the_job_is_reloadable_with_its_report(self):
433        def measure(candidate):
434            return {"tokens_per_s": 70.0 if candidate.settings else 50.0}
435
436        plan = self.plan(max_trials=1, dimensions=("kv",))
437        _, result = self.run_job(plan, measure)
438        saved = json.loads((self.tmp / "runs" / "job1" / "job.json").read_text())
439        self.assertEqual(saved["state"], "completed")
440        self.assertEqual(saved["id"], "job1")
441        self.assertTrue(saved["report"]["candidates"])
442        self.assertIn("excluded_dimensions", saved["report"])
443        self.assertIn("machine", json.dumps(tuning.machine_identity()))
444
445    def test_the_report_names_what_was_excluded_and_why(self):
446        plan = tuning.plan_tuning(Path("/nonexistent/strata"), "metal", "m", "generation",
447                                  {"prompt_tokens": 128})
448        self.assertIn("vram_reserve", {e["id"] for e in plan.excluded})
449        self.assertFalse(plan.engine_flags_known,
450                         "a plan must record that the engine could not be interrogated")
451
452    def test_objective_selects_the_metric(self):
453        self.assertEqual(self.plan(objective="generation").__class__.__name__, "TuningPlan")
454        tuner = tuning.Tuner(self.tmp / "runs", self.plan(objective="prefill"),
455                             lambda c: {"tokens_per_s": 1.0})
456        self.assertEqual(tuner._objective_metric(), "prefill_tokens_per_s")
457        tuner2 = tuning.Tuner(self.tmp / "runs2", self.plan(objective="latency"),
458                              lambda c: {"tokens_per_s": 1.0})
459        self.assertEqual(tuner2._objective_metric(), "ttft_ms")
460
461
462if __name__ == "__main__":
463    unittest.main()