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