okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
68a2916b7
main
1"""What a model still needs on this computer, in plain words: the one place the Folder step, the download question and the final summary ask. 2 3A model that is already installed is "already downloaded". What can still be missing are helper files, each with its own size: the 4draft layer (MTP, makes answers faster) and the picture reader. Only when the weights themselves are gone does it say the model 5is downloaded again. Nothing here reads more than a run config and file existence. 6""" 7 8from __future__import annotations 9 10import os 11from dataclasses import dataclass ,field 12from pathlib import Path 13 14from strata_control import discovery 15from strata_control .discovery import MMPROJ_GB ,MTP_FETCH_GB 16 17 18@dataclass 19class Part : 20kind :str # weights | mtp | mmproj 21label :str # "the draft layer" 22gb :float 23 24 25@dataclass 26class ModelState : 27installed :bool = False # a run config for this model exists and names files that are there 28own_files :bool = False # the person's own model files 29total_gb :float = 0.0 # the whole model (the catalog's figure) 30parts :list [Part ]= field (default_factory = list )# what is missing and would be downloaded 31folder :Path | None = None # where the model lives now (its data folder), None when not installed 32on_disk_gb :float = 0.0 # weights already in the model's folder (a partial download) 33notes :list [str ]= field (default_factory = list ) 34 35@property 36def remaining_gb (self )-> float : 37return sum (p .gb for p in self .parts ) 38 39@property 40def only_helpers (self )-> bool : 41return bool (self .parts )and all (p .kind != "weights" for p in self .parts ) 42 43def _names (self )-> str : 44names = [f" { p . label } ( { p . gb :.1f } GB)" for p in self .parts ] 45return names [0 ]if len (names )== 1 else ", " .join (names [:- 1 ])+ " and " + names [- 1 ] 46 47def headline (self )-> str : 48"""One plain sentence for the size line of the Folder step.""" 49if self .own_files : 50if not self .parts : 51return "Your model files are used where they are. Nothing needs to be downloaded." 52return f"Your model files are used where they are. Strata still needs to fetch { self . _names () } ." 53if self .installed and not self .parts : 54return f"Already downloaded ( { self . total_gb :.0f } GB on this computer). Nothing more to download." 55if self .installed and self .only_helpers : 56first = self .parts [0 ] 57if len (self .parts )== 1 : 58return f"The model is already downloaded ( { self . total_gb :.0f } GB). Only { first . label } is missing ( { first . gb :.1f } GB)." 59return f"The model is already downloaded ( { self . total_gb :.0f } GB). Only { self . _names () } are missing." 60if self .installed : 61return (f"The model's files are no longer all on this computer. About { self . remaining_gb :.0f } GB would be downloaded " 62f"( { self . _names () } )." ) 63if self .on_disk_gb >= 1 : 64return (f" { self . on_disk_gb :.0f } GB of the model is already in the folder. About { self . remaining_gb :.0f } GB left to download " 65f"(the whole model is { self . total_gb :.0f } GB)." ) 66return f"Not downloaded yet: about { self . remaining_gb :.0f } GB to download." 67 68def question (self )-> tuple [str ,str ]: 69"""(title, text) for the "Download?" pop-up before a start that needs a download.""" 70gb = self .remaining_gb 71if self .only_helpers : 72return (f"Download { self . _names () } ?" , 73"The model itself is already on this computer and is not downloaded again. Strata needs this extra file to start " 74"with the choices you made; an interrupted download continues where it stopped." ) 75return (f"Download about { gb :.0f } GB?" , 76f"This model is not on this computer yet. Strata will download about { gb :.0f } GB now; " 77"an interrupted download continues where it stopped." ) 78 79 80#: The families whose setup also fetches the draft layer and the picture reader after the model (setup.py steps 5 and 6). NVFP4 packs bring 81#: theirs inside the download, Qwen3.6 has its own engine path. 82HELPER_FAMILIES = ("qwen" ,"swift" ,"coder" ,"unsloth" ,"gyro" ) 83 84 85def resolved_drafting (drafting :str | None ,family :str | None ,* ,model_name :str | None = None ,args :list | None = None , 86vram_mib :float | None = None )-> str : 87"""The drafter a choice means for this family on this computer: ``dflash2`` | ``mtp`` | ``off`` (strata_control/drafting.py: Auto is DFlash2 where the engine 88has it). ``model_name`` / ``args`` / ``vram_mib``: the model's set and the card signals the start's decision reads (runner.auto_signals; the 12 GB card with 89IQ3_S is the MTP). Never raises; an unknown computer is the MTP.""" 90try : 91from strata_control import drafting as _d 92backend ,archs = _d .detect_hardware () 93return _d .choice_of (drafting ,family = family ,backend = backend ,archs = archs ,model_name = model_name ,args = args ,vram_mib = vram_mib ) 94except Exception :# noqa: BLE001 95return "mtp" 96 97 98def drafting_for_family (choice :str | None ,family :str | None )-> str | None : 99"""The Drafting choice to keep when the model changes to `family`: DFlash2/MTP/Off belong to Qwen3.8-Flash-Next (qwen, gyro, unsloth); any other model (Coder; 100Swift; NVFP4) goes back to Auto (None), so a choice made for one model never rides along to another. An unknown family keeps it.""" 101from strata_control import drafting as _d 102return choice if (not family or family in _d .SUPPORTED_FAMILIES )else None 103 104 105def drafting_to_save (key :str ,saved :object )-> str | None : 106"""What the Drafting step writes into the launch settings for the row the person chose. Auto stays "nobody chose" (None: a saved preset writes nothing), except when the 107model's own settings file already holds another choice (the app's Models screen writes its Drafting choice there and a launch starts from that file): then Auto is 108written as "auto", so it overrides the older choice instead of silently running it.""" 109if key != "auto" : 110return key 111from strata_control import drafting as _d 112return "auto" if saved is not None and _d .normalize (saved )!= "auto" else None 113 114 115def layer_off_without_choice (base :dict | None )-> bool : 116"""The model's installed config has its draft layer off ("mtp": false: setup's --mtp off from a Drafting Off launch, or the app's Draft layer switch) and holds 117no Drafting choice: the engine starts without a drafter, so the Drafting step shows Off; a drafter picked there is saved (runner.layer_back).""" 118return isinstance (base ,dict )and base .get ("drafting" )is None and base .get ("mtp" )is False 119 120 121def mtp_choice (mtp :str | None ,drafting :str | None = None )-> str | None : 122"""The draft-layer choice for what to fetch: off when the person said --mtp off, or the drafter is off or DFlash2 (``drafting`` is the resolved drafter, 123resolved_drafting(); nothing then uses the layer, so a new install does not download it), else as chosen.""" 124if str (drafting or "" ).strip ().lower ()in ("off" ,"dflash2" ): 125return "off" 126return mtp 127 128 129def mmproj_name (catalog ,family :str | None )-> str : 130try : 131_m ,families ,_c ,_s = catalog .tables () 132name = (families .get (family or "" )or {}).get ("mmproj" ) 133if name : 134return str (name ) 135mod = catalog .strata .setup_module () 136if mod is not None and getattr (mod ,"MMPROJ" ,None ): 137return str (mod .MMPROJ ) 138except Exception :# noqa: BLE001 139pass 140return "mmproj-Qwen3.8-Flash-Next-BF16.gguf" 141 142 143def assess (catalog ,family :str | None ,model :str | None ,* ,vision :str = "off" ,model_path :str | None = None , 144data_dir :str | Path | None = None ,config :Path | None = None ,desc :dict | None = None ,rows :list | None = None , 145mtp :str | None = None ,drafting :str | None = None ,use_installed :bool = True )-> ModelState : 146"""The state of `family model` for these choices. `config` / `desc` are the installed run config and its description (looked up when 147not given).""" 148st = ModelState () 149mtp = mtp_choice (mtp ,drafting ) 150row = next ((r for r in (rows if rows is not None else catalog .rows ())if r .family == family and r .model == model ),None )if (family and model )else None 151st .total_gb = float (row .download_gb )if row else 0.0 152wants_pictures = vision != "off" and (row is None or row .images ) 153data = Path (data_dir )if data_dir else None 154if model_path : 155st .own_files = True 156first = _first_gguf (Path (model_path )) 157beside = discovery .prepared_beside (first ,data_places (catalog ,data ))if first else {}# the model folder's own layout, then --data-dir and the remembered folder (where setup writes the draft layer) 158st .folder = beside .get ("data_dir" ) 159if beside .get ("pack" )is not None and beside .get ("mtp" )is None and mtp != "off" : 160st .parts .append (Part ("mtp" ,"the draft layer" ,MTP_FETCH_GB )) 161if wants_pictures and beside .get ("pack" )is not None and \ 162not reader_present (catalog ,family , [st .folder ,* data_places (catalog ,data )],own = first .parent if first else None ): 163st .parts .append (Part ("mmproj" ,"the picture reader" ,MMPROJ_GB )) 164return st 165if config is None and family and model and use_installed :# (False: the installed copy is in another data folder than the one this launch uses) 166config = catalog .installed_config (catalog .tag_of (family ,model )) 167cfg = None 168if config is not None : 169try : 170import json 171cfg = json .loads (Path (config ).read_text (encoding = "utf-8-sig" )) 172except (OSError ,ValueError ): 173cfg = None 174if cfg is not None : 175fp = discovery .footprint (cfg ,Path (config )) 176st .installed = True 177st .folder = fp .data_dir 178gone = [m for m in fp .missing ()if m .kind == "weights" ] 179if gone : 180st .installed = False 181st .parts .append (Part ("weights" ,"the model" ,max (st .total_gb ,0.0 ))) 182return st 183for m in fp .missing (): 184if m .kind == "mtp" and mtp != "off" : 185st .parts .append (Part ("mtp" ,"the draft layer" ,MTP_FETCH_GB )) 186elif m .kind == "mmproj" and wants_pictures : 187st .parts .append (Part ("mmproj" ,"the picture reader" ,MMPROJ_GB )) 188images = (desc or {}).get ("images" )if desc is not None else ("cpu" if fp .mmproj else "off" ) 189if wants_pictures and (images in (None ,"off" ))and not any (p .kind == "mmproj" for p in st .parts ): 190base = st .folder / "models" if st .folder else data 191have = (base / mmproj_name (catalog ,family ))if base else None 192if have is None or not have .exists (): 193st .parts .append (Part ("mmproj" ,"the picture reader" ,MMPROJ_GB )) 194return st 195# not installed: whatever of the weights is in the model's folder counts 196if family and model : 197base = data or Path (catalog .data_dir ()) 198folder = catalog .model_folder (base ,family ,model ) 199got = 0 200try : 201got = sum (f .stat ().st_size for f in folder .glob ("*.gguf" )if not f .name .lower ().startswith ("mmproj" )) 202except OSError : 203pass 204st .on_disk_gb = got / 1e9 205st .parts .append (Part ("weights" ,"the model" ,max (st .total_gb - st .on_disk_gb ,0.0 ))) 206if family in HELPER_FAMILIES : 207# setup fetches the draft layer and the picture reader after the model, so the question and the disk check count them too 208if mtp != "off" and not (base / "mtp" / "rt" / "experts.bin" ).is_file (): 209st .parts .append (Part ("mtp" ,"the draft layer" ,MTP_FETCH_GB )) 210if wants_pictures and not reader_present (catalog ,family , [base ,* data_places (catalog ,None )]):# setup's rule: the pinned name, here or in a folder it reuses 211st .parts .append (Part ("mmproj" ,"the picture reader" ,MMPROJ_GB )) 212return st 213 214 215def data_places (catalog ,data :Path | None )-> list [Path ]: 216"""The data folders besides the model folder's own layout that may already hold the draft layer: the one the launch names (--data-dir), then the one every command agrees on.""" 217out :list [Path ]= [data ]if data else [] 218try : 219default = catalog .data_dir () 220if default and not any (os .path .normcase (str (default ))== os .path .normcase (str (d ))for d in out ): 221out .append (Path (default )) 222except Exception :# noqa: BLE001 - a question asked early is never a reason to stop 223pass 224return out 225 226 227def mmproj_size (catalog ,family :str | None ,name :str )-> int | None : 228"""The pinned size of the family's picture reader (setup's fam["mmproj_sha256"] or ISTA_FILES), None when setup does not pin one.""" 229try : 230_m ,families ,_c ,_s = catalog .tables () 231pin = (families .get (family or "" )or {}).get ("mmproj_sha256" ) 232if not pin : 233mod = catalog .strata .setup_module () 234pin = (getattr (mod ,"ISTA_FILES" ,None )or {}).get (name )if mod is not None else None 235return int (pin [0 ])if pin else None 236except Exception :# noqa: BLE001 237return None 238 239 240def reader_present (catalog ,family :str | None ,data_folders ,own :Path | None = None )-> bool : 241"""Whether setup will find the picture reader without a download - setup's own rule (setup.py step 5 and mmproj_beside), not any 242mmproj*.gguf: the family's pinned file name in a data folder's models/ (the one in use, or a folder setup reuses), or with the person's own 243files in their folder (by name), or in the folder above it or that folder's models/ (by name, at the pinned size). Or, when there is no pinned 244file, a verified Unsloth mmproj-F16.gguf (setup.accepted_alt_reader: the same function the start uses).""" 245name = mmproj_name (catalog ,family ) 246for base in data_folders : 247if not base : 248continue 249for sub in ("models" ,"Models" ): 250try : 251if (Path (base )/ sub / name ).is_file (): 252return True 253except OSError : 254pass 255if own is not None : 256own = Path (own ) 257try : 258if (own / name ).is_file (): 259return True 260size = mmproj_size (catalog ,family ,name ) 261for r in (own .parent ,own .parent / "models" ): 262f = r / name 263if f .is_file ()and (size is None or f .stat ().st_size == size ): 264return True 265except OSError : 266pass 267try :# no pinned file: a verified Unsloth mmproj-F16.gguf the person already has counts, as in setup 268mod = catalog .strata .setup_module () 269alt = (getattr (mod ,"ALT_READERS" ,None )or {}).get (name )if mod is not None else None 270if alt is None : 271return False 272places = [Path (b )/ sub / alt [0 ]for b in data_folders if b for sub in ("models" ,"Models" )] 273if own is not None : 274places += [Path (own )/ alt [0 ],Path (own ).parent / alt [0 ],Path (own ).parent / "models" / alt [0 ]] 275return mod .accepted_alt_reader (name ,places ,start = False )is not None # (the plan hashes without writing a mark and says nothing) 276except Exception :# noqa: BLE001 - the plan must not fail on this 277return False 278 279 280def _first_gguf (path :Path )-> Path | None : 281try : 282if path .is_file (): 283return path 284found = sorted (p for p in path .glob ("*.gguf" )if not p .name .lower ().startswith ("mmproj" )) 285return found [0 ]if found else None 286except OSError : 287return None