okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
1"""Tests for tools/calibrate.py and setup's use of it, without a GPU: a stand-in engine whose decode speed is a 2function of the settings it runs with. 3 4python -m unittest tools.test_calibrate 5""" 6from __future__import annotations 7 8import json 9import os 10import sys 11import tempfile 12import threading 13import unittest 14from pathlib import Path 15from unittest import mock 16 17ROOT = Path (__file__ ).resolve ().parents [1 ] 18sys .path .insert (0 ,str (ROOT / "tools" )) 19sys .path .insert (0 ,str (ROOT )) 20import calibrate as CAL # noqa: E402 21 22 23class FakeEngine : 24"""Speed = f(pcie_frac, spec_min_p, workers): the GEN line's tune keys arrive as `strata_tune`. 25`dies`: setting values whose engine exits during its first generation (the #267 class, mid-measurement).""" 26 27def __init__ (self ,args ,speed ,info_workers = 6 ,starts = None ,adapt = None ,read = None ,reads = None ,dies = ()): 28self .args = list (args ) 29self .read ,self .reads = read ,reads # prompt read speed = read(prefill_pipe); the values it read with 30self .adapt_bonus = (adapt or {}).get (CAL .arg_value (args ,"--adapt-swaps" ),1.0 ) 31w = CAL .arg_value (args ,"--pool-workers" ) 32self .workers = int (w )if w else info_workers 33self .info = {"pool_workers" :info_workers ,"pcie_frac" :0.55 ,"spec_min_p" :float (CAL .arg_value (args ,"--spec-min-p" )or 0 )} 34self .speed = speed 35self .last = {} 36self .proc = None 37self .dies = CAL .arg_value (args ,"--adapt-swaps" )in dies or CAL .arg_value (args ,"--pool-workers" )in dies 38self .dead = False 39if starts is not None : 40starts .append (list (args )) 41 42def generate (self ,ids ,max_new ,sampling ,cancel ): 43if self .dies and not self .dead : 44self .dead = True 45raise RuntimeError ("the engine exited: ERR verify: the adaptive tier's copies for layer 47 never landed" 46" (the copy stream itself is not drained); restart the engine" ) 47tune = sampling .get ("strata_tune" )or {} 48rate = self .speed (tune .get ("pcie_frac" ,0.55 ),tune .get ("spec_min_p" ,self .info ["spec_min_p" ]),self .workers ) 49rate *= self .adapt_bonus 50for _ in range (max_new ): 51yield 1 52self .last = {"generated" :max_new ,"decode_ms" :max_new / rate * 1000.0 } 53if "prefill_pipe" in tune and self .read is not None : 54n = len (ids ) 55self .last .update (prompt_tokens = n ,prompt_read = n ,prompt_ms = n / self .read (tune ["prefill_pipe" ])* 1000.0 ) 56if self .reads is not None : 57self .reads .append (tune ["prefill_pipe" ]) 58 59 60BASE = ["--pack" ,"p" ,"--spec" ,"4" ,"--spec-min-p" ,"0.5" ,"--max-context" ,"8192" ] 61 62 63class Calibrate (unittest .TestCase ): 64def run_with (self ,speed ,workers = 6 ,base = BASE ,adapt = None ,read = None ,reads = None ,dies = ()): 65starts = [] 66res = CAL .measure (base , [[1 ,2 ,3 ]]* 3 , 67lambda a :FakeEngine (a ,speed ,workers ,starts ,adapt ,read ,reads ,dies ), 68say = lambda * _ :None ,long_prompt = lambda i ,n : [1 ]* n ) 69return res ,starts 70 71def test_prefill_pipe_on_a_layer_split (self ): 72# two stages that read fastest with b/a 1536: kept, and only one engine start measures it 73split = BASE + ["--layer-split" ,"auto" ] 74reads = [] 75res ,_ = self .run_with (lambda f ,p ,w :50.0 ,base = split ,reads = reads , 76read = lambda v : {1536 :600.0 ,768 :560.0 ,1 :520.0 }.get (v ,500.0 )) 77self .assertEqual (res ["settings" ].get ("--prefill-pipe" ),"1536" ) 78self .assertEqual (sorted (set (reads )),sorted (set (CAL .PIPE_VALUES ))) 79self .assertIn ("pipe_sweep" ,res ["report" ]) 80self .assertEqual (CAL .arg_value (CAL .apply (split ,res ["settings" ]),"--prefill-pipe" ),"1536" ) 81 82def test_prefill_pipe_noise_stays_off (self ): 83# 2% faster evened out: below MIN_GAIN, so the engine default (off) stays 84res ,_ = self .run_with (lambda f ,p ,w :50.0 ,base = BASE + ["--layer-split" ,"auto" ], 85read = lambda v :510.0 if v == 1 else 500.0 ) 86self .assertNotIn ("--prefill-pipe" ,res ["settings" ]) 87 88def test_prefill_pipe_must_win_every_round (self ): 89# 1536 looks 12% faster in the sweep and the median, but one paired round reads slower: noise, it stays off 90calls = {} 91 92def read (v ): 93calls [v ]= calls .get (v ,0 )+ 1 94if v != 1536 : 95return 500.0 96return [560.0 ,560.0 ,560.0 ,480.0 ,560.0 ,560.0 ][min (calls [v ],6 )- 1 ] 97res ,_ = self .run_with (lambda f ,p ,w :50.0 ,base = BASE + ["--layer-split" ,"auto" ],read = read ) 98self .assertNotIn ("--prefill-pipe" ,res ["settings" ]) 99self .assertEqual (len (res ["report" ]["pipe_confirm" ]["1536" ]),3 ) 100 101def test_prefill_pipe_reads_the_same_text (self ): 102# every read: the same stretch of text after a header of its own (only the chunks differ between values) 103tok = type ("T" , (), {"encode" :lambda s ,t ,** k : [ord (c )for c in t ]})() 104make = CAL .doc_prompt (tok ) 105a ,b = make (1 ,300 ),make (2 ,300 ) 106self .assertNotEqual (a [:40 ],b [:40 ]) 107self .assertEqual (a [- 320 :],b [- 320 :]) 108 109def test_prefill_pipe_only_on_a_layer_split (self ): 110reads = [] 111res ,_ = self .run_with (lambda f ,p ,w :50.0 ,read = lambda v :600.0 if v == 1536 else 500.0 ,reads = reads ) 112self .assertEqual (reads , []) 113self .assertNotIn ("--prefill-pipe" ,res ["settings" ]) 114# an old calibration's value goes when a new one does not keep it 115self .assertIsNone (CAL .arg_value (CAL .apply (BASE + ["--prefill-pipe" ,"800" ], {}),"--prefill-pipe" )) 116 117def test_prefill_pipe_follows_the_engines_stage_count (self ): 118# --layer-split that left one prompt stage (the engine says prefill_stages=1): nothing to measure 119reads = [] 120 121class OneStage (FakeEngine ): 122def __init__ (self ,* a ,** k ): 123super ().__init__ (* a ,** k ) 124self .info ["prefill_stages" ]= 1 125res = CAL .measure (BASE + ["--layer-split" ,"auto" ], [[1 ,2 ,3 ]]* 3 , 126lambda a :OneStage (a ,lambda f ,p ,w :50.0 ,6 ,None ,None , 127lambda v :600.0 if v == 1536 else 500.0 ,reads ), 128say = lambda * _ :None ,long_prompt = lambda i ,n : [1 ]* n ) 129self .assertEqual (reads , []) 130self .assertNotIn ("--prefill-pipe" ,res ["settings" ]) 131 132def test_defaults_kept_when_flat (self ): 133res ,_ = self .run_with (lambda f ,p ,w :50.0 ) 134self .assertEqual (res ["settings" ], {}) 135 136def test_measure_reports_bounded_stages_and_stops_between_samples (self ): 137events = [] 138stopped = threading .Event () 139 140def progress (stage ,completed ,total ): 141events .append ((stage ,completed ,total )) 142if stage == "pcie_share" and completed == 1 : 143stopped .set () 144 145with self .assertRaises (CAL .CalibrationCancelled ): 146CAL .measure (BASE , [[1 ,2 ,3 ]]* 3 , 147lambda args :FakeEngine (args ,lambda * _ :50.0 ), 148say = lambda * _ :None ,progress = progress ,cancel_event = stopped ) 149self .assertIn (("loading" ,1 ,1 ),events ) 150self .assertIn (("pcie_share" ,1 ,len (CAL .PCIE_FRACS )* CAL .SWEEP_ROUNDS ),events ) 151self .assertNotIn ("draft_floor" , [stage for stage ,_ ,_ in events ]) 152 153def test_active_generation_receives_shared_cancel_event (self ): 154stopped = threading .Event () 155seen = [] 156 157class Engine : 158def generate (self ,ids ,max_new ,sampling ,cancel ): 159seen .append (cancel ) 160cancel .set () 161yield None 162 163session = CAL .Session (Engine (), [[1 ,2 ,3 ]],stopped ) 164with self .assertRaises (CAL .CalibrationCancelled ): 165session .rate () 166self .assertEqual (seen , [stopped ]) 167 168def test_successful_sweep_covers_every_progress_stage (self ): 169events = [] 170CAL .measure (BASE , [[1 ,2 ,3 ]]* 3 , 171lambda args :FakeEngine (args ,lambda * _ :50.0 ), 172say = lambda * _ :None ,progress = lambda * item :events .append (item )) 173stages = list (dict .fromkeys (stage for stage ,_ ,_ in events )) 174self .assertEqual (stages , ["loading" ,"pcie_share" ,"draft_floor" ,"confirmation" , 175"cpu_workers" ,"expert_tier" ]) 176for stage in stages : 177readings = [(done ,total )for current ,done ,total in events if current == stage ] 178self .assertEqual (readings [0 ][0 ],0 ) 179self .assertEqual (readings [- 1 ][0 ],readings [- 1 ][1 ]) 180self .assertTrue (all (before [0 ]<= after [0 ]and before [1 ]== after [1 ] 181for before ,after in zip (readings ,readings [1 :]))) 182 183def test_small_gain_is_noise (self ): 184# 2% better at pcie 0.35: below MIN_GAIN, so the default stays 185res ,_ = self .run_with (lambda f ,p ,w :51.0 if abs (f - 0.35 )< 1e-6 else 50.0 ) 186self .assertEqual (res ["settings" ], {}) 187 188def test_finds_pcie_and_min_p (self ): 189def speed (f ,p ,w ): 190return 50.0 + (10.0 if abs (f - 0.2 )< 1e-6 else 0.0 )+ (5.0 if abs (p - 0.7 )< 1e-6 else 0.0 ) 191res ,_ = self .run_with (speed ) 192self .assertEqual (res ["settings" ].get ("--pcie-frac" ),"0.20" ) 193self .assertEqual (res ["settings" ].get ("--spec-min-p" ),"0.70" ) 194self .assertNotIn ("--pool-workers" ,res ["settings" ]) 195 196def test_fewer_workers (self ): 197# a hybrid CPU: half the workers is 20% faster 198res ,starts = self .run_with (lambda f ,p ,w :60.0 if w == 3 else 50.0 ,workers = 6 ) 199self .assertEqual (res ["settings" ].get ("--pool-workers" ),"3" ) 200# one start per worker count and per expert-tier candidate, plus the sweep 201self .assertEqual (len (starts ),1 + len (CAL .worker_candidates (6 ))+ len (CAL .ADAPT_CANDIDATES )) 202self .assertEqual (CAL .arg_value (starts [0 ],"--spec-min-p" ),"0.5" )# measured against the product default 203 204def test_a_failed_restart_keeps_the_measurements_1337 (self ): 205# the top PCIe share wins by far; every later restart (the worker counts, the expert tier) fails to start 206n = {"starts" :0 } 207 208def start (args ): 209n ["starts" ]+= 1 210if n ["starts" ]> 1 : 211raise RuntimeError ("the engine exited before it was ready: cudaMalloc failed (213 MiB free)" ) 212return FakeEngine (args ,lambda f ,p ,w :80.0 if f == 0.75 else 50.0 ,6 ) 213said = [] 214res = CAL .measure (BASE , [[1 ,2 ,3 ]]* 3 ,start ,say = said .append ) 215self .assertEqual (res ["settings" ].get ("--pcie-frac" ),"0.75" )# steps 1-3 survived 216self .assertGreater (len (res ["report" ]["failed_starts" ]),1 ) 217self .assertTrue (any ("did not start" in x and "cudaMalloc" in x for x in said )) 218self .assertEqual (res ["report" ]["workers" ], {}) 219self .assertEqual (res ["report" ]["adapt" ], {}) 220 221def test_one_failing_worker_count_only_drops_that_candidate_1337 (self ): 222def start (args ): 223if CAL .arg_value (args ,"--pool-workers" )== "3" : 224raise RuntimeError ("out of memory" ) 225return FakeEngine (args ,lambda f ,p ,w :60.0 if w == 2 else 50.0 ,6 ) 226res = CAL .measure (BASE , [[1 ,2 ,3 ]]* 3 ,start ,say = lambda * _ :None ) 227self .assertEqual (res ["settings" ].get ("--pool-workers" ),"2" ) 228self .assertEqual (list (res ["report" ]["failed_starts" ]), ["3 workers" ]) 229 230def test_adaptive_tier (self ): 231# a slow-RAM PC: swapping 160 experts per round is 10% faster, 80 is 2% (noise) 232res ,starts = self .run_with (lambda f ,p ,w :50.0 ,adapt = {"160" :1.10 ,"80" :1.02 }) 233self .assertEqual ([res ["settings" ].get (f )for f in CAL .ADAPT_FLAGS ], ["1" ,"160" ,"0.97" ]) 234flat ,_ = self .run_with (lambda f ,p ,w :50.0 ,adapt = {"160" :1.02 }) 235self .assertFalse (any (f in flat ["settings" ]for f in CAL .ADAPT_FLAGS )) 236# the candidates are measured with the worker count chosen before 237res ,starts = self .run_with (lambda f ,p ,w :60.0 if w == 3 else 50.0 ,workers = 6 ,adapt = {"160" :1.10 }) 238self .assertEqual (res ["settings" ].get ("--pool-workers" ),"3" ) 239self .assertTrue (all (CAL .arg_value (a ,"--pool-workers" )== "3" for a in starts [- len (CAL .ADAPT_CANDIDATES ):])) 240a = CAL .apply (BASE ,res ["settings" ]) 241self .assertEqual (CAL .arg_value (a ,"--adapt-swaps" ),"160" ) 242self .assertIsNone (CAL .arg_value (CAL .apply (a , {}),"--adapt-swaps" ))# an old calibration's tier goes 243 244def test_engine_death_during_tier_measurement_drops_only_that_candidate (self ): 245# the 160-swap candidate's engine dies during its own measurement (the adaptive gate's #267 livelock): 246# that candidate loses, 80 (10% faster) is still chosen, and the run returns with the earlier results 247res ,_ = self .run_with (lambda f ,p ,w :50.0 ,adapt = {"80" :1.10 },dies = ("160" ,)) 248self .assertEqual (res ["settings" ].get ("--adapt-swaps" ),"80" ) 249self .assertEqual (list (res ["report" ]["adapt" ]), ["default" ,"1/80/0.97" ]) 250self .assertIn ("the expert tier 1/160/0.97" ,res ["report" ]["failed_starts" ]) 251 252def test_engine_death_during_a_worker_measurement_keeps_the_run (self ): 253# 4 workers' engine dies mid-measurement: 3 and 2 are still measured, the default count stays, the tier runs 254res ,_ = self .run_with (lambda f ,p ,w :50.0 ,workers = 6 ,dies = ("4" ,)) 255self .assertNotIn ("--pool-workers" ,res ["settings" ]) 256self .assertEqual (sorted (int (k .split ()[0 ])for k in res ["report" ]["workers" ]), [2 ,3 ,6 ]) 257self .assertIn ("4 workers" ,res ["report" ]["failed_starts" ]) 258self .assertEqual (list (res ["report" ]["adapt" ]), ["default" ,"1/80/0.97" ,"1/160/0.97" ]) 259 260def test_old_calibration_is_the_baseline_reset (self ): 261# a config tuned earlier: the measurement starts from the product defaults, not from those values 262base = CAL .apply (BASE , {"--pcie-frac" :"0.20" ,"--pool-workers" :"3" ,"--spec-min-p" :"0.70" }) 263_ ,starts = self .run_with (lambda f ,p ,w :50.0 ,base = base ) 264self .assertIsNone (CAL .arg_value (starts [0 ],"--pcie-frac" )) 265self .assertIsNone (CAL .arg_value (starts [0 ],"--pool-workers" )) 266self .assertEqual (CAL .arg_value (starts [0 ],"--spec-min-p" ),"0.5" ) 267 268def test_sh_stream_is_measured_on_hip_only (self ): 269# #1272 / #816: the shared-expert fork is measured off (the HIP default) against on, each with a restart and 270# the engine variable set explicitly; it is kept only when it wins by more than MIN_GAIN 271def run (bonus ,hip = True ): 272starts ,envs = [], [] 273 274def start (args ,env = None ): 275envs .append (dict (env or {})) 276fork = (env or {}).get (CAL .SH_STREAM )== "1" 277return FakeEngine (args ,lambda f ,p ,w :50.0 * (bonus if fork else 1.0 ),6 ,starts ) 278res = CAL .measure (BASE , [[1 ,2 ,3 ]]* 3 ,start ,say = lambda * _ :None ,hip = hip ) 279return res ,starts ,envs 280res ,starts ,envs = run (1.08 ) 281self .assertEqual (res ["env" ], {CAL .SH_STREAM :"1" }) 282self .assertEqual (envs [- 2 :], [{CAL .SH_STREAM :"0" }, {CAL .SH_STREAM :"1" }]) 283self .assertEqual (starts [- 1 ],starts [- 2 ])# the same args for both: only the variable differs 284self .assertGreater (res ["report" ]["tok_s" ],52.0 )# the reported speed is the fork's 285flat ,_ ,_ = run (1.02 )# within noise: the default stays 286self .assertEqual (flat ["env" ], {}) 287self .assertEqual (set (flat ["report" ]["sh_stream" ]), {"0" ,"1" }) 288slower ,_ ,_ = run (0.80 ) 289self .assertEqual (slower ["env" ], {}) 290cuda ,_ ,envs = run (1.50 ,hip = False )# not AMD: no step, no engine variable 291self .assertEqual (cuda ["env" ], {}) 292self .assertNotIn ("sh_stream" ,cuda ["report" ]) 293self .assertTrue (all (e == {}for e in envs )) 294 295def test_a_failed_fork_start_keeps_the_default (self ): 296def start (args ,env = None ): 297if (env or {}).get (CAL .SH_STREAM )== "1" : 298raise RuntimeError ("out of memory" ) 299return FakeEngine (args ,lambda f ,p ,w :50.0 ,6 ) 300res = CAL .measure (BASE , [[1 ,2 ,3 ]]* 3 ,start ,say = lambda * _ :None ,hip = True ) 301self .assertEqual (res ["env" ], {}) 302self .assertIn (f" { CAL . SH_STREAM } =1" ,res ["report" ]["failed_starts" ]) 303 304def test_engine_death_during_a_fork_measurement_keeps_the_run (self ): 305# the forked engine exits mid-measurement (#267's class): that candidate loses, the run returns 306def start (args ,env = None ): 307e = FakeEngine (args ,lambda f ,p ,w :50.0 ,6 ) 308if (env or {}).get (CAL .SH_STREAM )== "1" : 309e .dies = True 310return e 311res = CAL .measure (BASE , [[1 ,2 ,3 ]]* 3 ,start ,say = lambda * _ :None ,hip = True ) 312self .assertEqual (res ["env" ], {}) 313self .assertEqual (list (res ["report" ]["sh_stream" ]), ["0" ]) 314self .assertIn (f" { CAL . SH_STREAM } =1" ,res ["report" ]["failed_starts" ]) 315 316def test_apply_env (self ): 317old = {"STRATA_ROCBLAS_TUNING" :"tools/hip" ,CAL .SH_STREAM :"1" } 318self .assertEqual (CAL .apply_env (old , {}), {"STRATA_ROCBLAS_TUNING" :"tools/hip" })# an older choice goes 319self .assertEqual (CAL .apply_env ({"X" :"1" }, {CAL .SH_STREAM :"1" }), {"X" :"1" ,CAL .SH_STREAM :"1" }) 320self .assertEqual (CAL .apply_env (None ,None ), {}) 321 322def test_apply (self ): 323a = CAL .apply (BASE , {"--pcie-frac" :"0.35" ,"--pool-workers" :"4" }) 324self .assertEqual (CAL .arg_value (a ,"--pcie-frac" ),"0.35" ) 325self .assertEqual (CAL .arg_value (a ,"--pool-workers" ),"4" ) 326self .assertEqual (CAL .arg_value (a ,"--spec-min-p" ),"0.5" ) 327b = CAL .apply (a , {})# back to the defaults 328self .assertIsNone (CAL .arg_value (b ,"--pcie-frac" )) 329self .assertIsNone (CAL .arg_value (b ,"--pool-workers" )) 330self .assertEqual (b .count ("--spec-min-p" ),1 ) 331 332def test_engine_args_are_the_servers (self ): 333# #447: a "gpu" list is a layer split only with two or more cards; "0,2" is one too; split_skip_if_fits counts 334helper = {"args" :BASE + ["--expert-cache-device1" ,"1800" ],"gpu" : [0 ],"env" : {"CUDA_VISIBLE_DEVICES" :"0,1" }} 335self .assertEqual (CAL .engine_args (helper ),helper ["args" ])# one stage + a helper card: no split 336self .assertEqual (CAL .engine_args ({"args" :BASE ,"gpu" :1 }),BASE ) 337self .assertEqual (CAL .engine_args ({"args" :BASE ,"gpu" : [0 ,2 ]}),BASE + ["--layer-split" ,"auto" ]) 338self .assertEqual (CAL .engine_args ({"args" :BASE ,"gpu" :"0,2" ,"layer_split" :"18" }), 339BASE + ["--layer-split" ,"18" ]) 340self .assertEqual (CAL .engine_args ({"args" :BASE ,"gpu" : [0 ,1 ],"split_skip_if_fits" :True }), 341BASE + ["--layer-split" ,"auto" ,"--split-skip-if-fits" ]) 342own = BASE + ["--layer-split" ,"" ]# the config's own value wins 343self .assertEqual (CAL .engine_args ({"args" :own ,"gpu" : [0 ,1 ]}),own ) 344 345def test_engine_args_name_the_engine_program_5720 (self ): 346# #5720: the drafter pack follows the engine program (a selector-Q4 pack only for a program that reads it, 347# strata_control/drafting.py pack_path); the calibration must pass the program as the server does, or its 348# sweep engines start with another pack than the server's 349from serve import server 350seen = [] 351 352def fake_apply (shaped ,** kw ): 353seen .append (kw .get ("engine" )) 354pack = "q4_0-selq4.pack" if kw .get ("engine" )else "q4_0.pack" 355shaped ["args" ]= shaped ["args" ]+ ["--draft" ,"dflash2" ,"--draft-model" ,pack ] 356return mock .Mock (note = None ,flags = [],drafter = "dflash2" ) 357 358cfg = {"args" :list (BASE ),"exe" :"/opt/strata/engine/strata" ,"drafting" :"dflash2" } 359with mock .patch .object (server .drafting ,"apply" ,side_effect = fake_apply ), \ 360mock .patch .object (server .drafting ,"detect_hardware" ,return_value = ("cuda" , ["120" ])): 361want = server .engine_args (dict (cfg ),cfg ["exe" ]) 362got = CAL .engine_args (dict (cfg )) 363self .assertEqual (seen , [cfg ["exe" ],cfg ["exe" ]]) 364self .assertEqual (got ,want ) 365self .assertEqual (CAL .arg_value (got ,"--draft-model" ),"q4_0-selq4.pack" ) 366 367def test_run_measures_with_the_servers_args (self ): 368with tempfile .TemporaryDirectory ()as d : 369tok = Path (d ) 370 (tok / "vocab.json" ).write_text (json .dumps ({"a" :0 ,"b" :1 })) 371 (tok / "merges.txt" ).write_text ("" ) 372 (tok / "token_type.json" ).write_text (json .dumps ([1 ,1 ])) 373seen = [] 374saved = CAL .measure 375CAL .measure = lambda args ,ids_list ,start_engine ,say = extra = (),long_prompt = None ,hip = False : ( 376seen .append ((args ,hip ))or {}) 377fake = type ("ST" , (), {"Tokenizer" :lambda * a :type ("T" , (), {"encode" :lambda s ,t ,** k : [0 ]})()}) 378try : 379with mock .patch .dict (sys .modules , {"strata_tokenizer" :fake }): 380CAL .run ({"tokenizer" :d ,"args" :list (BASE ),"gpu" : [0 ]},start_engine = lambda a :None ) 381CAL .run ({"tokenizer" :d ,"args" :list (BASE ),"gpu" : [0 ],"backend" :"hip" },start_engine = lambda a :None ) 382finally : 383CAL .measure = saved 384self .assertEqual (seen , [(BASE ,False ), (BASE ,True )])# the shared-expert step runs on AMD only 385 386def test_engine_error (self ): 387with tempfile .TemporaryDirectory ()as d : 388log = Path (d )/ "strata-x.log" 389log .write_text ("strata generate: an old error\n" ,encoding = "utf-8" ) 390since = log .stat ().st_size 391with open (log ,"a" ,encoding = "utf-8" )as f : 392f .write ("loading ...\nstrata generate: --expert-cache-remote with a layer split needs a GPU that runs " 393"no stage (2 visible, 2 used by the split)\n\n" ) 394self .assertEqual (CAL .engine_error (str (log ),since ),"strata generate: --expert-cache-remote with a layer " 395"split needs a GPU that runs no stage (2 visible, 2 used by the split)" ) 396with open (log ,"a" ,encoding = "utf-8" )as f : 397f .write ("Segmentation fault\n" ) 398self .assertIn ("--expert-cache-remote" ,CAL .engine_error (str (log ),since ))# the engine's own line first 399self .assertEqual (CAL .engine_error (str (log ),log .stat ().st_size ),None )# nothing new since 400self .assertIsNone (CAL .engine_error (None )) 401self .assertIsNone (CAL .engine_error (str (Path (d )/ "missing.log" ))) 402 403def test_worker_candidates (self ): 404self .assertEqual (CAL .worker_candidates (6 ), [6 ,4 ,3 ,2 ]) 405self .assertEqual (CAL .worker_candidates (23 ), [23 ,15 ,12 ,6 ])# a quarter: 4 beat 15 on 8P + 16E 406self .assertEqual (CAL .worker_candidates (23 , (7 ,)), [23 ,15 ,12 ,6 ,7 ])# P-cores - 1 407self .assertEqual (CAL .worker_candidates (35 , (17 ,)), [35 ,23 ,18 ,9 ,17 ])# 2 sockets: one socket's cores - 1 408self .assertEqual (CAL .worker_candidates (6 , (6 ,1 ,9 )), [6 ,4 ,3 ,2 ])# none above the default, none below 2 409self .assertEqual (CAL .worker_candidates (3 ), [3 ,2 ]) 410self .assertEqual (CAL .worker_candidates (1 ), [1 ]) 411 412def test_pick (self ): 413self .assertEqual (CAL .pick ({"a" : [50 ,51 ,49 ],"b" : [53 ,52 ,60 ]},"a" ),"b" ) 414self .assertEqual (CAL .pick ({"a" : [50 ,51 ,49 ],"b" : [51 ,51.5 ,51 ]},"a" ),"a" ) 415self .assertEqual (CAL .pick ({},"a" ),"a" ) 416 417 418class SetupIntegration (unittest .TestCase ): 419def setUp (self ): 420self .tmp = tempfile .TemporaryDirectory () 421self .old = {k :os .environ .get (k )for k in ("APPDATA" ,"XDG_CONFIG_HOME" )} 422os .environ ["APPDATA" ]= self .tmp .name 423os .environ ["XDG_CONFIG_HOME" ]= self .tmp .name 424import setup as S 425self .S = S 426self .saved = (S .gpu_info ,S .cpu_info ,S .ram_gb ,CAL .run ) 427S .gpu_info = lambda pick = None : {"name" :"RTX Test" ,"vram_gb" :12.0 ,"arch" :"120" ,"count" :1 ,"index" :0 } 428S .cpu_info = lambda : ("Test CPU" ,True ,True ) 429S .ram_gb = lambda :64.0 430 431def tearDown (self ): 432self .S .gpu_info ,self .S .cpu_info ,self .S .ram_gb ,CAL .run = self .saved 433for k ,v in self .old .items (): 434if v is None : 435os .environ .pop (k ,None ) 436else : 437os .environ [k ]= v 438self .tmp .cleanup () 439 440def test_calibrate_config_writes_and_remembers (self ): 441cfg_path = Path (self .tmp .name )/ "strata-q2_0.json" 442cfg = {"exe" :"x" ,"args" :list (BASE ),"model_name" :"qwen3.8-flash-next-q2_0" } 443cfg_path .write_text (json .dumps (cfg )) 444CAL .run = lambda c ,say = start_engine = None : {"settings" : {"--pcie-frac" :"0.20" },"report" : {"tok_s" :61.2 }} 445self .assertTrue (self .S .calibrate_config (cfg_path )) 446written = json .loads (cfg_path .read_text ()) 447self .assertEqual (CAL .arg_value (written ["args" ],"--pcie-frac" ),"0.20" ) 448saved = self .S .saved_calibration (written ) 449self .assertEqual (saved ["settings" ], {"--pcie-frac" :"0.20" }) 450# another model on the same PC has no calibration yet 451self .assertIsNone (self .S .saved_calibration ({** written ,"model_name" :"swift-iq2_xs" })) 452# another context size is another key (its KV cache changes the expert cache) 453other = dict (written ,args = CAL .with_arg (written ["args" ],"--max-context" ,"131072" )) 454self .assertIsNone (self .S .saved_calibration (other )) 455 456def test_calibrate_config_writes_the_env_choice (self ): 457# HIP: the measured engine variable goes into the config's "env" and the settings file; a re-run that finds it 458# no longer faster removes it again, and leaves the config's other variables alone 459cfg_path = Path (self .tmp .name )/ "strata-iq3_s.json" 460cfg = {"exe" :"x" ,"args" :list (BASE ),"model_name" :"m" ,"backend" :"hip" ,"env" : {"STRATA_ROCBLAS_TUNING" :"t" }} 461cfg_path .write_text (json .dumps (cfg )) 462CAL .run = lambda c ,say = start_engine = None : {"settings" : {},"env" : {CAL .SH_STREAM :"1" },"report" : {"tok_s" :70.1 }} 463self .assertTrue (self .S .calibrate_config (cfg_path )) 464written = json .loads (cfg_path .read_text ()) 465self .assertEqual (written ["env" ], {"STRATA_ROCBLAS_TUNING" :"t" ,CAL .SH_STREAM :"1" }) 466self .assertEqual (self .S .saved_calibration (written )["env" ], {CAL .SH_STREAM :"1" }) 467CAL .run = lambda c ,say = start_engine = None : {"settings" : {},"env" : {},"report" : {"tok_s" :65.0 }} 468self .assertTrue (self .S .calibrate_config (cfg_path )) 469self .assertEqual (json .loads (cfg_path .read_text ())["env" ], {"STRATA_ROCBLAS_TUNING" :"t" }) 470 471def test_failed_calibration_keeps_defaults (self ): 472cfg_path = Path (self .tmp .name )/ "strata-q2_0.json" 473cfg_path .write_text (json .dumps ({"exe" :"x" ,"args" :list (BASE ),"model_name" :"m" })) 474 475def boom (* a ,** k ): 476raise RuntimeError ("the engine exited before it was ready" ) 477CAL .run = boom 478self .assertFalse (self .S .calibrate_config (cfg_path )) 479self .assertEqual (json .loads (cfg_path .read_text ())["args" ],BASE ) 480self .assertIsNone (self .S .saved_calibration ({"args" :BASE ,"model_name" :"m" })) 481 482def test_failed_calibration_says_the_engines_reason (self ): 483# #447: the engine's last error line is printed, and the --calibrate run repeats the failure before it starts 484import contextlib 485import io 486log = Path (self .tmp .name )/ "strata-q2_0.log" 487log .write_text ("strata generate: an error of an earlier start\n" ,encoding = "utf-8" ) 488cfg_path = Path (self .tmp .name )/ "strata-q2_0.json" 489cfg_path .write_text (json .dumps ({"exe" :"x" ,"args" :list (BASE ),"model_name" :"m" ,"log" :str (log )})) 490 491def boom (* a ,** k ): 492with open (log ,"a" ,encoding = "utf-8" )as f : 493f .write ("strata generate: --expert-cache-remote with a layer split needs a GPU that runs no stage\n" ) 494raise RuntimeError (f"the engine exited before it was ready (see { log } )" ) 495CAL .run = boom 496out = io .StringIO () 497with contextlib .redirect_stdout (out ): 498self .assertFalse (self .S .calibrate_config (cfg_path )) 499self .assertIn ("the engine said: strata generate: --expert-cache-remote with a layer split" ,out .getvalue ()) 500self .assertNotIn ("an earlier start" ,out .getvalue ()) 501out = io .StringIO () 502with mock .patch .object (self .S ,"ROOT" ,Path (self .tmp .name )), \ 503mock .patch .object (self .S ,"data_folder" ,lambda d ,* a ,** k : (Path (self .tmp .name )/ "data" , [])), \ 504mock .patch .object (self .S ,"update_installed_engine" ,lambda * a :None ), \ 505mock .patch .object (sys ,"argv" , ["setup.py" ,"--calibrate" ,"--no-start" ]), \ 506contextlib .redirect_stdout (out ): 507self .assertEqual (self .S .main (),0 ) 508self .assertIn ("this PC is NOT tuned: the tuning failed (the reason is above); the model keeps the default " 509"settings" ,out .getvalue ()) 510 511 512if __name__ == "__main__" : 513unittest .main ()