okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bc6f248ff
main
1"""Bounded, read-only discovery of setup-written local model run configs. 2 3The setup installer writes strata-*.json beside setup.py. A configured model is 4not automatically a compatible or loadable model: component presence and native 5engine compatibility are reported separately. 6 7Finding an existing install: a terminal archive is a new folder with no run configs in it. The places where Strata 8installs keep run configs (the Terminal's own folder, the folders earlier installs remembered in the user's settings file, 9and the desktop app's install folder, which the Terminal shares) are searched read-only by strata_control/discovery.py, 10the same function the launch screens use; the first place that has any is the main one. Nothing is copied or moved: 11the configs name their engine and model files by absolute path, so the old install and its data folder keep 12serving the models. 13""" 14 15from __future__import annotations 16 17import hashlib 18import json 19import os 20import re 21import stat 22import sys 23from pathlib import Path 24 25from strata_control import discovery 26from strata_control .doctor import inspect as inspect_components 27from strata_control .gguf_preflight import inspect_metadata ,real_model_file 28from strata_control .profiles import ProfileError 29 30 31ROOT = Path (__file__ ).resolve ().parents [1 ] 32# a dot is allowed inside the name (DeepSeek-V4.1-Flash: "deepseek-v4.1-flash-ist-das-2.00bpw"), never two in a row and never first 33MODEL_ID = re .compile (r"[a-z0-9](?:[a-z0-9_-]|\.(?!\.)){0,127}\Z" ) 34MAX_CONFIG_BYTES = 1024 * 1024 35MAX_CONFIGS = 128 36MAX_IMPORT_SHARDS = 128 37SHARD = re .compile (r"(.+)-(\d{5})-of-(\d{5})\.gguf\Z" ,re .I ) 38SUPPORTED_SELECTIONS = frozenset ({"qwen/Q2_0" ,"qwen/IQ2_XS" ,"qwen/IQ3_XXS" ,"qwen/IQ3_S" , 39"swift/IQ2_XS" ,"swift/IQ3_XXS" ,"swift/IQ3_S" ,"coder/IQ1_M" , 40"unsloth/UD-IQ4_XS" ,"unsloth/UD-Q4_K_XL" ,"unsloth/UD-Q5_K_XL" ,"unsloth/UD-Q6_K_XL" , 41# round 0214: Unsloth's v3.1 sets (revision d9620119); the v3.1 UD-IQ4_XS has its own name, its Hub file names are UD-IQ4_XS's with four shards 42"unsloth/UD-IQ1_M" ,"unsloth/UD-Q2_0" ,"unsloth/UD-IQ2_XS" ,"unsloth/UD-Q2_K_XL" ,"unsloth/UD-IQ3_XXS" , 43"unsloth/UD-Q3_K_XL" ,"unsloth/UD-IQ4_XS-v31" , 44"unsloth/Q8_0" ,"gyro/Gyro-S" ,"gyro/Gyro-M" }) 45 46 47def settings_path ()-> Path : 48"""The user's Strata settings file: the same place setup.py writes it (%APPDATA%/Strata/settings.json, or 49$XDG_CONFIG_HOME/strata/settings.json). The desktop app sets STRATA_SETTINGS_FILE to a file of its own (in its data folder), so it 50never reads an older command-line install's list of Strata folders.""" 51return discovery .own_settings_file () 52 53 54def remembered_installs ()-> list [Path ]: 55"""Earlier Strata folders recorded in the settings file, newest first. Read-only; a missing or unreadable file 56is an empty list.""" 57return discovery ._installs_in (discovery ._read_json (settings_path ()))# noqa: SLF001 58 59 60def _has_configs (directory :Path )-> bool : 61try : 62return directory .is_dir ()and bool (_paths (directory )) 63except (ProfileError ,OSError ): 64return False 65 66 67def resolve_install (override :str | None = None )-> tuple [Path ,str ]: 68"""(the main install folder, how it was found): explicit (an argument or STRATA_INSTALL_DIR), here (this folder has run 69configs), remembered (an earlier install from the settings file), app (the desktop app's install folder, shared with the 70Terminal) or default (the app's folder, with no model in it yet).""" 71raw = override or os .environ .get ("STRATA_INSTALL_DIR" ) 72if raw is not None : 73path = Path (raw ).expanduser () 74if not path .is_absolute ()or not path .is_dir (): 75raise ProfileError ("install directory must be an existing absolute directory" ,5 ) 76return path .resolve (),"explicit" 77return discovery .find_install (here = ROOT ) 78 79 80def all_installs (override :str | None = None )-> list [tuple [Path ,str ]]: 81"""Every folder with run configs, main one first: what `strata models list` shows and what the launch screens read.""" 82directory ,source = resolve_install (override ) 83if source == "explicit" : 84return [(directory ,source )] 85found = [(p .path ,p .source )for p in discovery .places (here = ROOT )] 86return found or [(directory ,source )] 87 88 89def install_dir (override :str | None = None )-> Path : 90return resolve_install (override )[0 ] 91 92 93def _model_id (path :Path )-> str | None : 94if not path .name .startswith ("strata-" )or not path .name .endswith (".json" )or \ 95path .name .endswith (".shared-settings.json" ): 96return None 97value = path .name [len ("strata-" ):- len (".json" )] 98return value if MODEL_ID .fullmatch (value )else None 99 100 101def _paths (directory :Path )-> list [tuple [str ,Path ]]: 102try : 103entries = [(name ,path )for path in directory .iterdir ()if (name := _model_id (path ))is not None ] 104except OSError : 105raise ProfileError ("cannot read installed model directory" ,5 )from None 106if len (entries )> MAX_CONFIGS : 107raise ProfileError ("more than 128 model configs need inspection" ,5 ) 108return sorted (entries ,key = lambda item :item [0 ]) 109 110 111def _read (path :Path )-> tuple [bytes ,dict ]: 112flags = os .O_RDONLY | getattr (os ,"O_NOFOLLOW" ,0 ) 113try : 114if stat .S_ISLNK (path .lstat ().st_mode ): 115raise ProfileError ("run config must not be a symlink" ,5 ) 116descriptor = os .open (path ,flags ) 117with os .fdopen (descriptor ,"rb" )as stream : 118details = os .fstat (stream .fileno ()) 119if not stat .S_ISREG (details .st_mode )or details .st_size > MAX_CONFIG_BYTES : 120raise ProfileError ("run config must be a regular file under 1 MiB" ,5 ) 121raw = stream .read (MAX_CONFIG_BYTES + 1 ) 122if len (raw )> MAX_CONFIG_BYTES : 123raise ProfileError ("run config exceeds 1 MiB" ,5 ) 124value = json .loads (raw .decode ("utf-8-sig" )) 125except (OSError ,UnicodeError ,ValueError )as exc : 126if isinstance (exc ,ProfileError ): 127raise 128raise ProfileError ("run config is unreadable or invalid JSON" ,5 )from None 129if not isinstance (value ,dict )or not isinstance (value .get ("exe" ),str )or not value ["exe" ]or \ 130not isinstance (value .get ("tokenizer" ),str )or not value ["tokenizer" ]or \ 131not isinstance (value .get ("args" ),list )or \ 132not all (isinstance (arg ,str )for arg in value ["args" ]): 133raise ProfileError ("run config lacks engine, tokenizer or string arguments" ,5 ) 134return raw ,value 135 136 137def _short (value :object )-> str | None : 138if not isinstance (value ,str ): 139return None 140return "" .join (char if char .isprintable ()and char not in "\x1b\x7f" else " " for char in value )[:120 ] 141 142 143def _arg (args :list [str ],flag :str )-> str | None : 144try : 145index = args .index (flag ) 146return args [index + 1 ]if index + 1 < len (args )else None 147except ValueError : 148return None 149 150 151def _missing_parts (report :dict )-> list [dict ]: 152"""The required parts a model's run config names that are not there: {"part": the component, "file": its file or folder name, 153"status": "missing" | "invalid"}. The app names them so a person is not told only that "some files are missing" (#3478).""" 154found = [] 155for item in report .get ("components" , []): 156if item .get ("required" )and item .get ("status" )in ("missing" ,"invalid" ): 157where = item .get ("path" ) 158found .append ({"part" :_short (item .get ("name" )),"file" :_short (os .path .basename (str (where ).rstrip ("/\\" )))if where else None , 159"status" :item ["status" ]}) 160return found [:12 ] 161 162 163def _summary (model_id :str ,path :Path ,raw :bytes ,cfg :dict ,report :dict )-> dict : 164context = _arg (cfg ["args" ],"--max-context" ) 165context_tokens = int (context )if isinstance (context ,str )and 1 <= len (context )<= 8 and \ 166context .isascii ()and context .isdecimal ()and 1 <= int (context )<= 16_777_216 else None 167backend = cfg .get ("backend" ) 168return {"id" :model_id ,"name" :_short (cfg .get ("model_name" ))or model_id , 169"source_config" :str (path ),"source_sha256" :hashlib .sha256 (raw ).hexdigest (), 170"backend" :_short (backend )if backend is not None else None , 171"context_tokens" :context_tokens , 172"component_status" :"present" if report ["ok" ]else "missing_or_invalid" , 173"issue_codes" : [item .get ("code" )for item in report ["issues" ]][:32 ], 174"missing" :_missing_parts (report ), 175"execution_compatibility" :"unverified" } 176 177 178def _inspect_one (model_id :str ,path :Path )-> tuple [dict ,dict ]: 179raw ,cfg = _read (path ) 180from strata_control import retired 181if retired .config_reason (cfg )or retired .config_file_reason (path ): 182# DeepSeek: listed so the person sees it and where its files are, never inspected, started or written (strata_control/retired.py) 183report = {"ok" :False ,"issues" : []} 184summary = _summary (model_id ,path ,raw ,cfg ,report ) 185summary .update (component_status = "retired" ,retired = "deepseek" ,name = retired .title (cfg ,path ),retired_line = retired .row_line (cfg ), 186refusal = retired .refusal (cfg ,retired .title (cfg ,path )),execution_compatibility = "retired" ) 187return summary ,report 188try : 189report = inspect_components (path ) 190after ,_ = _read (path ) 191except (OSError ,ValueError ): 192raise ProfileError ("run config changed or became invalid during inspection" ,6 )from None 193if after != raw : 194raise ProfileError ("run config changed during inspection; retry" ,6 ) 195return _summary (model_id ,path ,raw ,cfg ,report ),report 196 197 198def list_installed (override :str | None = None )-> dict : 199directory ,source = resolve_install (override ) 200places = all_installs (override ) 201models = [] 202for place ,place_source in places : 203try : 204entries = _paths (place )if place .is_dir ()else [] 205except ProfileError as exc : 206models .append ({"id" :place .name ,"install_dir" :str (place ),"component_status" :"invalid" ,"error" :str (exc ), 207"execution_compatibility" :"unverified" }) 208continue 209for model_id ,path in entries : 210if any (m .get ("id" )== model_id for m in models ): 211continue # the same model in a later place: the main one wins 212try : 213summary ,_ = _inspect_one (model_id ,path ) 214except ProfileError as exc : 215summary = {"id" :model_id ,"source_config" :str (path ),"component_status" :"invalid" , 216"error" :str (exc ),"execution_compatibility" :"unverified" } 217summary ["install_dir" ]= str (place ) 218summary ["install_dir_source" ]= place_source 219models .append (summary ) 220return {"scope" :"local_run_configs" ,"install_dir" :str (directory ),"install_dir_source" :source , 221"install_dirs" : [str (p )for p ,_ in places ], 222"models" :models , 223"model_count" :len (models ),"discovery_limit" :MAX_CONFIGS } 224 225 226def inspect (model_id :str ,override :str | None = None )-> dict : 227if not isinstance (model_id ,str )or not MODEL_ID .fullmatch (model_id ): 228raise ProfileError ("model ID must be a setup config name without a path" ) 229directory ,path = None ,None 230for place ,_src in all_installs (override ): 231try : 232choices = dict (_paths (place ))if place .is_dir ()else {} 233except ProfileError : 234continue 235if model_id in choices : 236directory ,path = place ,choices [model_id ] 237break 238if path is None : 239raise ProfileError (f"model { model_id !r } is not configured in this installation" ,5 ) 240summary ,report = _inspect_one (model_id ,path ) 241return {"scope" :"local_run_config" ,"install_dir" :str (directory ),"model" :summary , 242"components" :report } 243 244 245def _gguf_header (path :Path )-> dict : 246"""The first bytes of one model file (a link to it is followed: Hugging Face cache snapshots and Ollama blobs are links).""" 247real = real_model_file (path ) 248try : 249descriptor = os .open (real ,os .O_RDONLY ) 250with os .fdopen (descriptor ,"rb" )as stream : 251details = os .fstat (stream .fileno ()) 252if not stat .S_ISREG (details .st_mode )or details .st_size < 8 : 253raise ProfileError ("GGUF shard is not a nonempty regular file" ,5 ) 254header = stream .read (8 ) 255except OSError : 256raise ProfileError ("GGUF shard is unreadable" ,5 )from None 257if header [:4 ]!= b"GGUF" : 258raise ProfileError ("file does not begin with a GGUF header" ,5 ) 259version = int .from_bytes (header [4 :8 ],"little" ) 260if version not in (2 ,3 ): 261raise ProfileError ("GGUF header version is not recognized" ,5 ) 262return {"name" :path .name ,"path" :str (path ),"bytes" :details .st_size , 263"gguf_version" :version } 264 265 266def _candidate_selection (shards :list [Path ])-> dict | None : 267fingerprint_file = ROOT / "data" / "gguf_fingerprints.json" 268try : 269if fingerprint_file .stat ().st_size > 128 * 1024 : 270raise ProfileError ("model fingerprint catalog exceeds 128 KiB" ,5 ) 271catalog = json .loads (fingerprint_file .read_text (encoding = "utf-8" )) 272except (OSError ,UnicodeError ,ValueError ): 273raise ProfileError ("model fingerprint catalog is unavailable" ,5 )from None 274names = {item .name for item in shards } 275for selection in sorted (SUPPORTED_SELECTIONS ): 276row = catalog .get (selection )if isinstance (catalog ,dict )else None 277expected = row .get ("files" )if isinstance (row ,dict )else None 278if isinstance (expected ,list )and expected and names == {Path (name ).name for name in expected }: 279family ,model = selection .split ("/" ,1 ) 280expected_experts = row .get ("expert_bytes" ) 281return {"family" :family ,"model" :model ,"basis" :"known_shard_names_only" , 282"expected_expert_types" :sorted (expected_experts )if isinstance (expected_experts ,dict )else [], 283"expected_tensor_count" :row .get ("tensors" )if type (row .get ("tensors" ))is int else None , 284"setup_args_hint" : ["--family" ,family ,"--model" ,model , 285"--gguf-dir" ,str (shards [0 ].parent )]} 286return None 287 288 289def _candidate_by_header (shards :list [Path ],tensors :int ,payload :int ,experts :set [str ])-> dict | None : 290"""A file set whose NAME setup does not know (renamed, or downloaded elsewhere) but whose header is exactly a known one: the same tensor 291count, the same payload size and the same expert formats as a row of the fingerprint table.""" 292try : 293catalog = json .loads ((ROOT / "data" / "gguf_fingerprints.json" ).read_text (encoding = "utf-8" )) 294except (OSError ,UnicodeError ,ValueError ): 295return None 296for selection in sorted (SUPPORTED_SELECTIONS ): 297row = catalog .get (selection )if isinstance (catalog ,dict )else None 298if not isinstance (row ,dict )or row .get ("tensors" )!= tensors or row .get ("bytes" )!= payload : 299continue 300expected = row .get ("expert_bytes" ) 301if not isinstance (expected ,dict )or set (expected )!= experts : 302continue 303family ,model = selection .split ("/" ,1 ) 304return {"family" :family ,"model" :model ,"basis" :"header_size_and_tensors" , 305"expected_expert_types" :sorted (expected ),"expected_tensor_count" :tensors , 306"setup_args_hint" : ["--family" ,family ,"--model" ,model ,"--gguf-dir" ,str (shards [0 ].parent )]} 307return None 308 309 310def known_set_by_header (first_shard :Any )-> str | None : 311"""``family/model`` (``qwen/IQ3_S``, ``unsloth/UD-Q4_K_XL``) of the file set that starts at ``first_shard`` when its header is EXACTLY one row of data/gguf_fingerprints.json: the same tensor count, 312the same payload size and the same expert formats over every shard (the other shards are found beside the first by their ``-00001-of-0000N`` names). Never the layout guess of 313``_candidate_by_layout``. None: no exact match, a shard missing, or a file that cannot be read.""" 314try : 315path = Path (first_shard ) 316match = SHARD .match (path .name ) 317if match : 318total = int (match .group (3 )) 319if not 1 <= total <= MAX_IMPORT_SHARDS : 320return None 321shards = [path .with_name (f" { match . group ( 1 ) } - { i :05d } -of- { total :05d } .gguf" )for i in range (1 ,total + 1 )] 322if not all (p .is_file ()for p in shards ): 323return None 324else : 325shards = [path ] 326tensors = payload = 0 327experts :set [str ]= set () 328for number ,item in enumerate (shards ): 329inspected = inspect_metadata (item ) 330# the first shard names the architecture; a later shard of a split set (llama.cpp's gguf-split, Strata's own IQ3_S) carries tensors only: no architecture is no objection, another one is 331if inspected ["architecture" ]!= "qwen4exp" and (number == 0 or inspected ["architecture" ]is not None ): 332return None 333experts .update (inspected ["expert_tensor_types" ]) 334tensors += inspected ["tensor_count_scanned" ] 335payload += int (inspected .get ("payload_bytes_required" )or 0 ) 336found = _candidate_by_header (shards ,tensors ,payload ,experts ) 337return f" { found [ 'family' ] } / { found [ 'model' ] } " if found else None 338except Exception :# noqa: BLE001 - a file that cannot be judged is not matched 339return None 340 341 342def _candidate_by_layout (shards :list [Path ],tensors :int ,payload :int ,experts :set [str ])-> dict | None : 343"""A qwen4exp file set that is no build Strata has tested (a fine-tune, a K-quant mix from another maker) but has the layout of one 344(#3651 #3777): the closest row by expert formats, then by size. Strata uses the files as that model and says so; it never refuses a 345working file for not being on the list (recommend, never force).""" 346try : 347catalog = json .loads ((ROOT / "data" / "gguf_fingerprints.json" ).read_text (encoding = "utf-8" )) 348except (OSError ,UnicodeError ,ValueError ): 349return None 350best = None 351for selection in sorted (SUPPORTED_SELECTIONS ): 352row = catalog .get (selection )if isinstance (catalog ,dict )else None 353if not isinstance (row ,dict )or row .get ("tensors" )!= tensors or not isinstance (row .get ("expert_bytes" ),dict ): 354continue 355have = set (row ["expert_bytes" ]) 356union = have | experts 357score = (len (have & experts )/ len (union ))if union else 0.0 358key = (- score ,abs (int (row .get ("bytes" )or 0 )- payload ),selection ) 359if score > 0 and (best is None or key < best [0 ]): 360best = (key ,selection ,have ) 361if best is None : 362return None 363family ,model = best [1 ].split ("/" ,1 ) 364return {"family" :family ,"model" :model ,"basis" :"same_layout_other_build" , 365"expected_expert_types" :sorted (best [2 ]| experts ),"expected_tensor_count" :tensors , 366"setup_args_hint" : ["--family" ,family ,"--model" ,model ,"--gguf-dir" ,str (shards [0 ].parent )]} 367 368 369def _already_set_up (shards :list [Path ],candidate :dict | None )-> dict | None : 370"""Is this model already installed (a run config of any known install names the file) and what was prepared beside it (pack, draft 371layer, picture reader)? Read-only; None when the file set is not one Strata knows.""" 372if not shards or candidate is None : 373return None 374first = shards [0 ] 375cfg = discovery .run_config_for (first ,discovery .places (here = ROOT )) 376beside = discovery .prepared_beside (first ,discovery .remembered_data_dirs ())# the data folder in use too: a model folder outside it must not hide the draft layer setup wrote there 377if cfg is None and not any (beside .get (k )for k in ("pack" ,"mtp" ,"mmproj" )): 378return {"config" :None ,"data_dir" :str (beside ["data_dir" ])if beside .get ("data_dir" )else None ,"pack" :None ,"mtp" :None ,"mmproj" :None } 379return {"config" :str (cfg )if cfg else None ,** {k : (str (v )if v else None )for k ,v in beside .items ()}} 380 381 382ISSUE_WORDS = { 383"multiple_model_groups" :"the folder holds more than one model" , 384"incomplete_or_invalid_shard_set" :"some parts of the model are missing" , 385"unrecognized_or_unsupported_model_variant" :"this is not a model size Strata knows" , 386"unsupported_or_missing_architecture" :"this model type is not supported by the Strata engine (add it as a Custom model API with llama-server instead)" , 387"unsupported_or_incomplete_tokenizer_metadata" :"the file has no usable tokenizer" , 388"missing_or_unexpected_expert_quantization" :"its quantization is not one Strata knows" , 389} 390# the checker's own sentences about one file, in words 391_REASON_WORDS = ( 392 ("not a nonempty regular file" ,"the file is empty or is not a file" ), 393 ("unreadable" ,"the file cannot be read (is it open in another program, or on a drive that is gone?)" ), 394 ("could not be read" ,"the file cannot be read (is it open in another program, or on a drive that is gone?)" ), 395 ("is missing" ,"the file is not there" ), 396 ("link to a file that is not there" ,"this is a shortcut to a file that is not there any more" ), 397 ("does not begin with a gguf header" ,"this is not a GGUF model file" ), 398 ("header version" ,"this GGUF is from a format Strata does not read" ), 399 ("requires gguf v3" ,"this GGUF is in an old format (version 2); Strata reads version 3" ), 400 ("metadata is truncated" ,"the file is cut short (a download or copy that did not finish)" ), 401 ("payload is shorter" ,"the file is shorter than its own header says (a download or copy that did not finish)" ), 402 ("exceeds the bounded inspection limit" ,"its header is larger than Strata reads" ), 403 ("too large to inspect" ,"its header is larger than Strata reads" ), 404 ("unsupported encoding or shape" ,"it stores weights in a format Strata does not read" ), 405 ("unsupported array type" ,"its header uses a type Strata does not read" ), 406 ("unsupported value type" ,"its header uses a type Strata does not read" ), 407 ("byte ranges overlap" ,"its header is damaged" ), 408 ("unsupported_architecture" ,"this model type is not supported by the Strata engine (add it as a Custom model API with llama-server instead)" ), 409 ("symlink" ,"this is a shortcut (symbolic link) that cannot be followed" ), 410) 411 412 413def plain_issue (code :str )-> str : 414"""One problem from the GGUF preview, in words, with the file's name when it is about one file 415(`file.gguf: GGUF shard is not a nonempty regular file`).""" 416code = str (code ) 417if code in ISSUE_WORDS : 418return ISSUE_WORDS [code ] 419name ,sep ,reason = code .partition (": " ) 420if not (sep and name .lower ().endswith (".gguf" )): 421name ,reason = "" ,code 422low = reason .lower () 423words = next ((w for key ,w in _REASON_WORDS if key in low ),reason .replace ("_" ," " )) 424return f" { name } : { words } " if name else words 425 426 427def missing_words (missing :list | None )-> str : 428""""x-00002-of-00002.gguf is missing" for the shards of a split model that are not in the folder (#3478); "" when none are known.""" 429names = [str (n )for n in missing or []] 430if not names : 431return "" 432if len (names )== 1 : 433return f" { names [ 0 ] } is missing" 434if len (names )== 2 : 435return f" { names [ 0 ] } and { names [ 1 ] } are missing" 436return f" { names [ 0 ] } , { names [ 1 ] } and { len ( names ) - 2 } more files are missing" 437 438 439def problem_words (issues :list ,limit :int = 3 ,missing :list | None = None )-> str : 440"""The problems of a file set as ONE sentence part, each said once: the same reason for several files names the files together 441("a.gguf and b.gguf: the file is cut short"), a reason that was already given is not given again, and a long list is cut with a count. 442A folder that holds several models does not also say "not a size Strata knows".""" 443codes = [str (x )for x in issues or []] 444named = missing_words (missing ) 445if named :# the generic "some parts are missing" is replaced by the files 446codes = [x for x in codes if x != "incomplete_or_invalid_shard_set" ] 447if "multiple_model_groups" in codes : 448codes = [x for x in codes if x != "unrecognized_or_unsupported_model_variant" ] 449by_reason :dict [str ,list [str ]]= {} 450for code in codes : 451words = plain_issue (code ) 452name ,sep ,reason = words .partition (": " ) 453if sep and name .lower ().endswith (".gguf" ): 454by_reason .setdefault (reason , []).append (name ) 455else : 456by_reason .setdefault (words , []) 457parts = [named ]if named else [] 458for reason ,names in by_reason .items (): 459if not names : 460parts .append (reason ) 461elif len (names )<= 2 : 462parts .append (f" { ' and ' . join ( names ) } : { reason } " ) 463else : 464parts .append (f" { names [ 0 ] } , { names [ 1 ] } and { len ( names ) - 2 } more files: { reason } " ) 465if len (parts )> limit : 466parts = parts [:limit ]+ [f"and { len ( parts ) - limit } more problem" + ("s" if len (parts )- limit > 1 else "" )] 467return "; " .join (parts ) 468 469 470UNSUPPORTED_MODEL_TYPE = ("This model type isn't supported by the Strata engine. " 471"Add it as a Custom model API (llama-server) instead." ) 472# The picture readers Strata ships a pinned copy of (setup downloads and checks one of these next to the model). 473# (name, size in bytes) as setup.py pins them: setup would delete a file of that name with another size, so only an exact 474# match is called "the official one". 475PINNED_PROJECTORS = {"mmproj-qwen3.8-flash-next-bf16.gguf" :907543008 ,"mmproj-f16.gguf" :899283584 } 476OUR_PROJECTOR_TYPES = {"qwen3vl_merger" } 477 478 479def _assess_projector (path :Path )-> dict : 480"""What a picture-reader file (mmproj*.gguf) next to a model is, in words; never blocks the import.""" 481try : 482size = path .stat ().st_size 483except OSError : 484size = - 1 485row = {"name" :path .name ,"status" :"unreadable" ,"pinned" :PINNED_PROJECTORS .get (path .name .lower ())== size } 486try : 487info = inspect_metadata (path ) 488except ProfileError : 489row ["plain" ]= f" { path . name } could not be read as a picture reader, so it is not used." 490return row 491row ["architecture" ],row ["projector_type" ]= info ["architecture" ],info .get ("projector_type" ) 492if info ["architecture" ]!= "clip" : 493row ["status" ]= "not_a_projector" 494row ["plain" ]= f" { path . name } is not a picture reader (mmproj) file, so it is not used." 495elif info .get ("projector_type" )not in OUR_PROJECTOR_TYPES : 496row ["status" ]= "unsupported" 497row ["plain" ]= (f" { path . name } reads pictures for a different kind of model. " 498"Strata cannot use it; add that model as a Custom model API (llama-server) instead." ) 499elif row ["pinned" ]: 500row ["status" ]= "ok" 501row ["plain" ]= f" { path . name } is the picture reader Strata uses for this model family; pictures will work." 502else : 503row ["status" ]= "other_name" 504row ["plain" ]= (f" { path . name } is a picture reader of the right kind but not the file Strata checks; " 505"Strata uses the official one (mmproj-Qwen3.8-Flash-Next-BF16.gguf) and " 506"downloads it when it is not in the folder." ) 507return row 508 509 510MAX_LISTED = 5000 # .gguf files looked at in one folder (the checker reads headers of the chosen set only) 511MAX_TREE_DIRS = 300 # folders looked into when the picked folder holds no GGUF itself 512TREE_DEPTH = 3 513SKIP_DIRS = frozenset ({"packs" ,"mtp" ,"engine" ,"node_modules" ,"windows" ,"program files" ,"program files (x86)" , 514"$recycle.bin" ,"system volume information" ,"appdata" }) 515 516 517DRAFT_LAYER = re .compile (r"mtp[-_][a-z0-9_.-]*\.gguf" ) 518 519 520def _list_gguf (folder :Path )-> tuple [list [Path ],list [str ],bool ]: 521"""(model files, picture-reader file names, cut) of one folder. A link to a file counts (it is followed when read); a name that 522only ends in .gguf but is a folder does not.""" 523shards :list [Path ]= [] 524readers :list [str ]= [] 525cut = False 526try : 527with os .scandir (folder )as entries : 528for entry in entries : 529low = entry .name .lower () 530if not low .endswith (".gguf" ): 531continue 532try : 533is_file = entry .is_file ()or entry .is_symlink () 534except OSError : 535is_file = False 536if not is_file : 537continue 538if low .startswith ("mmproj" ): 539readers .append (entry .name ) 540continue 541if DRAFT_LAYER .fullmatch (low ): 542continue # Strata's own draft layer (mtp-q2_0.gguf) is not a second model (#4693) 543if len (shards )>= MAX_LISTED : 544cut = True 545break 546shards .append (Path (entry .path )) 547except OSError : 548raise ProfileError ("cannot inspect GGUF directory" ,5 )from None 549return shards ,readers ,cut 550 551 552def _folders_with_models (root :Path )-> list [Path ]: 553"""The folders under `root` (a Strata data folder, a whole Hugging Face repository, a drive's model folder) that hold model files, 554breadth first, `TREE_DEPTH` levels deep. A folder with models is not searched further.""" 555found :list [Path ]= [] 556seen :set [str ]= set () 557queue = [(root ,0 )] 558while queue and len (seen )< MAX_TREE_DIRS : 559folder ,depth = queue .pop (0 ) 560try : 561key = os .path .normcase (os .path .realpath (folder )) 562except OSError : 563continue 564if key in seen : 565continue 566seen .add (key ) 567try : 568with os .scandir (folder )as scan : 569entries = sorted (scan ,key = lambda e :e .name .lower ()) 570except OSError : 571continue 572if any (e .name .lower ().endswith (".gguf" )and not e .name .lower ().startswith ("mmproj" )for e in entries ): 573found .append (folder ) 574continue 575if depth >= TREE_DEPTH : 576continue 577for e in entries : 578try : 579if e .is_dir ()and not e .name .startswith ("." )and e .name .lower ()not in SKIP_DIRS : 580queue .append ((Path (e .path ),depth + 1 )) 581except OSError : 582continue 583return found 584 585 586def _split_groups (shards :list [Path ])-> dict : 587"""Model files by set: (name before -0000i-of-0000N, N) -> files. A file with no shard number is a set of its own.""" 588groups :dict = {} 589for item in shards : 590match = SHARD .fullmatch (item .name ) 591key = (match .group (1 ),int (match .group (3 )))if match else (item .name ,1 ) 592groups .setdefault (key , []).append (item ) 593return groups 594 595 596def _known (members :list [Path ])-> dict | None : 597try : 598return _candidate_selection (sorted (members ,key = lambda item :item .name )) 599except ProfileError : 600return None 601 602 603def _holds (groups_by_place :list )-> list [dict ]: 604"""What a folder (or several) holds, set by set, for the message that asks the person to point at one.""" 605rows = [] 606for place ,members_by_key in groups_by_place : 607for key in sorted (members_by_key ): 608members = sorted (members_by_key [key ],key = lambda item :item .name ) 609sel = _known (members ) 610rows .append ({"file" :members [0 ].name ,"files" :len (members ),"folder" :str (place ), 611"family" :sel ["family" ]if sel else None ,"model" :sel ["model" ]if sel else None }) 612return rows 613 614 615def absolute (picked :str )-> str : 616"""The picked path as an absolute path, links left alone (a snapshot file in the Hugging Face cache keeps its model name).""" 617return os .path .abspath (os .path .expanduser (str (picked ))) 618 619 620def import_target (picked :str ,plan :dict )-> str : 621"""What to hand on as the person's model files: the file when they picked a file (a folder of several sizes needs the name), else the 622folder the model files are really in (they may have picked the folder above it).""" 623picked = absolute (picked ) 624try : 625if Path (picked ).is_file (): 626return picked 627except OSError : 628pass 629return plan .get ("model_dir" )or picked 630 631 632def own_path_problem (picked :str )-> tuple [str ,str ]| None : 633"""(what is wrong, what to do) when the path a person gave for their own model files is not there or holds no model file, in plain 634words; None when there is something to look at. Said before anything is installed or downloaded, with the path the person typed.""" 635path = Path (absolute (picked )) 636kind = "file" if path .name .lower ().endswith (".gguf" )else "folder" 637try : 638if not path .exists (): 639if path .is_symlink (): 640return (f"This { kind } is a shortcut to something that is not there any more: { path } ." , 641"Point it at the real folder, or at the .gguf file itself. Nothing was downloaded or changed." ) 642return (f"This { kind } does not exist: { path } ." , 643"Check the spelling, and that the drive or folder is connected (in Docker or a virtual machine it has to be shared with it). " 644"Nothing was downloaded or changed." ) 645if path .is_dir (): 646has_files = any (entry .name .lower ().endswith (".gguf" )for entry in os .scandir (path )) 647if not has_files and not _folders_with_models (path ): 648return (f"There are no .gguf model files in { path } , nor in the folders inside it." , 649"Point it at the folder that holds the model's .gguf files (names like ...-00001-of-00002.gguf), or at one of the files. " 650"Nothing was downloaded or changed." ) 651except OSError : 652return None 653return None 654 655 656def plan_import (raw_path :str )-> dict : 657"""Inspect a local candidate without copying, parsing tensors or adopting it. 658 659The picked path can be a .gguf file (any shard of a split set), the folder with the files, or a folder above it (a Strata data 660folder, a whole Hugging Face repository): the folder with the model is looked for, and when a folder holds several models 661the one Strata knows is used if it is the only one; with two it says which and asks for the file. The result's `model_dir` 662is the folder to hand to setup (--gguf-dir). Links to files and folders are followed.""" 663path = Path (raw_path ).expanduser () 664if not path .is_absolute (): 665raise ProfileError ("model import path must be absolute" ) 666try : 667details = path .stat () 668except OSError : 669raise ProfileError ("model import path does not exist (or is a link to something that is gone)" ,5 )from None 670from strata_control import retired 671if retired .folder_reason (path ):# DeepSeek files: named, never set up (strata_control/retired.py) 672raise ProfileError (retired .own_files (path ),5 ) 673notes :list [str ]= [] 674folder_holds :list [dict ]= [] 675issues :list [str ]= [] 676missing_shards :list [str ]= [] 677if stat .S_ISDIR (details .st_mode ): 678shards ,ignored_auxiliary ,cut = _list_gguf (path ) 679if cut : 680notes .append (f"This folder holds more than { MAX_LISTED } GGUF files; only the first { MAX_LISTED } were looked at." ) 681if not shards : 682places = _folders_with_models (path ) 683if not places : 684raise ProfileError ("no GGUF files found at the model import path (or in the folders inside it)" ,5 ) 685scanned = [(place ,* _list_gguf (place )[:2 ])for place in places ] 686usable = [(place ,files ,readers ,members )for place ,files ,readers in scanned 687for _key ,members in sorted (_split_groups (files ).items (),key = lambda kv :kv [0 ])if _known (members )] 688if len (usable )== 1 : 689place ,shards ,ignored_auxiliary ,members = usable [0 ] 690notes .append (f"The model files are in { place } ." ) 691else : 692place ,shards ,ignored_auxiliary = scanned [0 ] 693if len (usable )> 1 or len (scanned )> 1 : 694issues .append ("multiple_model_groups" ) 695folder_holds = _holds ([(p ,_split_groups (f ))for p ,f ,_r in scanned ]) 696else : 697notes .append (f"The model files are in { place } ." ) 698elif stat .S_ISREG (details .st_mode )and path .name .lower ().endswith (".gguf" ): 699ignored_auxiliary = [] 700try :# the picture reader that sits next to a chosen model file 701ignored_auxiliary = [c .name for c in path .parent .iterdir () 702if c .name .lower ().startswith ("mmproj" )and c .name .lower ().endswith (".gguf" )][:8 ] 703except OSError : 704pass 705if path .name .lower ().startswith ("mmproj" ): 706raise ProfileError ("this is a picture reader (mmproj), not a model. Choose the model's own " 707".gguf file; Strata finds the reader next to it" ,5 ) 708match = SHARD .fullmatch (path .name ) 709if match : 710total = int (match .group (3 )) 711if not 1 <= total <= MAX_IMPORT_SHARDS : 712raise ProfileError ("GGUF shard count must be in 1..128" ,5 ) 713shards = [path .with_name (f" { match . group ( 1 ) } - { i :05d } -of- { total :05d } .gguf" ) 714for i in range (1 ,total + 1 )] 715else : 716shards = [path ] 717else : 718raise ProfileError ("model import needs a GGUF file or directory" ,5 ) 719if not shards : 720raise ProfileError ("no GGUF files found at the model import path" ,5 ) 721shards .sort (key = lambda item :item .name ) 722groups = _split_groups (shards ) 723if len (groups )!= 1 and "multiple_model_groups" not in issues : 724known_sets = [key for key ,members in groups .items ()if _known (members )] 725if len (known_sets )== 1 : 726# one set in the folder is a model Strata knows: use it and say what else is there 727keep = known_sets [0 ] 728others = sorted (sorted (m ,key = lambda x :x .name )[0 ].name for k ,m in groups .items ()if k != keep ) 729shards = sorted (groups [keep ],key = lambda item :item .name ) 730notes .append ("The folder also holds " + ", " .join (others [:6 ])+ (" and more" if len (others )> 6 else "" )+ 731f"; Strata uses { shards [ 0 ]. name } and leaves the others alone." ) 732groups = {keep :shards } 733else : 734issues .append ("multiple_model_groups" ) 735folder_holds = _holds ([(shards [0 ].parent ,groups )]) 736if len (groups )== 1 and "multiple_model_groups" not in issues : 737 (_ ,total ),members = next (iter (groups .items ())) 738found = {int (m .group (2 ))for m in (SHARD .fullmatch (item .name )for item in members )if m }or {1 } 739if total > MAX_IMPORT_SHARDS or found != set (range (1 ,total + 1 )): 740issues .append ("incomplete_or_invalid_shard_set" ) 741sample = next ((SHARD .fullmatch (item .name )for item in members if SHARD .fullmatch (item .name )),None ) 742if sample and total <= MAX_IMPORT_SHARDS :# #3478: name the files that are not there 743missing_shards = [f" { sample . group ( 1 ) } - { i :05d } -of- { total :05d } .gguf" for i in range (1 ,total + 1 )if i not in found ] 744files = [] 745for item in shards : 746if missing_shards and not item .exists (): 747continue # a shard that is named only to be reported missing has no header to read 748try : 749files .append (_gguf_header (item )) 750except ProfileError as exc : 751issues .append (f" { item . name } : { exc } " ) 752metadata = None 753observed_experts :set [str ]= set () 754observed_tensor_count = 0 755observed_payload = 0 756if files and not issues : 757for item in shards : 758try : 759inspected = inspect_metadata (item ) 760except ProfileError as exc : 761issues .append (f" { item . name } : { exc } " ) 762continue 763if metadata is None : 764metadata = inspected 765observed_experts .update (inspected ["expert_tensor_types" ]) 766observed_tensor_count += inspected ["tensor_count_scanned" ] 767observed_payload += int (inspected .get ("payload_bytes_required" )or 0 ) 768if inspected ["architecture" ]is not None and inspected ["architecture" ]!= "qwen4exp" : 769issues .append (f" { item . name } : unsupported_architecture" ) 770if metadata is not None : 771if metadata ["architecture" ]!= "qwen4exp" : 772issues .append ("unsupported_or_missing_architecture" ) 773if metadata ["tokenizer_model" ]!= "gpt2" or not metadata ["tokenizer_tokens_present" ]or \ 774not metadata ["tokenizer_merges_present" ]: 775issues .append ("unsupported_or_incomplete_tokenizer_metadata" ) 776model_dir = shards [0 ].parent 777projectors = [_assess_projector (model_dir / n )for n in sorted (ignored_auxiliary )[:8 ]] 778messages = list (notes ) 779if folder_holds : 780several = len ({h .get ("folder" )for h in folder_holds })> 1 781names = [(f" { h [ 'family' ] } { h [ 'model' ] } " if h .get ("model" )else h ["file" ])+ (f" in { h [ 'folder' ] } " if several else f" ( { h [ 'file' ] } )" ) 782for h in folder_holds [:8 ]] 783messages .append (f"The folder holds { len ( folder_holds ) } models: " + "; " .join (names )+ (" and more" if len (folder_holds )> 8 else "" )+ 784". Choose the folder of the one you want, or type the path of its .gguf file." ) 785if any (i .endswith ("unsupported_architecture" )or i == "unsupported_or_missing_architecture" for i in issues ): 786messages .append (UNSUPPORTED_MODEL_TYPE ) 787elif projectors : 788messages .extend (p ["plain" ]for p in projectors ) 789candidate = _candidate_selection (shards ) 790if candidate is None and metadata is not None and not issues : 791candidate = _candidate_by_header (shards ,observed_tensor_count ,observed_payload ,observed_experts ) 792if candidate is None : 793candidate = _candidate_by_layout (shards ,observed_tensor_count ,observed_payload ,observed_experts ) 794if candidate is not None : 795messages .append (f"These files are not exactly a build Strata has tested; they have the layout of { candidate [ 'family' ] } " 796f" { candidate [ 'model' ] } , so Strata uses them as that model. Check a few answers before you rely on them." ) 797if "multiple_model_groups" in issues : 798candidate = None # nothing is chosen for the person 799if candidate is None and not {"multiple_model_groups" ,"incomplete_or_invalid_shard_set" }& set (issues ): 800issues .append ("unrecognized_or_unsupported_model_variant" ) 801elif candidate is not None and metadata is not None : 802expected = set (candidate ["expected_expert_types" ]) 803if not observed_experts or observed_experts - expected : 804issues .append ("missing_or_unexpected_expert_quantization" ) 805return {"source" :str (path ),"model_dir" :str (model_dir ),"scope" :"local_gguf_candidate" ,"files" :files , 806"file_count" :len (files ),"total_bytes" :sum (item ["bytes" ]for item in files ), 807"metadata" :metadata ,"candidate_selection" :candidate , 808"plain_issues" :list (dict .fromkeys ((missing_words (missing_shards )if (i == "incomplete_or_invalid_shard_set" and missing_shards )else plain_issue (i ))for i in issues )), 809"observed_expert_types" :sorted (observed_experts ), 810"observed_tensor_count" :observed_tensor_count , 811"ignored_auxiliary_files" :sorted (ignored_auxiliary ), 812"projectors" :projectors ,"messages" :messages ,"already_set_up" :_already_set_up (shards ,candidate ), 813"reads_pictures" :any (p ["status" ]in ("ok" ,"other_name" )for p in projectors )and 814not any (i .endswith ("unsupported_architecture" )for i in issues ), 815"folder_holds" :folder_holds ,"missing_shards" :missing_shards , 816"file_set_status" :"plausible" if not issues else "invalid_or_incomplete" , 817"issues" :issues ,"adoption_status" :"requires_architecture_quantization_tokenizer_and_engine_checks" , 818"execution_compatibility" :"unverified" ,"would_write" :False , 819"notes" : ["A known shard name is only a selection hint; it does not prove provenance or file integrity" , 820"Tensor directory, model-pack, engine version and hardware checks remain before adoption" , 821"No model is adopted or copied by this preview" ]}