okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""Getting the picture files (the mmproj, about 0.9 GB) onto this computer for a model that is already installed, and nothing else. 2 3A model whose run config has no ``vision`` section reads no pictures. The person turns "Read pictures" on (it is on by default), presses 4Load, and this module does the one thing that is missing: it finds the picture file (or downloads it once, pinned, size and SHA-256 5checked) and works out the run config's ``vision`` section for the engine in use. It never looks at the model's own files, never prepares 6the pack or the draft layer again, never changes the data folder, and never writes the run config: the caller does (apps/host). 7 8pictures.fetch(config_path, ...) the whole step; returns {"mmproj", "vision", "fetched", "note"} 9 10The file lives in ``<data folder>/models/`` beside the model files of that data folder (the place setup uses), shared by every model of 11the folder. The data folder is the one the model's own run config names (``--pack <data>/packs/<tag>``, strata_control/discovery.py 12``data_dir_of``), not the app's models folder. A copy that is already on this computer is used where it is: in that data folder, in the 13model's own folder, or one folder up from it (the layout of the Hugging Face repository). 14 15Only an explicit command reaches the network (strata_control/acquisition.py). With no internet the answer is the plain sentence of 16``PicturesError`` (code ``offline``) after one short probe, never a stalled bar. The apps/host caller then loads the model without 17pictures and says so. 18 19``python -c "...; pictures.main(sys.argv[1:])"`` is how the app runs it: ``fetch --config FILE --engine-dir DIR --vision yes ...`` 20with ``--output jsonl`` (one JSON line per progress step, a last line ``{"ok": true, "event": "result", ...}`` or ``{"ok": false, "error": ...}``). 21""" 22 23from __future__import annotations 24 25import argparse 26import json 27import os 28import re 29import shutil 30import sys 31import threading 32from dataclasses import dataclass 33from pathlib import Path 34from typing import Callable 35 36from strata_control import acquisition ,discovery ,transfer ,vision_reader 37 38Progress = Callable [[str ,int ,int ],None ]# (step in plain words, bytes done, bytes total) 39 40HF_DEFAULT = "https://huggingface.co" 41#: What a card of this kind needs for the picture reader (setup.py VISION): the images one picture becomes, and the CPU reader's thread cap. 42MAX_TOKENS = {"gpu" :1024 ,"cpu" :300 } 43THREADS_CAP = 16 44#: Room kept beyond the file itself: the download is written next to its final place and then renamed. 45SPARE_BYTES = 256 * 1024 * 1024 46 47 48class PicturesError (RuntimeError ): 49"""The picture files could not be had. ``code`` is for the caller, the message is plain words for the person.""" 50 51def __init__ (self ,code :str ,message :str ,details :str = "" ): 52super ().__init__ (message ) 53self .code = code 54self .details = details # the technical cause, for a "Details" area; never the message 55 56 57@dataclass( frozen = True ) 58class Projector : 59"""One pinned picture-reader file: the repository revision it comes from, its exact size and SHA-256.""" 60 61name :str 62size :int 63sha256 :str 64repo :str 65revision :str 66 67def url (self ,endpoint :str | None = None )-> str : 68base = (endpoint if endpoint is not None else (os .environ .get ("HF_ENDPOINT" )or "" ).strip ().rstrip ("/" )or HF_DEFAULT ) 69return f" { base } / { self . repo } /resolve/ { self . revision } / { self . name } " 70 71 72#: The same files and revisions as setup.py (ISTA_FILES, SWIFT_FILES, HF_REVISIONS); tests/terminal/test_pictures.py keeps the two the same. 73QWEN = Projector ("mmproj-Qwen3.8-Flash-Next-BF16.gguf" ,907543008 ,"b1a82259702816a5330d7bd7607cd9676b11780e79ff7348c21103ff3ce49bd0" , 74"ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF" ,"ed59f92082b1e93c0e96d60a8b11aab089b52f09" ) 75SWIFT = Projector ("mmproj-Swift-Qwen3.8-Flash-Next-BF16.gguf" ,907543520 ,"cd1140f4abba943ce8d9fa92fed8407e389954d26907efde7b72153c75bd8a60" , 76"ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF" ,"99bb8f7f95c7aa7b24a36a7786a4f657b30f5d3d" ) 77#: The families whose weights are a GGUF shard set read by the Flash-Next engine: the original, its Coder, Unsloth's and Gyro's files all use the 78#: original's picture reader. NVFP4 ready-made packs, Qwen3.6 (its own engine path) and DeepSeek (its own picture tower) are not handled here. 79PROJECTOR_BY_FAMILY = {"qwen" :QWEN ,"coder" :QWEN ,"unsloth" :QWEN ,"gyro" :QWEN ,"swift" :SWIFT } 80FAMILIES = tuple (PROJECTOR_BY_FAMILY ) 81 82WORDS = { 83"offline" :"There is no internet connection, so the picture files can't be downloaded now." , 84"disk" :"There is not enough free disk space for the picture files (about 1 GB)." , 85"failed" :"The picture files could not be downloaded." , 86"checksum" :"The downloaded picture files did not pass the safety check, so they were deleted." , 87"unsupported" :"This model's picture files are not downloaded by this step." , 88"no_reader" :"This engine has no picture reader." , 89"no_folder" :"Strata could not tell which folder this model's files are in." , 90"no_config" :"The model's settings file could not be read." , 91} 92 93 94# -------------------------------------------------------------------------------------------------------- what and where 95 96def family_of (cfg :dict ,gguf :Path | None ,asked :str | None = None )-> str | None : 97"""The family whose picture file this model uses; None for one this step does not handle. ``asked`` is the catalog's family (the app knows it); 98without it the model's own file name and name decide (Swift's files are called Swift-..., Qwen3.6's start with Qwen3.6).""" 99if asked : 100return asked .lower ()if asked .lower ()in PROJECTOR_BY_FAMILY else None 101arch = str (cfg .get ("arch" )or "" ).lower () 102names = [str (cfg .get ("model_name" )or "" ).lower (), (gguf .name .lower ()if gguf else "" )] 103from strata_control import retired 104if retired .config_reason (cfg )or any ("deepseek" in n for n in names ):# never a DeepSeek config (retired.py) 105return None 106if any (n .startswith ("qwen3.6" )or "qwen3.6-35b" in n for n in names ): 107return None 108if any (n .startswith ("swift" )for n in names ): 109return "swift" 110return "qwen" 111 112 113def run_folder (foot :"discovery.Footprint" )-> Path | None : 114"""The data folder the model really lives in, from its own run config: the folder that holds its ``packs/<tag>`` (or its ``mtp/rt``, or the 115``models/<tag>`` its files are in). A pack or draft layer in a folder of another shape says nothing about it.""" 116def above (path :Path | None ,child :str ,name :str | None = None )-> Path | None : 117if path is None : 118return None 119if name is not None and path .name .lower ()!= name : 120return None 121return path .parent .parent if path .parent .name .lower ()== child else None 122found = above (foot .pack ,"packs" )or above (foot .mtp ,"mtp" ,"rt" ) 123if found is not None : 124return found 125for w in foot .weights : 126for parent in w .parents : 127if parent .name .lower ()== "models" : 128return parent .parent 129return None 130 131 132def models_root (data :Path )-> Path : 133"""``<data>/models`` (``Models`` where that is what the folder has, as on Linux with an older install).""" 134for name in ("models" ,"Models" ): 135if (data / name ).is_dir (): 136return data / name 137return data / "models" 138 139 140def places (data :Path | None ,gguf :Path | None ,named :str | None ,projector :Projector )-> list [Path ]: 141"""Where a copy of the file may already be: the path the run config names, the data folder's models folder, the model's own folder and the 142folder above it (the Hugging Face repository layout keeps the picture file beside the size folders).""" 143out :list [Path ]= [] 144if named : 145out .append (Path (named )) 146if data is not None : 147out .append (models_root (data )/ projector .name ) 148if gguf is not None : 149out += [gguf .parent / projector .name ,gguf .parent .parent / projector .name ] 150seen :set [str ]= set () 151unique = [] 152for p in out : 153key = os .path .normcase (str (p )) 154if key not in seen : 155seen .add (key ) 156unique .append (p ) 157return unique 158 159 160def _mark (path :Path )-> Path : 161return path .with_name (path .name + ".done" ) 162 163 164def _marked (path :Path ,projector :Projector )-> bool : 165try : 166return f"sha256 { projector . sha256 } " in _mark (path ).read_text (encoding = "utf-8" ,errors = "replace" ) 167except OSError : 168return False 169 170 171def whole (path :Path ,projector :Projector ,report :Progress | None = None )-> bool : 172"""Is this the pinned file, whole? Size first, then the finish mark setup leaves, else the hash (a few seconds; the file is not changed).""" 173try : 174if not path .is_file ()or path .stat ().st_size != projector .size : 175return False 176if _marked (path ,projector ): 177return True 178if report : 179report ("Checking the picture files…" ,0 ,projector .size ) 180return transfer .sha256_file (path )== projector .sha256 181except OSError : 182return False 183 184 185def find (candidates :list [Path ],projector :Projector ,report :Progress | None = None )-> Path | None : 186for path in candidates : 187if whole (path ,projector ,report ): 188return path 189return None 190 191 192def target_for (data :Path | None ,named :str | None ,projector :Projector )-> Path : 193"""Where a download goes: the place the run config already names when its folder is there, else the data folder's models folder.""" 194if named : 195p = Path (named ) 196if p .parent .is_dir (): 197return p 198if data is None : 199raise PicturesError ("no_folder" ,WORDS ["no_folder" ]) 200return models_root (data )/ projector .name 201 202 203def _room (folder :Path ,need :int )-> None : 204above = folder 205while not above .exists ()and above .parent != above : 206above = above .parent 207try : 208free = shutil .disk_usage (above ).free 209except OSError : 210return # cannot tell: go on, the download reports a real failure 211if free < need + SPARE_BYTES : 212raise PicturesError ("disk" ,WORDS ["disk" ],f" { free / 1e9 :.1f } GB are free in { above } " ) 213 214 215# ----------------------------------------------------------------------------------------------------------- the reader 216 217def _numbers (value )-> list [int ]: 218if value is None or value == "" : 219return [] 220parts = list (value )if isinstance (value , (list ,tuple ,set ))else re .split (r"[;,\s]+" ,str (value )) 221out = [] 222for part in parts : 223m = re .search (r"\d+" ,str (part )) 224if m : 225out .append (int (m .group (0 ))) 226return sorted (set (out )) 227 228 229def _build (engine_dir :Path )-> dict : 230try : 231data = json .loads ((engine_dir / "BUILD.json" ).read_text (encoding = "utf-8-sig" )) 232return data if isinstance (data ,dict )else {} 233except (OSError ,ValueError ): 234return {} 235 236 237def _reader_archs (engine_dir :Path )-> list [str ]: 238for name ,keys in (("BUILD.json" , ("vision_archs" ,"archs" )), ("engine-component.json" , ("archs" ,))): 239try : 240data = json .loads ((engine_dir / name ).read_text (encoding = "utf-8-sig" )) 241except (OSError ,ValueError ): 242continue 243for key in keys : 244if isinstance (data ,dict )and data .get (key ): 245value = data [key ] 246parts = list (value )if isinstance (value , (list ,tuple ,set ))else re .split (r"[;,\s]+" ,str (value )) 247names = [str (p )for p in parts if str (p )] 248if names : 249return names 250return [] 251 252 253def threads (logical :int | None = None )-> int : 254return max (1 ,min ((logical if logical is not None else (os .cpu_count ()or 8 ))// 2 ,THREADS_CAP )) 255 256 257def reader_section (engine_dir :Path ,mmproj :Path ,gguf :Path ,asked :str ,hardware :dict | None = None ,previous :dict | None = None )-> tuple [dict | None ,str ]: 258"""The run config's ``vision`` section for this engine folder and card, and one plain note when it is not what was asked for. 259The same rule as setup (strata_control/vision_reader.py is the one place): the CPU reader under 24 GB of VRAM, the GPU reader from 24 GB; AMD and 260Intel Arc get their GPU reader with the CPU one behind it; a Mac has one program for both. (None, note) when the folder has no reader at all.""" 261hw = hardware or {} 262make = str (hw .get ("make" )or "" ).lower () 263mac = make == "apple" or sys .platform == "darwin" 264windows = os .name == "nt" 265wanted = vision_reader .wanted (asked ,hw .get ("vram_gb" ),make ,unified = mac ) 266if wanted == "none" : 267return None ,"" 268have = vision_reader .find (engine_dir ,windows ,mac = mac ) 269arch = hw .get ("arch" ) 270if mac : 271reader = vision_reader .choose (engine_dir ,wanted ,windows = False ,mac = True ) 272elif have ["gpu" ]is not None : 273reader = vision_reader .choose (engine_dir ,wanted ,windows = windows ,gpu_arch = str (arch or "" ),archs = _reader_archs (engine_dir )) 274elif have ["cpu" ]is not None : 275mode ,note = wanted ,"" 276if mode == "gpu" :# the ready-made reader may cover fewer cards than the engine (setup.py prebuilt_vision) 277build = _build (engine_dir ) 278built = _numbers (build .get ("vision_archs" ,build .get ("archs" ))) 279try : 280sm = int (arch ) 281except (TypeError ,ValueError ): 282sm = None 283if built and sm is not None and sm not in built and not (build .get ("ptx" )and sm > max (built )): 284mode ,note = "cpu" ,f"the picture reader has no code for your card (sm_ { sm } ): pictures are read on the CPU (a few seconds each)" 285reader = vision_reader .Reader (mode ,have ["cpu" ],note = note ) 286else : 287reader = vision_reader .Reader ("none" ,note = "this engine has no picture reader: pictures off" ) 288if reader .mode == "none" or reader .exe is None : 289return None ,reader .note or WORDS ["no_reader" ] 290earlier = (previous or {}).get ("max_tokens" ) 291same_device = bool ((previous or {}).get ("gpu" ))== (reader .mode == "gpu" ) 292tokens = int (earlier )if isinstance (earlier ,int )and earlier > 0 and same_device else MAX_TOKENS [reader .mode ] 293base = {"exe" :str (reader .exe ),"mmproj" :str (mmproj ),"model" :str (gguf ),"gpu" :reader .mode == "gpu" ,"max_tokens" :tokens } 294section = vision_reader .vision_section (reader ,base ) 295if reader .mode == "cpu" : 296section ["threads" ]= threads () 297return section ,reader .note 298 299 300# ------------------------------------------------------------------------------------------------------------- the step 301 302def fetch (config_path :str | Path ,* ,engine_dir :str | Path ,asked :str = "yes" ,data_dir :str | Path | None = None ,family :str | None = None , 303hardware :dict | None = None ,progress :Progress | None = None ,cancel :threading .Event | None = None , 304endpoint :str | None = None ,online :Callable [[str ],bool ]| None = None )-> dict : 305"""Make sure this model has its picture file and say what its ``vision`` section is. 306 307Returns {"mmproj": path, "vision": section | None, "fetched": bool, "note": str, "data_dir": path, "family": name}. Raises PicturesError. Nothing of the 308model changes; the only file written is the picture file (and its finish mark) when it was downloaded.""" 309report = progress or (lambda * _ :None ) 310config = Path (config_path ) 311try : 312cfg = json .loads (config .read_text (encoding = "utf-8-sig" )) 313if not isinstance (cfg ,dict ): 314raise ValueError ("not an object" ) 315except (OSError ,ValueError ): 316raise PicturesError ("no_config" ,WORDS ["no_config" ])from None 317foot = discovery .footprint (cfg ,config ) 318gguf = foot .weights [0 ]if foot .weights else None 319name = family_of (cfg ,gguf ,family ) 320projector = PROJECTOR_BY_FAMILY .get (name )if name else None 321if projector is None or gguf is None : 322raise PicturesError ("unsupported" ,WORDS ["unsupported" ]) 323data = run_folder (foot )or (Path (data_dir )if data_dir else None ) 324if data is None and gguf is not None : 325data = discovery .prepared_beside (gguf ).get ("data_dir" ) 326vision_now = cfg .get ("vision" )if isinstance (cfg .get ("vision" ),dict )else None 327named = str (vision_now ["mmproj" ])if vision_now and vision_now .get ("mmproj" )else None 328found = find (places (data ,gguf ,named ,projector ),projector ,report ) 329fetched = False 330if found is None : 331out = target_for (data ,named ,projector ) 332acquisition .require ("the picture files" ,"Load in the app, or strata install" ) 333url = projector .url (endpoint ) 334_room (out .parent ,projector .size ) 335if not (online or _online )(url ): 336raise PicturesError ("offline" ,WORDS ["offline" ]) 337out .parent .mkdir (parents = True ,exist_ok = True ) 338partial = out .with_name (out .name + ".part" ) 339try : 340transfer .download (url ,partial ,size = projector .size ,sha256 = projector .sha256 ,cancel = cancel ,what = "the picture reader" , 341progress = lambda d ,s :report ("Downloading the picture files…" ,d ,s )) 342except transfer .ChecksumMismatch : 343raise PicturesError ("checksum" ,f" { WORDS [ 'checksum' ] } Try again." )from None 344except transfer .Cancelled : 345raise 346except (transfer .TransferError ,OSError )as exc : 347raise PicturesError ("failed" ,f" { WORDS [ 'failed' ] } Try again; it continues where it stopped." ,str (exc ))from None 348os .replace (partial ,out ) 349try : 350_mark (out ).write_text (f"sha256 { projector . sha256 } " ,encoding = "utf-8" ) 351except OSError : 352pass # the mark only saves a second hashing 353found ,fetched = out ,True 354section ,note = reader_section (Path (engine_dir ),found ,gguf ,asked ,hardware ,vision_now ) 355if section is None : 356raise PicturesError ("no_reader" ,note or WORDS ["no_reader" ]) 357report ("The picture files are ready." ,projector .size ,projector .size ) 358return {"mmproj" :str (found ),"vision" :section ,"fetched" :fetched ,"note" :note ,"data_dir" :str (data )if data else None ,"family" :name } 359 360 361def _online (url :str )-> bool : 362from strata_control import drafting_fetch # here: it pulls in the network code 363return drafting_fetch .online (url ) 364 365 366# ------------------------------------------------------------------------------------------------------------ the command 367 368def main (argv :list [str ])-> int : 369ap = argparse .ArgumentParser (prog = "pictures" ) 370sub = ap .add_subparsers (dest = "command" ,required = True ) 371one = sub .add_parser ("fetch" ) 372one .add_argument ("--config" ,required = True ) 373one .add_argument ("--engine-dir" ,required = True ) 374one .add_argument ("--vision" ,default = "yes" ,choices = ("yes" ,"gpu" ,"cpu" )) 375one .add_argument ("--data-dir" ) 376one .add_argument ("--family" ) 377one .add_argument ("--vram-gb" ,type = float ) 378one .add_argument ("--make" ) 379one .add_argument ("--arch" ) 380a = ap .parse_args (argv ) 381cancel = threading .Event () 382 383def emit (obj :dict )-> None : 384sys .stdout .write (json .dumps (obj )+ "\n" ) 385sys .stdout .flush () 386 387last = {"step" :"" ,"pct" :- 1 } 388 389def show (step :str ,done :int ,total :int )-> None : 390pct = int (100 * done / total )if total else 0 391if step == last ["step" ]and pct == last ["pct" ]: 392return 393last ["step" ],last ["pct" ]= step ,pct 394emit ({"event" :"progress" ,"step" :step ,"done" :done ,"total" :total }) 395 396hardware = {"vram_gb" :a .vram_gb ,"make" :a .make ,"arch" :a .arch } 397try : 398result = fetch (a .config ,engine_dir = a .engine_dir ,asked = a .vision ,data_dir = a .data_dir ,family = a .family ,hardware = hardware ,progress = show ,cancel = cancel ) 399except PicturesError as exc : 400emit ({"ok" :False ,"error" : {"code" :exc .code ,"message" :str (exc ),"details" :exc .details }}) 401return 5 402except acquisition .AcquisitionRefused as exc : 403emit ({"ok" :False ,"error" : {"code" :"acquisition_refused" ,"message" :str (exc )}}) 404return 5 405except transfer .Cancelled : 406emit ({"ok" :False ,"error" : {"code" :"cancelled" ,"message" :"Stopped. The part that was downloaded is kept." }}) 407return 130 408emit ({"ok" :True ,"event" :"result" ,** result }) 409return 0 410 411 412if __name__ == "__main__" :# pragma: no cover 413sys .exit (main (sys .argv [1 :]))