okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c77572806
main
1"""Read-only inventory of the components a saved run config needs.""" 2 3from __future__import annotations 4 5import csv 6import io 7import json 8import os 9import platform 10from strata_control import sysinfo 11import re 12import shutil 13import subprocess 14import sys 15from importlib import metadata ,util 16from pathlib import Path 17 18from strata_control .profiles import read_run_config 19 20 21PATH_FLAGS = { 22"--pack" :"directory" , 23"--native" :"file" , 24"--ple-gguf" :"file" , 25"--expert-profile" :"file" , 26"--mtp" :"directory" , 27"--control-vector-scaled" :"file_with_scale" , 28} 29MONITOR_TEXTUAL_VERSION = "8.2.8" 30 31 32def _location (raw :str ,cfg :dict ,config_path :Path )-> Path : 33from strata_control import engine_component 34if engine_component .is_reference (raw ): 35try : 36return Path (engine_component .expand (raw ,cfg ,full = False )) 37except engine_component .EngineMissing : 38return engine_component .engine_dir ()/ "(no engine for this PC)" # reported as missing 39value = Path (raw ).expanduser () 40if value .is_absolute (): 41return value 42cwd = cfg .get ("cwd" ) 43return (Path (cwd )if isinstance (cwd ,str )and cwd else config_path .parent )/ value 44 45 46def _drafter_is_dflash2 (cfg :dict )-> bool : 47"""Does this run config's drafting choice mean DFlash2 on this computer (Auto included)? Never raises.""" 48try : 49from strata_control import drafting 50backend ,archs = drafting .detect_hardware () 51return cfg .get ("mtp" )is not False and drafting .choice_of (cfg .get ("drafting" ),model_name = cfg .get ("model_name" ),backend = backend ,archs = archs )== "dflash2" 52except Exception :# noqa: BLE001 - unknown means the MTP, which stays required 53return False 54 55 56def _drafter_needs_mtp (cfg :dict )-> bool : 57"""Will a start of this run config load the MTP layer? Not when the saved Drafting choice is Off, and not when the choice means DFlash2 (Auto 58included). Only then is the --mtp folder a required file (0.2.15 release test: an app model saved with Off and no MTP folder was reported as missing 59"rt" after a restart and could not load). A config that switched the layer off by hand ("mtp": false) is unchanged. Never raises; unknown keeps it 60required.""" 61try : 62from strata_control import drafting 63if drafting .normalize (cfg .get ("drafting" ))== "off" : 64return False 65except Exception :# noqa: BLE001 - unknown: decided below 66pass 67return not _drafter_is_dflash2 (cfg ) 68 69 70def _item (name :str ,path :Path ,kind :str ,* ,required :bool = True )-> dict : 71try : 72if kind == "file" : 73valid = path .is_file ()and path .stat ().st_size > 0 74else : 75valid = path .is_dir () 76except OSError : 77valid = False 78return {"name" :name ,"status" :"ok" if valid else ("missing" if required else "optional_missing" ), 79"path" :str (path ),"kind" :kind ,"required" :required } 80 81 82def _selected_indices (value :object )-> list [int ]| None : 83if value is None : 84return None 85if isinstance (value ,str ): 86parts :object = value .split ("," ) 87elif isinstance (value ,list ): 88parts = value 89else : 90parts = [value ] 91if not isinstance (parts ,list )or not 1 <= len (parts )<= 64 : 92raise ValueError ("GPU selection must contain 1..64 numeric device indices" ) 93result = [] 94for part in parts : 95if type (part )is int and 0 <= part <= 1023 : 96result .append (part ) 97elif isinstance (part ,str )and re .fullmatch (r"[0-9]{1,4}" ,part .strip ())and int (part )<= 1023 : 98result .append (int (part )) 99else : 100raise ValueError ("GPU selection must contain numeric device indices" ) 101if len (set (result ))!= len (result ): 102raise ValueError ("GPU selection repeats a device index" ) 103return result 104 105 106def _nvidia_cards ()-> tuple [list [dict ]| None ,str | None ]: 107"""One bounded, read-only host query. It does not establish engine compatibility.""" 108tool = shutil .which ("nvidia-smi" ) 109if tool is None : 110return None ,"nvidia-smi is not installed or is not on PATH" 111try : 112result = subprocess .run ( 113 [tool ,"--query-gpu=index,name,uuid,memory.total,driver_version" , 114"--format=csv,noheader,nounits" ],capture_output = True ,text = True ,errors = "replace" ,timeout = 5 ,check = False , 115 ) 116except (OSError ,UnicodeError ,subprocess .TimeoutExpired ): 117return None ,"nvidia-smi could not complete within five seconds" 118if result .returncode != 0 : 119return None ,"nvidia-smi returned an error" 120if len (result .stdout )> 65536 : 121return None ,"nvidia-smi output exceeded the size limit" 122cards = [] 123try : 124for row in csv .reader (io .StringIO (result .stdout )): 125if len (row )!= 5 or len (cards )>= 64 : 126raise ValueError ("invalid field count" ) 127index_raw ,name ,uuid ,memory_raw ,driver = [part .strip ()for part in row ] 128unified = memory_raw == "[N/A]" and sysinfo .machine ().lower ()in ("aarch64" ,"arm64" )# a DGX Spark's GB10: no separate graphics memory 129if not (re .fullmatch (r"[0-9]{1,4}" ,index_raw ) 130and (unified or re .fullmatch (r"[0-9]{1,9}" ,memory_raw )) 131and 0 <= int (index_raw )<= 1023 and (unified or int (memory_raw )> 0 ) 132and 1 <= len (name )<= 128 and 1 <= len (uuid )<= 128 133and 1 <= len (driver )<= 64 134and all (part .isprintable ()for part in (name ,uuid ,driver ))): 135raise ValueError ("invalid card fields" ) 136cards .append ({"index" :int (index_raw ),"name" :name ,"uuid" :uuid , 137"memory_mib" :None if unified else int (memory_raw ),"driver_version" :driver }) 138except (csv .Error ,ValueError ): 139return None ,"nvidia-smi returned an unrecognized card list" 140if not cards or len ({card ["index" ]for card in cards })!= len (cards ): 141return None ,"nvidia-smi returned no cards or duplicate device indices" 142return cards ,None 143 144 145def _live_probe (cfg :dict ,backend :str )-> tuple [dict ,list [dict ]]: 146try : 147selected = _selected_indices (cfg .get ("gpu" )) 148except ValueError as exc : 149return ({"status" :"invalid_selection" ,"selected_indices" :None ,"cards" : []}, 150 [{"code" :"GPU_SELECTION_INVALID" ,"severity" :"error" ,"message" :str (exc )}]) 151if backend == "cpu" and selected is None : 152return {"status" :"not_applicable" ,"selected_indices" :None ,"cards" : []}, [] 153if backend not in ("cuda" ,"cuda_or_cpu_unverified" ,"cpu" ): 154return ({"status" :"unverified" ,"selected_indices" :selected ,"cards" : [], 155"reason" :f" { backend } device numbering needs a qualified live probe" }, 156 [{"code" :"LIVE_GPU_PROBE_UNAVAILABLE" ,"severity" :"error" ,"message" : 157f" { backend } device/driver verification is not implemented for this command" }]) 158cards ,reason = _nvidia_cards () 159if cards is None : 160severity = "error" if selected is not None or backend == "cuda" else "warning" 161return ({"status" :"unavailable" ,"selected_indices" :selected ,"cards" : [],"reason" :reason }, 162 [{"code" :"LIVE_GPU_PROBE_UNAVAILABLE" ,"severity" :severity ,"message" :reason }]) 163available = {card ["index" ]for card in cards } 164missing = [index for index in selected or []if index not in available ] 165issues = ([{"code" :"GPU_NOT_VISIBLE" ,"severity" :"error" ,"message" : 166"selected NVIDIA device indices are not visible: " + ", " .join (map (str ,missing ))}] 167if missing else []) 168return ({"status" :"missing_selected" if missing else ("ok" if selected is not None else "selection_unverified" ), 169"selected_indices" :selected ,"cards" :cards , 170"scope" :"host card inventory only; engine execution, CUDA compatibility and topology unverified" },issues ) 171 172 173def inspect (config_path :Path | None ,* ,profile_id :str | None = None ,live :bool = False )-> dict : 174report = {"schema_version" :1 ,"profile" :profile_id ,"source_config" :str (config_path )if config_path else None , 175"components" : [],"issues" : [],"backend" :None ,"devices_selected" :None , 176"live_gpu_probe" :None } 177components :list [dict ]= report ["components" ] 178if config_path is None : 179report ["issues" ].append ({"code" :"PROFILE_NOT_SELECTED" ,"severity" :"info" , 180"message" :"select a run config or saved profile for model-specific checks" }) 181components .append ({"name" :"terminal_cli" ,"status" :"ok" ,"kind" :"python_module" ,"required" :True }) 182components .append (_monitor_component ()) 183if live : 184report ["issues" ].append ({"code" :"PROFILE_NOT_SELECTED_FOR_LIVE_PROBE" ,"severity" :"error" , 185"message" :"select a profile to compare its chosen devices with the host" }) 186report ["ok" ]= not live 187return report 188 189cfg = read_run_config (config_path ) 190report ["backend" ]= cfg .get ("backend" )or "cuda_or_cpu_unverified" 191report ["devices_selected" ]= cfg .get ("gpu" ) 192exe = _location (cfg ["exe" ],cfg ,config_path ) 193components .append (_item ("engine" ,exe ,"file" )) 194if components [- 1 ]["status" ]== "ok" and os .name != "nt" and not os .access (exe ,os .X_OK ): 195components [- 1 ]["status" ]= "invalid" 196components [- 1 ]["reason" ]= "engine file is not executable" 197build = exe .parent / "BUILD.json" 198if build .is_file (): 199try : 200value = json .loads (build .read_text (encoding = "utf-8" )) 201if isinstance (value ,dict ): 202components [- 1 ]["version" ]= value .get ("version" ) 203except (OSError ,ValueError ): 204components [- 1 ]["build_metadata" ]= "invalid" 205else : 206components [- 1 ]["build_metadata" ]= "unavailable" 207 208tokenizer = _location (cfg ["tokenizer" ],cfg ,config_path ) 209for child in ("vocab.json" ,"merges.txt" ,"token_type.json" ): 210components .append (_item (f"tokenizer/ { child } " ,tokenizer / child ,"file" )) 211 212args = cfg ["args" ] 213for index ,arg in enumerate (args ): 214kind = PATH_FLAGS .get (arg ) 215if kind is None : 216continue 217if index + 1 >= len (args ): 218components .append ({"name" :arg ,"status" :"invalid" ,"kind" :kind , 219"required" :True ,"reason" :"missing argument value" }) 220continue 221raw = args [index + 1 ] 222if arg == "--mtp" and str (raw ).isdigit (): 223continue # Qwen3.6: --mtp 2 is the draft depth, not a folder (#3298) 224if kind == "file_with_scale" : 225candidate ,separator ,scale = raw .rpartition (":" ) 226if separator : 227try : 228float (scale ) 229raw = candidate 230except ValueError : 231pass 232kind = "file" 233# The MTP layer is one of two drafters, never both: a model whose drafter is DFlash2, or Off, has no layer on disk, and the run config keeps `--mtp <folder>` 234# for a later switch to the MTP. Its absence then does not make the model unusable (strata_control/drafting.py loads the drafter that is there). 235components .append (_item (arg .lstrip ("-" ),_location (raw ,cfg ,config_path ),kind ,required =not (arg == "--mtp" and not _drafter_needs_mtp (cfg )))) 236 237vision = cfg .get ("vision" ) 238if isinstance (vision ,dict ): 239for key in ("exe" ,"mmproj" ,"model" ): 240raw = vision .get (key ) 241if isinstance (raw ,str )and raw : 242components .append (_item (f"vision/ { key } " ,_location (raw ,cfg ,config_path ),"file" )) 243else : 244components .append ({"name" :f"vision/ { key } " ,"status" :"invalid" ,"kind" :"file" , 245"required" :True ,"reason" :"missing path" }) 246 247components .append (_monitor_component ()) 248driver_name = "rocminfo" if cfg .get ("backend" )== "hip" else "nvidia-smi" 249components .append ({"name" :"gpu_driver_probe" ,"status" :"unverified" ,"kind" :"external_tool" , 250"required" :False ,"tool" :shutil .which (driver_name ), 251"reason" :"device/driver compatibility needs a live probe on the target host" }) 252for item in components : 253if item ["status" ]in ("missing" ,"invalid" )and item ["required" ]: 254report ["issues" ].append ({"code" :"COMPONENT_" + item ["status" ].upper (),"severity" :"error" , 255"component" :item ["name" ],"message" :item .get ("reason" )or "required component unavailable" }) 256access = _device_access_issue (cfg .get ("backend" )) 257if access : 258report ["issues" ].append (access ) 259cpu_pack = _cpu_pack_issue (cfg ,config_path ) 260if cpu_pack : 261report ["issues" ].append (cpu_pack ) 262if live : 263report ["live_gpu_probe" ],live_issues = _live_probe (cfg ,report ["backend" ]) 264report ["issues" ].extend (live_issues ) 265report ["ok" ]= not any (issue ["severity" ]== "error" for issue in report ["issues" ]) 266report ["integrity" ]= "unverified_no_manifest_hashes" 267return report 268 269 270def _device_access_issue (backend :str | None ,dev_root :str = "/dev" )-> dict | None : 271"""Linux Intel (SYCL) and AMD (HIP) open the card through /dev/dri/renderD* (and /dev/kfd): a user outside the `render` 272group gets "No device of requested type available" from the engine, which names nothing to fix. None when it is fine, 273cannot apply (other OS, other backend) or there is no such device node at all.""" 274if backend not in ("sycl" ,"hip" )or not sys .platform .startswith ("linux" ): 275return None 276nodes = sorted (Path (dev_root ,"dri" ).glob ("renderD*" )) 277if backend == "hip" and Path (dev_root ,"kfd" ).exists (): 278nodes .append (Path (dev_root ,"kfd" )) 279if not nodes or any (os .access (node ,os .R_OK | os .W_OK )for node in nodes ): 280return None 281return {"code" :"GPU_DEVICE_ACCESS" ,"severity" :"warning" , 282"message" :f"this user cannot open { ', ' . join ( str ( n ) for n in nodes ) } ; the { backend } engine will not see the card. " 283"Add the user to the `render` group (and `video` for some distributions), then log in again" } 284 285 286AVX512_FULL = {"avx512f" ,"avx512bw" ,"avx512vl" ,"avx512_vnni" ,"avx512vbmi" }# what the Q2_0 pack's CPU kernel uses 287 288 289def _cpu_flags (cpuinfo :str = "/proc/cpuinfo" )-> set [str ]| None : 290"""The CPU feature flags on Linux; None where they cannot be read (other OS, no /proc).""" 291if not sys .platform .startswith ("linux" ): 292return None 293try : 294for line in Path (cpuinfo ).read_text (encoding = "utf-8" ,errors = "replace" ).splitlines (): 295if line .startswith ("flags" ): 296return set (line .partition (":" )[2 ].split ()) 297except OSError : 298return None 299return None 300 301 302def _cpu_pack_issue (cfg :dict ,config_path :Path ,cpuinfo :str = "/proc/cpuinfo" )-> dict | None : 303"""The canonical Q2_0 pack (a --pack folder with index.txt and no native_experts.txt) has an AVX-512 CPU kernel; the engine stops at 304start on any other CPU with "this CPU cannot run the expert kernel". An i-quant, NVFP4 or Unsloth pack (native_experts.txt) runs on AVX2 305CPUs. None when it is fine, cannot apply (a pack of another engine, a CPU whose flags cannot be read) or there is no such pack.""" 306args = cfg .get ("args" )or [] 307if "--pack" not in args or args .index ("--pack" )+ 1 >= len (args ): 308return None 309pack = _location (args [args .index ("--pack" )+ 1 ],cfg ,config_path ) 310if not (pack / "index.txt" ).is_file ()or (pack / "native_experts.txt" ).exists ()or (pack / "ds4.txt" ).exists (): 311return None 312flags = _cpu_flags (cpuinfo ) 313if flags is None or AVX512_FULL <= flags : 314return None 315return {"code" :"CPU_PACK_NEEDS_AVX512" ,"severity" :"warning" , 316"message" :f" { pack } is the pack for CPUs with AVX-512 (it has no native_experts.txt), and this CPU has no AVX-512 (Ryzen 3000-5000 and " 317"Intel Core 12th-14th generation do not): the engine will stop at start. Run `strata setup` again; on this CPU it builds " 318"the pack that runs on AVX2" } 319 320 321def _monitor_component ()-> dict : 322component = {"name" :"monitor_tui" ,"kind" :"python_module" ,"required" :False , 323"expected_version" :MONITOR_TEXTUAL_VERSION } 324try : 325found = util .find_spec ("textual" ) 326except (ImportError ,ValueError ): 327found = None 328if found is None : 329return {** component ,"status" :"optional_missing" , 330"reason" :"install the optional monitor dependency from requirements-monitor.txt" } 331try : 332version = metadata .version ("textual" ) 333except metadata .PackageNotFoundError : 334return {** component ,"status" :"unverified" , 335"reason" :"Textual module is present but its installed version is unavailable" } 336if version != MONITOR_TEXTUAL_VERSION : 337return {** component ,"status" :"unverified" ,"version" :version , 338"reason" :f"interactive monitor was qualified with Textual { MONITOR_TEXTUAL_VERSION } " } 339return {** component ,"status" :"ok" ,"version" :version , 340"check" :"package_version_only" }