okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6a7187997
main
1"""0.2.2 flow walk, second round (phaseA-tests/flow-findings-022.md): what `strata launch` says and does with your own model files, the 2plan, the download figure, the long silent step and a tuning result that already exists.""" 3 4from __future__import annotations 5 6import json 7import os 8import tempfile 9import unittest 10from pathlib import Path 11from unittest import mock 12 13from strata_cli .launch import settings as S 14from strata_cli .launch .catalog import Catalog 15from strata_cli .launch .runner import LaunchError ,Runner 16from tests .terminal .launch_support import HW_12 ,Home ,run_cli 17from tests .terminal .test_own_files import IQ3XXS ,Q2 ,gguf_bytes 18 19 20class Base (unittest .TestCase ): 21def setUp (self ): 22self .home = Home ().__enter__ () 23self .addCleanup (self .home .__exit__ ,None ,None ,None ) 24p = mock .patch .object (Catalog ,"hardware" ,lambda self ,fresh = False :dict (HW_12 ,disk_free_gb = 500.0 )) 25p .start () 26self .addCleanup (p .stop ) 27self .tmp = tempfile .TemporaryDirectory (prefix = "strata-flow2-" ) 28self .addCleanup (self .tmp .cleanup ) 29self .base = Path (self .tmp .name ) 30 31def files (self ,folder :Path ,names :list [str ],kind :str )-> Path : 32folder .mkdir (parents = True ,exist_ok = True ) 33for n in names : 34 (folder / n ).write_bytes (gguf_bytes ([kind ])) 35return folder 36 37def runner (self ,** kw )-> Runner : 38return Runner (S .LaunchSettings (** kw ),catalog = Catalog (hardware = HW_12 )) 39 40 41class MissingOwnFiles (Base ): 42"""Finding 2: a --model-path that is not there, or holds no model, is said in plain words before anything starts.""" 43 44def test_a_folder_that_does_not_exist_is_named_and_nothing_is_promised (self ): 45missing = self .base / "models" 46code ,out ,err = run_cli (["launch" ,"--plan" ,"--model-path" ,str (missing )]) 47self .assertEqual (code ,2 ) 48self .assertIn (f"This folder does not exist: { missing } " ,err ) 49self .assertNotIn ("Qwen" ,err ) 50self .assertNotIn ("continues where it stopped" ,err ) 51self .assertNotIn ("could not be installed" ,err ) 52 53def test_a_missing_file_says_file (self ): 54code ,out ,err = run_cli (["launch" ,"--plan" ,"--model-path" ,str (self .base / "x-00001-of-00002.gguf" )]) 55self .assertEqual (code ,2 ) 56self .assertIn ("This file does not exist" ,err ) 57 58def test_an_empty_folder_says_there_are_no_gguf_files (self ): 59empty = self .base / "empty" 60empty .mkdir () 61code ,out ,err = run_cli (["launch" ,"--plan" ,"--model" ,"q2_0" ,"--model-path" ,str (empty )]) 62self .assertEqual (code ,2 ) 63self .assertIn ("no .gguf model files" ,err ) 64self .assertIn ("...-00001-of-00002.gguf" ,err ) 65 66def test_machine_output_carries_the_same_words (self ): 67code ,out ,err = run_cli (["launch" ,"--plan" ,"--output" ,"json" ,"--model-path" ,str (self .base / "gone" )]) 68self .assertEqual (code ,2 ) 69self .assertIn ("This folder does not exist" ,json .loads (out )["error" ]["message" ]) 70 71def test_the_engine_is_not_touched_for_a_wrong_path (self ): 72r = self .runner (model_path = str (self .base / "gone" )) 73with mock .patch .object (Runner ,"ensure_engine" ,side_effect = AssertionError ("engine step must not start" )): 74with self .assertRaises (LaunchError )as ctx : 75r .run () 76self .assertEqual (ctx .exception .code ,2 ) 77self .assertIn ("does not exist" ,ctx .exception .text ) 78 79def test_the_failure_hint_of_own_files_promises_no_download (self ): 80r = self .runner (model_path = str (self .files (self .base / "m" ,Q2 ,"Q2_0" )),family = "qwen" ,model = "Q2_0" ) 81proc = mock .Mock () 82proc .stdout = iter (["=== Step 5: Getting the model files ===" ,"[X] missing /m/x.gguf" ]) 83proc .wait .return_value = 1 84with mock .patch .object (Runner ,"_spawn" ,return_value = proc ),mock .patch .object (Runner ,"adopt_prepared_files" ,return_value = None ): 85with self .assertRaises (LaunchError )as ctx : 86r .ensure_model () 87self .assertNotIn ("download" ,ctx .exception .next ) 88self .assertIn ("finished steps are skipped" ,ctx .exception .next ) 89 90def test_the_screens_say_the_same (self ): 91from strata_control import models 92text ,nxt = models .own_path_problem (str (self .base / "nope" )) 93self .assertIn ("This folder does not exist" ,text ) 94self .assertIn ("Nothing was downloaded" ,nxt ) 95self .assertIsNone (models .own_path_problem (str (self .files (self .base / "ok" ,IQ3XXS ,"IQ3_XXS" )))) 96 97def test_a_folder_one_level_above_the_files_is_not_called_empty (self ): 98self .files (self .base / "repo" / "IQ3_XXS" ,IQ3XXS ,"IQ3_XXS" ) 99from strata_control import models 100self .assertIsNone (models .own_path_problem (str (self .base / "repo" ))) 101 102 103class LinkedShards (Base ): 104"""Finding 3: shards that are links are accepted with no --model, as with --model, and a problem is said once.""" 105 106def links (self ,names :list [str ],real :bool = True )-> Path : 107blobs = self .base / "blobs" 108snap = self .base / "snap" 109blobs .mkdir (exist_ok = True ) 110snap .mkdir (exist_ok = True ) 111for i ,n in enumerate (names ): 112target = blobs / f"sha { i } " 113if real : 114target .write_bytes (gguf_bytes (["Q2_0" ])) 115try : 116os .symlink (target ,snap / n ) 117except (OSError ,NotImplementedError ): 118self .skipTest ("this account cannot create symbolic links" ) 119return snap 120 121def test_linked_shards_without_a_model_name_are_used (self ): 122snap = self .links (Q2 ) 123code ,out ,err = run_cli (["launch" ,"--plan" ,"--output" ,"json" ,"--model-path" ,str (snap )]) 124self .assertEqual (code ,0 ,err or out ) 125s = json .loads (out )["plan" ]["settings" ] 126self .assertEqual ((s ["family" ],s ["model" ]), ("qwen" ,"Q2_0" )) 127self .assertEqual (Path (s ["model_path" ]),snap )# the link names stay (the shard names are what setup reads) 128 129def test_linked_shards_with_the_model_named_give_the_same_folder (self ): 130snap = self .links (Q2 ) 131code ,out ,err = run_cli (["launch" ,"--plan" ,"--output" ,"json" ,"--model" ,"q2_0" ,"--model-path" ,str (snap )]) 132self .assertEqual (code ,0 ,err or out ) 133self .assertEqual (Path (json .loads (out )["plan" ]["settings" ]["model_path" ]),snap ) 134 135def test_links_to_nothing_are_one_sentence_not_one_per_file (self ): 136snap = self .links (Q2 ,real = False ) 137code ,out ,err = run_cli (["launch" ,"--plan" ,"--model-path" ,str (snap )]) 138self .assertEqual (code ,5 ) 139self .assertEqual (err .count ("shortcut" ),1 ,err ) 140self .assertIn (Q2 [0 ],err ) 141self .assertIn (Q2 [1 ],err ) 142 143def test_the_same_problem_for_many_files_is_said_once (self ): 144from strata_control import models 145issues = [f"m-0000 { i } -of-00005.gguf: GGUF metadata is truncated" for i in range (1 ,6 )]+ ["incomplete_or_invalid_shard_set" ] 146words = models .problem_words (issues ) 147self .assertEqual (words .count ("the file is cut short" ),1 ) 148self .assertIn ("m-00001-of-00005.gguf, m-00002-of-00005.gguf and 3 more files" ,words ) 149self .assertEqual (models .problem_words (["a.gguf: GGUF metadata is truncated" ,"b.gguf: GGUF metadata is truncated" ]), 150"a.gguf and b.gguf: the file is cut short (a download or copy that did not finish)" ) 151self .assertEqual (models .problem_words (["multiple_model_groups" ,"unrecognized_or_unsupported_model_variant" ]), 152"the folder holds more than one model" ) 153many = [f"unsupported_or_missing_architecture" ,"incomplete_or_invalid_shard_set" ,"multiple_model_groups" , 154"unsupported_or_incomplete_tokenizer_metadata" ,"missing_or_unexpected_expert_quantization" ] 155self .assertTrue (models .problem_words (many ).endswith ("and 2 more problems" )) 156 157 158 159class PlanWords (Base ): 160"""Findings 1 and 7: --plan shows the real model, the picture setting, a copyable line, and what would be downloaded.""" 161 162def setUp (self ): 163super ().setUp () 164from tests .terminal .launch_support import not_intel 165not_intel (self ) 166 167def plan_text (self ,* args ): 168code ,out ,err = run_cli (["launch" ,"--plan" ,* args ]) 169self .assertEqual (code ,0 ,err or out ) 170return out 171 172def test_own_files_show_the_model_they_are (self ): 173folder = self .files (self .base / "IQ3_XXS" ,IQ3XXS ,"IQ3_XXS" ) 174out = self .plan_text ("--model-path" ,str (folder )) 175self .assertIn ("Plan for 'IQ3_XXS" ,out ) 176self .assertNotIn ("model default" ,out ) 177self .assertNotIn ("None" ,out ) 178self .assertIn ("Qwen3.8-Flash-Next IQ3_XXS" ,out ) 179self .assertIn (f"your files in { folder } " ,out ) 180self .assertRegex (out ,r"pictures (on|off)" ) 181self .assertIn ("--model iq3_xxs" ,out .split ("same as" )[1 ])# the copyable line names the model too 182self .assertIn (f'--model-path " { folder } "' ,out .split ("same as" )[1 ]) 183 184def test_a_named_catalog_model_shows_its_size_and_the_download (self ): 185out = self .plan_text ("--model" ,"q2_0" ) 186self .assertIn ("Qwen3.8-Flash-Next Q2_0, 66 GB" ,out ) 187self .assertRegex (out ,r"download\s+About 7\d\.\d GB to download: the model \(66\.4 GB\), the draft layer \(5\.2 GB\)" ) 188self .assertIn ("The engine for your graphics card is downloaded first" ,out ) 189 190def test_nothing_is_downloaded_when_everything_is_here (self ): 191folder = self .files (self .base / "IQ3_XXS" ,IQ3XXS ,"IQ3_XXS" ) 192data = self .base / "Strata" 193 (data / "models" / "x" ).mkdir (parents = True ) 194 (data / "mtp" / "rt" ).mkdir (parents = True ) 195 (data / "mtp" / "rt" / "experts.bin" ).write_bytes (b"x" ) 196 (data / "models" / "mmproj-Qwen3.8-Flash-Next-BF16.gguf" ).write_bytes (b"x" ) 197# the files sit under <data>/models/<tag>: the draft layer and the picture reader are found beside them 198moved = data / "models" / "iq3_xxs" 199folder .rename (moved ) 200out = self .plan_text ("--model-path" ,str (moved )) 201self .assertIn ("download Nothing to download: your model files are used where they are." ,out ) 202 203def test_own_files_with_no_draft_layer_say_what_is_fetched (self ): 204folder = self .files (self .base / "IQ3_XXS" ,IQ3XXS ,"IQ3_XXS" ) 205with mock .patch .object (Runner ,"existing_data_dir" ,return_value = None ),mock .patch .object (Catalog ,"data_dir" ,return_value = self .base / "emptydata" ): 206out = self .plan_text ("--model-path" ,str (folder ),"--vision" ,"off" ) 207self .assertIn ("About 5.2 GB to download: the draft layer (5.2 GB). Your model files are used where they are." ,out ) 208 209def test_a_model_whose_files_are_all_on_disk_does_not_list_a_zero_download (self ): 210from strata_cli .launch .modelstate import ModelState ,Part 211data = self .base / "d" 212 (data / "mtp" / "rt" ).mkdir (parents = True ) 213 (data / "mtp" / "rt" / "experts.bin" ).write_bytes (b"x" ) 214whole = ModelState (installed = False ,parts = [Part ("weights" ,"the model" ,0.0 )],on_disk_gb = 66.4 ,total_gb = 66.4 ) 215with mock .patch .object (Runner ,"model_state" ,return_value = whole ): 216out = self .plan_text ("--model" ,"q2_0" ,"--data-dir" ,str (data ),"--vision" ,"off" ) 217self .assertIn ("download Nothing to download: the model is already on this computer." ,out ) 218out = self .plan_text ("--model" ,"q2_0" ,"--data-dir" ,str (self .base / "other" ),"--vision" ,"off" ) 219self .assertIn ("About 5.2 GB to download: the draft layer (5.2 GB). 66 GB of the model is already in its folder." ,out ) 220self .assertNotIn ("0.0 GB" ,out ) 221 222def test_json_plan_carries_the_numbers (self ): 223code ,out ,err = run_cli (["launch" ,"--plan" ,"--output" ,"json" ,"--model" ,"q2_0" ,"--mtp" ,"off" ,"--vision" ,"off" ]) 224self .assertEqual (code ,0 ,err ) 225plan = json .loads (out )["plan" ] 226self .assertEqual (plan ["model" ]["title" ],"Qwen3.8-Flash-Next Q2_0" ) 227self .assertEqual (plan ["model" ]["model_gb" ],66.4 ) 228self .assertEqual (plan ["download" ]["gb" ],66.4 ) 229self .assertEqual ([p ["kind" ]for p in plan ["download" ]["parts" ]], ["weights" ]) 230 231 232 233class DownloadTotal (Base ): 234"""Finding 4: the figure counts every shard (and the picture reader), in the folder the setup is really given.""" 235 236def run_lines (self ,runner :Runner ,lines :list [str ])-> list [str ]: 237seen :list [str ]= [] 238runner .emit_cb = lambda ev :seen .append (ev .text ) 239proc = mock .Mock () 240proc .stdout = iter (lines ) 241proc .wait .return_value = 1 # stop after the lines: the failure path is not what is looked at 242with mock .patch .object (Runner ,"_spawn" ,return_value = proc ),mock .patch .object (Runner ,"adopt_prepared_files" ,return_value = None ): 243with self .assertRaises (LaunchError ): 244runner .ensure_model () 245return seen 246 247def test_the_total_is_the_whole_model_in_the_chosen_data_folder (self ): 248data = self .base / "mydata" 249folder = data / "models" / "Q2_0" 250folder .mkdir (parents = True ) 251first = folder / (Q2 [0 ]+ ".part" ) 252first .write_bytes (bytes (100_000_000 )) 253r = self .runner (family = "qwen" ,model = "Q2_0" ,data_dir = str (data ),vision = "on" ,context = 32768 ) 254job = r .progress_job () 255self .assertEqual (Path (job ["folder" ]),folder ) 256self .assertEqual (len (job ["files" ]),3 )# two shards and the picture reader 257seen = self .run_lines (r , ["=== Step 5: Getting the model files ===" ,f" { Q2 [ 0 ] } : 0.10 / 37.60 GB (0%)" ]) 258text = [x for x in seen if "GB" in x ] 259self .assertTrue (text ,seen ) 260self .assertIn ("of 67.3 GB" ,text [- 1 ])# 66.4 GB of shards + 0.9 GB picture reader 261self .assertNotIn ("37.6" ," " .join (text )) 262 263def test_the_default_data_folder_is_used_when_none_was_chosen (self ): 264r = self .runner (family = "qwen" ,model = "Q2_0" ,vision = "off" ,context = 32768 ) 265self .assertEqual (Path (r .progress_job ()["folder" ]).parts [- 2 :], ("models" ,"Q2_0" )) 266self .assertEqual (len (r .progress_job ()["files" ]),2 ) 267 268 269 270class QuietStep (Base ): 271"""Finding 5: setup step 6 (packing) prints nothing for minutes: the person sees the plain sentence and a 'still working' line.""" 272 273def slow (self ,steps ): 274import time 275for delay ,line in steps : 276time .sleep (delay ) 277yield line + "\n" 278 279def run_steps (self ,steps ,heartbeat = 0.3 ): 280r = self .runner (family = "qwen" ,model = "Q2_0" ,vision = "off" ,context = 32768 ) 281r .HEARTBEAT_S = heartbeat 282seen = [] 283r .emit_cb = lambda ev :seen .append (ev .text ) 284proc = mock .Mock () 285proc .stdout = self .slow (steps ) 286proc .wait .return_value = 1 287with mock .patch .object (Runner ,"_spawn" ,return_value = proc ),mock .patch .object (Runner ,"adopt_prepared_files" ,return_value = None ): 288with self .assertRaises (LaunchError ): 289r .ensure_model () 290return seen 291 292def test_a_silent_pack_step_says_what_it_does_and_that_it_is_still_going (self ): 293seen = self .run_steps ([(0 ,"=== Step 5: Getting the model files ===" ), (0 ,"all model files present" ), 294 (0 ,"=== Step 6: Preparing the model for Strata ===" ), 295 (0 ,"> python tools/iq_pack.py --gguf x --out y --experts-bin" ), (1.6 ,"[X] stopped for the test" )]) 296pack = [x for x in seen if x .startswith ("Packing the experts into one file" )] 297self .assertTrue (pack ,seen ) 298self .assertEqual (pack [0 ],"Packing the experts into one file for low-memory mode (one time)" ) 299beats = [x for x in pack if "still working" in x ] 300self .assertGreaterEqual (len (beats ),2 ,seen )# a line every interval of silence 301self .assertNotIn ("Setup step 6" ," " .join (seen )) 302 303def test_no_heartbeat_while_lines_keep_coming (self ): 304seen = self .run_steps ([(0 ,"=== Step 6: Preparing the model for Strata ===" ), (0 ,"> python tools/iq_pack.py --gguf x --out y --experts-bin" )]+ 305 [(0.1 ,f" layer { i } " )for i in range (5 )]+ [(0 ,"[X] stopped" )],heartbeat = 2.0 ) 306self .assertFalse ([x for x in seen if "still working" in x ]) 307 308def test_the_plain_printer_shows_each_heartbeat (self ): 309import io 310from strata_cli .launch import cmd 311from strata_cli .launch .runner import Event 312buf = io .StringIO () 313with mock .patch .object (cmd .sys ,"stdout" ,buf ): 314emit = cmd ._printer () 315emit (Event ("model" ,"Packing (still working, 30 s so far)" )) 316emit (Event ("model" ,"Packing (still working, 60 s so far)" )) 317emit (Event ("model" ,"Packing (still working, 60 s so far)" )) 318self .assertEqual (buf .getvalue ().count ("still working" ),2 ) 319 320 321 322class StoredTuning (Base ): 323"""Finding 6: a run by flags (no saved preset) reuses the tuning result stored for the same model, choices and computer.""" 324 325IDENT = {"hardware" : {"hard" : {"gpus" : ["RTX 5070" ],"cpu" :"test" ,"logical" :16 ,"ram_gib" :64 },"soft" : {}}, 326"engine" : {"backend" :"cuda" },"model" : {"sha256_shard1" :"abc" }} 327 328def setUp (self ): 329super ().setUp () 330from strata_control import presets 331self .presets = presets 332self .cfg_path = self .base / "launch.json" 333self .cfg = {"args" : ["--native" ,"x/model-00001-of-00002.gguf" ,"--max-context" ,"32768" ,"--kv" ,"int8" ],"model_name" :"qwen" } 334self .cfg_path .write_text (json .dumps (self .cfg ),encoding = "utf-8" ) 335self .ident = json .loads (json .dumps (self .IDENT )) 336p = mock .patch .object (presets ,"current_identity" ,lambda cfg ,** kw :self .ident ) 337p .start () 338self .addCleanup (p .stop ) 339 340def store (self ): 341return self .presets .create ({"settings" : {"args" : {},"env" : {},"per_request" : {}},"outcome" :"improved" }, 342choices = self .presets .choices_from_config (self .cfg ),identity = self .ident ,name = "Q2 32K - Full speed" ) 343 344def runner_for_tune (self ,retune = False ): 345r = self .runner (family = "qwen" ,model = "Q2_0" ,tune = "quick" ) 346r .retune = retune 347r .config_path = self .cfg_path 348return r 349 350def run_tune (self ,r ): 351seen = [] 352r .emit_cb = lambda ev :seen .append (ev .text ) 353with mock .patch .object (Runner ,"_spawn" ,side_effect = RuntimeError ("the tuner started" ))as spawn : 354try : 355r .tune () 356started = False 357except RuntimeError : 358started = True 359return seen ,started 360 361def test_nothing_stored_means_it_is_measured (self ): 362seen ,started = self .run_tune (self .runner_for_tune ()) 363self .assertTrue (started ) 364 365def test_a_big_model_gets_a_longer_start_wait_by_itself (self ):# #3949 #3459 366r = self .runner_for_tune () 367row = type ("Row" , (), {"family" :r .s .family ,"model" :r .s .model ,"download_gb" :20.0 }) 368with mock .patch .object (r .catalog ,"rows" ,return_value = [row ]): 369self .assertEqual (r .start_wait (),600 )# a small model keeps ten minutes 370row .download_gb = 250.0 371with mock .patch .object (r .catalog ,"rows" ,return_value = [row ]): 372self .assertEqual (r .start_wait (),1800 )# 600 + 210 x 8, capped at 30 minutes 373row .download_gb = 83.0 374with mock .patch .object (r .catalog ,"rows" ,return_value = [row ]): 375self .assertEqual (r .start_wait (),944 ) 376 377def test_a_stored_result_is_used_and_said (self ): 378saved = self .store () 379r = self .runner_for_tune () 380seen ,started = self .run_tune (r ) 381self .assertFalse (started ) 382text = seen [- 1 ] 383self .assertIn ("already tuned for this computer" ,text ) 384self .assertIn ("Add --retune to measure again" ,text ) 385self .assertIn ("Q2 32K - Full speed" ,text ) 386self .assertIn ("--retune" ,text ) 387self .assertEqual (r .s .tuned_preset ,saved ["id" ]) 388self .assertTrue (r .s .is_tuned ) 389 390def test_retune_measures_again (self ): 391self .store () 392seen ,started = self .run_tune (self .runner_for_tune (retune = True )) 393self .assertTrue (started ) 394 395def test_another_context_is_another_result (self ): 396self .store () 397self .cfg ["args" ][3 ]= "65536" 398self .cfg_path .write_text (json .dumps (self .cfg ),encoding = "utf-8" ) 399seen ,started = self .run_tune (self .runner_for_tune ()) 400self .assertTrue (started ) 401 402def test_a_changed_graphics_card_is_measured_again (self ): 403self .store () 404self .ident ["hardware" ]["hard" ]["gpus" ]= ["RTX 4090" ] 405seen ,started = self .run_tune (self .runner_for_tune ()) 406self .assertTrue (started ) 407 408def test_the_flag_asks_for_a_new_measurement_and_implies_quick (self ): 409code ,out ,err = run_cli (["launch" ,"--plan" ,"--output" ,"json" ,"--model" ,"q2_0" ,"--retune" ]) 410self .assertEqual (code ,0 ,err ) 411self .assertEqual (json .loads (out )["plan" ]["settings" ]["tune" ],"quick" ) 412code ,out ,err = run_cli (["launch" ,"--help" ]) 413self .assertIn ("--retune" ,out ) 414 415 416 417if __name__ == "__main__" : 418unittest .main ()