okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f7e12d23c
main
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 30def test_a_normal_done_line (self ): 31# DONE produced prompt_tokens prompt_ms decode_ms finish drafts_acc drafts_off ... 32d = te .parse_done ("DONE 128 512 210.5 1830.0 stop 40 55 0 0 0 12 3 3.4 12 0" ) 33self .assertEqual (d ["produced" ],128 ) 34self .assertEqual (d ["prompt_tokens" ],512 ) 35self .assertAlmostEqual (d ["prompt_ms" ],210.5 ) 36self .assertAlmostEqual (d ["decode_ms" ],1830.0 ) 37self .assertEqual (d ["finish" ],"stop" ) 38self .assertEqual (d ["drafts_accepted" ],40 ) 39 40def test_the_variable_tail_is_kept_not_required (self ): 41"""The engine appends lookup-chain counters only when that option is on.""" 42short = te .parse_done ("DONE 8 16 10.0 20.0 stop 1 2" ) 43self .assertEqual (short ["tail" ], []) 44long = 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" ) 45self .assertEqual (long ["tail" ], ["3" ,"4" ,"5" ,"6" ,"7" ,"8.0" ,"9" ,"10" ,"11" ,"12" ,"13" ]) 46 47def test_a_short_or_malformed_line_is_an_error_not_a_zero (self ): 48for bad in ("DONE 1 2" ,"DONE a b c d stop" ,"not a done line" ,"DONE 1 2 three 4.0 stop" ): 49with self .assertRaises (te .MeasurementError ,msg = bad ): 50te .parse_done (bad ) 51 52def test_unreadable_optional_fields_do_not_fail_the_parse (self ): 53d = te .parse_done ("DONE 8 16 10.0 20.0 stop x y" ) 54self .assertIsNone (d ["drafts_accepted" ]) 55self .assertIsNone (d ["drafts_offered" ]) 56 57 58class TestReadyAndPP (unittest .TestCase ): 59def test_ready_carries_the_context (self ): 60self .assertEqual (te .parse_ready ("READY 32768 stop" ),32768 ) 61 62def test_a_ready_without_a_context_is_an_error (self ): 63with self .assertRaises (te .MeasurementError ): 64te .parse_ready ("READY" ) 65 66def test_pp_with_and_without_the_rate (self ): 67a = te .parse_pp ("PP 1024 4096 800.0 1280.0" ) 68self .assertEqual (a ["processed" ],1024 ) 69self .assertEqual (a ["tok_s" ],1280.0 ) 70b = te .parse_pp ("PP 1024 4096 800.0" ) 71self .assertNotIn ("tok_s" ,b ) 72 73 74class TestMeasurements (unittest .TestCase ): 75"""The numbers, and the cases that must never produce one.""" 76 77def done (self ,** kw ): 78base = {"produced" :100 ,"prompt_tokens" :512 ,"prompt_ms" :200.0 ,"decode_ms" :1000.0 , 79"finish" :"stop" } 80base .update (kw ) 81return base 82 83def test_rates_come_from_the_engines_own_timings (self ): 84m = te .measurement_from_protocol (self .done (),tokens_seen = 100 ) 85self .assertAlmostEqual (m .decode_tokens_per_s ,100.0 )# 100 tokens / 1.0 s 86self .assertAlmostEqual (m .prompt_tokens_per_s ,2560.0 )# 512 / 0.2 s 87self .assertAlmostEqual (m .tokens_per_s ,100 * 1000 / 1200 )# whole request 88self .assertEqual (m .finish ,"stop" ) 89 90def test_ttft_is_the_prompt_plus_one_decode_step (self ): 91m = te .measurement_from_protocol (self .done (),tokens_seen = 100 ) 92# 200 ms prompt + (1000 ms / 100 tokens) = 210 ms 93self .assertAlmostEqual (m .ttft_ms ,210.0 ) 94 95def test_client_ttft_is_recorded_separately_and_labelled (self ): 96m = te .measurement_from_protocol (self .done (),tokens_seen = 100 ,client_ttft_ms = 375.0 ) 97self .assertAlmostEqual (m .ttft_ms ,210.0 ) 98self .assertAlmostEqual (m .client_ttft_ms ,375.0 ) 99 100def test_a_cancelled_run_is_not_a_measurement (self ): 101with self .assertRaises (te .MeasurementError ): 102te .measurement_from_protocol (self .done (finish = "cancel" ),tokens_seen = 100 ) 103 104def test_a_nonfinite_run_is_not_a_measurement (self ): 105with self .assertRaises (te .MeasurementError ): 106te .measurement_from_protocol (self .done (finish = "nonfinite" ),tokens_seen = 100 ) 107 108def test_zero_tokens_is_not_a_measurement_even_with_a_stop_finish (self ): 109with self .assertRaises (te .MeasurementError )as ctx : 110te .measurement_from_protocol (self .done (produced = 0 ),tokens_seen = 0 ) 111self .assertIn ("no tokens" ,str (ctx .exception )) 112 113def 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.""" 115with self .assertRaises (te .MeasurementError )as ctx : 116te .measurement_from_protocol (self .done (produced = 100 ),tokens_seen = 42 ) 117self .assertIn ("refusing to score" ,str (ctx .exception )) 118 119def test_a_length_finish_is_a_legitimate_measurement (self ): 120"""Hitting the output cap is a real measurement of the cap, not a failure.""" 121m = te .measurement_from_protocol (self .done (finish = "length" ),tokens_seen = 100 ) 122self .assertEqual (m .finish ,"length" ) 123 124def test_missing_metrics_stay_missing_rather_than_becoming_zero (self ): 125m = te .measurement_from_protocol ( 126 {"produced" :10 ,"prompt_tokens" :0 ,"prompt_ms" :0.0 ,"decode_ms" :500.0 , 127"finish" :"stop" },tokens_seen = 10 ) 128metrics = m .to_metrics () 129self .assertIn ("tokens_per_s" ,metrics ) 130self .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 143This cannot prove the engine measures what we think. It proves the harness's own contract: a 144boot failure, an early exit and an error line all become errors, and a good response becomes a 145measurement with the engine's numbers. 146""" 147 148def setUp (self ): 149self .tmp = Path (tempfile .mkdtemp (prefix = "strata-tune-engine-" )) 150 151def tearDown (self ): 152import shutil 153shutil .rmtree (self .tmp ,ignore_errors = True ) 154 155def stub (self ,body :str )-> Path : 156"""Write a stub engine that speaks the serve protocol. 157 158The stub is a Python script (the harness starts it as ``[sys.executable, stub.py]``, so it 159runs the same on every OS; a ``.sh`` stub is WinError 193 on Windows). ``body`` is Python 160using ``say(text)`` (print a line and flush) and ``wait()`` (block until the harness sends 161a line). Each body is explicit about how it blocks: ``wait()`` keeps the process, and so the 162stdout pipe, alive without leaving a child behind. 163""" 164p = self .tmp / "stub-engine.py" 165p .write_text (STUB_PRELUDE + body ) 166return p 167 168def test_a_good_response_becomes_a_measurement (self ): 169stub = 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' ) 176h = te .EngineHarness (stub , {},workload = {"prompt_tokens" :8 ,"max_new" :3 }) 177try : 178h .start () 179self .assertEqual (h ._context ,4096 ) 180m = h .measure () 181self .assertEqual (m .produced ,3 ) 182self .assertAlmostEqual (m .decode_tokens_per_s ,100.0 )# 3 / 0.030 s 183self .assertEqual (m .finish ,"stop" ) 184finally : 185h .close () 186 187def 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. 191stub = self .stub ('wait()\n' ) 192h = te .EngineHarness (stub , {},boot_timeout_s = 1.0 ) 193try : 194with self .assertRaises (te .MeasurementError )as ctx : 195h .start () 196self .assertIn ("READY" ,str (ctx .exception )) 197finally : 198h .close () 199 200def 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. 203stub = self .stub ('say("loading weights")\nsys.exit(0)\n' ) 204h = te .EngineHarness (stub , {},boot_timeout_s = 10.0 ) 205try : 206with self .assertRaises (te .MeasurementError )as ctx : 207h .start () 208self .assertIn ("before it was ready" ,str (ctx .exception )) 209finally : 210h .close () 211 212def test_an_engine_that_exits_immediately_reports_the_code (self ): 213stub = self .stub ('say("starting up")\nsys.exit(7)\n' ) 214h = te .EngineHarness (stub , {}) 215try : 216with self .assertRaises (te .MeasurementError )as ctx : 217h .start () 218self .assertIn ("7" ,str (ctx .exception )) 219finally : 220h .close () 221 222def test_an_error_line_from_the_engine_is_raised_verbatim (self ): 223stub = self .stub ('say("READY 4096 stop")\nwait()\nsay("ERR out of memory")\nwait()\n' ) 224h = te .EngineHarness (stub , {},workload = {"prompt_tokens" :4 ,"max_new" :1 }, 225request_timeout_s = 3.0 ) 226try : 227h .start () 228with self .assertRaises (te .MeasurementError )as ctx : 229h .measure () 230self .assertIn ("out of memory" ,str (ctx .exception )) 231finally : 232h .close () 233 234def 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.""" 236stub_path = Path (__file__ ).with_name ("stub_engine.py" ) 237speeds = {} 238for kv in ("int8" ,"fp16" ): 239h = te .EngineHarness (stub_path , {"--kv" :kv },workload = {"prompt_tokens" :8 ,"max_new" :4 }) 240try : 241h .start () 242m = h .measure () 243self .assertEqual (m .produced ,4 ) 244speeds [kv ]= m .decode_tokens_per_s 245finally : 246h .close () 247self .assertAlmostEqual (speeds ["int8" ],80.0 )# 4 tokens in 50 ms 248self .assertAlmostEqual (speeds ["fp16" ],40.0 )# 4 tokens in 100 ms 249 250def test_a_py_engine_runs_through_the_current_interpreter (self ): 251from strata_control import tuning 252self .assertEqual (tuning .engine_command (Path ("x" )/ "stub.py" ), [sys .executable ,str (Path ("x" )/ "stub.py" )]) 253self .assertEqual (tuning .engine_command (Path ("x" )/ "strata" ), [str (Path ("x" )/ "strata" )]) 254 255def test_a_missing_binary_is_an_error_before_any_process_starts (self ): 256h = te .EngineHarness (self .tmp / "nope" , {}) 257with self .assertRaises (te .MeasurementError )as ctx : 258h .start () 259self .assertIn ("not at" ,str (ctx .exception )) 260 261def test_the_declared_flags_are_passed_to_the_engine (self ): 262stub = self .stub ('say("READY 4096 stop")\nwait()\nsay("DONE 1 1 1.0 1.0 stop 0 0")\nwait()\n' ) 263h = te .EngineHarness (stub , {"--kv" :"int8" ,"--kv-grow" :"1" }) 264argv = h ._argv () 265self .assertIn ("--kv" ,argv ) 266self .assertIn ("int8" ,argv ) 267self .assertIn ("--kv-grow" ,argv ) 268try : 269h .start () 270h .measure () 271finally : 272h .close () 273 274def test_make_measure_returns_the_metric_dict_the_job_expects (self ): 275stub = self .stub ('say("READY 4096 stop")\nwait()\nsay("T 1")\nsay("DONE 1 16 8.0 4.0 stop 0 0")\nwait()\n' ) 276measure = te .make_measure (stub ,workload = {"prompt_tokens" :4 ,"max_new" :1 }) 277 278class C : 279args :dict = {} 280 281metrics = measure (C ()) 282self .assertIn ("tokens_per_s" ,metrics ) 283self .assertIsInstance (metrics ["tokens_per_s" ],float ) 284self .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 290def test_the_default_workload_is_deterministic (self ): 291w = te .DEFAULT_WORKLOAD 292self .assertEqual (w ["seed" ],1 ) 293self .assertEqual (w ["temperature" ],0.0 ) 294self .assertGreater (w ["prompt_tokens" ],0 ) 295self .assertGreater (w ["max_new" ],0 ) 296 297def test_the_same_prompt_ids_are_produced_every_time (self ): 298h = te .EngineHarness (Path ("/nonexistent" ), {},workload = {"prompt_tokens" :16 }) 299self .assertEqual (list (h ._prompt_tokens ()),list (h ._prompt_tokens ())) 300self .assertEqual (len (list (h ._prompt_tokens ())),16 ) 301 302 303if __name__ == "__main__" : 304unittest .main ()