okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
1"""FIX3 (11-04): three launcher and planning bugs found in round 0211. 2 31. The draft-layer lookup walked up from the model file to a folder named "models" and looked only beside it. With the model folder outside the data 4folder the plan asked for the 5.2 GB layer although <data-dir>/mtp/rt was there (a second download). 52. The all-cards split engine's fit counted each card's size. Cards other programs hold (8 GB free of 96) still got "split + MTP" and the 5.2 GB fetch; the fit 6counts free memory minus the reserve now. 73. The plan's card line gave no way to tell the --gpu number (GPU 2 is card 1) and listed cards CUDA_VISIBLE_DEVICES hides. It counts from 1 like the screens and now adds the number --gpu takes: 8"GPU 2 (--gpu 1)". 9All of it with fake cards and fake sysfs; nothing is started, probed or downloaded. 10""" 11 12from __future__import annotations 13 14import json 15import os 16import subprocess 17import tempfile 18import unittest 19from pathlib import Path 20from unittest import mock 21 22from strata_cli .launch import cmd as launch_cmd 23from strata_cli .launch import modelstate 24from strata_cli .launch import settings as S 25from strata_cli .launch .catalog import Catalog 26from strata_cli .launch .runner import Runner 27from strata_control import discovery ,gpu_roles ,split_engine as SE 28from tests .terminal .launch_support import HW_12 ,Home ,catalog ,run_cli 29from tests .terminal .test_own_files import IQ3XXS ,gguf_bytes 30 31 32class Base (unittest .TestCase ): 33one_card_pc = True # the plan tests run on a fake one-card PC; the others hand their own hardware to catalog() 34 35def setUp (self ): 36self .home = Home ().__enter__ () 37self .addCleanup (self .home .__exit__ ,None ,None ,None ) 38if self .one_card_pc : 39p = mock .patch .object (Catalog ,"hardware" ,lambda self ,fresh = False :dict (HW_12 ,disk_free_gb = 500.0 )) 40p .start () 41self .addCleanup (p .stop ) 42self .tmp = tempfile .TemporaryDirectory (prefix = "strata-fix3-" ) 43self .addCleanup (self .tmp .cleanup ) 44self .base = Path (self .tmp .name ) 45 46def model_files (self ,folder :Path )-> Path : 47folder .mkdir (parents = True ,exist_ok = True ) 48for n in IQ3XXS : 49 (folder / n ).write_bytes (gguf_bytes (["IQ3_XXS" ])) 50return folder 51 52def layer_in (self ,data :Path )-> Path : 53rt = data / "mtp" / "rt" 54rt .mkdir (parents = True ,exist_ok = True ) 55 (rt / "experts.bin" ).write_bytes (b"x" ) 56return rt 57 58def plan_text (self ,* args ): 59code ,out ,err = run_cli (["launch" ,"--plan" ,* args ]) 60self .assertEqual (code ,0 ,err or out ) 61return out 62 63 64# ----------------------------------------------------------------------------------------------------------------------- 1. the draft layer 65 66class DraftLayerInTheDataDir (Base ): 67def test_prepared_beside_looks_in_the_data_dir_when_the_model_folder_is_elsewhere (self ): 68data = self .base / "data" 69rt = self .layer_in (data ) 70first = self .model_files (self .base / "ext" / "models" / "iq3_xxs" )/ IQ3XXS [0 ] 71self .assertIsNone (discovery .prepared_beside (first )["mtp" ],"the old lookup: only beside the models folder" ) 72got = discovery .prepared_beside (first , [data ]) 73self .assertEqual (got ["mtp" ],rt ) 74self .assertEqual (got ["data_dir" ],self .base / "ext" ,"the folder the model sits in is still what data_dir says" ) 75 76def test_a_model_folder_with_no_models_ancestor_finds_it_too (self ): 77data = self .base / "data" 78rt = self .layer_in (data ) 79first = self .model_files (self .base / "somewhere" / "IQ3_XXS" )/ IQ3XXS [0 ] 80got = discovery .prepared_beside (first , [None ,self .base / "nope" ,data ]) 81self .assertEqual ((got ["mtp" ],got ["data_dir" ]), (rt ,None )) 82 83def test_the_layer_beside_the_models_folder_wins_and_nothing_is_invented (self ): 84beside ,data = self .base / "ext" ,self .base / "data" 85mine = self .layer_in (beside ) 86self .layer_in (data ) 87first = self .model_files (beside / "models" / "iq3_xxs" )/ IQ3XXS [0 ] 88self .assertEqual (discovery .prepared_beside (first , [data ])["mtp" ],mine ) 89none = discovery .prepared_beside (self .model_files (self .base / "lone" / "models" / "x" )/ IQ3XXS [0 ], [self .base / "empty" ]) 90self .assertEqual ((none ["mtp" ],none ["pack" ]), (None ,None )) 91 92def test_a_pack_in_the_data_dir_is_found_by_the_models_tag (self ): 93data = self .base / "data" 94 (data / "packs" / "iq3_xxs" ).mkdir (parents = True ) 95first = self .model_files (self .base / "ext" / "models" / "iq3_xxs" )/ IQ3XXS [0 ] 96self .assertIsNone (discovery .prepared_beside (first )["pack" ]) 97self .assertEqual (discovery .prepared_beside (first , [data ])["pack" ],data / "packs" / "iq3_xxs" ) 98 99def test_assess_counts_no_draft_layer_when_data_dir_has_it (self ): 100data = self .base / "data" 101 (data / "packs" / "iq3_xxs" ).mkdir (parents = True ) 102self .layer_in (data ) 103folder = self .model_files (self .base / "ext" / "models" / "iq3_xxs" ) 104c = catalog (HW_12 ) 105with mock .patch .object (Catalog ,"data_dir" ,return_value = self .base / "elsewhere" ): 106st = modelstate .assess (c ,"qwen" ,"IQ3_XXS" ,vision = "off" ,model_path = str (folder ),data_dir = data ) 107self .assertEqual ([p .kind for p in st .parts ], []) 108st = modelstate .assess (c ,"qwen" ,"IQ3_XXS" ,vision = "off" ,model_path = str (folder ),data_dir = self .base / "empty" ) 109self .assertEqual ([p .kind for p in st .parts ], [],"no pack anywhere: the draft layer is not counted either (as before)" ) 110 (self .base / "empty" / "packs" / "iq3_xxs" ).mkdir (parents = True ) 111st = modelstate .assess (c ,"qwen" ,"IQ3_XXS" ,vision = "off" ,model_path = str (folder ),data_dir = self .base / "empty" ) 112self .assertEqual ([p .kind for p in st .parts ], ["mtp" ],"a pack but no layer anywhere: it is still asked for" ) 113 114def test_assess_finds_the_picture_reader_in_the_data_dir_too (self ): 115data = self .base / "data" 116 (data / "packs" / "iq3_xxs" ).mkdir (parents = True ) 117self .layer_in (data ) 118folder = self .model_files (self .base / "ext" / "models" / "iq3_xxs" ) 119with mock .patch .object (Catalog ,"data_dir" ,return_value = self .base / "elsewhere" ): 120st = modelstate .assess (catalog (HW_12 ),"qwen" ,"IQ3_XXS" ,vision = "gpu" ,model_path = str (folder ),data_dir = data ) 121self .assertEqual ([p .kind for p in st .parts ], ["mmproj" ],"a pack in the data dir but no reader anywhere: the reader is asked for" ) 122 (data / "models" ).mkdir () 123 (data / "models" / "mmproj-Qwen3.8-Flash-Next-BF16.gguf" ).write_bytes (b"x" ) 124st = modelstate .assess (catalog (HW_12 ),"qwen" ,"IQ3_XXS" ,vision = "gpu" ,model_path = str (folder ),data_dir = data ) 125self .assertEqual ([p .kind for p in st .parts ], []) 126 127def test_the_remembered_data_dir_counts_when_none_is_given (self ): 128remembered = self .base / "remembered" 129 (remembered / "packs" / "iq3_xxs" ).mkdir (parents = True ) 130self .layer_in (remembered ) 131folder = self .model_files (self .base / "ext" / "models" / "iq3_xxs" ) 132with mock .patch .object (Catalog ,"data_dir" ,return_value = remembered ): 133st = modelstate .assess (catalog (HW_12 ),"qwen" ,"IQ3_XXS" ,vision = "off" ,model_path = str (folder )) 134self .assertEqual ([p .kind for p in st .parts ], []) 135 136# the plan as `strata launch --plan` prints it (check (a)) 137def test_plan_says_nothing_to_download_for_a_model_folder_outside_the_data_dir (self ): 138data = self .base / "data" 139self .layer_in (data ) 140folder = self .model_files (self .base / "ext" / "IQ3_XXS" ) 141with mock .patch .object (Runner ,"existing_data_dir" ,return_value = None ),mock .patch .object (Catalog ,"data_dir" ,return_value = self .base / "emptydata" ): 142out = self .plan_text ("--model-path" ,str (folder ),"--data-dir" ,str (data ),"--vision" ,"off" ) 143self .assertIn ("download Nothing to download: your model files are used where they are." ,out ) 144 145def test_plan_with_a_models_ancestor_outside_the_data_dir_is_the_same (self ): 146data = self .base / "data" 147self .layer_in (data ) 148folder = self .model_files (self .base / "ext" / "models" / "iq3_xxs" ) 149with mock .patch .object (Catalog ,"data_dir" ,return_value = self .base / "emptydata" ): 150out = self .plan_text ("--model-path" ,str (folder ),"--data-dir" ,str (data ),"--vision" ,"off" ) 151self .assertIn ("download Nothing to download: your model files are used where they are." ,out ) 152 153def test_plan_still_asks_for_the_layer_when_no_data_dir_has_it (self ): 154folder = self .model_files (self .base / "ext" / "models" / "iq3_xxs" ) 155with mock .patch .object (Catalog ,"data_dir" ,return_value = self .base / "emptydata" ),mock .patch .object (Runner ,"intel_chosen" ,lambda self :False ):# an Intel Arc in the box that runs the test would plan its own engine 156out = self .plan_text ("--model-path" ,str (folder ),"--data-dir" ,str (self .base / "data" ),"--vision" ,"off" ) 157self .assertIn ("About 5.2 GB to download: the draft layer (5.2 GB)." ,out ) 158 159def test_the_picture_reader_in_the_data_dir_is_found_too (self ): 160data = self .base / "data" 161self .layer_in (data ) 162 (data / "models" ).mkdir () 163 (data / "models" / "mmproj-Qwen3.8-Flash-Next-BF16.gguf" ).write_bytes (b"x" ) 164folder = self .model_files (self .base / "ext" / "IQ3_XXS" ) 165with mock .patch .object (Runner ,"existing_data_dir" ,return_value = None ),mock .patch .object (Catalog ,"data_dir" ,return_value = self .base / "emptydata" ): 166out = self .plan_text ("--model-path" ,str (folder ),"--data-dir" ,str (data ),"--vision" ,"on" ) 167self .assertIn ("download Nothing to download" ,out ) 168 169def test_the_import_preview_sees_the_layer_in_the_data_folder_in_use (self ): 170from strata_control import models 171data = self .base / "inuse" 172rt = self .layer_in (data ) 173first = self .model_files (self .base / "ext" / "models" / "iq3_xxs" )/ IQ3XXS [0 ] 174with mock .patch .object (discovery ,"remembered_data_dirs" ,return_value = [data ]): 175got = models ._already_set_up ([first ], {"family" :"qwen" ,"model" :"IQ3_XXS" }) 176self .assertEqual (got ["mtp" ],str (rt )) 177 178def test_remembered_data_dirs_reads_only_the_folders_that_exist (self ): 179with mock .patch .object (discovery ,"data_dir_choices" ,return_value = [(self .base ,"settings" ), (self .base / "gone" ,"app" ), (self .base ,"documents" )]): 180self .assertEqual (discovery .remembered_data_dirs (), [self .base ]) 181 182def test_dflash2_pack_is_looked_for_in_the_data_dir_that_was_named (self ): 183"""The DFlash2 lookup was never tied to the model folder: it asks the data dir (the one named, else the run config's).""" 184from strata_control import drafting 185data = self .base / "data" 186pack = drafting .target_path (data ) 187pack .parent .mkdir (parents = True ) 188with pack .open ("wb" )as f : 189f .truncate ((1 << 20 )+ 1 ) 190self .assertTrue (drafting .pack_ready (data )) 191self .assertFalse (drafting .pack_ready (self .base / "ext" )) 192r = Runner (S .LaunchSettings (model_path = str (self .model_files (self .base / "ext" / "IQ3_XXS" )),data_dir = str (data ),drafting = "dflash2" ,vision = "off" ), 193catalog = catalog (HW_12 )) 194with mock .patch ("strata_control.drafting.detect_hardware" ,lambda : ("cuda" , ["sm_86" ])): 195want = r .drafting_inputs ({}) 196self .assertEqual (Path (want ["data_dir" ]),data ) 197self .assertFalse (drafting .needs_pack (** want )) 198 199 200# ----------------------------------------------------------------------------------------------------------------------- 2. free memory 201 202def card (i ,total = 98304 ,free = None ,** kw ): 203spec = dict (name = "NVIDIA RTX PRO 6000" ,vram_mib = total ,cc = 120 ,free_mib = free ) 204spec .update (kw ) 205return SE .Card (i ,** spec ) 206 207 208GIB = 1 << 30 209UDQ4 = SE .ModelFacts (routed_types = {"Q4_K" :97 ,"Q5_K" :2 ,"Q5_1" :43 ,"Q8_0" :5 },routed_bytes = int (71.7 * GIB ),embd_type = "Q8_0" ,shexp_types = {"Q8_0" :144 }, 210embd_ram_bytes = int (27.5 * GIB ),layers = 48 ,experts = 512 ) 211 212 213def decide (cards ,model = UDQ4 ,** kw ): 214return SE .decide (enabled = True ,system = "linux" ,cards = cards ,ram_total_gib = 500.0 ,ram_available_gib = 400.0 ,model = model ,** kw ) 215 216 217class SplitFitCountsFreeMemory (unittest .TestCase ): 218def test_free_cards_decide_as_before (self ): 219before = decide ([card (0 ),card (1 )])# free not known: the size counts 220for free in (98304 ,98000 ,97500 ):# an idle card shows a few hundred MiB in use 221d = decide ([card (0 ,free = free ),card (1 ,free = free )]) 222self .assertEqual ((d .use_split ,d .reasons ,d .need_vram_gib ), (before .use_split ,before .reasons ,before .need_vram_gib ),free ) 223self .assertTrue (before .use_split ) 224 225def test_cards_held_to_8_gb_free_do_not_fit_the_experts (self ): 226d = decide ([card (0 ,free = 8192 ),card (1 ,free = 8192 )]) 227self .assertFalse (d .use_split ) 228self .assertTrue (any ("do not fit in the cards' memory" in r for r in d .reasons ),d .reasons ) 229self .assertIn ("has 7 GiB free)" ," " .join (d .reasons ),"free memory minus the 700 MiB reserve, and it says free" ) 230old = decide ([card (0 ,total = 4096 ),card (1 ,total = 4096 )]) 231self .assertIn ("has 4 GiB)" ," " .join (old .reasons ),"free memory not read: the old sentence, the size" ) 232 233def test_one_busy_card_is_enough (self ): 234self .assertFalse (decide ([card (0 ),card (1 ,free = 8192 )]).use_split ) 235 236def test_the_limit_is_free_minus_the_reserve (self ): 237need = decide ([card (0 ),card (1 )]).need_vram_gib * 1024 238edge = int (need )+ SE .FREE_RESERVE_MIB 239self .assertTrue (decide ([card (0 ,free = edge + 8 ),card (1 ,free = edge + 8 )]).use_split ) 240self .assertFalse (decide ([card (0 ,free = edge - 64 ),card (1 ,free = edge - 64 )]).use_split ) 241 242def test_free_cannot_raise_a_card_above_its_size (self ): 243c = card (0 ,total = 1000 ,free = 5000 ) 244self .assertEqual (c .room_mib ,1000 - SE .FREE_RESERVE_MIB ) 245self .assertEqual (card (0 ,total = 1000 ).room_mib ,1000 ,"not known: the size" ) 246 247def test_expected_is_false_on_busy_cards_and_true_on_free_ones (self ): 248ram = lambda : (500.0 ,400.0 )# noqa: E731 249probe = lambda cards_ : (lambda idx :cards_ )# noqa: E731 250self .assertTrue (SE .expected ({},probe = probe ([card (0 ,free = 90000 ),card (1 ,free = 90000 )]),ram = ram ,system = "linux" )) 251self .assertFalse (SE .expected ({},probe = probe ([card (0 ,free = 8192 ),card (1 ,free = 8192 )]),ram = ram ,system = "linux" ),"even a model not on disk needs the 9 GiB" ) 252self .assertTrue (SE .expected ({},probe = probe ([card (0 ),card (1 )]),ram = ram ,system = "linux" )) 253 254def test_a_busy_start_is_quiet_in_auto_and_told_with_on (self ): 255busy = [card (0 ,free = 8192 ),card (1 ,free = 8192 )] 256for m ,quiet in (("auto" ,True ), ("on" ,False )): 257cfg = {"args" : ["--native" ,"/m/x.gguf" ,"--mtp" ,"/m/mtp/rt" ],"exe" :"/e/strata" ,"split_engine" :m } 258with mock .patch .object (SE ,"scan_model" ,lambda p :UDQ4 ): 259d = SE .apply_to_config (cfg ,exe_for_cards = lambda n ,cc = None :"/e/strata-split-2" ,system = "linux" ,probe = lambda i :busy ,ram = lambda : (500.0 ,400.0 )) 260self .assertEqual ((d .use_split ,d .quiet ), (False ,quiet ),m ) 261self .assertNotIn ("split_fallback" ,cfg ,"the run config stays the layer split" ) 262 263def test_the_nvidia_probe_reads_memory_free_in_the_same_call (self ): 264out = "0, NVIDIA RTX PRO 6000, 97887, 12.0, 8123\n1, NVIDIA RTX PRO 6000, 97887, 12.0, [N/A]\n" 265seen = [] 266 267def fake (argv ,** kw ): 268seen .append (argv ) 269return subprocess .CompletedProcess (argv ,0 ,stdout = out ,stderr = "" ) 270with mock .patch ("subprocess.run" ,fake ),mock .patch .dict (os .environ ): 271os .environ .pop ("CUDA_VISIBLE_DEVICES" ,None ) 272got = SE .probe_nvidia_cards () 273self .assertEqual (len (seen ),1 ,"one nvidia-smi call, as before" ) 274self .assertIn ("memory.free" ,seen [0 ][1 ]) 275self .assertEqual ([(c .index ,c .vram_mib ,c .free_mib )for c in got ], [(0 ,97887 ,8123 ), (1 ,97887 ,None )]) 276 277def test_an_old_four_column_answer_still_counts_the_size (self ): 278out = "0, NVIDIA RTX PRO 6000, 97887, 12.0\n1, NVIDIA RTX PRO 6000, 97887, 12.0\n" 279with mock .patch ("subprocess.run" ,lambda argv ,** kw :subprocess .CompletedProcess (argv ,0 ,stdout = out ,stderr = "" )),mock .patch .dict (os .environ ): 280os .environ .pop ("CUDA_VISIBLE_DEVICES" ,None ) 281got = SE .probe_nvidia_cards () 282self .assertEqual ([c .free_mib for c in got ], [None ,None ]) 283self .assertEqual (len (got ),2 ) 284 285def test_the_amd_probe_reads_the_render_nodes_use (self ): 286with tempfile .TemporaryDirectory ()as t : 287root = Path (t ) 288for n , (minor ,used )in enumerate (((128 ,30 * (1 << 30 )), (129 ,1 << 20 ))): 289node = root / f"class/kfd/kfd/topology/nodes/ { n + 1 } " 290 (node / "mem_banks/0" ).mkdir (parents = True ) 291 (node / "properties" ).write_text (f"simd_count 128\ngfx_target_version 120001\nmarketing_name R9700\ndrm_render_minor { minor } \n" ) 292 (node / "mem_banks/0/properties" ).write_text (f"size_in_bytes { 32 * ( 1 << 30 ) } \n" ) 293dev = root / f"class/drm/renderD { minor } /device" 294dev .mkdir (parents = True ) 295 (dev / "mem_info_vram_used" ).write_text (str (used )) 296 (root / "class/kfd/kfd/topology/nodes/0" ).mkdir (parents = True ) 297 (root / "class/kfd/kfd/topology/nodes/0/properties" ).write_text ("simd_count 0\n" ) 298with mock .patch .dict (os .environ ): 299for k in ("ROCR_VISIBLE_DEVICES" ,"HIP_VISIBLE_DEVICES" ): 300os .environ .pop (k ,None ) 301got = SE .probe_amd_cards (root = str (root )) 302self .assertEqual ([(c .index ,c .vram_mib ,c .free_mib )for c in got ], [(0 ,32768 ,2048 ), (1 ,32768 ,32767 )]) 303 304def test_the_amd_probe_without_a_render_node_leaves_free_unknown (self ): 305with tempfile .TemporaryDirectory ()as t : 306node = Path (t )/ "class/kfd/kfd/topology/nodes/0" 307 (node / "mem_banks/0" ).mkdir (parents = True ) 308 (node / "properties" ).write_text ("simd_count 128\ngfx_target_version 120001\n" ) 309 (node / "mem_banks/0/properties" ).write_text (f"size_in_bytes { 32 * ( 1 << 30 ) } \n" ) 310with mock .patch .dict (os .environ ): 311for k in ("ROCR_VISIBLE_DEVICES" ,"HIP_VISIBLE_DEVICES" ): 312os .environ .pop (k ,None ) 313got = SE .probe_amd_cards (root = t ) 314self .assertEqual ([c .free_mib for c in got ], [None ]) 315 316 317class PlanOnBusyCards (Base ): 318"""The plan: busy cards get the layer split with DFlash2 and no 5.2 GB fetch; free cards still get the split with the MTP.""" 319one_card_pc = False 320 321def runner (self ,probe ,** kw ): 322s = S .LaunchSettings (** {"family" :"qwen" ,"model" :"UD-Q4_K_XL" ,"context" :131072 ,"tune" :"skip" ,"vision" :"off" ,"gpus" : [0 ,1 ],** kw }) 323r = Runner (s ,catalog = catalog ({** HW_12 ,"ram_gb" :125.0 ,"engine_vendor" :"nvidia" , 324"gpus" : [{"index" :i ,"name" :"NVIDIA RTX PRO 6000" ,"vram_gb" :96.0 ,"usable" :True ,"vendor" :"nvidia" }for i in range (2 )]})) 325for p in (mock .patch .object (SE ,"probe_cards" ,lambda idx = None :probe ),mock .patch .object (SE ,"ram_gib" ,lambda : (500.0 ,400.0 )), 326mock .patch ("strata_control.drafting.detect_hardware" ,lambda : ("cuda" , ["sm_120" ])), 327mock .patch ("sys.platform" ,"linux" ),# the all-cards split rule asks the host OS (Linux only): this fake PC is Linux 328mock .patch .object (Runner ,"intel_chosen" ,lambda self :False )):# and NVIDIA: the real box's Intel Arc must not make the launch an Intel one 329p .start () 330self .addCleanup (p .stop ) 331return r 332 333def test_busy_cards_resolve_to_dflash2_and_fetch_no_draft_layer (self ): 334r = self .runner ([card (0 ,free = 8192 ),card (1 ,free = 8192 )]) 335self .assertFalse (r .split_expected ()) 336self .assertEqual (r .resolved_drafting ("qwen" ),"dflash2" ) 337kinds = [p ["kind" ]for p in r .download_plan ()["parts" ]] 338self .assertNotIn ("mtp" ,kinds ) 339self .assertNotIn ("MTP" ,r .drafting_plan_line ()) 340 341def test_free_cards_still_resolve_to_the_split_with_the_mtp (self ): 342r = self .runner ([card (0 ,free = 97000 ),card (1 ,free = 97000 )]) 343self .assertTrue (r .split_expected ()) 344self .assertEqual (r .resolved_drafting ("qwen" ),"mtp" ) 345self .assertIn ("mtp" , [p ["kind" ]for p in r .download_plan ()["parts" ]]) 346self .assertEqual (r .drafting_plan_line (),"Drafting: MTP (the all-cards split engine uses the MTP draft layer, 5.2 GB)" ) 347 348def test_a_running_server_of_this_launch_is_not_busy_memory (self ): 349"""build_config runs before the old server is stopped: the memory it holds is given back, so it must not turn the split down on a restart.""" 350busy = [card (0 ,free = 8192 ),card (1 ,free = 8192 )] 351r = self .runner (busy ) 352self .assertIsNone (r .card_probe (),"nothing of ours is running: the engine's own probe" ) 353with mock .patch .object (Runner ,"serving_launches" ,lambda self : [{"profile" :self .profile ,"name" :"x" ,"port" :1 ,"choices" :None }]): 354r = self .runner (busy ) 355probe = r .card_probe () 356self .assertTrue (r .split_expected ()) 357self .assertEqual ([c .free_mib for c in probe (None )], [None ,None ]) 358 359def test_another_launch_on_another_port_is_busy_memory (self ): 360r = self .runner ([card (0 ,free = 8192 ),card (1 ,free = 8192 )]) 361with mock .patch .object (Runner ,"serving_launches" ,lambda self : [{"profile" :"launch-other" ,"name" :"other" ,"port" :int (self .s .port )+ 1 ,"choices" :None }]): 362self .assertIsNone (r .card_probe ()) 363 364 365class AppPlanWhileItsEngineRuns (Base ): 366"""The desktop app asks `drafting plan` before it unloads the running model: `--engines-unloading` says that engine's memory is given back, as Runner.card_probe does.""" 367one_card_pc = False 368 369def plan (self ,* extra ): 370data = self .base / "d" 371data .mkdir (exist_ok = True ) 372busy = [card (0 ,free = 8192 ),card (1 ,free = 8192 )] 373with mock .patch .object (SE ,"probe_cards" ,lambda idx = None :busy ),mock .patch .object (SE ,"ram_gib" ,lambda : (500.0 ,400.0 )),mock .patch ("strata_control.drafting.detect_hardware" ,lambda : ("cuda" , ["sm_120" ])),mock .patch ("sys.platform" ,"linux" ),mock .patch .object (Runner ,"intel_chosen" ,lambda self :False ):# the split rule asks the host OS (Linux only) and the make: this fake PC is Linux and NVIDIA 374code ,out ,err = run_cli (["drafting" ,"plan" ,"--family" ,"qwen" ,"--data-dir" ,str (data ),"--mode" ,"auto" ,"--output" ,"json" ,* extra ]) 375self .assertEqual (code ,0 ,err ) 376return json .loads (out ) 377 378def test_busy_cards_say_dflash2_unless_the_running_engine_is_about_to_be_unloaded (self ): 379p = self .plan () 380self .assertEqual ((p ["split" ],p ["choice" ]), (False ,"dflash2" )) 381p = self .plan ("--engines-unloading" ) 382self .assertEqual ((p ["split" ],p ["choice" ]), (True ,"mtp" )) 383 384 385# ----------------------------------------------------------------------------------------------------------------------- 3. the card numbers 386 387def four (vendor = "nvidia" ): 388return [{"index" :i ,"name" :"NVIDIA RTX A6000" ,"vram_gb" :48.0 ,"usable" :True ,"vendor" :vendor }for i in range (4 )] 389 390 391class CardNumbers (Base ): 392one_card_pc = False 393 394def line (self ,env = None ,vendor = "nvidia" ,cards = None ,** kw ): 395s = S .LaunchSettings (** {"family" :"qwen" ,"model" :"UD-Q4_K_XL" ,** kw }) 396c = catalog ({** HW_12 ,"engine_vendor" :vendor ,"gpus" :cards or four (vendor = vendor )}) 397with mock .patch .dict (os .environ ,env or {}): 398return launch_cmd .roles_line (s ,c ) 399 400def test_describe_keeps_the_screens_count_and_the_plan_adds_the_gpu_flag_number (self ): 401cs = [{"index" :0 ,"name" :"RTX 3060" ,"vram_gb" :12 }, {"index" :1 ,"name" :"RTX 4070 Ti" ,"vram_gb" :12 }] 402self .assertEqual (gpu_roles .describe ({0 :"helper" ,1 :"main" },cs ),"Main: GPU 2 RTX 4070 Ti. Helper: GPU 1 RTX 3060." ) 403self .assertEqual (gpu_roles .describe ({0 :"helper" ,1 :"main" },cs ,card_numbers = True ),"Main: GPU 2 (--gpu 1) RTX 4070 Ti. Helper: GPU 1 (--gpu 0) RTX 3060." ) 404 405def test_gpu_0_1_on_four_cards_with_cuda_visible_devices_0_1 (self ): 406got = self .line ({"CUDA_VISIBLE_DEVICES" :"0,1" },gpus = [0 ,1 ]) 407self .assertEqual (got ,"Main: GPU 2 (--gpu 1) RTX A6000. Helper: GPU 1 (--gpu 0) RTX A6000." ,"no Off cards for the ones the environment hides" ) 408 409def test_without_the_variable_the_other_cards_are_off_with_their_own_numbers (self ): 410got = self .line ({},gpus = [0 ,1 ]) 411self .assertEqual (got ,"Main: GPU 2 (--gpu 1) RTX A6000. Helper: GPU 1 (--gpu 0) RTX A6000. Off: GPU 3 (--gpu 2) RTX A6000, GPU 4 (--gpu 3) RTX A6000." ) 412 413def test_one_visible_card_named_by_number (self ): 414self .assertEqual (self .line ({"CUDA_VISIBLE_DEVICES" :"1" },gpus = [1 ]),"Main: GPU 2 (--gpu 1) RTX A6000." ) 415 416def test_a_named_card_the_environment_hides_stays_because_the_server_sets_visibility_from_it (self ): 417self .assertEqual (self .line ({"CUDA_VISIBLE_DEVICES" :"1" },gpus = [0 ]),"Main: GPU 1 (--gpu 0) RTX A6000. Off: GPU 2 (--gpu 1) RTX A6000." ) 418 419def test_roles_by_number (self ): 420got = self .line ({"CUDA_VISIBLE_DEVICES" :"2,3" },gpu_roles = {"2" :"helper" ,"3" :"main" }) 421self .assertEqual (got ,"Main: GPU 4 (--gpu 3) RTX A6000. Helper: GPU 3 (--gpu 2) RTX A6000." ) 422 423def test_amd_honours_hip_and_rocr (self ): 424amd = four (vendor = "amd" ) 425self .assertEqual (self .line ({"HIP_VISIBLE_DEVICES" :"0,1" },vendor = "amd" ,cards = amd ,gpus = [0 ,1 ]),"Main: GPU 2 (--gpu 1) RTX A6000. Helper: GPU 1 (--gpu 0) RTX A6000." ) 426# ROCR first (cards 1 and 3 of the box), then HIP numbers those: HIP 0 is box card 1 427self .assertEqual (self .line ({"ROCR_VISIBLE_DEVICES" :"1,3" ,"HIP_VISIBLE_DEVICES" :"0" },vendor = "amd" ,cards = amd ,gpus = [1 ]),"Main: GPU 2 (--gpu 1) RTX A6000." ) 428self .assertEqual (self .line ({"ROCR_VISIBLE_DEVICES" :"1,3" },vendor = "amd" ,cards = amd ,gpus = [1 ,3 ]),"Main: GPU 4 (--gpu 3) RTX A6000. Helper: GPU 2 (--gpu 1) RTX A6000." ) 429 430def test_cuda_visible_devices_does_not_hide_amd_cards (self ): 431self .assertEqual (self .line ({"CUDA_VISIBLE_DEVICES" :"0" },vendor = "amd" ,cards = four (vendor = "amd" ),gpus = [0 ,1 ]), 432"Main: GPU 2 (--gpu 1) RTX A6000. Helper: GPU 1 (--gpu 0) RTX A6000. Off: GPU 3 (--gpu 2) RTX A6000, GPU 4 (--gpu 3) RTX A6000." ) 433 434 435class EnvVisible (unittest .TestCase ): 436def test_numbers_and_order (self ): 437ev = lambda v ,env ,** kw :gpu_roles .env_visible ([0 ,1 ,2 ,3 ],v ,env ,** kw )# noqa: E731 438self .assertIsNone (ev ("nvidia" , {})) 439self .assertEqual (ev ("nvidia" , {"CUDA_VISIBLE_DEVICES" :"1,0" },alike = True ), [1 ,0 ]) 440self .assertEqual (ev ("nvidia" , {"CUDA_VISIBLE_DEVICES" :"" }), []) 441self .assertEqual (ev ("nvidia" , {"CUDA_VISIBLE_DEVICES" :"0,9,1" },alike = True ), [0 ],"an entry that is no card ends the list, as CUDA reads it" ) 442 443def test_a_uuid_or_an_ambiguous_order_is_not_guessed (self ): 444self .assertIsNone (gpu_roles .env_visible ([0 ,1 ],"nvidia" , {"CUDA_VISIBLE_DEVICES" :"GPU-1234" },alike = True )) 445self .assertIsNone (gpu_roles .env_visible ([0 ,1 ],"nvidia" , {"CUDA_VISIBLE_DEVICES" :"1" }),"different cards, CUDA's own order: not the nvidia-smi numbers" ) 446self .assertEqual (gpu_roles .env_visible ([0 ,1 ],"nvidia" , {"CUDA_VISIBLE_DEVICES" :"1" ,"CUDA_DEVICE_ORDER" :"PCI_BUS_ID" }), [1 ]) 447self .assertIsNone (gpu_roles .env_visible ([0 ,1 ],"amd" , {"ROCR_VISIBLE_DEVICES" :"GPU-1234" })) 448self .assertIsNone (gpu_roles .env_visible ([0 ,1 ],"intel" , {"CUDA_VISIBLE_DEVICES" :"0" })) 449 450 451class SplitProbeRespectsTheEnvironment (unittest .TestCase ): 452def probe (self ,env ,indexes = None ): 453smi = "" .join (f" { i } , NVIDIA RTX A6000, 49140, 8.6, 48000\n" for i in range (4 )) 454with mock .patch ("subprocess.run" ,lambda argv ,** kw :subprocess .CompletedProcess (argv ,0 ,stdout = smi ,stderr = "" )),mock .patch .dict (os .environ ): 455os .environ .pop ("CUDA_VISIBLE_DEVICES" ,None ) 456os .environ .update (env ) 457return [c .index for c in SE .probe_nvidia_cards (indexes )] 458 459def test_hidden_cards_are_not_counted_when_none_is_named (self ): 460self .assertEqual (self .probe ({"CUDA_VISIBLE_DEVICES" :"0,1" }), [0 ,1 ]) 461self .assertEqual (self .probe ({}), [0 ,1 ,2 ,3 ]) 462 463def test_named_cards_are_kept_as_named (self ): 464self .assertEqual (self .probe ({"CUDA_VISIBLE_DEVICES" :"0,1" }, [2 ,3 ]), [2 ,3 ]) 465 466 467if __name__ == "__main__" : 468unittest .main ()