okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""The DFlash2 option: where the engine can run it, the window it is started with, and the download when there is no internet or the files are already here. 2(tests/terminal/test_drafting.py has the table, the Terminal flag and the pinned download.)""" 3 4from __future__import annotations 5 6import hashlib 7import importlib .util 8import json 9import socket 10import sys 11import tempfile 12import time 13import unittest 14from pathlib import Path 15from unittest import mock 16 17from strata_control import drafting ,drafting_fetch 18from tests .terminal .launch_support import run_cli 19 20ROOT = Path (__file__ ).resolve ().parents [2 ] 21GYRO = "qwen3.8-flash-next-gyro-gyro-s" 22 23 24def serving_dflash2 (): 25return mock .patch .object (drafting ,"ENGINE_SERVES_DFLASH2" ,True ) 26 27 28class IntelCardsAreToldByName (unittest .TestCase ): 29"""The SYCL path gives no architecture: an Intel card is told by its Windows adapter name or its Linux PCI id. Arc A-series (A3xx / A5xx / A7xx) was measured (the A750) 30and counts as tested; B-series (Battlemage), the Pro cards and integrated graphics keep "has not been tested on your graphics card yet".""" 31 32def test_names (self ): 33k = drafting .sycl_arch_of_name 34for name in ("Intel(R) Arc(TM) A750 Graphics" ,"Intel(R) Arc(TM) A380 Graphics" ,"Intel(R) Arc(TM) A770 Graphics" ,"Intel(R) Arc(TM) A580 Graphics" , 35"Intel(R) Arc(TM) A770M Graphics" ,"Intel Arc A310" ): 36self .assertEqual (k (name ),"arc_a" ,name ) 37for name in ("Intel(R) Arc(TM) B580 Graphics" ,"Intel(R) Arc(TM) Pro B60 Graphics" ,"Intel(R) Arc(TM) Pro B50" ,"Intel(R) Arc(TM) B570 Graphics" ): 38self .assertEqual (k (name ),"arc_b" ,name ) 39for name in ("Intel(R) Arc(TM) Pro A60" ,"Intel(R) Arc(TM) Pro A40 Workstation" ): 40self .assertEqual (k (name ),"arc_a_pro" ,name ) 41for name in ("Intel(R) Arc(TM) Graphics" ,"Intel(R) Iris(R) Xe Graphics" ,"Intel(R) UHD Graphics 770" ,"" ,None ): 42self .assertEqual (k (name ),"intel_igpu" ,name ) 43 44def test_pci_ids (self ): 45k = drafting .sycl_arch_of_pci 46for devid in ("56a0" ,"56a1" ,"56a2" ,"56a5" ,"56a6" ,"5690" ,"5692" ,"0x56a1" ): 47self .assertEqual (k ("i915" ,devid ),"arc_a" ,devid ) 48for devid in ("e20b" ,"e211" ,"e221" ,"e223" ): 49self .assertEqual (k ("xe" ,devid ),"arc_b" ,devid ) 50self .assertEqual (k ("i915" ,"56b0" ),"arc_a_pro" ) 51for driver ,devid in (("i915" ,"4680" ), ("i915" ,"a7a0" ), ("xe" ,"7d55" ), ("i915" ,"zz" ), ("" ,"" )): 52self .assertEqual (k (driver ,devid ),"intel_igpu" , (driver ,devid )) 53 54def test_a_series_is_tested_and_the_rest_is_not (self ): 55h = drafting .hardware_support 56self .assertEqual (h ("sycl" , ["arc_a" ]),drafting .Support (True ,"tested" ,drafting .LINE_TESTED )) 57for arch in ("arc_b" ,"arc_a_pro" ,"intel_igpu" ): 58self .assertEqual (h ("sycl" , [arch ]),drafting .Support (True ,"untested" ,drafting .LINE_UNTESTED ),arch ) 59self .assertEqual (h ("sycl" , []).line ,drafting .LINE_UNTESTED ,"no card named: the not-tested line" ) 60self .assertNotIn ("has not been tested" ,h ("sycl" , ["arc_a" ]).line ) 61 62def test_the_probe_gives_the_card_class_on_a_sycl_computer (self ): 63from strata_control import engine_component 64with mock .patch .object (drafting ,"_HARDWARE" , []),mock .patch .object (engine_component ,"detect_backend" ,return_value = ("sycl" ,"test" )),mock .patch .object (engine_component ,"cuda_archs_present" ,return_value = []),mock .patch .object (engine_component ,"hip_archs_present" ,return_value = []),mock .patch .object (drafting ,"sycl_archs_present" ,return_value = ["arc_a" ]): 65self .assertEqual (drafting .detect_hardware (), ("sycl" , ["arc_a" ])) 66with mock .patch .object (drafting ,"_HARDWARE" , []),mock .patch .object (engine_component ,"detect_backend" ,return_value = ("sycl" ,"test" )),mock .patch .object (engine_component ,"cuda_archs_present" ,return_value = []),mock .patch .object (engine_component ,"hip_archs_present" ,return_value = []),mock .patch .object (drafting ,"sycl_archs_present" ,return_value = ["arc_b" ]): 67self .assertEqual (drafting .hardware_support (* drafting .detect_hardware ()).level ,"untested" ) 68 69def test_the_adapters_of_a_windows_pc_and_the_sysfs_cards_of_a_linux_one (self ): 70from strata_control import engine_component ,intel_spec 71adapters = [{"vendor" :"8086" ,"device" :0x56A1 ,"name" :"Intel(R) Arc(TM) A750 Graphics" }, {"vendor" :"10de" ,"device" :1 ,"name" :"NVIDIA GeForce" }, 72 {"vendor" :"8086" ,"device" :0x4680 ,"name" :"Intel(R) UHD Graphics 770" }] 73with mock .patch .object (drafting .os ,"name" ,"nt" ),mock .patch .object (engine_component ,"windows_display_adapters" ,return_value = adapters ): 74self .assertEqual (drafting .sycl_archs_present (), ["arc_a" ,"intel_igpu" ]) 75cards = [{"index" :0 ,"driver" :"i915" ,"devid" :"56a1" }, {"index" :1 ,"driver" :"xe" ,"devid" :"e223" }] 76with mock .patch .object (drafting .os ,"name" ,"posix" ),mock .patch .object (intel_spec ,"sysfs_cards" ,return_value = cards ): 77self .assertEqual (drafting .sycl_archs_present (), ["arc_a" ,"arc_b" ]) 78 79 80class WhereTheEngineCanRunIt (unittest .TestCase ): 81"""DFlash2 exists in the engines of drafting.DFLASH2_BACKENDS (CUDA, HIP, Metal; CMakeLists.txt STRATA_HAVE_DFLASH2): the choice is offered, and applied, only there.""" 82 83def test_the_matrix (self ): 84h = drafting .hardware_support 85for backend in ("" ,None ,"cpu" ): 86self .assertEqual (h (backend , ["sm_120" ]),drafting .Support (False ,"none" ,"" ),backend ) 87self .assertEqual (h ("sycl" , []).level ,"untested" ) 88self .assertEqual ((h ("cuda" , ["sm_120" ]).level ,h ("cuda" , ["sm_121" ]).level ,h ("hip" , ["gfx1151" ]).level ,h ("hip" , ["gfx1201" ]).level ), ("tested" ,)* 4 ) 89self .assertEqual (h ("cuda" , ["sm_86" ]).level ,"slower" ) 90for backend ,arch in (("cuda" ,"sm_75" ), ("cuda" ,"sm_89" ), ("cuda" ,"sm_90" ), ("cuda" ,"sm_61" ), ("hip" ,"gfx1100" ), ("hip" ,"gfx1030" ), ("cuda" ,None ), ("metal" ,None )): 91support = h (backend , [arch ]if arch else []) 92self .assertEqual ((support .can_run ,support .level ,support .line ), (True ,"untested" ,drafting .LINE_UNTESTED ), (backend ,arch )) 93for backend ,arch in (("cuda" ,"sm_120" ), ("cuda" ,"sm_86" ), ("cuda" ,"sm_75" )): 94self .assertTrue (h (backend , [arch ]).line ,"every card that is offered it gets one plain line" ) 95 96def test_no_verdicts_in_the_lines (self ): 97for line in (drafting .LINE_TESTED ,drafting .LINE_SLOWER ,drafting .LINE_UNTESTED ): 98for word in ("recommend" ,"best" ,"better" ,"should" ,"avoid" ): 99self .assertNotIn (word ,line .lower ()) 100 101def test_a_build_without_the_code_keeps_the_mtp_and_downloads_nothing (self ): 102tmp = tempfile .TemporaryDirectory () 103self .addCleanup (tmp .cleanup ) 104with serving_dflash2 (): 105for backend in ("cpu" ,): 106d = drafting .decide ("dflash2" ,klass = "other" ,model_name = GYRO ,data_dir = tmp .name ,backend = backend ,archs = []) 107self .assertEqual ((d .drafter ,d .note ), ("mtp" ,drafting .NOT_THIS_CARD ),backend ) 108self .assertFalse (drafting .needs_pack ("dflash2" ,klass = "other" ,model_name = GYRO ,data_dir = tmp .name ,backend = backend ,archs = []),backend ) 109self .assertTrue (drafting .needs_pack ("dflash2" ,klass = "blackwell" ,model_name = GYRO ,data_dir = tmp .name ,backend = "cuda" ,archs = ["sm_120" ])) 110self .assertEqual (drafting .decide ("auto" ,klass = "other" ,model_name = GYRO ,data_dir = tmp .name ,backend = "cpu" ,archs = []).note ,"" ,"Auto never nags" ) 111 112def test_a_window_or_confidence_the_person_set_by_hand_stays (self ): 113tmp = tempfile .TemporaryDirectory () 114self .addCleanup (tmp .cleanup ) 115pack = drafting .pack_path (tmp .name ) 116pack .parent .mkdir (parents = True ) 117pack .write_bytes (b"x" * (2 << 20 )) 118base = ["--pack" ,"/d/packs/g" ,"--mtp" ,"/d/mtp/rt" ,"--spec" ,"5" ,"--draft-conf" ,"0.5" ] 119with serving_dflash2 (): 120c = {"model_name" :GYRO ,"drafting" :"dflash2" ,"args" :list (base ),"user_args" : ["--spec" ,"5" ,"--draft-conf" ,"0.5" ]} 121drafting .apply (c ,klass = "blackwell" ,data_dir = tmp .name ,backend = "cuda" ,archs = ["sm_120" ]) 122self .assertEqual (c ["args" ][c ["args" ].index ("--spec" )+ 1 ],"5" ) 123self .assertEqual (c ["args" ][c ["args" ].index ("--draft-conf" )+ 1 ],"0.5" ) 124self .assertEqual ((c ["args" ].count ("--spec" ),c ["args" ].count ("--draft-conf" )), (1 ,1 )) 125layer = Path (tmp .name )/ "mtp" / "rt" # the MTP layer is on this computer 126layer .mkdir (parents = True ) 127 (layer / "experts.bin" ).write_bytes (b"e" ) 128base = [* base [:base .index ("--mtp" )+ 1 ],str (layer ),* base [base .index ("--mtp" )+ 2 :]] 129c = {"model_name" :GYRO ,"drafting" :"mtp" ,"args" : [* base ,"--draft" ,"dflash2" ,"--draft-model" ,"/p" ]} 130drafting .apply (c ,klass = "blackwell" ,data_dir = tmp .name ,backend = "cuda" ,archs = ["sm_120" ]) 131self .assertNotIn ("--draft-conf" ,c ["args" ],"back to MTP: DFlash2's confidence goes with it" ) 132self .assertEqual (c ["args" ][c ["args" ].index ("--spec" )+ 1 ],"5" ,"and the MTP window is untouched" ) 133 134def test_the_plan_reports_whether_this_computer_can_run_it (self ): 135tmp = tempfile .TemporaryDirectory () 136self .addCleanup (tmp .cleanup ) 137for hardware ,serves ,level in ((("cuda" , ["sm_120" ]),True ,"tested" ), (("cpu" , []),False ,"none" ), (("sycl" , []),True ,"untested" ), (("metal" , []),True ,"untested" ), (("hip" , ["gfx1201" ]),True ,"tested" )): 138with mock .patch .object (drafting ,"detect_hardware" ,return_value = hardware ): 139code ,out ,err = run_cli (["drafting" ,"plan" ,"--data-dir" ,tmp .name ,"--mode" ,"auto" ,"--output" ,"json" ]) 140self .assertEqual (code ,0 ,err ) 141payload = json .loads (out ) 142self .assertEqual ((payload ["serves" ],payload ["support" ]), (serves ,level ),hardware ) 143 144 145class ConfidenceFollowsTheSlots (unittest .TestCase ): 146"""--draft-conf by the expert slots the card holds once the drafter's 0.8 GB is taken (drafting.CONF_STEPS, measured on l620 and the R9700).""" 147 148def make (self ,args ,user_args = None ): 149tmp = tempfile .TemporaryDirectory () 150self .addCleanup (tmp .cleanup ) 151pack = drafting .pack_path (tmp .name ) 152pack .parent .mkdir (parents = True ) 153pack .write_bytes (b"x" * (2 << 20 )) 154c = {"model_name" :GYRO ,"drafting" :"dflash2" ,"args" :list (args ),"user_args" :list (user_args or [])} 155return c ,tmp .name 156 157def conf (self ,args ,vram_mib = None ,user_args = None ,backend = "cuda" ,archs = ("sm_120" ,)): 158c ,data = self .make (args ,user_args ) 159with serving_dflash2 (),mock .patch .object (drafting ,"detect_hardware" ,return_value = (backend ,list (archs ))): 160drafting .apply (c ,klass = "blackwell" ,data_dir = data ,backend = backend ,archs = list (archs ),vram_mib = vram_mib ) 161self .assertEqual (c ["args" ].count ("--draft-conf" ),1 ) 162return c ["args" ][c ["args" ].index ("--draft-conf" )+ 1 ] 163 164def test_the_steps (self ): 165f = drafting .conf_for_slots 166self .assertEqual ([f (n )for n in (24576 ,12570 ,12000 ,11999 ,7500 ,7499 ,5000 ,3000 ,2999 ,1000 ,300 ,0 )], 167 [0.35 ,0.35 ,0.35 ,0.5 ,0.5 ,0.7 ,0.7 ,0.7 ,0.8 ,0.8 ,0.8 ,0.8 ]) 168self .assertEqual (f (None ),0.35 ,"unknown: today's value" ) 169 170def test_an_explicit_expert_cache_decides (self ): 171base = ["--spec" ,"4" ] 172for given ,want in (("1000" ,"0.8" ), ("300" ,"0.8" ), ("5000" ,"0.7" ), ("8000" ,"0.5" ), ("12570" ,"0.35" ), ("24576" ,"0.35" )): 173self .assertEqual (self .conf ([* base ,"--expert-cache" ,given ]),want ,given ) 174# the steps are in the ENGINE's slots, an --expert-cache N holds about 1.3 N of them (IQ3_S: N = 1,000 -> 1,283 slots, 2,000 -> 2,582, 5,000 -> 6,528, 8,000 -> 10,452) 175for given ,want in (("2000" ,"0.8" ), ("2307" ,"0.8" ), ("2308" ,"0.7" ), ("2500" ,"0.7" ), ("5000" ,"0.7" ), ("5769" ,"0.7" ), ("5770" ,"0.5" ), ("9230" ,"0.5" ), ("9231" ,"0.35" ), ("12000" ,"0.35" )): 176self .assertEqual (self .conf ([* base ,"--expert-cache" ,given ]),want ,"--expert-cache " + given ) 177self .assertEqual (drafting .slots_of (["--expert-cache" ,"1000" ]),1300 ) 178self .assertEqual (drafting .slots_of (["--expert-cache" ,"30000" ]),drafting .MAX_SLOTS ,"never more than every (layer, expert) pair" ) 179self .assertEqual (self .conf ([* base ,"--expert-cache" ,"auto" ]),"0.35" ,"auto with no card reading: today's value" ) 180self .assertEqual (self .conf (base ),"0.35" ,"nothing known: today's value" ) 181 182def test_the_card_decides_when_the_cache_is_auto (self ): 183args = ["--expert-cache" ,"auto" ,"--max-context" ,"131072" ,"--kv" ,"int8" ] 184for vram ,want in ((8192 ,"0.8" ), (12288 ,"0.8" ), (16384 ,"0.7" ), (20480 ,"0.7" ), (24564 ,"0.5" ), (32768 ,"0.35" ), (49152 ,"0.35" ), (73415 ,"0.35" )): 185self .assertEqual (self .conf (args ,vram_mib = vram ),want ,vram ) 186self .assertEqual (self .conf (args ,vram_mib = 32768 ,backend = "hip" ,archs = ("gfx1201" ,)),"0.35" ,"the R9700 (12,570 slots measured) keeps 0.35" ) 187 188def test_the_estimate_matches_the_two_measured_starts (self ): 189n = drafting .expected_slots (32768 , ["--max-context" ,"131072" ,"--kv" ,"int8" ]) 190self .assertAlmostEqual (n ,12570 ,delta = 0.1 * 12570 )# the R9700 start: the DFlash2 is the only drafter, it takes the draft layer's allowance 191self .assertEqual (drafting .expected_slots (4096 , []),0 ,"a card that cannot hold the rest never goes negative" ) 192 193def test_the_persons_own_confidence_stays (self ): 194self .assertEqual (self .conf (["--expert-cache" ,"300" ,"--draft-conf" ,"0.5" ],user_args = ["--draft-conf" ,"0.5" ]),"0.5" ) 195 196def test_a_smaller_context_leaves_more_room (self ): 197big = drafting .expected_slots (16384 , ["--max-context" ,"131072" ]) 198small = drafting .expected_slots (16384 , ["--max-context" ,"32768" ]) 199self .assertGreater (small ,big ) 200 201 202class OfflineAndReuse (unittest .TestCase ): 203"""No internet is a plain sentence in seconds, never a hang; files that are already here are used, not fetched.""" 204 205@classmethod 206def setUpClass (cls ): 207sys .path .insert (0 ,str (ROOT / "tools" )) 208spec = importlib .util .spec_from_file_location ("t_pack2" ,ROOT / "tools" / "test_dflash2_pack.py" ) 209cls .synth = importlib .util .module_from_spec (spec ) 210spec .loader .exec_module (cls .synth ) 211 212def setUp (self ): 213self .tmp = tempfile .TemporaryDirectory () 214self .addCleanup (self .tmp .cleanup ) 215self .dir = Path (self .tmp .name ) 216self .synth .write_safetensors (self .dir / "m.safetensors" ,self .synth .tensors ()) 217 (self .dir / "c.json" ).write_text (json .dumps (self .synth .CFG )) 218self .blobs = {"config.json" : (self .dir / "c.json" ).read_bytes (),"model.safetensors" : (self .dir / "m.safetensors" ).read_bytes ()} 219self .files = tuple ((n ,len (b ),hashlib .sha256 (b ).hexdigest ())for n ,b in self .blobs .items ()) 220self .data = self .dir / "data" 221patcher = mock .patch .object (drafting ,"pack_ready" ,lambda d :bool (d )and drafting .pack_path (d ).is_file ()) 222patcher .start () 223self .addCleanup (patcher .stop ) 224 225def test_no_internet_is_a_plain_sentence_and_nothing_is_left_behind (self ): 226with mock .patch .object (drafting_fetch ,"online" ,return_value = False ),mock .patch .object (drafting_fetch .transfer ,"download" )as download : 227with self .assertRaises (drafting_fetch .DraftingError )as ctx : 228drafting_fetch .ensure (self .data ,files = self .files ) 229self .assertEqual (str (ctx .exception ),"There is no internet connection, so the DFlash2 drafter can't be downloaded now." ) 230download .assert_not_called () 231self .assertFalse (drafting .pack_path (self .data ).exists ()) 232 233def test_the_reachability_check_gives_up_fast_on_a_connection_that_hangs (self ): 234hung = socket .socket () 235hung .bind (("127.0.0.1" ,0 )) 236hung .listen (0 )# the kernel accepts the connection; nobody ever answers 237self .addCleanup (hung .close ) 238started = time .monotonic () 239self .assertFalse (drafting_fetch .online (f"http://127.0.0.1: { hung . getsockname ()[ 1 ] } /x" ,timeout = 1.0 )) 240self .assertLess (time .monotonic ()- started ,5 ) 241self .assertFalse (drafting_fetch .online ("http://127.0.0.1:9/x" ,timeout = 1.0 ),"nothing listens: refused at once" ) 242 243def test_verified_source_files_that_are_already_here_are_used_without_the_network (self ): 244src = drafting .pack_path (self .data ).parent / "src" 245src .mkdir (parents = True ) 246for name ,blob in self .blobs .items (): 247 (src / name ).write_bytes (blob ) 248with mock .patch .object (drafting_fetch ,"online" ,side_effect = AssertionError ("no network needed" )), \ 249mock .patch .object (drafting_fetch .transfer ,"download" ,side_effect = AssertionError ("nothing to download" )): 250out = drafting_fetch .ensure (self .data ,files = self .files ) 251self .assertEqual (out .read_bytes ()[:4 ],b"DF2P" ) 252self .assertFalse (src .exists ()) 253 254def test_a_copy_kept_by_the_hugging_face_tools_is_found_checked_and_never_deleted (self ): 255hub = self .dir / "hub" 256hub .mkdir () 257for name ,blob in self .blobs .items (): 258 (hub / name ).write_bytes (blob ) 259self .assertEqual (set (drafting_fetch ._present ([hub ],self .files )), {"config.json" ,"model.safetensors" }) 260 (hub / "model.safetensors" ).write_bytes (b"corrupt" ) 261self .assertNotIn ("model.safetensors" ,drafting_fetch ._present ([hub ],self .files ),"a copy whose hash differs is never used" ) 262 263def test_the_hub_folders_are_the_pinned_revision_only (self ): 264with mock .patch .dict ("os.environ" , {"HF_HOME" :str (self .dir / "hf" )}): 265folders = drafting_fetch ._hub_snapshots () 266self .assertIn (self .dir / "hf" / "hub" / "models--incoai--Qwen3.8-Flash-Next-DFlash2" / "snapshots" / drafting .REVISION ,folders ) 267 268 269class OneRequestAtATime (unittest .TestCase ): 270"""DFlash2 cannot run beside request slots (--batch); Strata fills slots in by itself, so a choice that means DFlash2 (named, or Auto) means one request.""" 271 272def test_the_choice_that_means_dflash2_on_a_computer_that_can_run_it (self ): 273want = drafting .wants_one_request 274with serving_dflash2 (): 275self .assertTrue (want ("dflash2" ,model_name = GYRO ,backend = "cuda" ,archs = ["sm_121" ])) 276self .assertTrue (want ("DFlash2" ,family = "qwen" ,backend = "hip" )) 277for mode in ("auto" ,None ): 278self .assertTrue (want (mode ,model_name = GYRO ,backend = "cuda" ,archs = ["sm_121" ]),mode ) 279for mode in ("mtp" ,"off" ): 280self .assertFalse (want (mode ,model_name = GYRO ,backend = "cuda" ,archs = ["sm_121" ]),mode ) 281self .assertFalse (want ("dflash2" ,model_name = "qwen3.8-flash-next-coder-iq1_m" ,backend = "cuda" ,archs = ["sm_121" ])) 282self .assertTrue (want ("auto" ,model_name = GYRO ,backend = "sycl" ,archs = []),"Intel runs DFlash2 one request at a time" ) 283self .assertFalse (want ("auto" ,model_name = GYRO ,backend = "cpu" ,archs = [])) 284self .assertTrue (want ("auto" ,model_name = GYRO ,backend = "metal" ,archs = [])) 285with mock .patch .object (drafting ,"ENGINE_SERVES_DFLASH2" ,False ): 286self .assertFalse (want ("dflash2" ,model_name = GYRO ,backend = "cuda" ,archs = ["sm_121" ]),"while the engine does not serve it" ) 287 288 289class TheQ4Pack (unittest .TestCase ): 290"""The owner chose the Q4_0 pack (522 MB, same speed as Q8, less memory): made on the person's computer from the pinned download, checked, and an old Q8 pack keeps working.""" 291 292def test_the_pins (self ): 293self .assertEqual (drafting .PACK_NAME ,"qwen3.8-flash-next-dflash2.q4_0.pack" ) 294self .assertEqual (drafting .PACK_BYTES ,522458112 ) 295self .assertEqual (len (drafting .PACK_SHA256 ),64 ) 296self .assertEqual (drafting .PACK_GB ,0.52 ) 297self .assertEqual (drafting .LEGACY_PACK_NAME ,"qwen3.8-flash-next-dflash2.q8.pack" ) 298 299def test_an_old_q8_pack_is_used_and_never_fetched_again (self ): 300tmp = tempfile .TemporaryDirectory () 301self .addCleanup (tmp .cleanup ) 302folder = Path (tmp .name )/ drafting .FOLDER 303folder .mkdir () 304old = folder / drafting .LEGACY_PACK_NAME 305old .write_bytes (b"x" * (2 << 20 )) 306self .assertEqual (drafting .pack_path (tmp .name ),old ) 307self .assertTrue (drafting .pack_ready (tmp .name )) 308with serving_dflash2 (): 309self .assertFalse (drafting .needs_pack ("dflash2" ,klass = "blackwell" ,model_name = GYRO ,data_dir = tmp .name )) 310self .assertEqual (drafting .decide ("dflash2" ,model_name = GYRO ,data_dir = tmp .name ,backend = "cuda" ).flags [3 ],str (old )) 311with mock .patch .object (drafting_fetch .transfer ,"download" ,side_effect = AssertionError ("no download for a pack that is here" )): 312self .assertEqual (drafting_fetch .ensure (tmp .name ),old ) 313self .assertEqual (drafting .target_path (tmp .name ),folder / drafting .PACK_NAME ,"a new fetch would write the Q4_0 name" ) 314 (folder / drafting .PACK_NAME ).write_bytes (b"y" * (2 << 20 )) 315self .assertEqual (drafting .pack_path (tmp .name ),folder / drafting .PACK_NAME ,"when both are there, the Q4_0 pack is the one used" ) 316 317def test_the_pack_is_made_q4_and_checked_against_its_pins (self ): 318sys .path .insert (0 ,str (ROOT / "tools" )) 319spec = importlib .util .spec_from_file_location ("t_pack3" ,ROOT / "tools" / "test_dflash2_pack.py" ) 320synth = importlib .util .module_from_spec (spec ) 321spec .loader .exec_module (synth ) 322tmp = tempfile .TemporaryDirectory () 323self .addCleanup (tmp .cleanup ) 324d = Path (tmp .name ) 325synth .write_safetensors (d / "m.safetensors" ,synth .tensors ()) 326 (d / "c.json" ).write_text (json .dumps (synth .CFG )) 327files = tuple ((n , (d / f ).stat ().st_size ,hashlib .sha256 ((d / f ).read_bytes ()).hexdigest ())for n ,f in (("config.json" ,"c.json" ), ("model.safetensors" ,"m.safetensors" ))) 328src = d / "data" / drafting .FOLDER / "src" 329src .mkdir (parents = True ) 330 (src / "config.json" ).write_bytes ((d / "c.json" ).read_bytes ()) 331 (src / "model.safetensors" ).write_bytes ((d / "m.safetensors" ).read_bytes ()) 332# not the real pinned files (files=...): the pack is made Q4_0 but the real pins do not apply 333with mock .patch .object (drafting ,"pack_ready" ,lambda x :False ): 334out = drafting_fetch .ensure (d / "data" ,files = files ) 335blob = out .read_bytes () 336self .assertEqual (out .name ,drafting .PACK_NAME ) 337self .assertIn (b"q4_0" ,blob [:4096 ]) 338# with the real list (files=None) a pack whose bytes are not the pinned ones is deleted and the words are plain 339 (d / "data2" ).mkdir () 340with mock .patch .object (drafting_fetch ,"_present" ,lambda folders ,spec : {"config.json" :d / "c.json" ,"model.safetensors" :d / "m.safetensors" }),mock .patch .object (drafting ,"pack_ready" ,lambda x :False ): 341with self .assertRaises (drafting_fetch .DraftingError )as ctx : 342drafting_fetch .ensure (d / "data2" ) 343self .assertIn ("did not pass the safety check" ,str (ctx .exception )) 344self .assertFalse (drafting .target_path (d / "data2" ).exists ()) 345self .assertFalse (drafting .target_path (d / "data2" ).with_suffix (".tmp" ).exists ()) 346# and with the pins set to what this pack really is, it is kept 347pins = {"PACK_BYTES" :len (blob ),"PACK_SHA256" :hashlib .sha256 (blob ).hexdigest ()} 348with mock .patch .object (drafting_fetch ,"_present" ,lambda folders ,spec : {"config.json" :d / "c.json" ,"model.safetensors" :d / "m.safetensors" }),mock .patch .object (drafting ,"pack_ready" ,lambda x :False ),mock .patch .multiple (drafting ,** pins ): 349self .assertEqual (drafting_fetch .ensure (d / "data2" ).read_bytes (),blob ) 350 351 352class TheTerminalStep (unittest .TestCase ): 353"""strata launch: the Drafting step exists only where there is something to choose.""" 354 355def flow (self ,family ,hardware ): 356from types import SimpleNamespace 357from strata_cli .launch .screens import flow_for 358ctx = SimpleNamespace (computer = SimpleNamespace (usable_gpus = [0 ]),settings = SimpleNamespace (family = family )) 359with mock .patch .object (drafting ,"detect_hardware" ,return_value = hardware ),serving_dflash2 (): 360return flow_for (ctx ) 361 362def test_only_flash_next_on_a_cuda_or_hip_engine_gets_the_step (self ): 363flow = self .flow ("qwen" , ("cuda" , ["sm_120" ])) 364self .assertIn ("drafting" ,flow ) 365self .assertEqual (flow .index ("drafting" ),flow .index ("pictures" )+ 1 ) 366self .assertIn ("drafting" ,self .flow ("gyro" , ("hip" , ["gfx1151" ]))) 367self .assertIn ("drafting" ,self .flow ("unsloth" , ("cuda" , ["sm_120" ]))) 368for family in ("swift" ,"coder" ,"nvfp4" ,"qwen36" ,None ): 369self .assertNotIn ("drafting" ,self .flow (family , ("cuda" , ["sm_120" ])),family ) 370self .assertIn ("drafting" ,self .flow ("qwen" , ("sycl" , []))) 371for hardware in (("cpu" , []), (None , [])): 372self .assertNotIn ("drafting" ,self .flow ("qwen" ,hardware ),hardware ) 373 374def test_the_choice_is_saved_as_the_flag_would_and_auto_writes_nothing (self ): 375from types import SimpleNamespace 376from strata_cli .launch import settings as S 377from strata_cli .launch .screens import DraftingScreen 378self .assertEqual ([k for k ,_ in DraftingScreen .CHOICES ],list (S .DRAFTING_MODES )) 379for key ,saved in (("dflash2" ,"dflash2" ), ("auto" ,None ), ("off" ,"off" )): 380fake = SimpleNamespace (ctx = SimpleNamespace (settings = S .LaunchSettings (),base_config = lambda :None ),menu = lambda key = key :SimpleNamespace (current = SimpleNamespace (key = key ))) 381DraftingScreen .commit (fake ) 382self .assertEqual (fake .ctx .settings .drafting ,saved ) 383# the model's file holds the app's older choice: Auto is written, so it wins; the other rows are as before 384for key ,in_file ,saved in (("auto" , {"drafting" :"mtp" },"auto" ), ("auto" , {"drafting" :"auto" },None ), ("auto" , {},None ), ("mtp" , {"drafting" :"dflash2" },"mtp" )): 385fake = SimpleNamespace (ctx = SimpleNamespace (settings = S .LaunchSettings (),base_config = lambda in_file = in_file :in_file ),menu = lambda key = key :SimpleNamespace (current = SimpleNamespace (key = key ))) 386DraftingScreen .commit (fake ) 387self .assertEqual (fake .ctx .settings .drafting ,saved , (key ,in_file )) 388 389def test_the_words_are_the_apps_words (self ): 390folder = ROOT / "apps" / "host" / "src" / "locales" 391en = json .loads ((folder / "df2-en.json" ).read_text (encoding = "utf-8" )) 392self .assertEqual ((en ["df03" ],en ["df04" ],en ["df05" ]), (drafting .LINE_TESTED ,drafting .LINE_SLOWER ,drafting .LINE_UNTESTED )) 393self .assertEqual (en ["df21" ],drafting .LINE_METAL ) 394self .assertEqual (en ["df06" ],drafting .mtp_line (drafting .NOT_THIS_CARD )) 395self .assertEqual (en ["df07" ],"There is no internet connection, so the DFlash2 drafter can't be downloaded now." ) 396self .assertEqual (en ["df09" ],drafting .ONE_REQUEST_NOTE ) 397self .assertEqual (en ["df10" ],drafting .line ("off" ,drafting .NONE_HERE )) 398self .assertEqual (en ["df11" ],drafting .line ("dflash2" ,drafting .NO_MTP )) 399self .assertEqual (en ["df12" ].replace ("{0}" ,"1.2" ),"Choosing DFlash2 downloads its drafter: about 1.2 GB, once." ) 400 401 402if __name__ == "__main__" : 403unittest .main ()