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