okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""A scratch world for one (machine class, model set): files, a stand-in for setup's output, and the patches that make the probes answer as that machine. 2 3Everything lives under one temporary folder that is also HOME, the data folder, the install folder and every per-user folder, so nothing real is read or written. 4No model file is needed (the model files are empty), no engine runs (the engine is a text stub that carries the strings the program's own checks read), nothing is 5downloaded (the drafter fetch is replaced by a recorder that writes a small stand-in file), and nothing touches the network. 6""" 7 8from __future__import annotations 9 10import contextlib 11import json 12import os 13import sys 14import tempfile 15from pathlib import Path 16from unittest import mock 17 18from .matrix import MACHINES ,Machine ,ModelSet 19 20ROOT = Path (__file__ ).resolve ().parents [2 ] 21if str (ROOT )not in sys .path : 22sys .path .insert (0 ,str (ROOT )) 23 24#: The engine stub: the strings drafting.engine_form / engine_reads_selector_q4 look for in the program file (a current engine carries them). 25ENGINE_STUB = (b"STRATA ENGINE STUB (config snapshot)\n--mtp-draft-vocab FILE (or --mtp DIR\n--draft-fallback\n" 26b"--spec 2 or more and --mtp DIR (for DIR/draft_vocab.bin)\nselector codebooks: Q4_0 rows\n" ) 27 28#: Environment variables a developer or CI may have set that would leak into a start; the world starts from a clean list. 29CLEAR = ("STRATA_SETTINGS_FILE" ,"STRATA_CONNECTION_DIR" ,"CUDA_VISIBLE_DEVICES" ,"HIP_VISIBLE_DEVICES" ,"ROCR_VISIBLE_DEVICES" ,"STRATA_API_KEY" , 30"STRATA_ENGINE_BACKEND" ,"STRATA_DFLASH2_TUNED_URL" ,"STRATA_UPDATE_FEED" ,"STRATA_NO_ACQUIRE" ,"STRATA_COMPONENTS_DIR" ) 31 32 33def context_for (machine :Machine ,model_set :ModelSet )-> int : 34if machine .key == "nv_12gb_streaming" : 35return 65536 36if machine .key == "mac_small" : 37return 32768 38return 131072 39 40 41class World : 42def __init__ (self ,machine :Machine ,mset :ModelSet ,root :Path | None = None ): 43self ._tmp = None 44if root is None : 45self ._tmp = tempfile .TemporaryDirectory (prefix = "strata-snap-" ) 46root = Path (self ._tmp .name ) 47self .machine ,self .mset ,self .root = machine ,mset ,Path (root ).resolve () 48r = self .root 49self .home ,self .install ,self .data = r / "home" ,r / "install" ,r / "data" 50self .engine_dir = r / "engine" 51self .models = self .data / "models" 52self .pack = self .data / "packs" / mset .key 53self .mtp = self .data / "mtp" / "rt" 54self .gguf_dir = self .models / mset .model 55self .exe = self .engine_dir / "strata" 56self .tag = ({"qwen" :"" ,"unsloth" :"unsloth-" }[mset .family ]+ mset .model ).lower () 57self .config_path = self .install / f"strata- { self . tag } .json" 58self .env = { 59"HOME" :str (self .home ),"USERPROFILE" :str (self .home ), 60"APPDATA" :str (r / "roaming" ),"LOCALAPPDATA" :str (r / "local" ), 61"XDG_CONFIG_HOME" :str (r / "xdg-config" ),"XDG_STATE_HOME" :str (r / "state" ),"XDG_DATA_HOME" :str (r / "xdg-data" ), 62"STRATA_PROFILE_DIR" :str (r / "config" / "profiles" ),"STRATA_PRESET_DIR" :str (r / "config" / "presets" ), 63"STRATA_LAUNCH_PRESET_DIR" :str (r / "config" / "launch-presets" ), 64"STRATA_INSTALL_DIR" :str (self .install ),"STRATA_RUNTIME_DIR" :str (r / "runtime" ), 65"TMPDIR" :str (r / "tmp" ),"TEMP" :str (r / "tmp" ),"TMP" :str (r / "tmp" ), 66"STRATA_SETTINGS_FILE" :str (r / "settings.json" ), 67 } 68self .fetches :list [dict ]= []# what the drafter fetch was asked for (see patches) 69 70# ------------------------------------------------------------------ files 71def build (self )-> "World" : 72for d in (self .home ,self .install ,self .data ,self .engine_dir ,self .models ,self .gguf_dir ,self .pack / "tokenizer" ,self .mtp , 73self .root / "tmp" ,self .root / "roaming" ,self .root / "local" ,self .root / "xdg-config" ,self .root / "state" ,self .root / "runtime" ): 74d .mkdir (parents = True ,exist_ok = True ) 75self .exe .write_bytes (ENGINE_STUB ) 76for shard in self .mset .shards : 77 (self .gguf_dir / shard ).write_bytes (b"GGUF" ) 78 (self .pack / "native_experts.txt" ).write_text ("x" ) 79 (self .mtp / "experts.bin" ).write_bytes (b"e" ) 80 (self .mtp / "draft_vocab.bin" ).write_bytes (b"v" ) 81 (self .data / "mtp" / "mtp-q2_0.gguf" ).write_bytes (b"m" ) 82 (self .root / "settings.json" ).write_text (json .dumps ({"data_dir" :str (self .data ),"installs" : [str (self .install )]}),encoding = "utf-8" ) 83self .config_path .write_text (json .dumps (self .base_config (),indent = 1 ),encoding = "utf-8" ) 84 (self .root / "world-info.json" ).write_text (json .dumps (self .info (),indent = 1 ),encoding = "utf-8" ) 85return self 86 87def info (self )-> dict : 88"""What the app driver (Node) needs to know about this world; written next to it so the two sides read the same facts.""" 89m = self .machine 90platform = {"windows" :"windows-x86_64" ,"linux" :f"linux- { m . machine } " ,"macos" :"macos-arm64" }[m .os ] 91family = self .mset .family 92return {"tag" :self .tag ,"family" :family ,"title" :family ,"modelName" :self .mset .model_name ,"model" :self .mset .model ,"sizeId" :self .tag , 93"configPath" :str (self .config_path ),"hardware" :self .hardware_report (),"backend" :m .backend ,"platform" :platform ,"exe" :str (self .exe ), 94"context" :context_for (m ,self .mset )} 95 96def close (self )-> None : 97if self ._tmp is not None : 98self ._tmp .cleanup () 99 100# ------------------------------------------------------------------ the stand-in for setup.py's output 101def base_config (self )-> dict : 102"""What setup.py writes for this class and set, rebuilt from setup.py's own rules (the qwen block around line 10975-11200). 103It is a STAND-IN: setup.py itself cannot be driven without a model download, an engine and a GPU probe (see RESULTS-STEP0.md), so the entry points 104that start from a saved model all start from this same file. Differences between entry points are therefore never caused by it.""" 105m ,s = self .machine ,self .mset 106ctx = context_for (m ,s ) 107shard1 = self .gguf_dir / s .shards [0 ] 108ple = self .gguf_dir / s .shards [min (1 ,len (s .shards )- 1 )] 109args = ["--pack" ,str (self .pack ),"--native" ,str (shard1 )] 110if len (s .shards )<= 2 : 111args += ["--ple-gguf" ,str (ple )] 112args += ["--expert-profile" ,str (ROOT / "data" / "expert-profile.bin" ),"--expert-cache" ,"auto" ,"--prefill" ,"auto" ,"--spec" ,"4" , 113"--spec-min-p" ,"0.5" ,"--mtp" ,str (self .mtp ),"--max-context" ,str (ctx )] 114if ctx > 8192 : 115args += ["--kv" ,"int8" ] 116if m .key == "dgx_spark" : 117args += ["--mmap-experts" ] 118args [args .index ("--prefill" )+ 1 ]= "auto:32768" 119args += ["--mtp-q4" ,"all" ,"--mtp-hnorm" ,"stream" ] 120if ctx >= 65536 and m .key == "nv_12gb_streaming" : 121args += ["--kv-resident" ,"32768" ] 122if s .family == "unsloth" : 123args += ["--resident-budget-gib" ,"24" if m .ram_gb < 100 else "48" ] 124cfg = {"exe" :str (self .exe ),"args" :args ,"cwd" :str (ROOT ),"tokenizer" :str (self .pack / "tokenizer" ), 125"model_name" :s .model_name ,"log" :str (self .install / f"strata- { self . tag } .log" ),"lib_dirs" : [],"port" :8080 } 126if m .backend in ("hip" ,"metal" ,"sycl" ): 127cfg ["backend" ]= m .backend 128if m .cards > 1 : 129cfg ["gpu" ]= list (range (m .cards )) 130return cfg 131 132# ------------------------------------------------------------------ what the probes answer 133def hardware_report (self )-> dict : 134"""The hardware report the Terminal's catalog and the app's host read (the shape tests/terminal/launch_support.py and the host tests use).""" 135m = self .machine 136card = {"index" :0 ,"name" :m .card ,"vendor" :m .vendor ,"vram_gb" :m .vram_gb ,"usable" :True } 137if m .arch_field is not None : 138card ["arch" ]= m .arch_field 139if m .unified : 140card ["unified_gb" ]= m .ram_gb 141card ["uma" ]= True 142hw = {"ram_gb" :m .ram_gb ,"os" : {"windows" :"Windows 11" ,"linux" :"Linux" ,"macos" :"Darwin" }[m .os ],"disk_free_gb" :2000.0 , 143"cpu" : {"avx2" :m .machine in ("x86_64" ,)or None ,"name" :"snapshot cpu" ,"cores" :16 },"gpus" : [card ],"engine_vendor" :m .vendor if m .vendor != "apple" else None } 144if m .os == "macos" : 145hw ["mac" ]= {"chip" :m .card ,"macos" :"27.2" ,"unified_gb" :m .ram_gb } 146return hw 147 148def vram_mib (self )-> float | None : 149"""What the telemetry reader would answer for the ONE card (None for a shared-memory chip, as drafting.card_vram_mib does).""" 150return self .machine .vram_mib or None 151 152@ contextlib . contextmanager 153def patched (self ): 154"""The Python side of the machine class: engine family, cards, card memory, platform, environment. Nothing else is replaced.""" 155from strata_control import drafting ,drafting_fetch ,engine_component 156m = self .machine 157archs = list (m .archs ) 158vram = self .vram_mib () 159saved_env = dict (os .environ ) 160fetches = self .fetches 161 162class Reader : 163def ok (self_ ):# noqa: N805 164return vram is not None 165 166def read (self_ ):# noqa: N805 167return {"mem_total" :int (vram * (1 << 20 ))if vram else 0 } 168 169def exists (path )-> bool : 170try : 171p = Path (path ) 172return p .is_file ()and p .stat ().st_size > 0 173except OSError : 174return False 175 176def fake_converted_ok (data_dir ,* ,size = None ,sha256 = None ,name = None ): 177return bool (data_dir )and exists (Path (data_dir )/ drafting .FOLDER / (name or drafting .CONVERTED_NAME )) 178 179def put (path :Path )-> Path : 180path .parent .mkdir (parents = True ,exist_ok = True ) 181path .write_bytes (b"snapshot drafter stand-in\n" ) 182return path 183 184def fake_ensure_tuned (data_dir ,* ,progress = None ,cancel = None ,url = None ,size = None ,sha256 = None ,name = None ,feed = None ,throttle = False ,backend = None ,variant = None ): 185pin = drafting .tuned_pack (variant ) 186fetches .append ({"call" :"ensure_tuned" ,"file" :name or pin .name ,"variant" :variant or "selq4" ,"backend" :backend ,"gb" :pin .gb }) 187return put (Path (data_dir )/ drafting .FOLDER / (name or pin .name )) 188 189def fake_ensure (data_dir ,* ,progress = None ,cancel = None ,base_url = None ,files = None ): 190fetches .append ({"call" :"ensure" ,"file" :drafting .PACK_NAME ,"gb" :drafting .DOWNLOAD_GB }) 191put (drafting .target_path (data_dir )) 192 (Path (data_dir )/ drafting .FOLDER / drafting .VOCAB_NAME ).write_bytes (b"v" ) 193return drafting .target_path (data_dir ) 194 195def fake_convert (data_dir ,** kw ): 196fetches .append ({"call" :"convert_selector" }) 197return put (drafting .converted_path (data_dir )) 198 199with contextlib .ExitStack ()as st : 200st .enter_context (mock .patch .dict (os .environ ,self .env )) 201for k in CLEAR : 202if k not in self .env : 203os .environ .pop (k ,None ) 204os .environ ["PATH" ]= str (self .engine_dir )# nothing on PATH is probed; the engine is named by the config 205st .enter_context (mock .patch .object (drafting ,"ENGINE_SERVES_DFLASH2" ,True )) 206st .enter_context (mock .patch .object (drafting ,"_HARDWARE" , [(m .backend ,archs )])) 207st .enter_context (mock .patch .object (drafting ,"converted_ok" ,fake_converted_ok )) 208st .enter_context (mock .patch .object (drafting ,"_here" ,exists )) 209st .enter_context (mock .patch .object (drafting ,"engine_has_selector_q4" ,lambda :True )) 210st .enter_context (mock .patch .object (drafting ,"installed_engine_exe" ,lambda :self .exe )) 211st .enter_context (mock .patch .object (drafting ,"card_vram_mib" ,lambda cfg ,backend ,archs = None :None if m .unified else vram )) 212st .enter_context (mock .patch .object (drafting_fetch ,"ensure_tuned" ,fake_ensure_tuned )) 213st .enter_context (mock .patch .object (drafting_fetch ,"ensure" ,fake_ensure )) 214st .enter_context (mock .patch .object (drafting_fetch ,"convert_selector" ,fake_convert )) 215st .enter_context (mock .patch .object (drafting_fetch ,"online" ,lambda * a ,** k :True )) 216st .enter_context (mock .patch .object (engine_component ,"detect_backend" ,lambda : (m .backend ,"snapshot" ))) 217st .enter_context (mock .patch .object (engine_component ,"cuda_archs_present" ,lambda :archs if m .backend == "cuda" else [])) 218st .enter_context (mock .patch .object (engine_component ,"hip_archs_present" ,lambda :archs if m .backend == "hip" else [])) 219with contextlib .suppress (ImportError ): 220from serve import telemetry 221st .enter_context (mock .patch .object (telemetry ,"gpu_reader" ,lambda * a ,** k :Reader ())) 222try : 223from serve import server 224st .enter_context (mock .patch .object (server ,"_CARD_CLASS" , [drafting .card_class (archs )])) 225st .enter_context (mock .patch .object (server ,"gpu_vram_mib" ,lambda gl ,hip = False : {}if m .unified or vram is None else {int ((gl or [0 ])[0 ]):vram })) 226except ImportError :# serve needs its packages: a world without them still plans 227pass 228if m .os == "macos" : 229st .enter_context (mock .patch .object (sys ,"platform" ,"darwin" )) 230yield self 231os .environ .clear () 232os .environ .update (saved_env ) 233 234 235def worlds (machine_keys = None ,set_keys = None ): 236for m in MACHINES : 237if machine_keys and m .key not in machine_keys : 238continue 239from .matrix import MODEL_SETS 240for s in MODEL_SETS : 241if set_keys and s .key not in set_keys : 242continue 243yield m ,s