okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b749503db
main
1"""Tests for setup on a Mac (metal/setup_mac.py and setup.py's hand-over): the Mac check, the pack recommended by 2unified memory, what a bigger choice risks, the engine arguments with the Metal defaults and the config. Runs on any 3PC: sysctl / sw_vers / xcode-select are mocked. No GPU, no network. 4 5python -m unittest tools.test_setup_mac 6""" 7from __future__import annotations 8 9import os 10import subprocess 11import sys 12import tempfile 13import unittest 14from pathlib import Path 15from unittest import mock 16 17ROOT = Path (__file__ ).resolve ().parents [1 ] 18sys .path .insert (0 ,str (ROOT )) 19sys .path .insert (0 ,str (ROOT / "metal" )) 20import setup # noqa: E402 21import setup_mac as M # noqa: E402 22 23 24def fake_run (values :dict ,clt_rc = 0 ): 25def run (cmd ,** kw ): 26if cmd [0 ]== "sysctl" : 27return subprocess .CompletedProcess (cmd ,0 ,values .get (cmd [2 ],"" ),"" ) 28if cmd [0 ]== "sw_vers" : 29return subprocess .CompletedProcess (cmd ,0 ,values .get ("macos" ,"" ),"" ) 30if cmd [0 ]== "xcode-select" : 31return subprocess .CompletedProcess (cmd ,clt_rc ,"/Library/Developer/CommandLineTools" if clt_rc == 0 else "" , 32"" ) 33raise AssertionError (cmd ) 34return run 35 36 37M5 = {"machdep.cpu.brand_string" :"Apple M5 Max" ,"hw.memsize" :str (128 * 2 ** 30 ),"macos" :"27.2" , 38"hw.perflevel0.physicalcpu" :"12" } 39 40 41class MacCheck (unittest .TestCase ): 42def test_reads_chip_memory_macos_and_tools (self ): 43with mock .patch .object (M .platform ,"machine" ,return_value = "arm64" ): 44info = M .mac_info (fake_run (M5 )) 45self .assertEqual (info ["chip" ],"Apple M5 Max" ) 46self .assertAlmostEqual (info ["ram_gb" ],128.0 ) 47self .assertEqual (info ["macos" ],"27.2" ) 48self .assertTrue (info ["arm64" ]) 49self .assertTrue (info ["clt" ]) 50self .assertEqual (M .mac_problems (info ), []) 51 52def test_an_intel_python_on_apple_silicon_is_still_an_apple_silicon_mac (self ):# #3894 53with mock .patch .object (M .platform ,"machine" ,return_value = "x86_64" ): 54info = M .mac_info (fake_run ({** M5 ,"machdep.cpu.brand_string" :"Apple M1 Max" })) 55self .assertTrue (info ["arm64" ]) 56self .assertTrue (info ["rosetta_python" ]) 57self .assertNotIn ("Intel" ," " .join (M .mac_problems (info ))) 58 59def test_intel_old_macos_and_missing_tools_are_named (self ): 60with mock .patch .object (M .platform ,"machine" ,return_value = "x86_64" ): 61info = M .mac_info (fake_run ({** M5 ,"macos" :"14.6" ,"machdep.cpu.brand_string" :"Intel Core i9" },clt_rc = 2 )) 62p = " | " .join (M .mac_problems (info )) 63self .assertIn ("Apple Silicon" ,p ) 64self .assertIn ("macOS 15" ,p ) 65self .assertIn ("xcode-select --install" ,p ) 66 67 68class Recommendation (unittest .TestCase ): 69def test_by_memory (self ): 70# IQ3_S and UD-Q4_K_XL are the recommended sizes; IQ3_S is the default wherever it stays resident 71self .assertEqual (M .RECOMMENDED , ("IQ3_S" ,"UD-Q4_K_XL" )) 72rec ,notes = M .recommend_model (128 ) 73self .assertEqual (rec ,"IQ3_S" ) 74self .assertTrue (any ("UD-Q4_K_XL" in n and "higher quality" in n for n in notes ))# named next to it 75rec96 ,notes96 = M .recommend_model (96 ) 76self .assertEqual (rec96 ,"IQ3_S" ) 77self .assertFalse (notes96 )# UD-Q4_K_XL does not fit 96 GB resident: no note 78self .assertEqual (M .recommend_model (64 )[0 ],"Q2_0" )# no recommended size fits: the largest that does 79self .assertEqual (M .recommend_model (80 )[0 ],"IQ3_XXS" ) 80rec ,notes = M .recommend_model (32 ) 81self .assertEqual (rec ,"Q2_0" ) 82self .assertTrue (notes and "stream" in notes [0 ]and "~14 tok/s" in notes [0 ]) 83self .assertTrue (M .streams ("Q2_0" ,32 )and M .streams ("Q2_0" ,48 )and not M .streams ("Q2_0" ,64 )) 84 85def test_a_bigger_choice_is_kept_with_a_note (self ): 86notes = M .model_note ("IQ3_XXS" ,64 ) 87self .assertTrue (any ("stream from the SSD" in n for n in notes )) 88self .assertEqual (M .model_note ("Q2_0" ,128 ), []) 89self .assertEqual (M .model_note ("IQ3_S" ,128 ), []) 90 91def test_context (self ): 92self .assertEqual (M .recommend_context (64 ),32768 ) 93self .assertEqual (M .recommend_context (128 ),65536 ) 94 95 96class Config (unittest .TestCase ): 97def test_engine_args_carry_the_metal_defaults (self ): 98args = M .engine_args (Path ("/p/packs/q2_0" ), [Path ("/m/a-00001.gguf" ),Path ("/m/a-00002.gguf" )], 99Path ("/d/mtp/rt" ),32768 ) 100self .assertEqual (args [args .index ("--spec" )+ 1 ],"2" ) 101self .assertEqual (args [args .index ("--native" )+ 1 ],str (Path ("/m/a-00001.gguf" ))) 102self .assertEqual (args [args .index ("--ple-gguf" )+ 1 ],str (Path ("/m/a-00002.gguf" ))) 103self .assertEqual (args [args .index ("--mtp" )+ 1 ],str (Path ("/d/mtp/rt" ))) 104self .assertIn ("--expert-profile" ,args ) 105self .assertNotIn ("--hc-q8" ,args )# Q8_0 HC is the engine's own default on Metal 106st = M .engine_args (Path ("/p" ), [Path ("/a1.gguf" ),Path ("/a2.gguf" )],Path ("/d/mtp/rt" ),32768 ,stream = True ) 107self .assertNotIn ("--mtp" ,st )# streaming: one token per step, no draft layer 108self .assertEqual (st [st .index ("--suffix-draft" )+ 1 ],"0" ) 109self .assertEqual (st [st .index ("--spec" )+ 1 ],"2" ) 110# a big Mac that streams (UD-Q5/Q6 on 128 GB) keeps the draft layer, with a longer window 111big = M .engine_args (Path ("/p" ), [Path ("/a1.gguf" ),Path ("/a2.gguf" )],Path ("/d/mtp/rt" ),65536 ,stream = True , 112ram_gb = 128 ) 113self .assertEqual (big [big .index ("--mtp" )+ 1 ],str (Path ("/d/mtp/rt" ))) 114self .assertEqual (big [big .index ("--spec" )+ 1 ],"3" ) 115self .assertEqual (big [big .index ("--suffix-draft" )+ 1 ],"0" ) 116small = M .engine_args (Path ("/p" ), [Path ("/a1.gguf" ),Path ("/a2.gguf" )],Path ("/d/mtp/rt" ),32768 ,stream = True , 117ram_gb = 32 ) 118self .assertNotIn ("--mtp" ,small ) 119self .assertTrue (M .stream_mtp (False ,16 )and M .stream_mtp (True ,128 )and not M .stream_mtp (True ,64 )) 120 121def test_iq3_s_runs_a_three_token_window_with_min_p (self ): 122# M5 Max, MTP, 5 interleaved pairs, identical tokens: --spec 3 --spec-min-p 0.5 over --spec 2: IQ3_S -0.9% / +2.5% / +16.7% / +4.9% 123# (story / code / JSON / agent turn), Q2_0 +0.4% / +11.5% / +6.3% / +1.9% 124shards = [Path ("/m/a-00001.gguf" ),Path ("/m/a-00002.gguf" )] 125iq = M .engine_args (Path ("/p/packs/iq3_s" ),shards ,Path ("/d/mtp/rt" ),32768 ,model = "IQ3_S" ) 126self .assertEqual (iq [iq .index ("--spec" )+ 1 ],"3" ) 127self .assertEqual (iq [iq .index ("--spec-min-p" )+ 1 ],"0.5" ) 128self .assertIn ("--mtp" ,iq ) 129q2 = M .engine_args (Path ("/p/packs/q2_0" ),shards ,Path ("/d/mtp/rt" ),32768 ,model = "Q2_0" ) 130self .assertEqual (q2 [q2 .index ("--spec" )+ 1 ],"3" ) 131self .assertEqual (q2 [q2 .index ("--spec-min-p" )+ 1 ],"0.5" ) 132coder = M .engine_args (Path ("/p/packs/coder" ),shards ,Path ("/d/mtp/rt" ),32768 ,model = "Coder" )# 5 pairs: story -2.5%, code +7.1%, JSON +9.3%, agent +12.5% 133self .assertEqual (coder [coder .index ("--spec" )+ 1 ],"3" ) 134self .assertEqual (coder [coder .index ("--spec-min-p" )+ 1 ],"0.5" ) 135other = M .engine_args (Path ("/p/packs/iq3_xxs" ),shards ,Path ("/d/mtp/rt" ),32768 ,model = "IQ3_XXS" )# not measured: the old default 136self .assertEqual (other [other .index ("--spec" )+ 1 ],"2" ) 137self .assertNotIn ("--spec-min-p" ,other ) 138none = M .engine_args (Path ("/p" ),shards ,Path ("/d/mtp/rt" ),32768 )# no model named: the old default 139self .assertEqual (none [none .index ("--spec" )+ 1 ],"2" ) 140self .assertNotIn ("--spec-min-p" ,none ) 141# a streaming IQ3_S keeps its own rules: no draft layer on a small Mac (spec 2, nothing else), --spec 3 only on a big one 142small = M .engine_args (Path ("/p" ),shards ,Path ("/d/mtp/rt" ),32768 ,stream = True ,ram_gb = 32 ,model = "IQ3_S" ) 143self .assertNotIn ("--spec-min-p" ,small ) 144self .assertEqual (small [small .index ("--spec" )+ 1 ],"2" ) 145big = M .engine_args (Path ("/p" ),shards ,Path ("/d/mtp/rt" ),65536 ,stream = True ,ram_gb = 128 ,model = "IQ3_S" ) 146self .assertEqual (big [big .index ("--spec" )+ 1 ],"3" ) 147self .assertNotIn ("--spec-min-p" ,big ) 148 149def test_fp16_decode_is_the_engines_own_default (self ): 150# STRATA_METAL_F16 for a resident IQ3_S / Q2_0 pack is decided by the engine (metal window.cpp f16_auto_for); setup writes nothing for it 151self .assertFalse (hasattr (M ._fit ,"engine_env" )) 152self .assertFalse (hasattr (M ._fit ,"F16_MODELS" )) 153 154def test_config_is_a_model_config_with_the_metal_backend (self ): 155cfg = M .mac_config (Path ("/r/build-metal/strata" ), ["--pack" ,"x" ],Path ("/p" ),"qwen3.8-flash-next-q2_0" , 156"Q2_0" ,8080 ) 157self .assertEqual (cfg ["backend" ],"metal" ) 158self .assertEqual (cfg ["tokenizer" ],str (Path ("/p" )/ "tokenizer" )) 159self .assertTrue (cfg ["exe" ]and isinstance (cfg ["args" ],list )) 160 161 162class Vision (unittest .TestCase ): 163def test_the_projector_is_pinned_and_the_encoder_builds_with_metal (self ): 164self .assertIn ("mmproj-Qwen3.8-Flash-Next-BF16.gguf" ,M .VISION_SHA256 ) 165src = (ROOT / "metal" / "setup_mac.py" ).read_text (encoding = "utf-8" ) 166self .assertIn ('"-DSTRATA_VISION_CUDA=OFF"' ,src ) 167self .assertIn ('cfg["args"] += ["--vision"]' ,src ) 168 169 170class ExpertsFile (unittest .TestCase ): 171"""The streaming Mac's <model>.experts: written only with room on the disk, else a warning and the GGUF.""" 172 173def run_it (self ,free_gb ,done = False ): 174import tempfile 175sys .path .insert (0 ,str (ROOT / "metal" / "tools" )) 176import stream_experts 177d = Path (tempfile .mkdtemp ()) 178native = d / "m.gguf" 179native .write_bytes (b"" ) 180if done : 181 (d / "m.gguf.experts" ).write_bytes (b"" ) 182 (d / "m.gguf.experts.done" ).write_text ("x" ) 183with mock .patch .object (stream_experts ,"size_bytes" ,return_value = 40e9 ), \ 184mock .patch .object (M .S ,"free_gb" ,return_value = free_gb ), \ 185mock .patch .object (M .S ,"run" )as run ,mock .patch .object (M .S ,"warn" )as warn , \ 186mock .patch .object (M .S ,"mark" )as mark ,mock .patch .object (M .S ,"say" ),mock .patch .object (M .S ,"ok" ): 187M .experts_file (native ) 188return run ,warn ,mark 189 190def test_fits_needs_the_margin (self ): 191self .assertFalse (M .experts_file_fits (40 ,40 + M .EXPERTS_MARGIN_GB - 0.1 )) 192self .assertTrue (M .experts_file_fits (40 ,40 + M .EXPERTS_MARGIN_GB )) 193 194def test_written_and_verified_with_room (self ): 195run ,warn ,mark = self .run_it (100 ) 196self .assertIn ("--verify" ,run .call_args [0 ][0 ]) 197self .assertTrue (str (run .call_args [0 ][0 ][1 ]).endswith ("stream_experts.py" )) 198mark .assert_called_once () 199warn .assert_not_called () 200 201def test_too_little_disk_warns_and_goes_on (self ): 202run ,warn ,mark = self .run_it (45 ) 203run .assert_not_called () 204mark .assert_not_called () 205self .assertIn ("not written" ,warn .call_args [0 ][0 ]) 206 207def test_done_is_not_written_again (self ): 208run ,warn ,mark = self .run_it (100 ,done = True ) 209run .assert_not_called () 210 211 212class V31Sets (unittest .TestCase ): 213"""Round 0214: Unsloth's v3.1 sets on a Mac. One switch (mac_fit.METAL_Q5_0_DOWN) lists the sets with Q5_0 expert downs; until the Metal kernel exists they carry "missing".""" 214NEW = ("UD-IQ1_M" ,"UD-Q2_0" ,"UD-IQ2_XS" ,"UD-Q2_K_XL" ,"UD-IQ3_XXS" ,"UD-Q3_K_XL" ,"UD-IQ4_XS-v31" ) 215Q5_0 = ("UD-IQ2_XS" ,"UD-Q2_K_XL" ,"UD-Q3_K_XL" ,"UD-IQ4_XS-v31" ) 216 217def test_entries_and_files (self ): 218for m in self .NEW : 219d = M .MAC_MODELS [m ] 220self .assertEqual (d ["family" ],"unsloth" ) 221self .assertEqual (d ["shards" ],setup .MODELS [m ]["shards" ]) 222self .assertAlmostEqual (d ["shard1_gb" ],setup .MODELS [m ]["download_gb" ]- 28.8 ,delta = 0.15 )# the download less the n-gram table 223self .assertEqual (M .model_shard_names (m ), [setup .model_file (setup .FAMILIES ["unsloth" ],m ,i )for i in range (1 ,d ["shards" ]+ 1 )]) 224self .assertTrue (all (M .shard_sha (n )for n in M .model_shard_names (m )),m ) 225self .assertIn (m ,M .MAC_ABOUT ) 226 227def test_all_seven_are_listed_now_the_metal_kernel_exists (self ): 228from strata_control import mac_fit 229self .assertTrue (mac_fit .METAL_Q5_0_DOWN )# f-0214-metal: the Q5_0 down kernels 230for m in self .NEW : 231self .assertFalse (mac_fit .MAC_MODELS [m ].get ("missing" ),m ) 232self .assertNotIn ("does not run on this Metal engine yet" ,"" .join (mac_fit .model_note ("UD-Q3_K_XL" ,128 ))) 233 234def test_the_switch_lists_them_all (self ): 235from strata_control import mac_fit 236ns = {"__name__" :"mac_fit_on" ,"__file__" :mac_fit .__file__ } 237src = Path (mac_fit .__file__ ).read_text (encoding = "utf-8" ).replace ("METAL_Q5_0_DOWN = True" ,"METAL_Q5_0_DOWN = False" ) 238exec (compile (src ,mac_fit .__file__ ,"exec" ),ns )# the switch off: the four Q5_0-down sets are held back again 239self .assertEqual ([m for m in self .NEW if ns ["MAC_MODELS" ][m ].get ("missing" )],list (self .Q5_0 )) 240 241 242class HandOver (unittest .TestCase ): 243def test_darwin_hands_the_run_to_setup_mac (self ): 244with mock .patch .object (setup .sys ,"platform" ,"darwin" ), \ 245mock .patch .object (setup .subprocess ,"call" ,return_value = 0 )as call , \ 246mock .patch .object (setup .sys ,"argv" , ["setup.py" ,"--model" ,"Q2_0" ,"--yes" ]): 247self .assertEqual (setup .main (),0 ) 248cmd = call .call_args [0 ][0 ] 249self .assertTrue (cmd [1 ].endswith (str (Path ("metal" )/ "setup_mac.py" ))) 250self .assertEqual (cmd [2 :], ["--model" ,"Q2_0" ,"--yes" ]) 251 252def test_other_platforms_never_reach_it (self ): 253src = (ROOT / "setup.py" ).read_text (encoding = "utf-8" ) 254self .assertIn ('if sys.platform == "darwin":' ,src ) 255with mock .patch .object (setup ,"mac_setup" ,side_effect = AssertionError ("called" )), \ 256mock .patch .object (setup .sys ,"platform" ,"linux" ), \ 257mock .patch .object (setup .sys ,"argv" , ["setup.py" ,"--inspect" ,"x" ]), \ 258mock .patch .object (setup .subprocess ,"run" ,return_value = subprocess .CompletedProcess ([],0 )): 259with self .assertRaises (SystemExit ): 260setup .main () 261 262def test_setup_sh_fetches_a_pinned_python_on_macos_only (self ): 263sh = (ROOT / "setup.sh" ).read_text (encoding = "utf-8" ) 264self .assertIn ('[ "$(uname -s)" = Darwin ]' ,sh ) 265self .assertIn ("83dcb04777c798bd95f3687acf9ae84b09860272ee6bdfb05be8bcf9447f75b8" ,sh ) 266 267 268class RepackGuard (unittest .TestCase ): 269"""No engine beside a repack: the locks, and the resident rule that matches the engine's arena_budget.h.""" 270 271def test_resident_rule_matches_the_engine (self ): 272# the resident cap: Metal's working set (3/4), and on a Mac of 64 GB or more the RAM less 30% 273self .assertAlmostEqual (M .gpu_budget_gb (128 ),128 * 1.073741824 * 0.70 ,places = 3 )# 96.2 GB, as arena_budget.h 274self .assertAlmostEqual (M .gpu_budget_gb (96 ),96 * 1.073741824 * 0.70 ,places = 3 ) 275self .assertAlmostEqual (M .gpu_budget_gb (32 ),32 * 1.073741824 * 0.75 ,places = 3 )# a small Mac: the working set 276self .assertFalse (M .streams ("UD-Q4_K_XL" ,128 ))# 82.6 + 8 GB: resident (measured: nothing compressed) 277self .assertTrue (M .streams ("UD-Q5_K_XL" ,128 )) 278self .assertTrue (M .streams ("UD-Q4_K_XL" ,96 )) 279 280@ unittest . skipIf ( sys . platform == "win32" , "os.kill(pid, 0) is a probe on macOS and Linux only" ) 281def test_a_live_lock_is_seen_a_stale_one_is_dropped (self ): 282import os 283import tempfile 284with tempfile .TemporaryDirectory ()as d : 285d = Path (d ) 286self .assertEqual (M .repack_running (d ), []) 287 (d / "m-metal.gguf.repack.lock" ).write_text (str (os .getppid ()))# a live process that is not us 288self .assertEqual (M .repack_running (d ), [os .getppid ()]) 289 (d / "m-metal.gguf.repack.lock" ).write_text ("999999999" )# no such process 290self .assertEqual (M .repack_running (d ), []) 291self .assertFalse ((d / "m-metal.gguf.repack.lock" ).exists ())# the stale lock was removed 292 (d / M .PREPARE_LOCK ).write_text (str (os .getppid ())) 293self .assertEqual (M .repack_running (d ), [os .getppid ()]) 294 (d / M .PREPARE_LOCK ).write_text (str (os .getpid ()))# our own setup's lock does not stop us 295self .assertEqual (M .repack_running (d ), []) 296 297@ unittest . skipIf ( sys . platform == "win32" , "os.kill(pid, 0) is a probe on macOS and Linux only" ) 298def test_start_refuses_while_a_repack_runs (self ): 299import json 300import os 301import tempfile 302with tempfile .TemporaryDirectory ()as d : 303d = Path (d ) 304gguf ,exe = d / "m-metal.gguf" ,d / "strata" 305gguf .write_bytes (b"x" ) 306exe .write_bytes (b"x" ) 307cfg = d / "strata-x.json" 308cfg .write_text (json .dumps ({"exe" :str (exe ),"args" : ["--native" ,str (gguf )],"port" :8080 })) 309 (d / "m-metal.gguf.repack.lock" ).write_text (str (os .getppid ())) 310with mock .patch .object (M .subprocess ,"call" ,side_effect = AssertionError ("started" )), \ 311mock .patch .object (M .S ,"fail" ,side_effect = SystemExit ("refused" ))as fail : 312with self .assertRaises (SystemExit ): 313M .start (cfg ,None ,False ) 314self .assertIn ("repack is still running" ,fail .call_args [0 ][0 ]) 315 316def test_only_this_users_engine_stops_setup (self ): 317"""On a shared Mac another user's engine is not ours to stop: pgrep is asked for this user's uid only.""" 318seen = [] 319 320def run (cmd ,** kw ): 321seen .append (cmd ) 322return subprocess .CompletedProcess (cmd ,0 ,"4242 " ,"" ) 323with mock .patch .object (M .os ,"getuid" ,return_value = 501 ,create = True ): 324self .assertEqual (M .engine_pids (run ), [4242 ]) 325self .assertEqual (seen , [["pgrep" ,"-u" ,"501" ,"-x" ,"strata" ]]) 326self .assertEqual (M .engine_pids (lambda cmd ,** kw :subprocess .CompletedProcess (cmd ,1 ,"" ,"" )), []) 327 328def test_the_repack_writes_in_bounded_pieces (self ): 329src = (ROOT / "metal" / "tools" / "metal_repack.py" ).read_text (encoding = "utf-8" ) 330self .assertIn ("SYNC_EVERY = 1 << 30" ,src )# flushed every GiB 331self .assertIn ("nocache(o)" ,src )# F_NOCACHE on the output 332self .assertIn ("buffering=0" ,src )# write() is a write 333self .assertNotIn ("mmap" ,src )# no dirty mapping of the output 334 335 336M4 = {"machdep.cpu.brand_string" :"Apple M4" ,"hw.memsize" :str (32 * 2 ** 30 ),"macos" :"27.2" ,"hw.perflevel0.physicalcpu" :"4" } 337 338 339class ControlMode (unittest .TestCase ): 340"""The app on a Mac (STRATA_CONTROL_INSTALL=1): model files and a run config naming the engine component. No source build, no 341metal/setup_mac.py, no Command Line Tools; the Mac rules are strata_control/mac_fit.py's, the module setup_mac.py uses too.""" 342 343def setUp (self ): 344self .tmp = tempfile .TemporaryDirectory () 345self .addCleanup (self .tmp .cleanup ) 346self .home = Path (self .tmp .name ).resolve ()/ "install" 347self .data = Path (self .tmp .name ).resolve ()/ "data" 348self .models = Path (self .tmp .name ).resolve ()/ "own" 349self .home .mkdir () 350self .models .mkdir () 351fam = setup .FAMILIES ["qwen" ] 352self .files = [] 353for i in (1 ,2 ): 354f = self .models / setup .model_file (fam ,"Q2_0" ,i ) 355f .write_bytes (b"x" ) 356f .with_name (f .name + ".done" ).write_text ("whole" ) 357self .files .append (f ) 358 359def run_setup (self ,hw = M4 ,argv = ("--yes" ,"--no-start" ,"--family" ,"qwen" ,"--model" ,"Q2_0" ,"--context" ,"8192" ),clt_rc = 0 ,tool = None ,free = 500.0 ): 360from strata_control import engine_component ,mac_fit 361ran = [] 362 363def fake_tool (cmd ,** kw ): 364ran .append (cmd ) 365pack = Path (cmd [cmd .index ("--out" )+ 1 ]) 366 (pack / "tokenizer" ).mkdir (parents = True ,exist_ok = True ) 367 (pack / "native_experts.txt" ).write_text ("x" ) 368 (pack / "tokenizer" / "vocab.json" ).write_text ("{}" ) 369patches = [ 370mock .patch .object (setup ,"CONTROL" ,True ),mock .patch .object (setup ,"_CONTROL_HOME" ,self .home ), 371mock .patch .object (setup .sys ,"platform" ,"darwin" ), 372mock .patch .object (setup .sys ,"argv" , ["setup.py" ,* argv ,"--data-dir" ,str (self .data ),"--gguf-dir" ,str (self .models )]), 373mock .patch .object (mac_fit ,"mac_info" ,lambda run = None ,_real = mac_fit .mac_info :_real (fake_run (hw ,clt_rc ))), 374mock .patch .object (setup ,"load_settings" ,lambda : {}),mock .patch .object (setup ,"save_settings" ,lambda s :None ), 375mock .patch .object (setup ,"get_llama_cpp" ,lambda :Path (self .tmp .name )/ "llama" ), 376mock .patch .object (setup ,"whole_shard" ,lambda s :True ),mock .patch .object (setup ,"check_shards" ,lambda s :None ), 377mock .patch .object (setup ,"run" ,tool or fake_tool ),mock .patch .object (setup ,"free_gb" ,lambda p :free ), 378mock .patch .object (setup ,"say" ,lambda * a ,** k :self .said .append (" " .join (str (x )for x in a ))), 379mock .patch .object (setup ,"ok" ,lambda * a ,** k :None ), 380mock .patch .object (setup ,"step" ,lambda * a ,** k :None ), 381mock .patch .object (setup ,"warn" ,lambda * a ,** k :self .warnings .append (" " .join (str (x )for x in a ))), 382mock .patch .object (mac_fit .platform ,"machine" ,return_value = "arm64" ), 383mock .patch .object (engine_component ,"resolve" ,side_effect = engine_component .EngineMissing ("no package here" ,None )), 384mock .patch .object (setup ,"mac_setup" ,side_effect = AssertionError ("setup_mac.py must not run in Control mode" )), 385mock .patch .object (setup .subprocess ,"call" ,side_effect = AssertionError ("nothing is started or built" )), 386 ] 387self .warnings ,self .said = [], [] 388for p in patches : 389p .start () 390self .addCleanup (p .stop ) 391rc = setup .main () 392return rc ,ran 393 394def config (self ,tag = "q2_0" ): 395import json 396return json .loads ((self .home / f"strata- { tag } .json" ).read_text (encoding = "utf-8" )) 397 398def test_the_install_writes_a_run_config_for_the_engine_component (self ): 399rc ,ran = self .run_setup () 400self .assertEqual (rc ,0 ) 401cfg = self .config () 402self .assertEqual (cfg ["exe" ],"component:strata-engine" ) 403self .assertEqual (cfg ["backend" ],"metal" ) 404args = cfg ["args" ] 405# a 32 GB Mac streams Q2_0's experts from the SSD: one token per step, no draft layer, the GGUF mapped in place 406self .assertEqual (args [args .index ("--native" )+ 1 ],str (self .files [0 ])) 407self .assertEqual (args [args .index ("--ple-gguf" )+ 1 ],str (self .files [1 ])) 408self .assertIn ("--mmap-experts" ,args ) 409self .assertNotIn ("--mtp" ,args ) 410self .assertEqual (args [args .index ("--suffix-draft" )+ 1 ],"0" ) 411self .assertEqual (args [args .index ("--max-context" )+ 1 ],"8192" ) 412self .assertEqual (cfg ["env" ], {"STRATA_METAL_STREAM" :"1" }) 413self .assertEqual (cfg ["tokenizer" ],str (self .data / "packs" / "q2_0" / "tokenizer" )) 414self .assertEqual (len (ran ),1 ,"only the pack is made (tools/iq_pack.py): no draft layer, no build" ) 415self .assertTrue (ran [0 ][1 ].endswith ("iq_pack.py" )) 416self .assertFalse ((ROOT / "build-metal" ).exists ()and any ((ROOT / "build-metal" ).glob ("*.stamp" ))) 417 418def test_a_model_without_a_draft_layer_is_said_on_a_streaming_mac_too (self ): 419# a feed model whose entry says "drafter: none" (mac_fit's no_mtp) on a Mac that streams (no draft layer there anyway): the model 420# list's line is said as on Windows and Linux (tools/feed_model_install_gate.py; GitHub's macOS runner did not get it) 421from strata_control import mac_fit 422with mock .patch .dict (mac_fit .MAC_MODELS ["Q2_0" ], {"no_mtp" :True }): 423rc ,_ = self .run_setup () 424self .assertEqual (rc ,0 ) 425self .assertIn (" The model list says this model has no draft layer (MTP), so none is fetched or used." ,self .said ) 426self .assertNotIn ("--mtp" ,self .config ()["args" ]) 427rc ,_ = self .run_setup ()# the Flash-Next size itself says nothing of the kind 428self .assertFalse ([s for s in self .said if "model list says" in s ]) 429 430def test_a_big_mac_keeps_the_pack_in_memory_and_adds_the_draft_layer (self ): 431rc ,ran = self .run_setup (hw = M5 ,argv = ("--yes" ,"--no-start" ,"--model" ,"IQ3_XXS" )) 432self .assertEqual (rc ,0 ) 433cfg = self .config ("iq3_xxs" ) 434self .assertIn ("--mtp" ,cfg ["args" ]) 435self .assertEqual (cfg ["env" ], {"STRATA_METAL_STREAM" :"0" }) 436self .assertEqual (cfg ["args" ][cfg ["args" ].index ("--max-context" )+ 1 ],"65536" )# the default context by memory 437 438def test_no_command_line_tools_needed_and_ud_iq1_s_is_not_offered (self ): 439rc ,_ = self .run_setup (clt_rc = 2 ) 440self .assertEqual (rc ,0 ) 441# UD-IQ1_S: never offered. A name the built-in tables do not know is looked up in the signed feed first (a feed model): no feed here 442with self .assertRaises (SystemExit ),mock .patch .object (setup ,"feed_models_setup" ,lambda * a ,** k :None ): 443self .run_setup (argv = ("--yes" ,"--no-start" ,"--model" ,"UD-IQ1_S" )) 444 445def test_gyro_is_offered_on_a_mac_as_one_file_with_a_compat_bf16_pack (self ): 446fam = setup .FAMILIES ["gyro" ] 447g = self .models / setup .model_file (fam ,"Gyro-S" ,1 ) 448g .write_bytes (b"x" ) 449g .with_name (g .name + ".done" ).write_text ("whole" ) 450rc ,ran = self .run_setup (argv = ("--yes" ,"--no-start" ,"--family" ,"gyro" ,"--model" ,"Gyro-S" ,"--context" ,"8192" )) 451self .assertEqual (rc ,0 ) 452cfg = self .config ("gyro-gyro-s" ) 453args = cfg ["args" ] 454self .assertEqual (args [args .index ("--native" )+ 1 ],str (g ),"the one file is the model" ) 455self .assertEqual (args [args .index ("--ple-gguf" )+ 1 ],str (g ),"... and holds its n-gram table" ) 456self .assertEqual (cfg ["backend" ],"metal" ) 457self .assertEqual (cfg ["env" ], {"STRATA_METAL_STREAM" :"1" },"29.7 GB of weights stream on a 32 GB Mac" ) 458self .assertNotIn ("--mtp" ,args ) 459self .assertTrue (ran [0 ][1 ].endswith ("iq_pack.py" )) 460self .assertIn ("--compat-bf16" ,ran [0 ],"Gyro's pack converts the small Q6_K / Q5_K tensors (docs/GYRO.md)" ) 461self .assertEqual (cfg ["tokenizer" ],str (self .data / "packs" / "gyro-gyro-s" / "tokenizer" )) 462 463def test_gyro_m_on_a_small_mac_is_a_warning_not_a_refusal (self ): 464fam = setup .FAMILIES ["gyro" ] 465g = self .models / setup .model_file (fam ,"Gyro-M" ,1 ) 466g .write_bytes (b"x" ) 467g .with_name (g .name + ".done" ).write_text ("whole" ) 468rc ,_ = self .run_setup (argv = ("--yes" ,"--no-start" ,"--family" ,"gyro" ,"--model" ,"Gyro-M" ,"--context" ,"8192" )) 469self .assertEqual (rc ,0 ) 470said = " " .join (self .warnings ) 471self .assertIn ("Gyro-M" ,said ) 472self .assertIn ("stream from the SSD" ,said ) 473self .assertIn ("not been measured on a Mac" ,said ) 474 475def test_other_platforms_and_the_terminal_still_use_their_own_setup (self ): 476src = (ROOT / "setup.py" ).read_text (encoding = "utf-8" ) 477self .assertIn ('if sys.platform == "darwin" and not CONTROL:' ,src ) 478self .assertIn ('if sys.platform == "darwin" and CONTROL:' ,src ) 479 480 481class MacAppUnsloth (unittest .TestCase ): 482"""Round 0214: the Mac app installs Unsloth's sets as the Terminal's setup_mac does: the shards -> ONE GGUF for the GPU (metal_repack.py --verify, the n-gram table 483left out), the pack from that file, --native the repacked file, --ple-gguf the table's shard, --mmap-experts. Header-only fixtures (tests/fixtures/unsloth_v31): no 484Mac, no weights; the repack and the pack tools are recorded, not run.""" 485setUp = ControlMode .setUp 486run_setup = ControlMode .run_setup 487config = ControlMode .config 488NEW = ("UD-IQ1_M" ,"UD-Q2_0" ,"UD-IQ2_XS" ,"UD-Q2_K_XL" ,"UD-IQ3_XXS" ,"UD-Q3_K_XL" ,"UD-IQ4_XS-v31" ) 489 490def shards (self ,model ): 491sys .path .insert (0 ,str (ROOT / "tools" )) 492import unsloth_v31_fixture as FX 493doc = FX .load () 494hub = "UD-IQ4_XS" if model == "UD-IQ4_XS-v31" else model 495for old in self .models .glob ("*" ): 496old .unlink () 497out = [] 498for i ,s in enumerate (doc ["sets" ][hub ]["shards" ]): 499h = s ["header" ]or {"split" : [0 ,len (doc ["sets" ][hub ]["shards" ]),1224 ],"tensors" : []} 500p = FX .materialize ({"header" :h },self .models / s ["name" ],first = (i == 0 )) 501p .with_name (p .name + ".done" ).write_text ("whole" ) 502out .append (p ) 503return out 504 505def tool (self ,ran ): 506def fake (cmd ,** kw ): 507ran .append ([str (x )for x in cmd ]) 508if cmd [1 ].endswith ("metal_repack.py" ): 509Path (cmd [cmd .index ("--out" )+ 1 ]).write_bytes (b"x" ) 510else : 511pack = Path (cmd [cmd .index ("--out" )+ 1 ]) 512 (pack / "tokenizer" ).mkdir (parents = True ,exist_ok = True ) 513 (pack / "native_experts.txt" ).write_text ("x" ) 514 (pack / "tokenizer" / "vocab.json" ).write_text ("{}" ) 515return fake 516 517def install (self ,model ,hw = M5 ,** kw ): 518ran = [] 519engines = kw .pop ("engines" , []) 520with mock .patch .object (setup ,"mac_engine_pids" ,lambda :engines ): 521rc ,_ = self .run_setup (hw = hw ,argv = ("--yes" ,"--no-start" ,"--family" ,"unsloth" ,"--model" ,model ,"--context" ,"8192" ,"--mtp" ,"off" ), 522tool = self .tool (ran ),** kw ) 523return rc ,ran 524 525def test_the_repack_the_pack_and_the_config (self ): 526for model in self .NEW : 527with self .subTest (model = model ): 528files = self .shards (model ) 529shutil_native = self .data / "metal" / f"unsloth- { model . lower () } -metal.gguf" 530if shutil_native .exists (): 531shutil_native .unlink () 532shutil_native .with_name (shutil_native .name + ".done" ).unlink (missing_ok = True ) 533rc ,ran = self .install (model ) 534self .assertEqual (rc ,0 ) 535self .assertEqual (len (ran ),2 ,ran ) 536repack ,pack = ran 537self .assertTrue (repack [1 ].endswith ("metal_repack.py" )) 538self .assertEqual (repack [repack .index ("--shard1" )+ 1 ],str (files [0 ])) 539self .assertEqual (repack [repack .index ("--out" )+ 1 ],str (shutil_native )) 540self .assertIn ("--verify" ,repack ) 541self .assertTrue (pack [1 ].endswith ("iq_pack.py" )) 542self .assertEqual (pack [pack .index ("--gguf" )+ 1 ],str (shutil_native ))# the pack is read from the repacked file 543self .assertIn ("--compat-bf16" ,pack ) 544cfg = self .config ("unsloth-" + model .lower ()) 545a = cfg ["args" ] 546self .assertEqual (cfg ["exe" ],"component:strata-engine" ) 547self .assertEqual (a [a .index ("--native" )+ 1 ],str (shutil_native )) 548self .assertEqual (a [a .index ("--native-dense-gguf" )+ 1 ],str (shutil_native )) 549self .assertEqual (a [a .index ("--ple-gguf" )+ 1 ],str (files [- 1 ]))# the n-gram table: the LAST shard of these sets 550self .assertIn ("--mmap-experts" ,a ) 551self .assertEqual (cfg ["env" ]["STRATA_METAL_STREAM" ],"1" if M .streams (model ,128.0 )else "0" ) 552self .assertEqual (cfg ["tokenizer" ],str (self .data / "packs" / ("unsloth-" + model .lower ())/ "tokenizer" )) 553self .assertEqual (cfg ["model_name" ],"qwen3.8-flash-next-unsloth-" + model .lower ()) 554self .assertFalse ((shutil_native .parent / ".preparing.lock" ).exists (),"the prepare lock is gone" ) 555 556def test_an_already_repacked_set_is_not_repacked_again (self ): 557model = "UD-IQ1_M" 558self .shards (model ) 559native = self .data / "metal" / "unsloth-ud-iq1_m-metal.gguf" 560native .parent .mkdir (parents = True ) 561native .write_bytes (b"x" ) 562setup .mark (native ) 563rc ,ran = self .install (model ) 564self .assertEqual (rc ,0 ) 565self .assertEqual ([str (r [1 ]).replace ("\\" ,"/" ).rsplit ("/" ,1 )[- 1 ]for r in ran ], ["iq_pack.py" ])# (the path is C:\...\iq_pack.py on Windows) 566 567def test_a_running_engine_stops_the_repack_before_anything_is_written (self ): 568self .shards ("UD-IQ1_M" ) 569with self .assertRaises (SystemExit ): 570self .install ("UD-IQ1_M" ,engines = [4242 ]) 571self .assertFalse ((self .data / "metal" ).exists ()and any ((self .data / "metal" ).iterdir ())) 572 573def test_the_apps_hint_for_a_running_engine (self ): 574self .shards ("UD-IQ1_M" ) 575said = [] 576 577def fail (msg ,hint = None ): 578said .append ((msg ,hint )) 579raise SystemExit (1 ) 580with mock .patch .object (setup ,"fail" ,fail ): 581with self .assertRaises (SystemExit ): 582self .install ("UD-IQ1_M" ,engines = [4242 ]) 583self .assertEqual (said [0 ][0 ],"a Strata engine is running (pid 4242): preparing a model beside it can freeze this Mac" ) 584self .assertEqual (said [0 ][1 ],"stop the model in Strata (unload it), then install again" ) 585 586def test_the_disk_check_counts_the_repacked_file (self ): 587self .shards ("UD-IQ1_M" ) 588self .install ("UD-IQ1_M" ,free = 30.0 ) 589said = [w for w in self .warnings if "are needed on the disk" in w ] 590self .assertEqual (len (said ),1 ,self .warnings ) 591self .assertIn ("about 45 GB" ,said [0 ])# nothing to download (the files are here), the 39.2 GB repacked file and 6 GB to work in 592 593def test_a_set_the_engine_cannot_run_is_not_offered (self ): 594from strata_control import mac_fit 595self .shards ("UD-Q3_K_XL" ) 596with mock .patch .dict (mac_fit .MAC_MODELS , {"UD-Q3_K_XL" : {** mac_fit .MAC_MODELS ["UD-Q3_K_XL" ],"missing" :"the Q5_0 expert kernels" }}): 597with self .assertRaises (SystemExit ): 598self .install ("UD-Q3_K_XL" ) 599 600def test_the_bundle_carries_the_repack_tools (self ): 601sys .path .insert (0 ,str (ROOT / "packaging" )) 602import package_terminal as pt 603self .assertEqual (pt .INSTALLER_METAL_TOOLS , ("metal_repack" ,"stream_experts" )) 604for n in pt .INSTALLER_METAL_TOOLS : 605self .assertTrue ((ROOT / "metal" / "tools" / f" { n } .py" ).is_file ()) 606with tempfile .TemporaryDirectory ()as t : 607out = pt .add_installer (Path (t )) 608self .assertIn ("metal/tools/metal_repack.py" ,out ["files" ]) 609self .assertTrue ((Path (t )/ "metal" / "tools" / "stream_experts.py" ).is_file ()) 610 611 612class UpdateFlow (unittest .TestCase ): 613"""update.sh asks the same questions as a setup run but does not download model files: a model chosen there must 614be named, not dropped in silence (an M1 Max picked IQ3_S in update.sh and got no model and no message).""" 615 616def setUp (self ): 617self .tmp = tempfile .TemporaryDirectory () 618self .addCleanup (self .tmp .cleanup ) 619self .data = Path (self .tmp .name ).resolve ()/ "data" 620self .models = Path (self .tmp .name ).resolve ()/ "own" 621self .data .mkdir () 622self .models .mkdir () 623self .said ,self .warned = [], [] 624 625def run_update (self ,argv = ("--update" ,"--model" ,"IQ3_S" ,"--vision" ,"no" ,"--yes" )): 626with mock .patch .object (M ,"mac_configs" ,lambda : []), \ 627mock .patch .object (M .S ,"data_folder_for" ,lambda a : (self .data , [])), \ 628mock .patch .object (M ,"mac_info" ,lambda run = None : {"chip" :"Apple M1 Max" ,"ram_gb" :32.0 , 629"macos" :"26.6.2" ,"arm64" :True ,"clt" :True }), \ 630mock .patch .object (M ,"mac_problems" ,lambda info : []), \ 631mock .patch .object (M .S ,"free_gb" ,lambda p :200.0 ), \ 632mock .patch .object (M .S ,"step" ,lambda * a ,** k :None ), \ 633mock .patch .object (M .S ,"say" ,lambda * a ,** k :self .said .append (" " .join (str (x )for x in a ))), \ 634mock .patch .object (M .S ,"ok" ,lambda * a ,** k :None ), \ 635mock .patch .object (M .S ,"warn" ,lambda * a ,** k :self .warned .append (" " .join (str (x )for x in a ))), \ 636mock .patch .object (M .S ,"pip_install" ,lambda * a ,** k :None ), \ 637mock .patch .object (M .S ,"get_llama_cpp" ,lambda :self .data / "llama" ), \ 638mock .patch .object (M ,"build_engine" ,lambda llama ,jobs = None :self .data / "strata" ), \ 639mock .patch .object (M .S ,"download" ,side_effect = AssertionError ("an update must not download" )): 640return M .main ([* argv ,"--data-dir" ,str (self .data ),"--gguf-dir" ,str (self .models )]) 641 642def test_a_model_chosen_in_an_update_is_named_not_dropped (self ): 643self .assertEqual (self .run_update (),0 ) 644self .assertIn ("IQ3_S is not installed here" ," " .join (self .warned )) 645self .assertIn ("does not download model files" ," " .join (self .warned )) 646self .assertIn ("./setup.sh --setup" ," " .join (self .said )) 647 648def test_an_installed_model_keeps_the_update_quiet (self ): 649for n in M .model_shard_names ("IQ3_S" ): 650f = self .models / n 651f .write_bytes (b"x" ) 652f .with_name (f .name + ".done" ).write_text ("whole" ) 653tag = M .S .FAMILIES ["qwen" ]["tag" ]+ "IQ3_S" 654pack = self .data / "packs" / tag .lower () 655 (pack / "tokenizer" ).mkdir (parents = True ) 656 (pack / "native_experts.txt" ).write_text ("x" ) 657 (pack / "tokenizer" / "vocab.json" ).write_text ("{}" ) 658self .assertEqual (self .run_update (),0 ) 659self .assertFalse ([w for w in self .warned if "not installed here" in w ],self .warned ) 660 661 662class Source (unittest .TestCase ): 663"""setup.py hands a Mac over before its own parser runs, so the Mac parser has to know --source: 664source_hint() recommends it on every platform (#2363).""" 665 666def test_the_source_flag_reaches_strata_source (self ): 667env = mock .patch .dict (os .environ , {},clear = False ) 668env .start () 669self .addCleanup (env .stop ) 670os .environ .pop ("STRATA_SOURCE" ,None ) 671warnings = [] 672# setup.data_folder() is mocked: the real one moves the model files of this checkout and of the data folder in 673# the user's settings.json into --data-dir, and saves that dir as the new data folder; with a temp dir that 674# deletes the models on exit and leaves settings.json pointing at a deleted directory 675with tempfile .TemporaryDirectory ()as tmp , \ 676mock .patch .object (setup ,"data_folder" ,lambda requested ,* a ,** k : (Path (tmp ), [])), \ 677mock .patch ("subprocess.run" ,fake_run (M5 )), \ 678mock .patch .object (setup ,"warn" ,lambda * a ,** k :warnings .append (" " .join (str (x )for x in a ))), \ 679mock .patch .object (setup ,"say" ,lambda * a ,** k :None ), \ 680mock .patch .object (setup ,"ok" ,lambda * a ,** k :None ), \ 681mock .patch .object (setup ,"step" ,lambda * a ,** k :None ): 682M .main (["--source" ,"modelscope" ,"--yes" ,"--check" ,"--data-dir" ,tmp ]) 683self .assertEqual (os .environ .get ("STRATA_SOURCE" ),"modelscope" ) 684self .assertFalse ([w for w in warnings if "--source" in w ], 685f"--source was not used: { warnings } " ) 686 687 688if __name__ == "__main__" : 689unittest .main ()