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
13.1 KiB304 linesraw
1"""Engine measurement tests.
2
3The parsing is tested against the engine's real line formats, taken from
4`src/program/generate.cpp`, and the failure handling is tested with a stub engine that speaks the
5same protocol. That combination is deliberate: real hardware needs a model that does not fit this
6machine, but the *contract* — what counts as a measurement and what must be rejected — is fully
7testable here, and it is the part that decides whether a tuning result can be trusted.
8
9The risk these tests exist for is specific: a tuning harness that scores a failed or incomplete run
10as a slow one will happily recommend a configuration that does not work.
11"""
12
13from __future__ import annotations
14
15import os
16import stat
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 tune_engine as te  # noqa: E402
25
26
27class TestDoneParsing(unittest.TestCase):
28    """`DONE` is what the engine reports; the field order is the engine's, not ours."""
29
30    def test_a_normal_done_line(self):
31        # DONE produced prompt_tokens prompt_ms decode_ms finish drafts_acc drafts_off ...
32        d = te.parse_done("DONE 128 512 210.5 1830.0 stop 40 55 0 0 0 12 3 3.4 12 0")
33        self.assertEqual(d["produced"], 128)
34        self.assertEqual(d["prompt_tokens"], 512)
35        self.assertAlmostEqual(d["prompt_ms"], 210.5)
36        self.assertAlmostEqual(d["decode_ms"], 1830.0)
37        self.assertEqual(d["finish"], "stop")
38        self.assertEqual(d["drafts_accepted"], 40)
39
40    def test_the_variable_tail_is_kept_not_required(self):
41        """The engine appends lookup-chain counters only when that option is on."""
42        short = te.parse_done("DONE 8 16 10.0 20.0 stop 1 2")
43        self.assertEqual(short["tail"], [])
44        long = te.parse_done("DONE 8 16 10.0 20.0 stop 1 2 3 4 5 6 7 8.0 9 10 11 12 13")
45        self.assertEqual(long["tail"], ["3", "4", "5", "6", "7", "8.0", "9", "10", "11", "12", "13"])
46
47    def test_a_short_or_malformed_line_is_an_error_not_a_zero(self):
48        for bad in ("DONE 1 2", "DONE a b c d stop", "not a done line", "DONE 1 2 three 4.0 stop"):
49            with self.assertRaises(te.MeasurementError, msg=bad):
50                te.parse_done(bad)
51
52    def test_unreadable_optional_fields_do_not_fail_the_parse(self):
53        d = te.parse_done("DONE 8 16 10.0 20.0 stop x y")
54        self.assertIsNone(d["drafts_accepted"])
55        self.assertIsNone(d["drafts_offered"])
56
57
58class TestReadyAndPP(unittest.TestCase):
59    def test_ready_carries_the_context(self):
60        self.assertEqual(te.parse_ready("READY 32768 stop"), 32768)
61
62    def test_a_ready_without_a_context_is_an_error(self):
63        with self.assertRaises(te.MeasurementError):
64            te.parse_ready("READY")
65
66    def test_pp_with_and_without_the_rate(self):
67        a = te.parse_pp("PP 1024 4096 800.0 1280.0")
68        self.assertEqual(a["processed"], 1024)
69        self.assertEqual(a["tok_s"], 1280.0)
70        b = te.parse_pp("PP 1024 4096 800.0")
71        self.assertNotIn("tok_s", b)
72
73
74class TestMeasurements(unittest.TestCase):
75    """The numbers, and the cases that must never produce one."""
76
77    def done(self, **kw):
78        base = {"produced": 100, "prompt_tokens": 512, "prompt_ms": 200.0, "decode_ms": 1000.0,
79                "finish": "stop"}
80        base.update(kw)
81        return base
82
83    def test_rates_come_from_the_engines_own_timings(self):
84        m = te.measurement_from_protocol(self.done(), tokens_seen=100)
85        self.assertAlmostEqual(m.decode_tokens_per_s, 100.0)          # 100 tokens / 1.0 s
86        self.assertAlmostEqual(m.prompt_tokens_per_s, 2560.0)         # 512 / 0.2 s
87        self.assertAlmostEqual(m.tokens_per_s, 100 * 1000 / 1200)     # whole request
88        self.assertEqual(m.finish, "stop")
89
90    def test_ttft_is_the_prompt_plus_one_decode_step(self):
91        m = te.measurement_from_protocol(self.done(), tokens_seen=100)
92        # 200 ms prompt + (1000 ms / 100 tokens) = 210 ms
93        self.assertAlmostEqual(m.ttft_ms, 210.0)
94
95    def test_client_ttft_is_recorded_separately_and_labelled(self):
96        m = te.measurement_from_protocol(self.done(), tokens_seen=100, client_ttft_ms=375.0)
97        self.assertAlmostEqual(m.ttft_ms, 210.0)
98        self.assertAlmostEqual(m.client_ttft_ms, 375.0)
99
100    def test_a_cancelled_run_is_not_a_measurement(self):
101        with self.assertRaises(te.MeasurementError):
102            te.measurement_from_protocol(self.done(finish="cancel"), tokens_seen=100)
103
104    def test_a_nonfinite_run_is_not_a_measurement(self):
105        with self.assertRaises(te.MeasurementError):
106            te.measurement_from_protocol(self.done(finish="nonfinite"), tokens_seen=100)
107
108    def test_zero_tokens_is_not_a_measurement_even_with_a_stop_finish(self):
109        with self.assertRaises(te.MeasurementError) as ctx:
110            te.measurement_from_protocol(self.done(produced=0), tokens_seen=0)
111        self.assertIn("no tokens", str(ctx.exception))
112
113    def test_a_token_count_that_disagrees_with_the_stream_is_refused(self):
114        """If the stream and the summary disagree, neither can be trusted for a rate."""
115        with self.assertRaises(te.MeasurementError) as ctx:
116            te.measurement_from_protocol(self.done(produced=100), tokens_seen=42)
117        self.assertIn("refusing to score", str(ctx.exception))
118
119    def test_a_length_finish_is_a_legitimate_measurement(self):
120        """Hitting the output cap is a real measurement of the cap, not a failure."""
121        m = te.measurement_from_protocol(self.done(finish="length"), tokens_seen=100)
122        self.assertEqual(m.finish, "length")
123
124    def test_missing_metrics_stay_missing_rather_than_becoming_zero(self):
125        m = te.measurement_from_protocol(
126            {"produced": 10, "prompt_tokens": 0, "prompt_ms": 0.0, "decode_ms": 500.0,
127             "finish": "stop"}, tokens_seen=10)
128        metrics = m.to_metrics()
129        self.assertIn("tokens_per_s", metrics)
130        self.assertNotIn("prompt_tokens_per_s", metrics,
131                         "an unmeasurable prompt rate must be absent, not zero")
132
133
134STUB_PRELUDE = (
135    "import sys\n"
136    "def say(text):\n    print(text, flush=True)\n"
137    "def wait():\n    sys.stdin.readline()\n")
138
139
140class TestEngineHarnessWithAStub(unittest.TestCase):
141    """The harness against a stub that speaks the real protocol.
142
143    This cannot prove the engine measures what we think. It proves the harness's own contract: a
144    boot failure, an early exit and an error line all become errors, and a good response becomes a
145    measurement with the engine's numbers.
146    """
147
148    def setUp(self):
149        self.tmp = Path(tempfile.mkdtemp(prefix="strata-tune-engine-"))
150
151    def tearDown(self):
152        import shutil
153        shutil.rmtree(self.tmp, ignore_errors=True)
154
155    def stub(self, body: str) -> Path:
156        """Write a stub engine that speaks the serve protocol.
157
158        The stub is a Python script (the harness starts it as ``[sys.executable, stub.py]``, so it
159        runs the same on every OS; a ``.sh`` stub is WinError 193 on Windows). ``body`` is Python
160        using ``say(text)`` (print a line and flush) and ``wait()`` (block until the harness sends
161        a line). Each body is explicit about how it blocks: ``wait()`` keeps the process, and so the
162        stdout pipe, alive without leaving a child behind.
163        """
164        p = self.tmp / "stub-engine.py"
165        p.write_text(STUB_PRELUDE + body)
166        return p
167
168    def test_a_good_response_becomes_a_measurement(self):
169        stub = self.stub(
170            'say("READY 4096 stop")\n'
171            'wait()\n'
172            'say("PP 512 512 200.0 2560.0")\n'
173            'say("T 1"); say("T 2"); say("T 3")\n'
174            'say("DONE 3 512 200.0 30.0 stop 0 0")\n'
175            'wait()\n')
176        h = te.EngineHarness(stub, {}, workload={"prompt_tokens": 8, "max_new": 3})
177        try:
178            h.start()
179            self.assertEqual(h._context, 4096)
180            m = h.measure()
181            self.assertEqual(m.produced, 3)
182            self.assertAlmostEqual(m.decode_tokens_per_s, 100.0)   # 3 / 0.030 s
183            self.assertEqual(m.finish, "stop")
184        finally:
185            h.close()
186
187    def test_an_engine_that_never_reports_ready_times_out(self):
188        # The stub must block *in its own process* with stdout open. A shell `sleep` child would
189        # hold the pipe open after the shell exits, so the harness would keep waiting on a process
190        # that is already gone -- which made this test hang rather than fail.
191        stub = self.stub('wait()\n')
192        h = te.EngineHarness(stub, {}, boot_timeout_s=1.0)
193        try:
194            with self.assertRaises(te.MeasurementError) as ctx:
195                h.start()
196            self.assertIn("READY", str(ctx.exception))
197        finally:
198            h.close()
199
200    def test_an_engine_that_exits_without_ready_is_reported_as_an_early_exit(self):
201        # It prints something and *then* dies without READY, which is the realistic shape: the
202        # engine got far enough to log, then failed.
203        stub = self.stub('say("loading weights")\nsys.exit(0)\n')
204        h = te.EngineHarness(stub, {}, boot_timeout_s=10.0)
205        try:
206            with self.assertRaises(te.MeasurementError) as ctx:
207                h.start()
208            self.assertIn("before it was ready", str(ctx.exception))
209        finally:
210            h.close()
211
212    def test_an_engine_that_exits_immediately_reports_the_code(self):
213        stub = self.stub('say("starting up")\nsys.exit(7)\n')
214        h = te.EngineHarness(stub, {})
215        try:
216            with self.assertRaises(te.MeasurementError) as ctx:
217                h.start()
218            self.assertIn("7", str(ctx.exception))
219        finally:
220            h.close()
221
222    def test_an_error_line_from_the_engine_is_raised_verbatim(self):
223        stub = self.stub('say("READY 4096 stop")\nwait()\nsay("ERR out of memory")\nwait()\n')
224        h = te.EngineHarness(stub, {}, workload={"prompt_tokens": 4, "max_new": 1},
225                             request_timeout_s=3.0)
226        try:
227            h.start()
228            with self.assertRaises(te.MeasurementError) as ctx:
229                h.measure()
230            self.assertIn("out of memory", str(ctx.exception))
231        finally:
232            h.close()
233
234    def test_the_shared_stub_engine_speaks_the_protocol_and_reacts_to_kv(self):
235        """tests/tuning/stub_engine.py is the engine every sweep test uses, on every OS."""
236        stub_path = Path(__file__).with_name("stub_engine.py")
237        speeds = {}
238        for kv in ("int8", "fp16"):
239            h = te.EngineHarness(stub_path, {"--kv": kv}, workload={"prompt_tokens": 8, "max_new": 4})
240            try:
241                h.start()
242                m = h.measure()
243                self.assertEqual(m.produced, 4)
244                speeds[kv] = m.decode_tokens_per_s
245            finally:
246                h.close()
247        self.assertAlmostEqual(speeds["int8"], 80.0)     # 4 tokens in 50 ms
248        self.assertAlmostEqual(speeds["fp16"], 40.0)     # 4 tokens in 100 ms
249
250    def test_a_py_engine_runs_through_the_current_interpreter(self):
251        from strata_control import tuning
252        self.assertEqual(tuning.engine_command(Path("x") / "stub.py"), [sys.executable, str(Path("x") / "stub.py")])
253        self.assertEqual(tuning.engine_command(Path("x") / "strata"), [str(Path("x") / "strata")])
254
255    def test_a_missing_binary_is_an_error_before_any_process_starts(self):
256        h = te.EngineHarness(self.tmp / "nope", {})
257        with self.assertRaises(te.MeasurementError) as ctx:
258            h.start()
259        self.assertIn("not at", str(ctx.exception))
260
261    def test_the_declared_flags_are_passed_to_the_engine(self):
262        stub = self.stub('say("READY 4096 stop")\nwait()\nsay("DONE 1 1 1.0 1.0 stop 0 0")\nwait()\n')
263        h = te.EngineHarness(stub, {"--kv": "int8", "--kv-grow": "1"})
264        argv = h._argv()
265        self.assertIn("--kv", argv)
266        self.assertIn("int8", argv)
267        self.assertIn("--kv-grow", argv)
268        try:
269            h.start()
270            h.measure()
271        finally:
272            h.close()
273
274    def test_make_measure_returns_the_metric_dict_the_job_expects(self):
275        stub = self.stub('say("READY 4096 stop")\nwait()\nsay("T 1")\nsay("DONE 1 16 8.0 4.0 stop 0 0")\nwait()\n')
276        measure = te.make_measure(stub, workload={"prompt_tokens": 4, "max_new": 1})
277
278        class C:
279            args: dict = {}
280
281        metrics = measure(C())
282        self.assertIn("tokens_per_s", metrics)
283        self.assertIsInstance(metrics["tokens_per_s"], float)
284        self.assertGreater(metrics["tokens_per_s"], 0)
285
286
287class TestWorkloadIsFixed(unittest.TestCase):
288    """A sweep is only comparable if every candidate did the same work."""
289
290    def test_the_default_workload_is_deterministic(self):
291        w = te.DEFAULT_WORKLOAD
292        self.assertEqual(w["seed"], 1)
293        self.assertEqual(w["temperature"], 0.0)
294        self.assertGreater(w["prompt_tokens"], 0)
295        self.assertGreater(w["max_new"], 0)
296
297    def test_the_same_prompt_ids_are_produced_every_time(self):
298        h = te.EngineHarness(Path("/nonexistent"), {}, workload={"prompt_tokens": 16})
299        self.assertEqual(list(h._prompt_tokens()), list(h._prompt_tokens()))
300        self.assertEqual(len(list(h._prompt_tokens())), 16)
301
302
303if __name__ == "__main__":
304    unittest.main()