okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
714ff8242
main
1"""The owner's rule for setup (#403 #406 #364 #384): setup RECOMMENDS, it never forces - and the recommended answers 2stay exactly what they were. setup.main() with --yes (and with Enter for every question) on a few PCs writes the same 3run config, byte for byte, as 0.1.32 plus the fixes on top of it did (tools/test_setup_golden.json, written by that 4setup). Every outside effect is mocked: no GPU, no downloads, nothing written outside a temp folder. 5 6python -m unittest tools.test_setup_golden 7python tools/test_setup_golden.py --write (only to record a new baseline on purpose) 8""" 9from __future__import annotations 10 11import contextlib 12import io 13import json 14import re 15import sys 16import tempfile 17import types 18import unittest 19from pathlib import Path 20from unittest import mock 21 22ROOT = Path (__file__ ).resolve ().parents [1 ] 23sys .path .insert (0 ,str (ROOT )) 24import setup # noqa: E402 25 26GOLDEN = Path (__file__ ).with_name ("test_setup_golden.json" ) 27 28 29def card (i ,name ,vram ,arch ): 30return {"index" :i ,"name" :name ,"vram_gb" :vram ,"arch" :arch ,"driver" :"580.97" } 31 32 33# the PCs: total RAM as ram_gb() reads it (a little under the label), the cards as nvidia-smi lists them 34PROFILES = { 35"64GB-1x32GB" : (63.7 , [card (0 ,"NVIDIA GeForce RTX 5090" ,31.8 ,"120" )]),# #406 36"32GB-2x24GB" : (31.9 , [card (i ,"NVIDIA GeForce RTX 3090" ,24.0 ,"86" )for i in range (2 )]),# #364 37"47GB-2x16GB" : (47.0 , [card (i ,"NVIDIA GeForce RTX 5060 Ti" ,15.9 ,"120" )for i in range (2 )]),# #384 38"96GB-1x16GB" : (95.8 , [card (0 ,"NVIDIA GeForce RTX 5080" ,15.9 ,"120" )]), 39"128GB-1x24GB" : (127.8 , [card (0 ,"NVIDIA GeForce RTX 4090" ,24.0 ,"89" )]), 40} 41# (family, model): None = the recommended size 42MODELS = [("qwen" ,None ), ("qwen" ,"Q2_0" ), ("qwen" ,"IQ3_XXS" ), ("qwen" ,"IQ3_S" ), ("unsloth" ,"UD-Q4_K_XL" )] 43 44 45class FakeGGUF : 46"""gguf_reader.GGUFFile: shard 2 holds the PLE table.""" 47def __init__ (self ,path ): 48names = ["per_layer_token_embd.weight" ]if "00002-of" in str (path )else ["blk.0.ffn_up_exps.weight" ] 49self .tensors = [types .SimpleNamespace (name = n )for n in names ] 50 51 52def normalize (v ,t :Path ): 53"""The config with the temp folder and the platform's names taken out (it compares on Windows and Linux).""" 54if isinstance (v ,dict ): 55return {k :normalize (x ,t )for k ,x in v .items ()} 56if isinstance (v ,list ): 57return [normalize (x ,t )for x in v ] 58if isinstance (v ,str ): 59v = v .replace (str (t ),"<T>" ).replace ("\\" ,"/" ) 60# the platform's own names of the programs (strata.exe or strata, strata-vision.exe or strata-vision, ...) so the baseline compares on Windows and Linux (#3325) 61for name ,label in ((setup .HVEXE ,"<HVEXE>" ), (setup .VEXE ,"<VEXE>" ), (setup .EXE ,"<EXE>" )): 62v = re .sub (rf"(?<![w.-]) { re . escape ( name ) } (?![w.-])" ,label ,v )# #973: only the whole name, not "strata-x.log" on Linux 63return v 64return v 65 66 67def install (ram ,found ,argv ,answers = None ,extra = (),avx512 = False ,configs = ()): 68"""setup.main() on a mocked PC -> (exit code, printed text, the written config or None, the questions asked). 69answers: None = --yes (a question fails the run), "" = Enter for every question, a list of answers in order, or 70{words of a question: its answer} (Enter for the others). 71extra: more patches (mock.patch objects). configs: (name, dict) run configs already in the Strata folder.""" 72with tempfile .TemporaryDirectory ()as tmp : 73t = Path (tmp ) 74 (t / "data" / "mtp" / "rt" ).mkdir (parents = True ) 75 (t / "data" / "mtp" / "rt" / "experts.bin" ).write_bytes (b"" ) 76eng = t / "engine" 77eng .mkdir () 78 (eng / "BUILD.json" ).write_text (json .dumps ({"version" :"0.1.32" ,"source" :"local" ,"cuda_dirs" : ["<cuda>" ]})) 79for name ,c in configs : 80 (t / name ).write_text (json .dumps (c )) 81asked = [] 82 83def fake_input (prompt = "" ): 84asked .append (prompt ) 85if answers is None : 86raise AssertionError (f"asked { prompt !r } with --yes" ) 87if isinstance (answers ,list ): 88return answers .pop (0 )if answers else "" 89if isinstance (answers ,dict ):# {words of the question: answer}, else Enter 90return next ((v for k ,v in answers .items ()if k in prompt ),"" ) 91return answers 92 93def fake_download (url ,dst ,what = None ): 94dst .parent .mkdir (parents = True ,exist_ok = True ) 95dst .write_bytes (b"" ) 96setup .mark (dst ) 97 98patches = [ 99mock .patch .object (setup ,"ROOT" ,t ), 100mock .patch .object (setup ,"GPU_PICK" ,None ), 101mock .patch .object (setup ,"data_folder" ,lambda d ,* a ,** k : (t / "data" , [])), 102mock .patch .object (setup ,"load_settings" ,lambda : {}), 103mock .patch .object (setup ,"save_settings" ,lambda s :None ), 104mock .patch .object (setup ,"gpus" ,lambda :found ), 105mock .patch .object (setup ,"card_speeds" ,lambda : {}), 106mock .patch .object (setup ,"amd_gpus" ,lambda : []), 107mock .patch .object (setup ,"ram_gb" ,lambda :ram ), 108mock .patch .object (setup ,"cpu_info" ,lambda : ("Test CPU" ,True ,avx512 )), 109mock .patch .object (setup ,"cpu_cores" ,lambda :None ),# #642: not a hybrid CPU 110mock .patch .object (setup ,"vision_threads" ,lambda logical = None :6 ),# the baseline PC has 12 logical CPUs; the runner's own count must not change the golden config 111mock .patch .object (setup ,"page_file_gb" ,lambda :16.0 ), 112mock .patch .object (setup ,"is_wsl" ,lambda :False ), 113mock .patch .object (setup ,"rotational_disk" ,lambda p :None ),# #605: the test PC's own disk 114mock .patch .object (setup ,"ple_ram_platform_ok" ,lambda :False ),# 147-verify: the golden configs as on Windows 115mock .patch .object (setup ,"free_gb" ,lambda p :900.0 ), 116mock .patch .object (setup ,"pip_install" ,lambda * a ,** k :None ), 117mock .patch .object (setup ,"get_llama_cpp" ,lambda :t / "llama.cpp" ), 118mock .patch .object (setup ,"get_prebuilt" ,lambda * a ,** k :eng ), 119mock .patch .object (setup ,"update_installed_engine" ,lambda * a ,** k :None ), 120mock .patch .object (setup ,"download" ,fake_download ), 121mock .patch .object (setup ,"check_shards" ,lambda shards :None ), 122mock .patch .object (setup ,"verify_sha256" ,lambda * a ,** k :None ), 123mock .patch .object (setup ,"run" ,lambda * a ,** k :None ), 124mock .patch .object (setup ,"mtp_corrupt" ,lambda * a ,** k :False ), 125mock .patch .object (setup ,"refresh_draft_vocab" ,lambda * a ,** k :None ), 126mock .patch .object (setup ,"write_run_script" ,lambda tag ,cfg ,port ,* _ :t / f"run- { tag } .bat" ), 127mock .patch .object (setup ,"saved_calibration" ,lambda cfg :None ), 128mock .patch .object (setup ,"calibrate_config" ,mock .Mock (side_effect = AssertionError ("calibrated" ))), 129mock .patch .dict (sys .modules , {"gguf_reader" :types .SimpleNamespace (GGUFFile = FakeGGUF )}), 130mock .patch .object (sys ,"argv" , ["setup.py" ,"--models-dir" ,str (t / "models" ),* argv ] 131+ (["--yes" ]if answers is None else [])), 132mock .patch ("builtins.input" ,fake_input ), 133* extra , 134 ] 135out = io .StringIO () 136code = None 137with contextlib .ExitStack ()as st : 138for p in patches : 139st .enter_context (p ) 140with contextlib .redirect_stdout (out ): 141try : 142code = setup .main () 143except SystemExit as e : 144code = e .code 145# the config this run wrote: a new file or one whose bytes changed, not just the newest time (a fast run on a coarse clock, GitHub's 146# Windows runner, wrote strata-iq3_s.json in the same tick as the strata-iq3_xxs.json put here before it, and the name order won) 147before = {name :json .dumps (c )for name ,c in configs } 148changed = [p for p in t .glob ("strata-*.json" )if before .get (p .name )!= p .read_text (encoding = "utf-8" )] 149written = sorted (changed or t .glob ("strata-*.json" ),key = lambda p :p .stat ().st_mtime_ns ) 150cfg = None 151if written and code == 0 : 152cfg = normalize (json .loads (written [- 1 ].read_text (encoding = "utf-8" )),t ) 153# "args_written" (strata_control/user_args.py): the arguments as setup wrote them, so a later hand edit can be told; the golden configs keep their own keys 154assert cfg .pop ("args_written" ,cfg .get ("args" ))== cfg .get ("args" ),"args_written is not the written args" 155return code ,out .getvalue (),cfg ,asked 156 157 158def argv_for (family ,model ): 159return ["--family" ,family ,"--no-start" ]+ (["--model" ,model ]if model else []) 160 161 162def record ()-> dict : 163"""Every profile x model with --yes: the exit code and the config (the baseline this test compares against).""" 164res = {} 165for prof , (ram ,found )in PROFILES .items (): 166for family ,model in MODELS : 167code ,out ,cfg ,_ = install (ram ,found ,argv_for (family ,model )) 168res [f" { prof } { family } { model or 'recommended' } " ]= {"code" :code ,"config" :cfg } 169return res 170 171 172class Golden (unittest .TestCase ): 173"""--yes and Enter: the same config as the baseline wherever the baseline wrote one.""" 174 175@classmethod 176def setUpClass (cls ): 177cls .golden = json .loads (GOLDEN .read_text (encoding = "utf-8" )) 178 179def cases (self ): 180for prof , (ram ,found )in PROFILES .items (): 181for family ,model in MODELS : 182key = f" { prof } { family } { model or 'recommended' } " 183if self .golden [key ]["code" ]== 0 : 184yield key ,ram ,found ,family ,model 185 186def test_the_baseline_covers_every_kind_of_pc (self ): 187written = [k for k ,v in self .golden .items ()if v ["code" ]== 0 ] 188self .assertGreaterEqual (len (written ),20 ) 189lowram_multi = self .golden ["32GB-2x24GB qwen IQ3_XXS" ]["config" ]# #364 -> #642: low-RAM, two cards -> both 190self .assertIn ("--resident-experts" if "--resident-experts" in lowram_multi ["args" ]else "--mmap-experts" , 191lowram_multi ["args" ]) 192self .assertEqual (lowram_multi .get ("gpu" ), [0 ,1 ])# 0.1.40 (#642): resident on both cards; roles: Main 1 goes last, as before 193 194def test_yes (self ): 195for key ,ram ,found ,family ,model in self .cases (): 196with self .subTest (key ): 197code ,out ,cfg ,asked = install (ram ,found ,argv_for (family ,model )) 198self .assertEqual (code ,0 ,out [- 3000 :]) 199self .assertEqual (cfg ,self .golden [key ]["config" ],out [- 3000 :]) 200self .assertEqual (asked , []) 201 202def test_enter_for_every_question (self ): 203for key ,ram ,found ,family ,model in self .cases (): 204if "UD-Q4_K_XL" in key and ram < 48 :# --yes consents to the risk; Enter declines it (the 205continue # "Install it anyway? [n]" question), by design 206with self .subTest (key ): 207code ,out ,cfg ,asked = install (ram ,found ,argv_for (family ,model ),answers = "" ) 208self .assertEqual (code ,0 ,out [- 3000 :]) 209self .assertEqual (cfg ,self .golden [key ]["config" ],out [- 3000 :]) 210 211def test_the_refusals_with_yes_alone_stay (self ): 212"""A size the baseline refused with --yes and no explicit --model still stops (--yes alone is no consent).""" 213for prof , (ram ,found )in PROFILES .items (): 214for family ,model in MODELS : 215key = f" { prof } { family } { model or 'recommended' } " 216if self .golden [key ]["code" ]!= 0 and model is None : 217with self .subTest (key ): 218self .assertNotEqual (install (ram ,found ,argv_for (family ,model ))[0 ],0 ) 219 220 221if __name__ == "__main__" : 222if "--write" in sys .argv : 223GOLDEN .write_text (json .dumps (record (),indent = 1 ,sort_keys = True )+ "\n" ,encoding = "utf-8" ) 224f"wrote { GOLDEN } " ) 225else : 226unittest .main ()