okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fdfca1d9d
main
1"""The engines installed on this computer: list them, switch to any of them, delete one. Local only: nothing here downloads. 2 3One truth for the app (Settings > Engine) and the Terminal (`strata components engines | use | remove | rollback`). Updates keep every older 4engine (strata_control/updater.py), so a person can go back to an older engine to test something and return to the newest later. 5 6The Qwen engine (every model): packages in ``<components>/engine/<version>-<platform>-<backend>[-<variant>]/``. What a start runs is the pinned 7package (``.updates/state.json`` engine.pinned), else the newest that fits this PC (engine_component.resolve). The engine of a model shape has the 8same mechanism in its own folder. (DeepSeek's engine-dsv41/ folder, from Strata 0.2.13 and earlier, is not listed and never touched here.) 9 10A switch warns, it does not refuse, wherever the engine can run at all. What cannot be switched to is a package this computer cannot run (another 11operating system or make of graphics card, a driver that is too old, damaged files, a Strata that is too old for it). The engine in use cannot be 12deleted, nor one a running program uses. 13""" 14from __future__import annotations 15 16import os 17import shutil 18import uuid 19from pathlib import Path 20 21from strata_control import engine_component as ec ,folder_use ,longpath ,retired ,shape_engine ,signing 22from strata_control import updater 23from strata_control .targets import backend_supported ,host_platform 24 25QWEN = "qwen" 26FAMILIES = (QWEN ,) 27TITLES = {QWEN :"Qwen and other models" } 28#: The engine of a Qwen4 model shape (strata_control/shape_engine.py): family "shape:<shape>", one per installed shape, listed after the two above. The family 29#: string is an id for the app and the Terminal, never shown: the app titles the group with the model's own catalog title ("title" here is None). 30SHAPE_PREFIX = "shape:" 31 32 33def shape_of_family (family )-> str | None : 34"""shape:q4_lite -> q4_lite; None for anything else.""" 35if not isinstance (family ,str )or not family .startswith (SHAPE_PREFIX ): 36return None 37shape = family [len (SHAPE_PREFIX ):] 38return shape if shape_engine .valid (shape )else None 39 40 41def _walk_bytes (folder :Path )-> int : 42total = 0 43try : 44for base ,_dirs ,files in os .walk (longpath .long_path (folder )): 45for name in files : 46try : 47total += os .lstat (os .path .join (base ,name )).st_size 48except OSError : 49continue 50except OSError : 51pass 52return total 53 54 55def _version_of (folder_name :str )-> str : 56return str (folder_name ).split ("-" )[0 ] 57 58 59def _label (version :str ,backend :str ,variant :str = "" )-> str : 60return version + (f" ( { backend } { '-' + variant if variant else '' } )" if backend else "" ) 61 62 63# ----------------------------------------------------------------------------------------------- Qwen engine 64 65def _unfit (item :ec .EngineComponent ,* ,wanted :str | None ,target :str ,runtime :str | None ,cuda_here :list [str ],driver_here :str | None , 66hip_here :list [str ],other_makes :frozenset = frozenset ())-> tuple [str ,str ,list [str ]]| None : 67"""Why this computer cannot run the package, as (plain English, a code the app translates, its values), or None. The same checks as 68engine_component.resolve, one package at a time. ``other_makes``: the other makes of graphics card this PC also has (a PC with an NVIDIA 69card and an AMD card); an engine for one of them runs on that card, so it is not "for a different kind of graphics card".""" 70if item .platform != target : 71return ("It was made for a different operating system." ,"os" , []) 72ok ,_why = backend_supported (item .backend ,target ) 73if not ok or (wanted and item .backend != wanted and item .backend not in other_makes ): 74return ("It was made for a different kind of graphics card than this computer has." ,"gpu_make" , []) 75if item .min_runtime and runtime and ec ._version_key (runtime )< ec ._version_key (item .min_runtime ): 76return (f"It needs Strata { item . min_runtime } or newer; this is { runtime } ." ,"strata" , [item .min_runtime ,runtime ]) 77if item .cuda_archs and cuda_here and not ec .arch_covers (item .cuda_archs ,cuda_here ): 78return ("It does not include support for this computer's graphics card." ,"gpu_arch" , []) 79if item .hip_archs and hip_here and not set (item .hip_archs )& set (hip_here ): 80return ("It does not include support for this computer's graphics card." ,"gpu_arch" , []) 81need = item .min_driver .get ("nvidia" ) 82if need and driver_here and ec ._version_key (driver_here )< ec ._version_key (need ): 83return (f"It needs NVIDIA driver { need } or newer; this computer has { driver_here } ." ,"driver" , [need ,driver_here ]) 84try : 85ec .verify (item ,full = False ) 86except ec .ComponentProblem : 87return ("Some of its files are missing or changed, so it is not safe to start." ,"files" , []) 88return None 89 90 91def _process_uses (folder :Path )-> bool : 92try : 93return folder_use .in_use (folder ) 94except Exception :# noqa: BLE001 - unknown means not blocked by this check 95return False 96 97 98def _qwen_entries (ctx :"updater.Context" ,root :Path | None = None ,component_id :str = ec .COMPONENT_ID ,family :str = QWEN )-> list [dict ]: 99"""The Qwen engine's packages; with root, component_id and family those of a model shape's engine (the same package layout and checks).""" 100root = ctx .components if root is None else root 101found ,problems = ec .scan (root ,component_id ) 102wanted = ctx .hardware .get ("backend" ) 103runtime = ctx .hardware .get ("runtime" )or ec .runtime_version () 104target = ctx .hardware .get ("platform" )or host_platform () 105other_makes = frozenset (m for m in (ctx .hardware .get ("makes" )or [])if m in updater .GPU_MAKES and m != wanted ) 106seen = {wanted ,* other_makes } 107cuda_here = ec .cuda_archs_present ()if "cuda" in seen else [] 108driver_here = ec .nvidia_driver_version ()if "cuda" in seen else None 109hip_here = ec .hip_archs_present ()if "hip" in seen else [] 110try : 111active = ec .resolve (root ,backend = wanted ,full = False ,runtime = ctx .hardware .get ("runtime" ),component_id = component_id ).root .name 112except ec .EngineMissing : 113active = None 114pin = ec .pinned_folder (root ) 115rows = [] 116for item in found : 117why ,code ,args = _unfit (item ,wanted = wanted ,target = target ,runtime = runtime ,cuda_here = cuda_here ,driver_here = driver_here , 118hip_here = hip_here ,other_makes = other_makes )or (None ,None , []) 119rows .append ({"family" :family ,"folder" :item .root .name ,"version" :item .version ,"backend" :item .backend ,"platform" :item .platform , 120"variant" :item .variant ,"bytes" :sum (f [2 ]for f in item .files ),"signed" :bool (item .signature ),"fits" :why is None , 121"why_not" :why ,"why_code" :code ,"why_args" :args ,"active" :item .root .name == active ,"build_id" :item .build_id ,"path" :longpath .plain (item .root ), 122"other_card" :bool (wanted and item .backend != wanted and item .backend in other_makes )}) 123for bad in problems : 124folder = Path (bad ["folder" ]) 125rows .append ({"family" :family ,"folder" :folder .name ,"version" :_version_of (folder .name ),"backend" :"" ,"platform" :"" ,"variant" :"" , 126"bytes" :_walk_bytes (folder ),"signed" :False ,"fits" :False ,"active" :False ,"build_id" :"" ,"path" :longpath .plain (folder ), 127"why_not" :"Its description is missing or damaged, so it cannot be started." ,"why_code" :"manifest" ,"why_args" : [], 128"detail" :bad ["problem" ]}) 129fitting = [r for r in rows if r ["fits" ]and not r .get ("other_card" )]or [r for r in rows if r ["fits" ]]# "newest" = what updates follow 130newest = max (fitting ,key = lambda r : (ec ._version_key (r ["version" ]),r ["folder" ]),default = None ) 131for row in rows : 132row ["newest" ]= row is newest 133row ["pinned" ]= row ["folder" ]== pin 134return rows 135 136 137# ----------------------------------------------------------------------------------------------- the list 138 139def _decorate (rows :list [dict ],serving :bool )-> None : 140for row in rows : 141busy = _process_uses (Path (row ["path" ])) 142row ["running" ]= busy 143if row ["active" ]: 144row ["can_delete" ],row ["delete_blocked" ],row ["blocked_code" ]= False ,"This is the engine in use. Switch to another one first." ,"active" 145elif busy : 146row ["can_delete" ],row ["delete_blocked" ],row ["blocked_code" ]= False ,"A running program is using it. Stop the model first." ,"running" 147else : 148row ["can_delete" ],row ["delete_blocked" ],row ["blocked_code" ]= True ,None ,None 149row ["can_use" ]= bool (row ["fits" ])and not row ["active" ] 150 151 152def list_engines (ctx :"updater.Context" )-> dict : 153"""Every installed engine package, by family: ``{"families": [{"family", "title", "engines": [...]}], "total_bytes", "serving"}``. A family with 154no package is left out, except the Qwen one, which is always there. Reads files only; nothing is changed or downloaded.""" 155try : 156serving = bool (ctx .serving ()) 157except Exception :# noqa: BLE001 158serving = False 159qwen = _qwen_entries (ctx ) 160shapes = _shape_families (ctx ) 161for rows in (qwen ,* (f ["engines" ]for f in shapes )): 162_decorate (rows ,serving ) 163rows .sort (key = lambda r : (ec ._version_key (r ["version" ]),r ["folder" ]),reverse = True ) 164families = [{"family" :QWEN ,"title" :TITLES [QWEN ],"engines" :qwen }] 165families += shapes # none on a PC that never had a model of another shape: the list is what it was 166return {"schema_version" :1 ,"components_dir" :str (ctx .components ),"families" :families , 167"total_bytes" :sum (r ["bytes" ]for fam in families for r in fam ["engines" ]),"serving" :serving } 168 169 170def _shape_families (ctx :"updater.Context" )-> list [dict ]: 171"""One family per model shape whose engine is installed here (shape_engine.py: <components>/shapes/<shape>/engine/), each with its packages.""" 172out = [] 173try : 174shapes = shape_engine .installed_shapes (ctx .components ) 175except Exception :# noqa: BLE001 - a shapes folder that cannot be read lists nothing, as before 176return [] 177for shape in shapes : 178rows = _qwen_entries (ctx ,shape_engine .root (shape ,ctx .components ),shape_engine .component_id (shape ),SHAPE_PREFIX + shape ) 179if rows : 180out .append ({"family" :SHAPE_PREFIX + shape ,"shape" :shape ,"title" :None ,"engines" :rows }) 181return out 182 183 184def find_entry (listing :dict ,spec :str ,family :str | None = None )-> dict : 185"""The one entry a person's words name: a folder name, a version, or ``newest``. Ambiguous or unknown is an UpdateError (exit 2) that says what to type.""" 186entries = [e for fam in listing ["families" ]for e in fam ["engines" ]if family in (None ,fam ["family" ])] 187spec = str (spec ).strip () 188if spec .lower ()in ("newest" ,"latest" ): 189picks = [e for e in entries if e ["newest" ]] 190else : 191picks = [e for e in entries if e ["folder" ]== spec ]or [e for e in entries if e ["version" ]== spec ] 192if not picks : 193have = ", " .join (sorted ({e ["version" ]for e in entries }))or "none" 194raise updater .UpdateError (f"no installed engine matches { spec !r } (installed: { have } ); `strata components engines` lists them" ,2 ) 195if len (picks )> 1 : 196raise updater .UpdateError (f" { spec !r } matches more than one installed engine ( { ', ' . join ( p [ 'folder' ] for p in picks ) } ); use the folder name" ,2 ) 197return picks [0 ] 198 199 200# ----------------------------------------------------------------------------------------------- switch 201 202class SwitchBusy (updater .Busy ): 203"""A model is running, so the engine is not switched. One plain answer; the running model keeps the engine it started with.""" 204 205def __init__ (self ,serving :list [dict ]): 206updater .UpdateError .__init__ (self ,"A model is running, so the engine was not switched. Stop the model first (`strata launch --stop`, or Unload in the app), " 207"then switch. The running model keeps the engine it started with. Nothing was changed." ,7 ) 208self .serving = serving 209 210 211def use_engine (ctx :"updater.Context" ,family :str ,folder :str ,root :str | None = None )-> dict : 212"""Make an installed engine the one that starts from now on. Nothing is downloaded or deleted. Waits for / refuses while a model is running 213(`updater.Busy`, exit 7); the running model keeps the engine it started with. The newest engine is selected without a pin, so it follows updates again.""" 214shape = shape_of_family (family ) 215if retired .is_name (family ): 216raise updater .UpdateError (retired .NOT_OFFERED ,2 ) 217if family not in FAMILIES and shape is None : 218raise updater .UpdateError ("choose the Qwen engine" ,2 ) 219if not folder or folder != Path (folder ).name or folder .startswith ("." ): 220raise updater .UpdateError ("that is not an installed engine" ,2 ) 221with updater .update_lock (ctx .components ): 222try : 223updater .wait_until_idle (ctx .serving ,wait = ctx .wait ,emit = ctx .emit ,cancel = ctx .cancel ,poll = ctx .poll ) 224except updater .Busy as busy : 225raise SwitchBusy (busy .serving )from None 226if shape is not None : 227return _use_shape (ctx ,shape ,folder ) 228return _use_qwen (ctx ,folder ) 229 230 231def _use_shape (ctx :"updater.Context" ,shape :str ,folder :str )-> dict : 232"""The switch for a model shape's engine: the same pin as the Qwen engine's (``.updates/state.json`` engine.pinned), in the shape's own folder, which 233engine_component.resolve reads at every start of a model of that shape. The newest package is selected without a pin, so it follows updates again.""" 234base ,cid ,family = shape_engine .root (shape ,ctx .components ),shape_engine .component_id (shape ),SHAPE_PREFIX + shape 235found ,_ = ec .scan (base ,cid ) 236target = next ((item for item in found if item .root .name == folder ),None ) 237if target is None : 238raise updater .UpdateError ("that engine is not installed (it may have been deleted already)" ,2 ) 239backend ,runtime = ctx .hardware .get ("backend" ),ctx .hardware .get ("runtime" ) 240 241def picked ()-> str | None : 242try : 243return ec .resolve (base ,backend = backend ,full = True ,runtime = runtime ,component_id = cid ).root .name 244except ec .EngineMissing : 245return None 246before = picked () 247if before == folder : 248return {"component" :cid ,"family" :family ,"status" :"already" ,"changed" :False ,"to" :target .version ,"folder" :folder } 249try : 250signing .ensure_component_verifier () 251ec .verify_signature (target ) 252ec .verify (target ,full = True ) 253except (ec .ComponentProblem ,signing .SignatureError ,OSError )as exc : 254raise updater .UpdateError (f"engine { target . version } can no longer be used: { exc } " ,5 )from None 255state = updater .State (base ) 256section = state .section ("engine" ) 257old_pin = section .pop ("pinned" ,None ) 258state .save () 259automatic = picked ()== folder 260if not automatic : 261section ["pinned" ]= folder 262state .save () 263if picked ()!= folder : 264if old_pin : 265section ["pinned" ]= old_pin 266else : 267section .pop ("pinned" ,None ) 268state .save () 269raise updater .UpdateError (f"engine { target . version } can no longer be used: a start would not pick it" ,5 ) 270state .history ({"at" : (ctx .now or updater .dt .datetime .now (updater .dt .timezone .utc )).isoformat (),"action" :"use-shape-engine" ,"shape" :shape , 271"from" :_version_of (before )if before else None ,"to" :target .version ,"ok" :True }) 272state .save () 273return {"component" :cid ,"family" :family ,"status" :"switched" ,"changed" :True ,"automatic" :automatic , 274"from" :_version_of (before )if before else None ,"to" :target .version ,"folder" :folder } 275 276 277def _use_qwen (ctx :"updater.Context" ,folder :str )-> dict : 278found ,_ = ec .scan (ctx .components ) 279target = next ((item for item in found if item .root .name == folder ),None ) 280wanted = ctx .hardware .get ("backend" ) 281if target is not None and wanted and target .backend != wanted and target .backend in (ctx .hardware .get ("makes" )or []): 282# An engine for this PC's other card (an AMD card beside an NVIDIA one): choosing it is choosing that card, the same choice 283# `strata launch --backend amd` keeps ("now and next time"). Without it a start would go on picking the engine of the first make. 284before = ec .saved_backend () 285ec .save_backend (target .backend ) 286ctx .hardware = {** updater .detect_hardware (),"backend_source" :"saved choice" } 287try : 288out = use_qwen_unlocked (ctx ,updater .State (ctx .components ),folder ) 289except BaseException : 290ec .save_backend (before )# nothing was switched: the make chosen before stays 291raise 292return {** out ,"backend_saved" :target .backend } 293return use_qwen_unlocked (ctx ,updater .State (ctx .components ),folder ) 294 295 296def use_qwen_unlocked (ctx :"updater.Context" ,state :"updater.State" ,folder :str )-> dict : 297"""The switch itself, for a caller that already holds the update lock (the update that finds its engine already installed).""" 298found ,_ = ec .scan (ctx .components ) 299target = next ((item for item in found if item .root .name == folder ),None ) 300if target is None : 301raise updater .UpdateError ("that engine is not installed (it may have been deleted already)" ,2 ) 302current ,_why = updater .installed_engine (ctx .components ,ctx .hardware ) 303if current is not None and current .root .name == folder : 304return {"component" :"engine" ,"family" :QWEN ,"status" :"already" ,"changed" :False ,"to" :target .version ,"folder" :folder } 305try : 306signing .ensure_component_verifier () 307ec .verify_signature (target ) 308ec .verify (target ,full = True ) 309except (ec .ComponentProblem ,signing .SignatureError ,OSError )as exc : 310raise updater .UpdateError (f"engine { target . version } can no longer be used: { exc } " ,5 )from None 311out = updater .switch_engine (ctx ,state ,folder ,target ,unpin_if_automatic = True ) 312return {** out ,"family" :QWEN ,"changed" :True ,"status" :"switched" } 313 314 315# ----------------------------------------------------------------------------------------------- delete 316 317def delete_engine (ctx :"updater.Context" ,family :str ,folder :str ,root :str | None = None )-> dict : 318"""Delete one installed engine package. Refused (exit 2, nothing changed) for the engine in use and for one a running program uses. Models, settings 319and the other family are not touched. The folder is renamed away first, so a package that is held open is left whole, not half removed.""" 320shape = shape_of_family (family ) 321if retired .is_name (family ): 322raise updater .UpdateError (retired .NOT_OFFERED ,2 ) 323if family not in FAMILIES and shape is None : 324raise updater .UpdateError ("choose the Qwen engine" ,2 ) 325if not folder or folder != Path (folder ).name or folder .startswith ("." ): 326raise updater .UpdateError ("that is not an installed engine" ,2 ) 327with updater .update_lock (ctx .components ): 328listing = list_engines (ctx ) 329fam = next ((f for f in listing ["families" ]if f ["family" ]== family ),None ) 330rows = [e for e in (fam ["engines" ]if fam else [])if e ["folder" ]== folder and (root is None or e .get ("root" )in (None ,root ))] 331if not rows : 332raise updater .UpdateError ("that engine is not installed (it may have been deleted already)" ,2 ) 333row = rows [0 ] 334if not row ["can_delete" ]: 335raise updater .UpdateError (row ["delete_blocked" ],2 ) 336target = Path (row ["path" ]) 337aside = target .with_name (f".deleting- { uuid . uuid4 (). hex [: 8 ] } " ) 338try : 339os .replace (longpath .long_path (target ),longpath .long_path (aside )) 340except OSError as exc : 341raise updater .UpdateError (f"the engine could not be removed because something is using it ( { longpath . describe_oserror ( exc ) } ). " 342"Close programs that use Strata and try again; nothing was changed." ,6 )from None 343shutil .rmtree (longpath .long_path (aside ),ignore_errors = True )# a file that is held stays in .deleting-*; the next delete sweeps it 344_sweep (target .parent ) 345if family == QWEN : 346state = updater .State (ctx .components ) 347section = state .section ("engine" ) 348if section .get ("previous" )== folder : 349section ["previous" ]= None 350if section .get ("pinned" )== folder : 351section .pop ("pinned" ,None ) 352if row ["version" ]not in {e ["version" ]for e in rows_of (list_engines (ctx ),QWEN )}: 353 (section .get ("failed" )or {}).pop (row ["version" ],None ) 354state .history ({"at" : (ctx .now or updater .dt .datetime .now (updater .dt .timezone .utc )).isoformat (),"action" :"delete-engine" , 355"from" :row ["version" ],"to" :None ,"ok" :True }) 356state .save () 357elif shape is not None : 358state = updater .State (shape_engine .root (shape ,ctx .components )) 359section = state .section ("engine" ) 360if section .get ("pinned" )== folder : 361section .pop ("pinned" ,None ) 362state .history ({"at" : (ctx .now or updater .dt .datetime .now (updater .dt .timezone .utc )).isoformat (),"action" :"delete-shape-engine" ,"shape" :shape , 363"from" :row ["version" ],"to" :None ,"ok" :True }) 364state .save () 365return {"component" : ("engine" if family == QWEN else shape_engine .component_id (shape )),"family" :family ,"status" :"deleted" ,"changed" :True ,"folder" :folder , 366"version" :row ["version" ],"freed_bytes" :row ["bytes" ]} 367 368 369def rows_of (listing :dict ,family :str )-> list [dict ]: 370return next ((f ["engines" ]for f in listing ["families" ]if f ["family" ]== family ), []) 371 372 373def _sweep (engine_folder :Path )-> None : 374"""Remove what an earlier delete could not (a file that was held open at the time).""" 375try : 376for entry in engine_folder .iterdir (): 377if entry .is_dir ()and entry .name .startswith (".deleting-" ): 378shutil .rmtree (longpath .long_path (entry ),ignore_errors = True ) 379except OSError : 380pass