okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""The model list in the signed update feed (feed member ``models``): the cache of the last verified list, and how a feed model becomes a catalog entry. 2 3A new model can ship as a signed feed update, with no new Control package. The feed carries, for each model, the Hugging Face repository at a pinned revision, 4every file's exact size and SHA-256, the engine family, the licence and the first engine version that reads it (strata_control/feed.py ``FeedModel``). Setup, the 5Terminal's `strata launch` and the app read the SAME tables (setup.py's MODELS / FAMILIES / OWN_PATH_FAMILIES), so a feed model is added to those tables here and 6every screen shows it after the built-in ones. It then goes through the code a built-in model goes through: the same pins (REPO_PINS / REV_PINS, HF_REVISIONS), the 7same SHA-256 check after the download and the same ``.bad`` handling (setup.py ``download`` / ``verify_sha256`` / ``keep_bad``). 8 9Rules: 10 11* With no ``models`` member in the feed (and no cached one) nothing here changes anything: no table is touched, nothing is written. 12* A model whose family the installed engine does not run (``strata --families``) is listed as not available on this engine and is never offered to install. 13* Offline, the models of the last feed that verified are shown (the signature is checked again when the cache is read). 14* A model that would clash with a built-in one (an id, a tag, a file name pinned to other bytes) is left out with a log line; a built-in model is never replaced. 15""" 16 17from __future__import annotations 18 19import base64 20import json 21import logging 22import os 23import re 24import tempfile 25from dataclasses import dataclass ,field 26from pathlib import Path 27 28from strata_control import feed as feedmod ,shape_engine 29 30_log = logging .getLogger ("strata.feed" ) 31 32CACHE_NAME = "feed-models.json" 33ENV_OFF = "STRATA_FEED_MODELS" # "0": setup and the screens do not read or fetch the feed's model list (tests, a locked-down PC) 34FETCH_TIMEOUT = 5.0 35 36# ---- the words a person can see (agreed with the coordinator before they ship) 37UNAVAILABLE_ENGINE = "needs a newer Strata engine: update Strata to use it" 38UNAVAILABLE_UNKNOWN = "this Strata version doesn't know this model yet: update Strata to use it" 39 40 41#: What happens to a model whose family the installed engine does not run (the owner decides; a one-line switch): 42#: "not_offered": it is listed as not available and never offered to install; 43#: (owner, 11-06: "warn_allow", his standing rule: warn plainly, still allow the download, never refuse) 44#: "warn_allow": it is offered like any other model with the same sentence as a warning, and the install goes on (a family this Control does not know is still not offered). 45UNAVAILABLE_POLICY = "warn_allow" 46 47 48def unavailable_reason (family :str )-> str : 49"""The sentence a person sees. The family name is not part of it (support finds it in the log line).""" 50return UNAVAILABLE_ENGINE if family in feedmod .MODEL_FAMILIES_INSTALLABLE else UNAVAILABLE_UNKNOWN 51 52 53# ---------------------------------------------------------------------------------------------------- the cache of the last verified list 54 55def cache_file (root :str | os .PathLike | None = None )-> Path : 56"""``<components>/.updates/feed-models.json``, beside the updater's state (STRATA_COMPONENTS_DIR moves both).""" 57from strata_control import engine_component ,updater 58return updater .updates_dir (Path (root )if root else engine_component .components_dir ())/ CACHE_NAME 59 60 61def remember (feed :feedmod .Feed ,root :str | os .PathLike | None = None )-> None : 62"""Keep the signed feed document that carried a model list, so the list can be shown offline. A feed without models removes an older cache (the list was withdrawn); 63when there is no cache and no models, nothing is written. Never raises: a read-only folder just means no offline list.""" 64try : 65path = cache_file (root ) 66if not feed .models : 67if path .is_file (): 68path .unlink () 69return 70if not feed .signature : 71return 72doc = {"schema_version" :1 ,"sequence" :feed .sequence ,"channel" :feed .channel ,"source" :feed .source , 73"payload" :base64 .b64encode (feed .raw ).decode ("ascii" ),"signature" :base64 .b64encode (feed .signature ).decode ("ascii" )} 74path .parent .mkdir (parents = True ,exist_ok = True ) 75descriptor ,temp = tempfile .mkstemp (prefix = ".feed-models-" ,suffix = ".tmp" ,dir = path .parent ) 76try : 77with os .fdopen (descriptor ,"w" ,encoding = "utf-8" )as stream : 78json .dump (doc ,stream ) 79os .replace (temp ,path ) 80finally : 81if os .path .exists (temp ): 82os .unlink (temp ) 83except OSError as exc : 84_log .warning ("the model list of the update feed could not be kept for offline use: %s" ,exc ) 85 86 87def _read_cache (root ,trusted :dict )-> feedmod .Feed | None : 88"""The cached feed, its signature checked again against the trusted keys (a cache file edited by hand is worth nothing). Expiry is not applied: the list of an old 89feed is what an offline PC has. None when there is no cache or it does not verify.""" 90from strata_control import signing 91try : 92doc = json .loads (cache_file (root ).read_text (encoding = "utf-8" )) 93payload = base64 .b64decode (doc ["payload" ],validate = True ) 94signature = base64 .b64decode (doc ["signature" ],validate = True ) 95key_id = signing .verify_bytes (trusted ,payload ,json .loads (signature .decode ("utf-8-sig" ))) 96return feedmod .parse (payload ,source = "cache" ,key_id = key_id ) 97except (OSError ,ValueError ,KeyError ,TypeError ,signing .SignatureError ,feedmod .FeedError ): 98return None 99 100 101@dataclass 102class Loaded : 103models :tuple = () 104dropped :tuple = () 105via :str = "none" # "feed" (read now), "cache" (the last verified list) or "none" 106sequence :int | None = None 107notes :list = field (default_factory = list ) 108 109 110def load (source :str | None = None ,* ,fetch :bool = True ,root = None ,trusted :dict | None = None ,timeout :float = FETCH_TIMEOUT , 111say = None )-> Loaded : 112"""The feed's models: the feed itself when it can be read now (and verifies, and is not older than the cached one), else the cache. Silent either way: 113nothing is printed and no error is raised. ``fetch=False`` reads the cache only (the Terminal and app lists).""" 114if os .environ .get (ENV_OFF ,"" ).strip ()== "0" : 115return Loaded () 116from strata_control import signing 117try : 118trusted = trusted if trusted is not None else signing .load_trusted_keys () 119except Exception :# noqa: BLE001 - a build without keys has no verified list 120return Loaded () 121if not trusted : 122return Loaded () 123cached = _read_cache (root ,trusted ) 124if fetch and source : 125try : 126got = feedmod .fetch (source ,trusted ,timeout = timeout ,channel = "stable" ,last_sequence = cached .sequence if cached else None , 127say = say ) 128except feedmod .FeedError as exc :# offline, expired, a downgrade, a bad signature: the last verified list stays 129_log .info ("the update feed's model list could not be refreshed: %s" ,exc ) 130except Exception as exc :# noqa: BLE001 131_log .info ("the update feed's model list could not be refreshed: %s" ,exc ) 132else : 133remember (got ,root ) 134return Loaded (models = got .models ,dropped = got .models_dropped ,via = "feed" ,sequence = got .sequence ) 135if cached is not None and cached .models : 136return Loaded (models = cached .models ,dropped = cached .models_dropped ,via = "cache" ,sequence = cached .sequence ) 137return Loaded () 138 139 140# ---------------------------------------------------------------------------------------------------- feed model -> catalog entry 141 142class _ByQuant (str ): 143"""A catalog string that depends on the size: ``fam["file"].format(q=quant)`` and ``fam["hf"].format(q=quant)`` are how the built-in code asks for a 144file name or a download folder; the feed names each size's files explicitly, so the answer comes from a table.""" 145 146def __new__ (cls ,table :dict ): 147obj = super ().__new__ (cls ,next (iter (table .values ()),"" )) 148obj .table = dict (table ) 149return obj 150 151def format (self ,* args ,** kw ):# noqa: A003 - the override is the point 152return self .table [kw ["q" ]] 153 154 155def _template (names :list [str ])-> str | None : 156"""The ``file`` template (``{i}`` the shard number, 1 to 9) that gives exactly these names in order, or None.""" 157if len (names )== 1 : 158return names [0 ]if not re .search (r"[{}]" ,names [0 ])else None 159if len (names )> 9 or any (re .search (r"[{}]" ,n )for n in names ): 160return None 161first = names [0 ] 162if "-00001-of-" not in first : 163return None 164tpl = first .replace ("-00001-of-" ,"-0000{i}-of-" ) 165return tpl if [tpl .format (i = i )for i in range (1 ,len (names )+ 1 )]== names else None 166 167 168def _engine_tuple (version :str )-> tuple | None : 169"""setup.py's engine versions are 3-tuples (0, 1, 57); a fourth number only when the feed's version has one.""" 170if not version : 171return None 172key = feedmod .version_key (version ) 173return key if key [3 ]else key [:3 ] 174 175 176def _endpoint (setup )-> str : 177"""The model host setup downloads from (a mirror when the person set one), read off setup's own url builder so this module names no host.""" 178repo = next (iter (setup .HF_REVISIONS )) 179return setup .hf (repo ).split (f"/ { repo } /resolve/" )[0 ] 180 181 182def _urlbase (repo :str ,revision :str ,endpoint :str )-> str : 183return f" { endpoint } / { repo } /resolve/ { revision } /" 184 185 186@dataclass 187class Applied : 188registered :list = field (default_factory = list )# ids now in setup's tables 189unavailable :dict = field (default_factory = dict )# id -> {"title", "by", "family", "reason"} 190skipped :list = field (default_factory = list )# plain lines, one for each model left out (also logged) 191 192 193def _skip (result :Applied ,model ,why :str )-> None : 194line = f"The update feed's model { model . id !r } is left out: { why } " 195result .skipped .append (line ) 196_log .warning (line ) 197 198 199def _taken_tags (setup )-> list [str ]: 200tags = [d .get ("tag" ,"" )for d in (* setup .FAMILIES .values (),* setup .OWN_PATH_FAMILIES .values ())] 201return [t for t in tags if t ] 202 203 204def apply (setup ,models ,engine_families = None )-> Applied : 205"""Add the feed's models to setup's tables (``setup`` is the setup.py module). ``engine_families``: the set ``strata --families`` printed for the installed 206engine, or None when no engine is installed to ask (then every installable family is offered and setup checks the engine when it installs, as for any model). 207Safe to call again with the same list: a model already added is skipped quietly. Built-in entries are never replaced.""" 208result = Applied () 209if not models : 210return result 211done_before = getattr (setup ,"FEED_MODELS" ,None ) 212if done_before is None : 213done_before = setup .FEED_MODELS = {} 214setup .FEED_UNAVAILABLE = {} 215for model in models : 216if model .id in done_before : 217if model .id not in setup .FEED_UNAVAILABLE : 218result .registered .append (model .id ) 219continue 220if model .id in setup .FAMILIES or model .id in setup .OWN_PATH_FAMILIES : 221_skip (result ,model ,"its id is the name of a built-in model" ) 222continue 223tag = model .id + "-" 224if any (t .startswith (tag )or tag .startswith (t )for t in _taken_tags (setup )): 225_skip (result ,model ,"its name would be mistaken for a built-in model's files" ) 226continue 227shape = model .shape 228known = model .family in feedmod .MODEL_FAMILIES_INSTALLABLE or shape is not None 229# a model of its own shape runs on that shape's engine, which setup fetches when the model is chosen (strata_control/shape_engine.py): the Strata engine's families do not decide 230runs = known and (shape is not None or engine_families is None or model .family in engine_families ) 231if not runs : 232allowed = known and UNAVAILABLE_POLICY == "warn_allow" 233reason = unavailable_reason (model .family ) 234_log .info ("feed model %s: family %s is not run by the installed engine (%s); policy %s" ,model .id ,model .family , 235"unknown to this Control" if not known else "engine families " + "," .join (sorted (engine_families or ())),UNAVAILABLE_POLICY ) 236setup .FEED_UNAVAILABLE [model .id ]= {"title" :model .title ,"by" :model .by ,"family" :model .family ,"reason" :reason ,"allowed" :allowed } 237result .unavailable [model .id ]= setup .FEED_UNAVAILABLE [model .id ] 238if not allowed : 239done_before [model .id ]= model 240continue 241try : 242 (_own_path if model .family == "qwen35moe" else _flash_next )(setup ,model ) 243except _Unsupported as exc : 244_skip (result ,model ,str (exc )) 245continue 246done_before [model .id ]= model 247result .registered .append (model .id ) 248return result 249 250 251class _Unsupported (Exception ): 252pass 253 254 255def _check_pins (setup ,model )-> dict : 256"""The model's files as setup pins them: name -> (size, sha256). A file name that setup already pins to other bytes (the picture reader is one file shared by 257several models) refuses the model rather than replace the pin.""" 258pins :dict = {} 259for quant in model .quants : 260for f in quant .files : 261pins [f .name ]= (f .size ,f .sha256 ) 262if model .mmproj is not None : 263pins [model .mmproj .name ]= (model .mmproj .size ,model .mmproj .sha256 ) 264for repo_pins in setup .REPO_PINS .values (): 265known = repo_pins .get (model .mmproj .name ) 266if known and tuple (known )!= pins [model .mmproj .name ]: 267raise _Unsupported ("its picture reader file has the name of another model's, with other bytes" ) 268return pins 269 270 271def _pin_repo (setup ,model ,pins :dict )-> str : 272"""Register the revision and the file pins where setup's download looks them up (file_pin: REV_PINS first), and return the download folder.""" 273setup .REV_PINS .setdefault ((model .repo ,model .revision ), {}).update (pins ) 274setup .HF_REVISIONS .setdefault (model .repo ,model .revision ) 275return _urlbase (model .repo ,model .revision ,_endpoint (setup )) 276 277 278def _licence (model )-> str : 279return f" { model . licence } : { model . licence_url } " 280 281 282def _dirs (model )-> set [str ]: 283return {f .repo_path .rpartition ("/" )[0 ]for q in model .quants for f in q .files } 284 285 286def _flash_next (setup ,model )-> None : 287"""A qwen4exp model: the family and size tables the Unsloth sets use (GGUF shards in the repository, packed on this PC), one MODELS entry for each size.""" 288template = setup .FAMILIES .get ("unsloth" )or {} 289names_by_quant = {q .name : [f .name for f in q .files ]for q in model .quants } 290files = {} 291for qname ,names in names_by_quant .items (): 292tpl = _template (names ) 293if tpl is None : 294raise _Unsupported (f"the files of { qname } are not a single file or numbered parts 00001-of-0000N" ) 295files [qname ]= tpl 296pins = _check_pins (setup ,model ) 297base = _pin_repo (setup ,model ,pins ) 298folders = {q .name : (q .files [0 ].repo_path .rpartition ("/" )[0 ]+ "/" if q .files [0 ].repo_path .rpartition ("/" )[0 ]else "" )for q in model .quants } 299keys = {} 300for q in model .quants : 301key = q .name if q .name not in setup .MODELS and q .name not in keys .values ()else f" { q . name } - { model . id } " 302if key in setup .MODELS or key in keys .values (): 303raise _Unsupported (f"the size name { q . name } clashes with a built-in size" ) 304keys [q .name ]= key 305fam = {"title" :model .title ,"by" :model .by ,"about" :model .about ,"hf" :_ByQuant ({q :base + folders [q ]for q in files }), 306"file" :_ByQuant (files ),"shards" :2 ,"tag" :model .id + "-" ,"name" :model .id ,"vision" :bool (model .pictures ), 307"pack_args" :list (template .get ("pack_args" , ["--compat-bf16" ])),"sha256" :dict (pins ),"license" :_licence (model ),"feed" :True , 308"drafter" :model .drafter } 309if model .mmproj is not None : 310fam .update (mmproj_hf = base + (model .mmproj .repo_path .rpartition ("/" )[0 ]+ "/" if "/" in model .mmproj .repo_path else "" ), 311mmproj = model .mmproj .name ,mmproj_sha256 = (model .mmproj .size ,model .mmproj .sha256 )) 312else : 313fam .update (vision = False ) 314engine = _engine_tuple (model .min_engine ) 315# nothing is added to the shared tables until every check above has passed 316for q in model .quants : 317gb = round (q .download_bytes / 1e9 ,1 ) 318entry = {"about" :q .about or f" { q . name } quantization" ,"download_gb" :gb ,"ram_gb" :q .ram_gb , 319"arena_gb" :q .arena_gb or round (gb * 0.93 ,1 ),"families" : (model .id ,),"shards" :len (q .files ), 320"file" :files [q .name ],"quant" :q .name ,"vision" :bool (model .pictures )} 321entry ["budget" ]= True # the Unsloth-set install: the GGUF read in place with a RAM budget of its experts (what the built-in UD sizes do). Without it 322# setup picks the low-RAM mode on a PC with little RAM, which copies all the experts into a second file (77 GB for UD-Q4_K_XL) 323if engine : 324entry ["engine" ]= engine 325setup .MODELS [keys [q .name ]]= entry 326if model .shape :# its own engine: the run config names it, setup fetches it (strata_control/shape_engine.py) 327fam ["shape" ]= model .shape 328for key in keys .values ():# its min_engine is about that engine, which the feed carries: the app must not compare it with the Strata engine 329setup .MODELS [key ].pop ("engine" ,None ) 330setup .FAMILIES [model .id ]= fam 331_mac_entries (model ,keys ) 332 333 334def _mac_entries (model ,keys :dict )-> None : 335"""The Mac (Metal) tables: a size of one or two files is offered like the Qwen GSQ-RCO sizes (no repack), "not measured on a Mac". More files: not offered on a Mac.""" 336try : 337from strata_control import mac_fit 338except Exception :# noqa: BLE001 339return 340if any (len (q .files )> 2 for q in model .quants ): 341return 342for q in model .quants : 343key = keys [q .name ] 344mac_fit .MAC_MODELS [key ]= {"shard1_gb" :round (q .download_bytes / 1e9 ,1 ),"tested" :False ,"family" :model .id ,"shards" :len (q .files ),"no_mtp" :model .drafter == "none" } 345mac_fit .MAC_ABOUT [key ]= q .about or f" { q . name } quantization" 346if model .id not in mac_fit .FEED_FAMILIES : 347mac_fit .FEED_FAMILIES .append (model .id ) 348 349 350def _own_path (setup ,model )-> None : 351"""A qwen35moe model: the Qwen3.6-35B-A3B install path (one GGUF, read in place by the engine). One file for each size, all in one folder.""" 352if any (len (q .files )!= 1 for q in model .quants ): 353raise _Unsupported ("this install path takes one file for each size" ) 354if len (_dirs (model ))!= 1 : 355raise _Unsupported ("this install path takes all sizes from one folder of the repository" ) 356if model .mmproj is not None and model .mmproj .repo_path .rpartition ("/" )[0 ]!= next (iter (_dirs (model ))): 357raise _Unsupported ("the picture reader is not in the folder of the model files" ) 358names = {q .name :q .files [0 ].name for q in model .quants } 359pins = _check_pins (setup ,model ) 360base = _pin_repo (setup ,model ,pins ) 361folder = next (iter (_dirs (model ))) 362base = base + (folder + "/" if folder else "" ) 363fam = {"title" :model .title ,"by" :model .by ,"arch" :"qwen35moe" ,"about" :model .about ,"hf" :base ,"file" :_ByQuant (names ),"tag" :model .id + "-" , 364"mmproj_hf" :base ,"mmproj" :model .mmproj .name if model .mmproj else "" ,"name" :model .id ,"license" :_licence (model ), 365"models" : {q .name : {"about" :q .about or f" { q . name } quantization" ,"ram_gb" :q .ram_gb }for q in model .quants }, 366"sha256" :dict (pins ),"kv_bytes_per_token" :model .kv_bytes_per_token ,"mtp" :model .mtp_drafts , 367"vision" :bool (model .pictures ),"state_gb" :model .state_gb ,"feed" :True } 368setup .OWN_PATH_FAMILIES [model .id ]= fam