okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
1"""The picture files of a model that is already installed (strata_control/pictures.py): found or downloaded once, the data folder and the model's 2other files left exactly as they are, no internet answered in a sentence, and the run config's ``vision`` section worked out for the engine in use. 3 4The file is pinned (size and SHA-256), so the tests swap in a tiny pinned file of their own and a folder on disk for the download address.""" 5 6from __future__import annotations 7 8import hashlib 9import io 10import json 11import os 12import sys 13import tempfile 14import unittest 15from contextlib import redirect_stdout 16from pathlib import Path 17from unittest import mock 18 19import setup 20from strata_control import acquisition ,pictures 21 22ROOT = Path (__file__ ).resolve ().parents [2 ] 23BODY = b"mmproj-bytes-" * 5000 24TINY = pictures .Projector ("mmproj-Tiny.gguf" ,len (BODY ),hashlib .sha256 (BODY ).hexdigest (),"owner/repo" ,"rev1" ) 25NAME = TINY .name 26 27 28def tree (root :Path )-> dict : 29"""Every file under root with its size and modified time: what must not change.""" 30out = {} 31for p in sorted (root .rglob ("*" )): 32if p .is_file (): 33st = p .stat () 34out [p .relative_to (root ).as_posix ()]= (st .st_size ,st .st_mtime_ns ) 35return out 36 37 38class Layout : 39"""A model in its own folder (not <data>/models/<tag>) with its pack and draft layer in a data folder that is not the models folder.""" 40 41def __init__ (self ,base :Path ,* ,ordinary :bool = False ,with_vision :bool = False ): 42self .base = base 43self .data = base / ("Strata-data" if ordinary else "own-data" ) 44self .model_dir = (self .data / "models" / "IQ3_S" )if ordinary else (base / "downloads" / "IQ3_S" ) 45self .model_dir .mkdir (parents = True ) 46self .gguf = self .model_dir / "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf" 47self .gguf .write_bytes (b"GGUF" ) 48 (self .model_dir / "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf" ).write_bytes (b"GGUF" ) 49self .pack = self .data / "packs" / "iq3_s" 50 (self .pack / "tokenizer" ).mkdir (parents = True ) 51 (self .pack / "native_experts.txt" ).write_text ("x" ) 52self .mtp = self .data / "mtp" / "rt" 53self .mtp .mkdir (parents = True ) 54 (self .mtp / "experts.bin" ).write_bytes (b"e" ) 55 (self .data / "mtp" / "mtp-q2_0.gguf" ).write_bytes (b"m" ) 56self .engine = base / "engine" 57self .engine .mkdir () 58exe = "strata-vision.exe" if os .name == "nt" else "strata-vision" 59 (self .engine / exe ).write_bytes (b"x" ) 60self .reader = self .engine / exe 61self .config = base / "install" / "strata-iq3_s.json" 62self .config .parent .mkdir () 63cfg = {"exe" :"component:strata-engine" ,"model_name" :"qwen3.8-flash-next-iq3_s" , 64"args" : ["--pack" ,str (self .pack ),"--native" ,str (self .gguf ),"--mtp" ,str (self .mtp ),"--max-context" ,"8192" ]} 65if with_vision : 66cfg ["vision" ]= {"exe" :str (self .reader ),"mmproj" :str (self .data / "models" / NAME ),"model" :str (self .gguf ),"gpu" :False ,"max_tokens" :450 } 67self .config .write_text (json .dumps (cfg )) 68self .mirror = base / "mirror" 69served = self .mirror / "owner" / "repo" / "resolve" / "rev1" 70served .mkdir (parents = True ) 71 (served / NAME ).write_bytes (BODY ) 72 73def fetch (self ,** kw ): 74kw .setdefault ("engine_dir" ,self .engine ) 75kw .setdefault ("hardware" , {"vram_gb" :12 ,"make" :"nvidia" ,"arch" :120 }) 76kw .setdefault ("endpoint" ,self .mirror .as_uri ()) 77kw .setdefault ("online" ,lambda url :True ) 78with mock .patch .dict (pictures .PROJECTOR_BY_FAMILY , {"qwen" :TINY }),mock .patch .dict (os .environ , {"STRATA_NO_ACQUIRE" :"" }): 79return pictures .fetch (self .config ,** kw ) 80 81 82class FetchInOwnFolder (unittest .TestCase ): 83def setUp (self ): 84self ._tmp = tempfile .TemporaryDirectory () 85self .addCleanup (self ._tmp .cleanup ) 86self .base = Path (self ._tmp .name ) 87 88def test_the_file_goes_to_the_data_folder_of_the_run_config_and_nothing_else_changes (self ): 89lay = Layout (self .base ) 90before = tree (lay .data )| {f"gguf/ { k } " :v for k ,v in tree (lay .model_dir ).items ()} 91cfg_before = lay .config .read_bytes () 92seen = [] 93result = lay .fetch (progress = lambda step ,d ,t :seen .append ((step ,d ,t ))) 94self .assertTrue (result ["fetched" ]) 95self .assertEqual (Path (result ["mmproj" ]),lay .data / "models" / NAME ,"beside the pack and draft layer the model uses, not the app's models folder" ) 96self .assertEqual (result ["data_dir" ],str (lay .data )) 97self .assertEqual ((lay .data / "models" / NAME ).read_bytes (),BODY ) 98self .assertFalse ((lay .data / "models" / (NAME + ".part" )).exists ()) 99self .assertIn ("Downloading the picture files…" , [s for s ,_d ,_t in seen ]) 100after = tree (lay .data )| {f"gguf/ { k } " :v for k ,v in tree (lay .model_dir ).items ()} 101added = sorted (set (after )- set (before )) 102self .assertEqual (added , [f"models/ { NAME } " ,f"models/ { NAME } .done" ],"only the picture file and its finish mark" ) 103for key ,value in before .items (): 104self .assertEqual (after [key ],value ,f" { key } was left alone" ) 105self .assertEqual (lay .config .read_bytes (),cfg_before ,"the run config is the caller's to write" ) 106self .assertFalse ((self .base / "Strata-data" ).exists (),"no second data folder" ) 107 108def test_the_section_is_the_one_setup_writes_for_this_card (self ): 109lay = Layout (self .base ) 110small = lay .fetch (hardware = {"vram_gb" :12 ,"make" :"nvidia" ,"arch" :120 })["vision" ] 111self .assertEqual ((small ["gpu" ],small ["max_tokens" ]), (False ,300 ),"under 24 GB the CPU reader" ) 112self .assertEqual (small ["exe" ],str (lay .reader )) 113self .assertEqual (small ["model" ],str (lay .gguf )) 114self .assertEqual (small ["mmproj" ],str (lay .data / "models" / NAME )) 115self .assertGreaterEqual (small ["threads" ],1 ) 116big = lay .fetch (hardware = {"vram_gb" :48 ,"make" :"nvidia" ,"arch" :86 })["vision" ] 117self .assertEqual ((big ["gpu" ],big ["max_tokens" ]), (True ,1024 ),"from 24 GB the GPU reader" ) 118self .assertNotIn ("threads" ,big ) 119cpu = lay .fetch (asked = "cpu" ,hardware = {"vram_gb" :48 ,"make" :"nvidia" ,"arch" :86 })["vision" ] 120self .assertFalse (cpu ["gpu" ],"what the person asked for is kept" ) 121 122def test_a_copy_already_on_the_computer_is_used_where_it_is (self ): 123lay = Layout (self .base ) 124lay .model_dir .parent .joinpath (NAME ).write_bytes (BODY )# one folder up from the model files: the repository layout 125result = lay .fetch (online = lambda url :self .fail ("no network for a file that is here" )) 126self .assertFalse (result ["fetched" ]) 127self .assertEqual (Path (result ["mmproj" ]),lay .model_dir .parent / NAME ) 128self .assertFalse ((lay .data / "models" ).exists (),"nothing is written" ) 129 130def test_a_copy_with_the_wrong_bytes_is_not_used_and_not_deleted (self ): 131lay = Layout (self .base ) 132wrong = lay .data / "models" / NAME 133wrong .parent .mkdir () 134wrong .write_bytes (b"x" * len (BODY ))# right size, wrong content 135result = lay .fetch () 136self .assertTrue (result ["fetched" ],"downloaded because the copy there is not the pinned file" ) 137self .assertEqual (wrong .read_bytes (),BODY ,"the bad copy was replaced by the checked download" ) 138 139def test_the_path_the_run_config_names_is_kept_when_its_folder_is_there (self ): 140lay = Layout (self .base ,with_vision = True ) 141named = Path (json .loads (lay .config .read_text ())["vision" ]["mmproj" ]) 142named .parent .mkdir (parents = True ,exist_ok = True ) 143result = lay .fetch () 144self .assertEqual (Path (result ["mmproj" ]),named ) 145self .assertEqual (result ["vision" ]["max_tokens" ],450 ,"what the person set for the same reader is kept" ) 146cfg = json .loads (lay .config .read_text ()) 147cfg ["vision" ]["gpu" ]= True # an earlier value for the other reader does not carry over 148lay .config .write_text (json .dumps (cfg )) 149self .assertEqual (lay .fetch ()["vision" ]["max_tokens" ],300 ) 150 151def test_an_ordinary_install_keeps_the_file_in_its_own_models_folder (self ): 152lay = Layout (self .base ,ordinary = True ) 153result = lay .fetch () 154self .assertEqual (Path (result ["mmproj" ]),lay .data / "models" / NAME ) 155self .assertEqual (result ["data_dir" ],str (lay .data )) 156 157def test_the_data_folder_from_the_caller_is_used_when_the_config_names_none (self ): 158lay = Layout (self .base ) 159cfg = json .loads (lay .config .read_text ()) 160cfg ["args" ]= ["--native" ,str (lay .gguf )]# no --pack, no --mtp: nothing says where the data folder is 161lay .config .write_text (json .dumps (cfg )) 162elsewhere = self .base / "chosen" 163elsewhere .mkdir () 164result = lay .fetch (data_dir = elsewhere ) 165self .assertEqual (Path (result ["mmproj" ]),elsewhere / "models" / NAME ) 166 167def test_no_internet_is_a_sentence_after_one_short_probe_and_nothing_is_written (self ): 168lay = Layout (self .base ) 169before = tree (lay .base ) 170with self .assertRaises (pictures .PicturesError )as caught : 171lay .fetch (online = lambda url :False ) 172self .assertEqual (caught .exception .code ,"offline" ) 173self .assertEqual (str (caught .exception ),"There is no internet connection, so the picture files can't be downloaded now." ) 174self .assertEqual (tree (lay .base ),before ,"not even an empty file or folder" ) 175 176def test_a_download_that_does_not_match_is_deleted_and_said (self ): 177lay = Layout (self .base ) 178 (lay .mirror / "owner" / "repo" / "resolve" / "rev1" / NAME ).write_bytes (b"y" * len (BODY )) 179with self .assertRaises (pictures .PicturesError )as caught : 180lay .fetch () 181self .assertEqual (caught .exception .code ,"checksum" ) 182self .assertFalse ((lay .data / "models" / NAME ).exists ()) 183self .assertFalse ((lay .data / "models" / (NAME + ".part" )).exists ()) 184 185def test_a_half_download_is_continued (self ): 186lay = Layout (self .base ) 187partial = lay .data / "models" / (NAME + ".part" ) 188partial .parent .mkdir () 189partial .write_bytes (BODY [:1000 ]) 190lay .fetch () 191self .assertEqual ((lay .data / "models" / NAME ).read_bytes (),BODY ) 192 193def test_not_enough_disk_is_said_before_anything_is_fetched (self ): 194lay = Layout (self .base ) 195full = mock .Mock (free = 10 ) 196with mock .patch .object (pictures .shutil ,"disk_usage" ,return_value = full ),self .assertRaises (pictures .PicturesError )as caught : 197lay .fetch (online = lambda url :self .fail ("the space is checked first" )) 198self .assertEqual (caught .exception .code ,"disk" ) 199self .assertIn ("1 GB" ,str (caught .exception )) 200 201def test_a_start_never_downloads (self ): 202lay = Layout (self .base ) 203with mock .patch .dict (pictures .PROJECTOR_BY_FAMILY , {"qwen" :TINY }),mock .patch .dict (os .environ , {"STRATA_NO_ACQUIRE" :"1" }): 204with self .assertRaises (acquisition .AcquisitionRefused ): 205pictures .fetch (lay .config ,engine_dir = lay .engine ,endpoint = lay .mirror .as_uri (),online = lambda url :True ) 206self .assertFalse ((lay .data / "models" ).exists ()) 207 208def test_a_model_this_step_does_not_know_is_left_alone (self ): 209lay = Layout (self .base ) 210cfg = json .loads (lay .config .read_text ()) 211cfg ["model_name" ]= "qwen3.6-35b-a3b-ud-q4_k_xl" 212lay .config .write_text (json .dumps (cfg )) 213with self .assertRaises (pictures .PicturesError )as caught : 214lay .fetch () 215self .assertEqual (caught .exception .code ,"unsupported" ) 216cfg .update ({"model_name" :"x" ,"arch" :"deepseek41" }) 217lay .config .write_text (json .dumps (cfg )) 218with self .assertRaises (pictures .PicturesError )as caught : 219lay .fetch () 220self .assertEqual (caught .exception .code ,"unsupported" ) 221 222def test_an_engine_without_a_picture_reader_is_a_clear_answer (self ): 223lay = Layout (self .base ) 224lay .reader .unlink () 225with self .assertRaises (pictures .PicturesError )as caught : 226lay .fetch () 227self .assertEqual (caught .exception .code ,"no_reader" ) 228 229 230class Families (unittest .TestCase ): 231def test_the_family_comes_from_the_catalog_or_from_the_names (self ): 232g = Path ("Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf" ) 233self .assertEqual (pictures .family_of ({},g ,"swift" ),"swift" ) 234self .assertEqual (pictures .family_of ({},g ,"qwen36" ),None ) 235self .assertEqual (pictures .family_of ({},g ,"nvfp4" ),None ) 236self .assertEqual (pictures .family_of ({"model_name" :"iq3_s" },g ),"qwen" ,"a hand-made name still gets the original's file" ) 237self .assertEqual (pictures .family_of ({"model_name" :"swift-1.5-iq3_s" },g ),"swift" ) 238self .assertEqual (pictures .family_of ({},Path ("Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf" )),"swift" ) 239self .assertIsNone (pictures .family_of ({"model_name" :"qwen3.6-35b-a3b-q8_0" },Path ("Qwen3.6-35B-A3B-Q8_0.gguf" ))) 240self .assertIsNone (pictures .family_of ({"arch" :"deepseek41" },None )) 241 242def test_the_pins_are_the_ones_setup_downloads (self ): 243for name ,projector ,repo in (("qwen" ,pictures .QWEN ,"ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" ), ("swift" ,pictures .SWIFT ,"ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF" )): 244fam = setup .FAMILIES [name ] 245self .assertEqual (projector .name ,fam ["mmproj" ]) 246self .assertEqual (projector .repo ,repo ) 247self .assertEqual (projector .revision ,setup .HF_REVISIONS [repo ]) 248self .assertEqual (fam ["mmproj_hf" ],f" { setup . hf_endpoint () } / { repo } /resolve/ { projector . revision } /" ) 249pins = {** setup .ISTA_FILES ,** setup .SWIFT_FILES }[projector .name ] 250self .assertEqual ((projector .size ,projector .sha256 ),tuple (pins )) 251for name in ("coder" ,"unsloth" ,"gyro" ): 252self .assertEqual (setup .FAMILIES [name ]["mmproj" ],pictures .PROJECTOR_BY_FAMILY [name ].name ,name ) 253self .assertEqual (tuple (setup .CODER_FILES [pictures .QWEN .name ]), (pictures .QWEN .size ,pictures .QWEN .sha256 ),"the Coder's file is the original's" ) 254 255def test_the_address_follows_hf_endpoint_like_setup (self ): 256with mock .patch .dict (os .environ , {"HF_ENDPOINT" :"http://127.0.0.1:9/" }): 257self .assertEqual (pictures .QWEN .url (),f"http://127.0.0.1:9/ { pictures . QWEN . repo } /resolve/ { pictures . QWEN . revision } / { pictures . QWEN . name } " ) 258with mock .patch .dict (os .environ , {"HF_ENDPOINT" :"" }): 259self .assertTrue (pictures .QWEN .url ().startswith ("https://huggingface.co/" )) 260 261 262class RunFolder (unittest .TestCase ): 263def foot (self ,* args ): 264from strata_control import discovery 265return discovery .footprint ({"args" :list (args )}) 266 267def test_the_folder_comes_from_where_the_pack_and_the_draft_layer_are (self ): 268self .assertEqual (pictures .run_folder (self .foot ("--pack" ,"/d/packs/iq3_s" ,"--native" ,"/other/IQ3_S/a.gguf" )),Path ("/d" )) 269self .assertEqual (pictures .run_folder (self .foot ("--mtp" ,"/x/mtp/rt" ,"--native" ,"/other/a.gguf" )),Path ("/x" )) 270self .assertEqual (pictures .run_folder (self .foot ("--native" ,"/data/models/IQ3_S/a.gguf" )),Path ("/data" )) 271 272def test_a_pack_in_a_folder_of_another_shape_says_nothing_about_the_data_folder (self ): 273self .assertIsNone (pictures .run_folder (self .foot ("--pack" ,"/d/my-pack" ,"--native" ,"/other/IQ3_S/a.gguf" ))) 274self .assertIsNone (pictures .run_folder (self .foot ("--mtp" ,"/x/draft" ,"--native" ,"/other/a.gguf" ))) 275self .assertIsNone (pictures .run_folder (self .foot ("--mtp" ,"7" )),"a draft depth is not a folder" ) 276 277 278class ReaderRule (unittest .TestCase ): 279def setUp (self ): 280self ._tmp = tempfile .TemporaryDirectory () 281self .addCleanup (self ._tmp .cleanup ) 282self .engine = Path (self ._tmp .name ) 283self .cpu = "strata-vision.exe" if os .name == "nt" else "strata-vision" 284self .hip = "strata-vision-hip.exe" if os .name == "nt" else "strata-vision-hip" 285 286def make (self ,* names ,build = None ): 287for n in names : 288 (self .engine / n ).write_bytes (b"x" ) 289if build is not None : 290 (self .engine / "BUILD.json" ).write_text (json .dumps (build )) 291 292def section (self ,asked = "yes" ,** hw ): 293return pictures .reader_section (self .engine ,Path ("/m/mm.gguf" ),Path ("/m/a.gguf" ),asked ,hw ) 294 295def test_amd_gets_the_gpu_reader_with_the_cpu_one_behind_it_from_24_gb (self ): 296self .make (self .cpu ,self .hip ,build = {"vision_archs" :"gfx1201;gfx1100" }) 297s ,_ = self .section (vram_gb = 32 ,make = "amd" ,arch = "gfx1201" ) 298self .assertEqual ((s ["gpu" ],Path (s ["exe" ]).name ,Path (s ["cpu_exe" ]).name ), (True ,self .hip ,self .cpu )) 299s ,_ = self .section (vram_gb = 16 ,make = "amd" ,arch = "gfx1201" ) 300self .assertEqual ((s ["gpu" ],Path (s ["exe" ]).name ), (False ,self .cpu ),"a 16 GB card reads on the CPU" ) 301s ,note = self .section ("gpu" ,vram_gb = 32 ,make = "amd" ,arch = "gfx1030" ) 302self .assertFalse (s ["gpu" ]) 303self .assertIn ("gfx1030" ,note ) 304 305def test_nvidia_reader_the_build_has_no_code_for_runs_on_the_cpu (self ): 306self .make (self .cpu ,build = {"vision_archs" :"86;89" ,"ptx" :False }) 307s ,note = self .section ("gpu" ,vram_gb = 48 ,make = "nvidia" ,arch = 75 ) 308self .assertFalse (s ["gpu" ]) 309self .assertIn ("sm_75" ,note ) 310s ,_ = self .section ("gpu" ,vram_gb = 48 ,make = "nvidia" ,arch = 86 ) 311self .assertTrue (s ["gpu" ]) 312 313def test_off_and_no_reader (self ): 314self .make () 315self .assertEqual (self .section ("yes" ,vram_gb = 12 ,make = "nvidia" )[0 ],None ) 316self .make (self .cpu ) 317self .assertIsNone (pictures .reader_section (self .engine ,Path ("m" ),Path ("g" ),"no" , {})[0 ]) 318 319 320class Command (unittest .TestCase ): 321def test_the_command_speaks_json_lines_and_exits_with_the_sentence (self ): 322with tempfile .TemporaryDirectory ()as tmp : 323lay = Layout (Path (tmp )) 324out = io .StringIO () 325with mock .patch .dict (pictures .PROJECTOR_BY_FAMILY , {"qwen" :TINY }),mock .patch .dict (os .environ , {"STRATA_NO_ACQUIRE" :"" ,"HF_ENDPOINT" :"" }), \ 326mock .patch .object (pictures ,"_online" ,return_value = False ),redirect_stdout (out ): 327code = pictures .main (["fetch" ,"--config" ,str (lay .config ),"--engine-dir" ,str (lay .engine ),"--vision" ,"yes" ,"--vram-gb" ,"12" ,"--make" ,"nvidia" ,"--arch" ,"120" ]) 328self .assertEqual (code ,5 ) 329last = json .loads (out .getvalue ().strip ().splitlines ()[- 1 ]) 330self .assertEqual (last ["ok" ],False ) 331self .assertEqual (last ["error" ]["code" ],"offline" ) 332out = io .StringIO () 333with mock .patch .dict (pictures .PROJECTOR_BY_FAMILY , {"qwen" :TINY }),mock .patch .dict (os .environ , {"STRATA_NO_ACQUIRE" :"" ,"HF_ENDPOINT" :lay .mirror .as_uri ()}), \ 334mock .patch .object (pictures ,"_online" ,return_value = True ),redirect_stdout (out ): 335code = pictures .main (["fetch" ,"--config" ,str (lay .config ),"--engine-dir" ,str (lay .engine ),"--vram-gb" ,"12" ,"--make" ,"nvidia" ,"--arch" ,"120" ]) 336lines = [json .loads (line )for line in out .getvalue ().strip ().splitlines ()] 337self .assertEqual (code ,0 ,lines [- 1 ]) 338self .assertEqual ([l ["event" ]for l in lines [:- 1 ]], ["progress" ]* (len (lines )- 1 )) 339self .assertTrue (lines [- 1 ]["ok" ]and lines [- 1 ]["event" ]== "result" and lines [- 1 ]["fetched" ]) 340 341 342if __name__ == "__main__" : 343unittest .main ()