okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1b4018870
main
1"""What `strata launch` does after the choices are made: get the engine and the model, write the run config, tune, start, open access. 2 3Every step reports plain-word events through one callback (`emit`), so the TUI (progress screen), `--no-tui` (printed lines) and the 4tests see the same thing. Nothing here prints or reads the keyboard. The steps reuse what is already in the Terminal: 5 6* the engine comes from the signed feed (`strata update`, the one explicit step that downloads); 7* the model comes from setup.py in the app's own installer mode (STRATA_CONTROL_INSTALL), the same job the desktop app runs; 8* the run config the engine uses is a private copy of the installed one with this launch's choices applied; the profile 9`launch-<name>` (the shared profiles store) points at it, and carries host, port and parallel; 10* tuning is `strata tune auto`, its result lives in the shared presets store and is applied at every start; 11* start and stop are `strata runtime start|stop` (a background service: it keeps serving after this terminal closes). 12""" 13 14from __future__import annotations 15 16import json 17import os 18import re 19import subprocess 20import sys 21import tempfile 22import threading 23import time 24from strata_control import vram_fit 25from strata_control .childenv import quiet_crash_env 26from strata_control import reader_room 27from strata_control import atomic as _atomic_mod 28from dataclasses import dataclass ,field 29from pathlib import Path 30from typing import Any ,Callable 31 32from strata_cli .launch import access as acc 33from strata_cli .launch import modelstate 34from strata_cli .launch import settings as S 35from strata_cli .launch .catalog import Catalog ,CatalogUnavailable 36 37ROOT = Path (__file__ ).resolve ().parents [2 ] 38WINDOWS = os .name == "nt" 39 40 41def install_isolation_words (catalog ,data_dir :str | os .PathLike | None = None )-> list [str ]: 42"""Round 8, N5: a clean test (a scratch data folder) silently ran an OLDER install found elsewhere (its run config and engine 0.1.41). 43When a data folder was chosen (--data-dir, or STRATA_DATA_DIR from the installer) and the install in use is outside it, say which one is used 44and why. Nothing is moved or switched.""" 45chosen = data_dir or os .environ .get ("STRATA_DATA_DIR" ) 46places = getattr (catalog ,"places" ,None )or [] 47if not chosen or not places or places [0 ].source == "explicit" : 48return [] 49main = Path (places [0 ].path ) 50try : 51inside = os .path .commonpath ([os .path .abspath (main ),os .path .abspath (chosen )])== os .path .abspath (chosen ) 52except ValueError : 53inside = False 54if inside : 55return [] 56return [f"Strata is using the earlier install in { main } ( { places [ 0 ]. configs } saved model setting(s) and its engine settings), not a clean one in " 57f" { chosen } : the data folder only says where model files are kept. To test from scratch, use a new user account or remove the earlier install first." ] 58 59 60#: the first engine whose Metal build reads Gyro files (round 8, M: 0.1.45.3 was reused and failed on missing TQK6/TQK7 kernels) 61GYRO_METAL_ENGINE = (0 ,1 ,47 ) 62 63 64def version_tuple (version :str | None )-> tuple [int , ...]: 65"""'0.1.45.3' -> (0, 1, 45, 3); () when it is not a dotted run of numbers (a source build says so itself).""" 66m = re .match (r"\d+(?:\.\d+)*" ,str (version or "" ).strip ()) 67return tuple (int (x )for x in m .group (0 ).split ("." ))if m else () 68 69 70def python_failure (lines :list [str ])-> str | None : 71"""The last line of a Python traceback in setup.py's output (ModuleNotFoundError: No module named 'calibrate'), or None when the 72output holds no traceback. Frames are skipped; the exception line is the first unindented line after the last 'Traceback'.""" 73for i in range (len (lines )- 1 ,- 1 ,- 1 ): 74if lines [i ].startswith ("Traceback (most recent call last)" ): 75for line in lines [i + 1 :]: 76if line .strip ()and not line [:1 ].isspace (): 77return line .strip ()[:300 ] 78return None 79return None 80 81 82def argparse_failure (lines :list [str ])-> str : 83"""setup.py's own refusal of an option ("setup.py: error: argument --kv: invalid choice: ..."), which is neither an [X] line nor a 84traceback (#3785): the words after "error:" are the cause.""" 85for line in reversed (lines ): 86found = re .match (r"\s*(?:setup|strata)(?:\.py)?: error: (.+)" ,line ) 87if found : 88return found .group (1 ).strip ()[:300 ] 89return "" 90 91 92def missing_file (failure :str )-> bool : 93"""An import or file error: the install itself is short of a file, which an update of Strata brings back.""" 94return failure .startswith (("ModuleNotFoundError" ,"ImportError" ,"FileNotFoundError" )) 95 96 97def capital (text :str )-> str : 98"""A reason that was written to stand alone ("the update feed could not be read: ...") starts the sentence it is joined to with a capital. 99A host name stays as it is written ("github.com did not answer ...", strata_control/netpolicy.py).""" 100first = text .split (" " ,1 )[0 ] 101if "." in first .strip ("." )and re .fullmatch (r"[a-z0-9.-]+" ,first .rstrip ("." )): 102return text 103return text [:1 ].upper ()+ text [1 :] 104 105 106class LaunchError (RuntimeError ): 107"""A step could not be done. `text` says what it means; `next` says what to do.""" 108 109def __init__ (self ,text :str ,next :str = "" ,code :int = 6 ): 110super ().__init__ ((text + " " + next ).strip ()) 111self .text ,self .next ,self .code = text ,next ,code 112 113 114def setup_failure (lines :list [str ],err :str ,hint :str ,details :str | None ,own_files :bool )-> LaunchError : 115"""The error for a setup.py run that exited non-zero. setup.py's own `[X]` line (err) is the message when there is one; when it 116stopped with a Python error instead, that error's last line is (#3613, #3467: a file missing from the Terminal's tools/ ended every 117launch after a tune with only "The model could not be installed"). `details` is the file that holds the rest of its output.""" 118err = err or argparse_failure (lines ) 119crashed = python_failure (lines )if not err else None 120if crashed : 121where = f" The whole setup output is in { details } ." if details else "" 122if missing_file (crashed ): 123return LaunchError (f"The model could not be installed. A file that setup needs is missing from this Strata install ( { crashed } )." , 124"Update Strata (`strata update`) and run it again." + where ,6 ) 125if crashed .startswith ("PermissionError" ): 126folder = re .findall (r"'([^']+)'" ,crashed ) 127shown = folder [- 1 ]if folder else None 128try :# the folder Strata was told to use, not a file inside it 129shown = str (Path (shown ).parent )if shown and Path (shown ).name in ("models" ,"packs" ,"mtp" )else shown 130except (OSError ,ValueError ): 131pass 132return LaunchError ("The model could not be installed. " + (f"Windows would not let Strata write to { shown } " if shown else 133"Windows would not let Strata write to a folder" )+ " (access denied)." , 134"Pick a folder you own for the model files (the Folder step, or --data-dir D:\\Strata-models) and start again. " 135"Nothing was downloaded." + where ,6 ) 136return LaunchError (f"The model could not be installed. Setup stopped with an error ( { crashed } )." ,"Run it again." + where ,6 ) 137return LaunchError ("The model could not be installed." + (f" { capital ( err . rstrip ( '.' )) } ." if err else "" ), 138 (hint or ("Run it again: finished steps are skipped." if own_files else 139"Run it again: finished steps are skipped and a download continues where it stopped." )) 140+ (f" Details: { details } " if details else "" ),6 ) 141 142 143class Cancelled (LaunchError ): 144def __init__ (self ): 145super ().__init__ ("Stopped. Nothing was changed on your computer beyond files already downloaded." ,"" ,130 ) 146 147 148@dataclass 149class Event : 150stage :str # engine | model | config | tune | start | access | done 151text :str 152pct :float | None = None 153level :str = "info" # info | warn | error 154data :dict = field (default_factory = dict ) 155 156 157@dataclass 158class Result : 159profile :str 160urls :list [str ] 161key :str | None 162tune_word :str | None 163notices :list [str ] 164config :str 165tunnel :str | None = None 166serving :bool = True # False: the model is ready but nothing was started (no engine yet) 167engine_problem :str | None = None # the plain reason there is no engine, when serving is False 168final_text :str = "" # what to tell the person when serving is False 169reused :bool = False # the same choices were already serving: nothing was stopped or started 170 171 172NO_ENGINE_NEXT = ("Update Strata (`strata update`) and run `strata launch` again. Nothing was downloaded, and any model files you already have are kept." ) 173 174STAGES = ("engine" ,"model" ,"config" ,"tune" ,"start" ,"access" ) 175 176NO_ENGINE_STEP = ("run `strata update` to get the newest engines and start again; if this stays, your graphics card is not one Strata supports yet, " 177"and the model files stay on this computer for when it is" ) 178 179#: no graphics card Strata can use at all (an Intel UHD/Iris only, an AMD APU-only laptop, a virtual machine, Windows on ARM) 180NO_GPU_PREFIX = "no graphics card that Strata can use was found" 181NO_GPU_STEP = ("Strata needs an NVIDIA or AMD graphics card, an Intel Arc card or an Apple Silicon Mac, and there is no CPU-only engine for this " 182"computer. Run Strata on a computer that has one; the model files stay here" ) 183 184 185def no_gpu_words (names :list [str ]| None = None )-> str : 186"""The plain reason when nothing Strata can run on is in this computer, naming what is there when it is known.""" 187names = [n for n in (names or [])if n ] 188if names : 189return f" { NO_GPU_PREFIX } ; this computer has { ', ' . join ( names [: 3 ]) } " 190return NO_GPU_PREFIX 191 192 193def _step_for (reason :str )-> str : 194return NO_GPU_STEP if reason .startswith (NO_GPU_PREFIX )else NO_ENGINE_STEP 195 196 197def no_engine_warning (reason :str )-> str : 198"""The plain warning shown before a model is downloaded on a computer with no engine to run it.""" 199reason = reason .strip ().rstrip ("." ) 200if reason .startswith (NO_GPU_PREFIX ): 201return (f"Strata can't run on this computer: { reason } . The model will download, but it will not run here " 202f"(next step: { NO_GPU_STEP } )." ) 203return (f"Strata couldn't find an engine for this computer ( { reason } ). The model will download, but it may not run until you install " 204f"the right engine (next step: { NO_ENGINE_STEP } )." ) 205 206 207def no_engine_final (reason :str ,name :str = "" )-> str : 208reason = reason .strip ().rstrip ("." ) 209if reason .startswith (NO_GPU_PREFIX ): 210return f"The model is ready, but Strata can't start it on this computer: { reason } . Next step: { NO_GPU_STEP } ." 211return (f"The model is ready, but Strata can't start it yet: it couldn't find an engine for this computer ( { reason } ). " 212f"Next step: { NO_ENGINE_STEP } . The model files stay on this computer." ) 213 214 215def tune_words (result :dict | None ,code :int | None = None )-> tuple [str ,str ]: 216"""(short word, plain sentence) for a tuner result: faster / already fastest / busy PC / failed / stopped.""" 217if not result : 218return "failed" ,"The tuner did not finish, so the standard settings run. Nothing was changed." 219out = result .get ("outcome" ) 220if out == "improved" : 221gain = result .get ("gain_pct" ) 222return "faster" , (f"Done: answers are about { gain :.0f } % faster with the tuned settings." if isinstance (gain , (int ,float )) 223else "Done: the tuned settings are faster." ) 224if out == "default_confirmed" and result .get ("not_tried" ): 225n = int (result ["not_tried" ])# some candidates were never measured: "already fastest" would be untrue (#5122) 226return "some not tried" ,f" { n } setting { 's' if n != 1 else '' } could not be tried: not enough free memory" 227if out == "default_confirmed" : 228return "already fastest" ,"Your computer already runs at its best with the standard settings. Nothing needed changing." 229if out == "inconclusive" : 230return "busy PC" , ("The computer was too busy to tell a real gain from noise, so the standard settings run. " 231"Close other programs and tune again later (strata tune auto)." ) 232if out == "cancelled" : 233return "stopped" ,"Tuning was stopped. Your settings were not changed." 234return "failed" , (result .get ("message" )or "Tuning could not run here." )+ " The standard settings run." 235 236 237# ----------------------------------------------------------------------------------------------- run config 238 239def runtime_max_wait ()-> int : 240from strata_control import runtime 241return int (runtime .MAX_START_WAIT ) 242 243 244def read_config (path :Path )-> dict : 245return json .loads (Path (path ).read_text (encoding = "utf-8-sig" )) 246 247 248def desc_matches (desc :dict ,s :S .LaunchSettings )-> bool : 249"""Does the installed model's config already carry the context, memory format and picture choice of these settings? 250(The graphics cards are not part of it: they go into each launch's own config, see apply_cards.)""" 251if s .context and desc .get ("context" )!= s .context : 252return False 253want_kv = s .kv or ("int8" if (s .context or 32768 )> 8192 else "fp16" ) 254if desc .get ("kv" )not in (None ,want_kv )and (s .context or 32768 )> 8192 : 255return False 256images = desc .get ("images" )or "off" 257if s .vision is None : 258return True # no preference yet: the run settles it before it compares 259if (s .vision == "off" )!= (images == "off" ): 260return False 261if s .vision in ("gpu" ,"cpu" )and images != s .vision : 262return False 263return True 264 265 266def _inside (path :Path ,folder :Path )-> bool : 267a ,b = os .path .normcase (str (path )),os .path .normcase (str (folder )) 268return a == b or a .startswith (b .rstrip ("\\/" )+ os .sep ) 269 270 271def files_present (cfg :dict )-> list [str ]: 272"""The model files a run config names that are missing (empty list: all there).""" 273missing = [] 274for tok in cfg .get ("args" )or []: 275if isinstance (tok ,str )and tok .lower ().endswith (".gguf" )and not Path (tok ).exists (): 276missing .append (tok ) 277for flag in ("--pack" ,"--mtp" ): 278args = [str (a )for a in cfg .get ("args" )or []] 279if flag == "--mtp" and flag in args and args .index (flag )+ 1 < len (args )and args [args .index (flag )+ 1 ].isdigit (): 280continue # Qwen3.6: a number is the draft depth, not a folder (#3298) 281if flag in args and args .index (flag )+ 1 < len (args )and not Path (args [args .index (flag )+ 1 ]).exists (): 282missing .append (args [args .index (flag )+ 1 ]) 283vision = cfg .get ("vision" ) 284if isinstance (vision ,dict )and vision .get ("mmproj" )and not Path (str (vision ["mmproj" ])).exists (): 285missing .append (str (vision ["mmproj" ]))# the picture reader's file: setup fetches it again 286return missing 287 288 289def apply_choices (cfg :dict ,s :S .LaunchSettings )-> dict : 290"""A copy of the installed run config with this launch's context, memory format and picture choice on its engine command, so the command 291the Advanced step shows is the one these choices run (the installed config only holds the choices it was installed with). Only the command 292preview and the comparison use this; the start itself goes through setup, which writes the same values.""" 293import copy 294cfg = copy .deepcopy (cfg ) 295args = [str (a )for a in cfg .get ("args" )or []] 296 297def put (flag :str ,value :str )-> None : 298if flag in args : 299i = args .index (flag ) 300if i + 1 < len (args )and not args [i + 1 ].startswith ("--" ): 301args [i + 1 ]= value 302return 303args .insert (i + 1 ,value ) 304else : 305args .extend ([flag ,value ]) 306 307if s .context : 308put ("--max-context" ,str (int (s .context ))) 309kv = s .kv or ("int8" if (s .context or 32768 )> 8192 else "fp16" ) 310if "--kv" in args or s .kv : 311put ("--kv" ,kv ) 312if s .vision == "off" : 313args = [a for a in args if a != "--vision" ] 314cfg .pop ("vision" ,None )# the picture reader's own settings: the server adds --vision for them 315elif s .vision and "--vision" not in args : 316args .append ("--vision" ) 317cfg ["args" ]= args 318return cfg 319 320 321def card_signals (cfg :dict ,gpus :Any ,want :dict )-> dict : 322"""Runner.drafting_signals for a run config and the launch's cards ``gpus``: the arguments with the person's own options over them, and the ONE card's memory.""" 323try : 324from strata_control import drafting ,user_args 325args = [str (a )for a in cfg .get ("args" )or []] 326if cfg .get ("user_args" ): 327args = user_args .merge (args ,cfg ["user_args" ]) 328run = {** cfg ,"gpu" : [int (g )for g in gpus ]if gpus else cfg .get ("gpu" )} 329return {"args" :args ,"vram_mib" :drafting .card_vram_mib (run ,want .get ("backend" ),want .get ("archs" ))} 330except Exception :# noqa: BLE001 - no signal means the tuned pack is not fetched 331return {"args" : [],"vram_mib" :None } 332 333 334def auto_signals (catalog ,s :S .LaunchSettings ,family :str | None )-> dict : 335"""What the start's drafting decision reads besides the choice (drafting_inputs / drafting_signals): the model's set and the card signals of the installed config 336(or none yet) with this launch's context and cards. With them, what setup is told to fetch and what the plan lists are the drafter the start runs: on the 12 GB 337card with IQ3_S Auto is the MTP (drafting.CLASS_DEFAULTS); without them setup was told DFlash2, skipped the draft layer, and the start had no drafter (0.2.14 338real-use run); on a Mac the set decides (Metal IQ3_S is the MTP, the other sets DFlash2). Never raises.""" 339try : 340from strata_control import drafting 341path = catalog .installed_config (catalog .tag_of (s .family ,s .model )) 342cfg = apply_choices (read_config (path )if path is not None else {},s ) 343backend ,archs = drafting .detect_hardware () 344return {"model_name" :cfg .get ("model_name" )or catalog .model_name_of (family ,s .model ), 345** card_signals (cfg ,s .gpus , {"backend" :backend ,"archs" :archs })} 346except Exception :# noqa: BLE001 - no signal: Auto as before 347return {} 348 349 350def apply_cards (cfg :dict ,gpus :"list[int] | dict | None" )-> None : 351"""The graphics cards of THIS launch go into its run config, whatever card the model was installed with (no reinstall): one card is a number, 352several are a list with the automatic layer split. None: the installed config's own choice stays. A dict is the roles of every card 353(strata_control/gpu_roles.mirror: "gpu_roles" plus the legacy "gpu" with the Main card last).""" 354if isinstance (gpus ,dict ): 355for k in ("gpu" ,"gpu_order" ,"gpu_none" ,"gpu_roles" ,"gpu_cards" ): 356cfg .pop (k ,None ) 357cfg .update (gpus ) 358cfg ["gpus_asked" ]= True 359cfg .pop ("hip_ordinal" ,None ) 360on = gpus .get ("gpu" ) 361if isinstance (on ,list )and len (on )> 1 : 362cfg ["layer_split" ]= cfg .get ("layer_split" )or "auto" 363else : 364cfg .pop ("layer_split" ,None ) 365return 366if not gpus : 367return 368for k in ("gpu_roles" ,"gpu_cards" ,"gpu_none" ,"gpu_order" ):# a plain card list replaces an earlier roles choice; the engine orders it 369cfg .pop (k ,None ) 370gpus = [int (g )for g in gpus ] 371cfg ["gpu" ]= gpus [0 ]if len (gpus )== 1 else gpus 372cfg ["gpus_asked" ]= True 373cfg .pop ("hip_ordinal" ,None )# an old AMD config's ordinal of ITS card would win over the card named now 374if len (gpus )> 1 : 375cfg ["layer_split" ]= cfg .get ("layer_split" )or "auto" 376else : 377cfg .pop ("layer_split" ,None ) 378 379 380def installed_cards (base :dict | None ,usable :list [dict ]| None = None )-> list [int ]| None : 381"""The cards the installed model's own config names after a choice (setup --gpu / --gpus, the app's card pick: "gpus_asked"), in its order; 382None when it names none or was never asked, or when setup picked them itself ("gpus_by": "setup"). `usable` is not used any more (it told a 383DeepSeek config's own pick apart) and is kept for the callers.""" 384if not isinstance (base ,dict )or not (base .get ("gpus_asked" )or base .get ("gpu_roles" )): 385return None 386if not base .get ("gpu_roles" )and base .get ("gpus_by" )== "setup" : 387return None 388g = base .get ("gpu" ) 389if g is None or g == "" : 390return None 391try : 392cards = [int (str (x ).strip ())for x in (g if isinstance (g , (list ,tuple ))else str (g ).split ("," ))if str (x ).strip ()!= "" ] 393except ValueError : 394return None 395return cards or None 396 397 398def cards_for_launch (s :S .LaunchSettings ,catalog ,ram_gb :float | None = None ,base :dict | None = None )-> "list[int] | dict | None" : 399"""The cards this launch uses: the ones named (--gpu / --gpus, the Cards step), else the cards the installed config was set to (a person's 400earlier choice, "gpu": 1 or [1, 0] - never replaced by the automatic pick, which would put the first of equal cards back), else the 401recommended ones by the shared fit rule (strata_control/gpu_fit.py) when the computer has more than one card that counts, else None.""" 402if s .gpu_roles : 403try : 404from strata_control import gpu_roles 405comp = catalog .computer () 406cards = gpu_roles .rows (comp .gpus ,comp .engine_vendor ) 407named = {int (k ):v for k ,v in s .gpu_roles .items ()} 408roles = gpu_roles .normalize ({int (c .get ("index" ,0 )):named .get (int (c .get ("index" ,0 )),"off" )for c in cards },cards ) 409return gpu_roles .mirror (roles ,cards ) 410except Exception :# noqa: BLE001 - never block a launch over the choice of cards 411return None 412if s .gpus : 413return [int (g )for g in s .gpus ] 414try : 415usable_now = catalog .computer ().usable_gpus 416except Exception :# noqa: BLE001 - without the card list a saved card is kept, as before 417usable_now = None 418if installed_cards (base ,usable_now )or (isinstance (base ,dict )and base .get ("gpu_roles" )): 419return None 420try : 421from strata_control import gpu_roles 422comp = catalog .computer () 423if len (comp .usable_gpus )< 2 : 424return None 425cards = gpu_roles .rows (comp .gpus ,comp .engine_vendor ) 426rec = gpu_roles .recommend (cards ,comp .engine_vendor )["roles" ] 427return gpu_roles .order (rec ,cards )or None 428except Exception :# noqa: BLE001 - never block a launch over the choice of cards 429return None 430 431 432def used_cards (computer ,s :"S.LaunchSettings" )-> list : 433"""The cards this launch uses: the ones named (--gpu, the Cards step; a role other than off), else every card that can be used.""" 434cards = list (computer .usable_gpus ) 435chosen = None 436if s .gpu_roles : 437chosen = {int (k )for k ,v in s .gpu_roles .items ()if str (v )!= "off" } 438elif s .gpus : 439chosen = {int (g )for g in s .gpus } 440if chosen is not None : 441cards = [c for c in cards if int (c .get ("index" ,0 ))in chosen ] 442return cards 443 444 445def uses_integrated_gpu (computer ,s :"S.LaunchSettings" )-> bool : 446"""Does the launch run on an integrated / unified-memory GPU (Strix Halo, gfx1151, Radeon 8060S: the hardware probe marks it uma, integrated or 447unified_memory)? A Mac is left out.""" 448for c in used_cards (computer ,s ): 449if str (c .get ("vendor" ))== "apple" or c .get ("unified_gb" ): 450continue 451if c .get ("integrated" )or c .get ("uma" )or c .get ("unified_memory" ): 452return True 453return False 454 455 456_SETUP_LOG_NAME = re .compile (r"^strata-[A-Za-z0-9_.-]+\.log$" ) 457 458 459def own_log_path (base :dict )-> str | None : 460"""The log path a person wrote into the model's config themselves (#3656): setup names its own `strata-<model>.log`, so any other 461name is theirs and a launch keeps it instead of writing its per-profile log file.""" 462value = base .get ("log" ) 463if not isinstance (value ,str )or not value .strip (): 464return None 465return None if _SETUP_LOG_NAME .match (Path (value .replace ("\\" ,"/" )).name )else value 466 467 468def derive_config (base :dict ,s :S .LaunchSettings ,* ,bool_flags :frozenset [str ],log :str | None = None ,gpus :"list[int] | dict | None" = None , 469prev :dict | None = None )-> dict : 470"""The private run config of this launch: the installed one plus the choices that are not setup's (host, port, key, cards, advanced). 471`prev` is the config this launch wrote last time: its calibrated values and hand edits are kept (strata_control/arg_layers.py: explicit 472launch values, then persisted overrides, then calibrated values, then Auto).""" 473from strata_control import arg_layers ,tune_knobs 474cfg = json .loads (json .dumps (base )) 475cfg ["host" ]= acc .host_for (s .access ) 476cfg ["port" ]= int (s .port ) 477if s .api_key : 478cfg ["api_key" ]= s .api_key 479elif s .no_key and s .access != "local" : 480cfg ["api_key" ]= "none" # served without a key on purpose (the server warns once at start) 481else : 482cfg .pop ("api_key" ,None ) 483chosen = s .drafting 484if chosen :# strata_control/drafting.py: serve/server.py applies it at every start 485cfg ["drafting" ]= chosen 486if s .split_engine :# strata_control/split_engine.py: read by apply_split_engine; "off" survives every update 487cfg ["split_engine" ]= s .split_engine 488cfg .setdefault ("exe" ,"component:strata-engine" ) 489cfg ["open_browser" ]= False # strata launch never opens a browser by itself (only `--open` does, after the start) 490if isinstance (cfg .get ("args" ),list ): 491cfg ["args" ]= [a for a in cfg ["args" ]if a != "--open" ] 492if log and not own_log_path (base ): 493cfg ["log" ]= log 494apply_cards (cfg ,gpus ) 495from strata_control import drafting as _drafting 496drafting_off = _drafting .normalize (chosen if chosen is not None else cfg .get ("drafting" ))== "off" 497if s .mtp == "off" or drafting_off :# no draft layer for this launch (serve/server.py applies "mtp": false at every start) 498from strata_control import draft_layer # --drafting off: the written file carries no --mtp either (it was left in before) 499cfg ["mtp" ]= False 500draft_layer .apply (cfg ) 501elif s .mtp == "on" : 502cfg ["mtp" ]= True 503if cfg .get ("backend" )== "sycl" :# exactly two Arc B-series cards: --spec 2 (strata_control/intel_spec.py); the person's 504from strata_control import intel_spec # own choices (user_args, an extra option below) come after it and win 505intel_spec .apply_for_launch (cfg ) 506word_flags = S .WORD_VALUE_FLAGS 507a_changes ,e_changes = S .as_argv_changes (s .extra ,bool_flags ,word_flags )if s .extra else ({}, {}) 508arg_layers .layer (cfg ,a_changes ,prev ,bool_flags )# the one place that decides which value an option has 509if e_changes : 510cfg ["env" ]= tune_knobs .apply_to_env (dict (cfg .get ("env" )or {}),e_changes ) 511from strata_control import draft_layer 512draft_layer .apply (cfg )# "mtp": false (from the installed config too) never sits beside --mtp in the saved args (B10) 513return cfg 514 515 516def write_private (path :Path ,data :dict )-> None : 517path .parent .mkdir (parents = True ,exist_ok = True ) 518fd ,tmp = tempfile .mkstemp (prefix = ".launch-cfg-" ,suffix = ".tmp" ,dir = path .parent ) 519try : 520with os .fdopen (fd ,"wb" )as fh : 521fh .write ((json .dumps (data ,indent = 1 ,ensure_ascii = False )+ "\n" ).encode ("utf-8" )) 522try : 523os .chmod (tmp ,0o600 ) 524except OSError : 525pass 526_atomic_mod .replace (tmp ,path ) 527finally : 528if os .path .exists (tmp ): 529os .unlink (tmp ) 530if WINDOWS : 531try : 532from strata_control import private_files 533private_files .restrict_to_current_user (path ,directory = False ) 534except Exception :# noqa: BLE001 535pass 536 537 538def launch_dir ()-> Path : 539from strata_control import paths 540d = paths .state_base ()/ "launch" 541d .mkdir (parents = True ,exist_ok = True ) 542return d 543 544 545def launch_name_of (s )-> str : 546"""The name of the launch these settings make (Runner.name): its run config is launch/<name>.json.""" 547return S .slug (s .name or (s .model or "model" )+ "-" + S .context_label (s .context ).lower ()) 548 549 550def saved_launch_word (name :str )-> str | None : 551"""The Drafting word the launch `name` (Runner.name) was given last time, as its own run config (launch/<name>.json) keeps it: auto | mtp | dflash2 | off, 552or None when there is none or it cannot be read. The TUI's Drafting step and Runner.keep_saved_word read it.""" 553try : 554from strata_control import drafting 555prev = read_config (launch_dir ()/ f" { name } .json" ) 556word = prev .get ("drafting" )if isinstance (prev ,dict )else None 557word = word .strip ().lower ()if isinstance (word ,str )else None 558return word if word in drafting .MODES else None 559except Exception :# noqa: BLE001 - no readable file, no word 560return None 561 562 563# ----------------------------------------------------------------------------------------------- the runner 564 565 566def download_text (dl :dict ,already :bool ,label :str | None = None )-> str : 567"""The step line for a download or a check. `label` is what is being fetched, in words (strata_control/progress_words.py). A model whose 568files were all on disk before this run says so instead of "Downloading 58.5 of 58.5 GB".""" 569if already : 570return f"The model files are already on this computer ( { dl [ 'total_gb' ]:.1f } GB); checking them" 571return f" { label } : { dl [ 'done_gb' ]:.1f } of { dl [ 'total_gb' ]:.1f } GB" if label else f"Downloading { dl [ 'done_gb' ]:.1f } of { dl [ 'total_gb' ]:.1f } GB" 572 573 574_END = object () 575 576 577def _elapsed (seconds :float )-> str : 578"""'40 s', '3 min' (plain, rounded down).""" 579seconds = int (seconds ) 580return f" { seconds } s" if seconds < 90 else f" { seconds // 60 } min" 581 582 583class Runner : 584def __init__ (self ,s :S .LaunchSettings ,* ,catalog :Catalog | None = None ,emit :Callable [[Event ],None ]| None = None , 585cancel :threading .Event | None = None ,feed :str | None = None ,python :str | None = None , 586components_dir :str | None = None ,hardware :dict | None = None , 587confirm :Callable [[str ,str ],bool ]| None = None ,assume_yes :bool = False ,move_data :bool = False , 588retune :bool = False ,restart :bool = False ,confirm_restart :Callable [[str ,str ],bool ]| None = None , 589after_check :Callable [[],None ]| None = None ): 590self .s = s 591self .after_check = after_check # called once when nothing blocks the launch (no server, the same one, or "Restart" was answered): the screens save the preset then 592self .restart = restart # --restart: a server that serves other choices (or holds this port) is stopped and replaced without asking 593self .confirm_restart = confirm_restart # the screens: asked (question, detail) once; True = restart. None (no screens) and no --restart: refuse in one line 594self ._stop_first :list [str ]= []# other launch profiles that hold this port; stopped before the measuring and the start 595self .retune = retune # --retune: measure again even when a tuning result for this model on this computer is stored 596self .move_data = move_data # --move-data / the answer "move": the model files already here go to the new --data-dir 597self .confirm = confirm # asked (title, text) before a model is downloaded with no engine; True = go on 598self .assume_yes = assume_yes # --yes: no questions 599self .engine_problem :str | None = None 600self .key_written_notice :str | None = None # the sentence "a new API key was made", held by the command until the run config that holds the key is on disk 601self .key_written = False 602self ._catalog = catalog 603self .emit_cb = emit or (lambda e :None ) 604self .cancel = cancel or threading .Event () 605self .feed = feed 606self .python = python or sys .executable 607self .components_dir = components_dir 608self .hardware_override = hardware 609self .children :list [subprocess .Popen ]= [] 610self .notices :list [str ]= [] 611self .identity_notes :list [str ]= [] 612self .tune_result :dict | None = None 613self .config_path :Path | None = None 614self ._own_checked = False 615 616# ---- small helpers 617def emit (self ,stage :str ,text :str ,pct :float | None = None ,level :str = "info" ,** data :Any )-> None : 618self .emit_cb (Event (stage ,text ,pct ,level ,data )) 619 620def check_cancel (self )-> None : 621if self .cancel .is_set (): 622raise Cancelled () 623 624@property 625def catalog (self )-> Catalog : 626if self ._catalog is None : 627try : 628self ._catalog = Catalog (hardware = self .hardware_override ) 629except CatalogUnavailable as e : 630raise LaunchError (str (e ),"" ,5 )from None 631return self ._catalog 632 633@property 634def name (self )-> str : 635return launch_name_of (self .s ) 636 637@property 638def profile (self )-> str : 639return "launch-" + self .name 640 641def _env (self )-> dict [str ,str ]: 642env = quiet_crash_env (dict (os .environ ,PYTHONUNBUFFERED = "1" ,PYTHONIOENCODING = "utf-8" ))# no debugger on a user's machine 643env .pop ("STRATA_NO_ACQUIRE" ,None )# launch is the explicit step that may download 644if self .components_dir : 645env ["STRATA_COMPONENTS_DIR" ]= self .components_dir 646return env 647 648def _spawn (self ,argv :list [str ],* ,env :dict | None = None ,cwd :str | None = None )-> subprocess .Popen : 649kw = {"creationflags" :subprocess .CREATE_NO_WINDOW }if WINDOWS else {} 650p = subprocess .Popen (argv ,stdin = subprocess .DEVNULL ,stdout = subprocess .PIPE ,stderr = subprocess .STDOUT ,text = True , 651encoding = "utf-8" ,errors = "replace" ,env = env or self ._env (),cwd = cwd ,bufsize = 1 ,** kw ) 652self .children .append (p ) 653return p 654 655def _stop_children (self )-> None : 656"""End only the processes this runner started (by the handles it holds).""" 657for p in self .children : 658if p .poll ()is None : 659try : 660p .terminate () 661p .wait (timeout = 15 ) 662except Exception :# noqa: BLE001 663try : 664p .kill () 665except Exception :# noqa: BLE001 666pass 667 668def _cli (self ,* args :str )-> list [str ]: 669return [self .python ,str (ROOT / "strata.py" ),* args ] 670 671def warn_wsl_amd (self )-> None : 672"""Under WSL the Linux AMD engines hang (no /dev/kfd, librocdxg never completes a GPU command): say so plainly with one next step, 673and go on (a warning, never a refusal).""" 674try : 675from strata_control import engine_component as ec 676note = ec .wsl_amd_note ("hip" )and ec .wsl_amd_note (ec .detect_backend ()[0 ])# the cheap file test first: no GPU tool is run on other systems 677except Exception :# noqa: BLE001 - a nicety, never a reason to stop 678return 679if note : 680self .emit ("engine" ,note ,level = "warn" ) 681if note not in self .notices : 682self .notices .append (note ) 683 684# ---- 1. the engine 685def ensure_engine (self )-> None : 686self .warn_wsl_amd () 687shape = self .model_shape () 688if shape :# a Qwen4 model of its own shape: its engine is a separate component (strata_control/shape_engine.py) 689self .ensure_shape_engine (shape ) 690return 691self .emit ("engine" ,"Checking the engine for this computer…" ) 692from strata_control import engine_component as ec 693root = Path (self .components_dir )if self .components_dir else None 694report = ec .status (root ) 695stale = None 696if report .get ("usable" ): 697eng = report ["engine" ] 698stale = self .stale_engine (eng .get ("version" )) 699if not stale : 700self .emit ("engine" ,f"Engine { eng [ 'version' ] } ( { eng [ 'backend' ] } ) is installed." ,100 ) 701return 702feed = self .feed or os .environ .get ("STRATA_UPDATE_FEED" ) 703if stale : 704blocked = self .stale_update_blocked (stale ) 705if blocked :# an engine update is the person's choice, and never beside a loaded model 706self .notices .append (blocked ) 707self .emit ("engine" ,blocked ,100 ,level = "warn" ) 708return 709self .emit ("engine" ,stale + " Looking for a newer one…" ,0 ,level = "warn" ) 710else : 711self .emit ("engine" ,"No engine is installed yet. Getting the one for your graphics card…" ,0 ) 712argv = self ._cli ("update" ,"--no-control" ,"--output" ,"jsonl" ) 713if feed : 714argv += ["--feed" ,feed ] 715if self .components_dir : 716argv += ["--components-dir" ,self .components_dir ] 717env = self ._env () 718for key ,value in self .s .extra .items ():# the engine's own environment settings (device selectors, ...) apply to its test start too 719if not key .startswith ("--" )and value .lower ()not in ("off" ,"unset" ,"none" ): 720env [key ]= value 721p = self ._spawn (argv ,env = env ) 722last = None 723tail :list [str ]= [] 724for line in p .stdout :# type: ignore[union-attr] 725self .check_cancel () 726line = line .strip () 727if not line : 728continue 729try : 730ev = json .loads (line ) 731except ValueError : 732tail .append (line ) 733continue 734if ev .get ("event" )== "progress" : 735self .emit ("engine" ,f"Downloading the engine… { ev . get ( 'percent' , 0 ) } %" ,float (ev .get ("percent" ,0 ))) 736elif ev .get ("event" )in ("phase" ,"waiting" ): 737if ev .get ("phase" )== "warn" : 738self .emit ("engine" ,str (ev .get ("message" )or "" ),level = "warn" ) 739else : 740self .emit ("engine" ,str (ev .get ("message" )or "" )) 741last = ev 742code = p .wait () 743if stale : 744# an engine is there and was too old: warn, never refuse (round 8, M: 0.1.45.3 was reused although 0.1.47 existed, and Gyro-S failed 745# on kernels only the newer engine has). Whatever the update did, say where it stands. 746after = ec .status (root ) 747now = (after .get ("engine" )or {}).get ("version" )if after .get ("usable" )else None 748still = self .stale_engine (now )if now else stale 749if still : 750self .notices .append (still + " Run `strata update`, then start it again." ) 751self .emit ("engine" ,still + (" The update did not bring a newer one." if code == 0 else " The update did not finish." )+ 752" Run `strata update`, then start it again." ,100 ,level = "warn" ) 753else : 754self .emit ("engine" ,f"Engine { now } is installed." ,100 ) 755return 756if code == 0 : 757# `strata update` exits 0 when the feed simply has no engine for this PC (or only one for another card family). That is not an 758# engine: refuse here, before the model (tens of GB) is touched. 759after = ec .status (root ) 760if not after .get ("usable" ): 761self .no_engine (self ._no_engine_words (last ,after )) 762return 763if code != 0 : 764why = "" 765if isinstance (last ,dict ): 766why = str ((last .get ("error" )or {}).get ("message" )or last .get ("message" )or "" ) 767if not why : 768for res in last .get ("results" )or []: 769if isinstance (res ,dict )and res .get ("status" )== "failed" and res .get ("error" ): 770why = str (res ["error" ]) 771break 772why = why or (tail [- 1 ]if tail else "" ) 773why = capital (why )# (joined after a sentence: "the update feed could not be read ..." starts a new one) 774raise LaunchError ("The engine could not be installed." + (f" { why } " if why else "" ), 775"Check your internet connection, or point Strata at an update source with --feed, then try again." ,6 ) 776self .emit ("engine" ,"The engine is installed." ,100 ) 777 778def stale_update_blocked (self ,stale :str )-> str | None : 779"""The engine here is older than this model needs. Updating it is the person's choice (owner, 11-01: an engine update never starts by itself): 780None when they said yes (--yes, or the answer to the question on the screens), else the one plain sentence that says why nothing was 781updated and the next step. A model that is loaded blocks it whatever was answered. Warn, never refuse: the launch goes on.""" 782from strata_control import engine_update ,updater 783try : 784models = engine_update .running_models (updater .serving_now ()) 785except Exception :# noqa: BLE001 - not knowing is not a reason to update 786models = [] 787if models : 788names = ", " .join (m .label for m in models ) 789return (f" { stale } { names } { 'is' if len ( models ) == 1 else 'are' } running, so Strata did not update the engine. " 790"Stop it (`strata launch --stop`), run `strata update`, then start again." ) 791if self .assume_yes : 792return None 793if self .confirm is not None and self .confirm ("Update the engine?" ,stale + " Update it now? Nothing else is changed; your models are kept." ): 794return None 795return stale + " Strata did not update it. Run `strata update` (or start with --yes) and start again." 796 797def model_shape (self )-> str | None : 798"""The model shape whose own engine runs the chosen model (a feed model of a shape other than Flash-Next's: setup's FAMILIES entry has "shape"), or None.""" 799try : 800fam = (getattr (self .catalog .strata .setup_module (),"FAMILIES" ,None )or {}).get (self .s .family )or {} 801shape = fam .get ("shape" ) 802return shape if isinstance (shape ,str )and shape else None 803except Exception :# noqa: BLE001 - no table, no shape: the Strata engine 804return None 805 806def model_title (self )-> str | None : 807"""The chosen model's title ("Q4 Lite Shape"), which the lines about its engine name instead of the geometry's name; None when the table has none.""" 808try : 809title = ((getattr (self .catalog .strata .setup_module (),"FAMILIES" ,None )or {}).get (self .s .family )or {}).get ("title" ) 810return title if isinstance (title ,str )and title else None 811except Exception :# noqa: BLE001 812return None 813 814def ensure_shape_engine (self ,shape :str )-> None : 815"""Step 1 for a model of its own shape: the engine of that shape is installed (and the feed's newer one fetched), next to the Strata engine, which is not touched.""" 816import argparse 817from strata_cli import update_cmd 818from strata_control import engine_component as ec ,shape_engine 819root = Path (self .components_dir )if self .components_dir else None 820title = self .model_title () 821name = shape_engine .shown (shape ,title ) 822self .emit ("engine" ,shape_engine .WORDS ["checking" ].format (model = name )) 823source = update_cmd ._feed_source (argparse .Namespace (feed = self .feed or os .environ .get ("STRATA_UPDATE_FEED" )),root or ec .components_dir ()) 824said :list [str ]= [] 825exe = shape_engine .ensure (shape ,source ,components = root ,emit = lambda m : (said .append (m ),self .emit ("engine" ,m ,0 )),title = title , 826automatic = True )# with an engine installed, a check nobody asked for (netpolicy rule 4b) 827if exe is None : 828self .no_engine (said [- 1 ]if said else shape_engine .WORDS ["fetch_failed" ].format (model = name ,why = "nothing was fetched" )) 829return 830found = shape_engine .find (shape ,root ,full = False ,title = title ) 831self .emit ("engine" ,shape_engine .WORDS ["ready" ].format (model = name ,version = found .version ,backend = found .backend ),100 ) 832 833def needed_engine (self )-> tuple [int , ...]| None : 834"""The oldest engine this model runs on, from setup.py's own tables (MIN_ENGINE for everything, GYRO_ENGINE for Gyro), or None.""" 835try : 836mod = self .catalog .strata .setup_module () 837need = tuple (getattr (mod ,"MIN_ENGINE" , ())or ()) 838if self .s .family == "gyro" : 839need = max (need ,tuple (getattr (mod ,"GYRO_ENGINE" , ())or ())) 840if sys .platform == "darwin" : 841need = max (need ,GYRO_METAL_ENGINE )# the Metal Gyro kernels (TQK6/TQK7/TQ2_T) first shipped in 0.1.47; CUDA, HIP, SYCL had them earlier 842return need or None 843except Exception :# noqa: BLE001 - no table, no check 844return None 845 846def stale_engine (self ,version :str | None )-> str | None : 847"""A plain sentence when the installed engine is older than the model needs, else None.""" 848have = version_tuple (version ) 849need = self .needed_engine () 850if not have or not need or have >= need : 851return None 852return f"The engine installed here ( { version } ) is older than this model needs ( { '.' . join ( map ( str , need )) } or newer)." 853 854def no_engine (self ,reason :str )-> None : 855"""There is no engine for this computer and none to get. This is a warning, not a refusal: the model may still be downloaded, because 856the engine can be installed afterwards. Ask first (the answer is yes unless the person says no; --yes skips the question) when a 857download is about to happen; otherwise just remember the problem for the final message.""" 858self .engine_problem = reason 859warning = no_engine_warning (reason ) 860self .emit ("engine" ,warning ,100 ,level = "warn" ) 861if self .assume_yes or self .confirm is None : 862return 863try : 864gb = self .download_gb () 865except Exception :# noqa: BLE001 866gb = 0.0 867if gb < 0.05 : 868return # nothing would be downloaded: no question, only the final message 869if not self .confirm ("No engine for this computer yet" ,warning + f" Download the model now (about { gb :.0f } GB)?" ): 870raise LaunchError ("Stopped. Nothing was downloaded." ,"Install the engine first, or run this again and answer yes." ,130 ) 871 872@staticmethod 873def _no_engine_words (last :object ,report :dict )-> str : 874"""The one plain sentence for "no usable engine for this PC": the update's own note (the wrong-card-family line, or "the feed has no 875engine package for this PC"), else the engine report's plain notice. Never the raw list of reasons.""" 876note = "" 877if isinstance (last ,dict ): 878for res in last .get ("results" )or []: 879if isinstance (res ,dict )and res .get ("component" )== "engine" : 880note = str (res .get ("note" )or "" ).strip () 881if not note : 882note = str (report .get ("notice" )or "" ).strip () 883if "backend" in report and report ["backend" ]is None :# not even a graphics card Strata knows: say that, not "the feed has nothing" 884names = [] 885try : 886from strata_control import engine_component as ec 887names = [a .get ("name" ,"" )for a in ec .windows_display_adapters ()]if os .name == "nt" else [] 888except Exception :# noqa: BLE001 - the names are a nicety 889pass 890return no_gpu_words (names ) 891if not note or note .startswith ("No engine for this PC was found" ): 892note = "There is no engine for this computer's graphics card in the update source." 893return note 894 895# ---- 2. the model 896def resolved_vision (self )-> str : 897"""The picture setting of this launch: the chosen one, or (nothing chosen) the default for this model and engine (catalog.picture_default).""" 898s = self .s 899if s .vision is None : 900row = next ((r for r in self .catalog .rows ()if (r .family ,r .model )== (s .family ,s .model )),None ) 901s .vision = self .catalog .picture_default (bool (row .images )if row is not None else False ) 902return s .vision 903 904def vision_word (self )-> str : 905"""What setup is told for the picture choice. "on" is setup's "yes": setup (Control mode) picks the CPU encoder on a card under 24 GB 906and the GPU encoder from 24 GB (any make of card), and downloads the pinned picture-reader file (mmproj) with the model.""" 907s = self .s 908self .resolved_vision () 909if s .vision == "off" : 910return "no" 911return "yes" if s .vision == "on" else s .vision 912 913def check_pictures (self ,path :Path )-> None : 914"""Pictures were asked for: say so in plain words when the installed settings still have them off.""" 915s = self .s 916if s .vision == "off" : 917return 918try : 919desc = self .catalog .strata .describe_config (path ) 920except Exception :# noqa: BLE001 921return 922if (desc or {}).get ("images" )in (None ,"off" ): 923note = ("Pictures could not be switched on: this engine does not carry the picture reader, or this model cannot read pictures, " 924"so it will answer text only." ) 925self .notices .append (note ) 926self .emit ("model" ,note ,100 ,level = "warn" ) 927 928def setup_args (self )-> list [str ]: 929cat ,s = self .catalog ,self .s 930fam ,model = s .family ,s .model 931try :# a saved preset or choices file keeps the lower-case tag ("iq3_xxs", #4209), while setup's 932fam ,model = cat .resolve (str (model ),None if fam is None else str (fam ))# --model takes the table's own key 933except Exception :# noqa: BLE001 a name the list does not hold, or a list that cannot be read here, is setup's 934pass # to report: passing the values on unchanged keeps the launch behaving as it did before 935args = ["--yes" ,"--no-start" ,"--family" ,str (fam ),"--model" ,str (model )] 936ctx = s .context 937if ctx : 938args += ["--context" ,str (ctx )] 939args += ["--vision" ,self .vision_word ()] 940if s .kv : 941args += ["--kv" ,s .kv ] 942if fam in ("qwen" ,"coder" ): 943args += ["--experimental-speed-projection" ,"off" ] 944layer_fetch = getattr (self ,"_layer_fetch" ,False )# the start's safety net (fetch_missing_drafter): setup fetches the draft layer 945resolved = "mtp" if layer_fetch else self .resolved_drafting (fam ) 946mtp_word = s .mtp if resolved != "off" else "off" 947if mtp_word is None and (layer_fetch or self .layer_back ()): 948mtp_word = "on" # a drafter chosen again after Off: the "mtp": false that Off's "--mtp off" left goes (REAL-USE-1) 949if mtp_word in ("on" ,"off" )and fam in modelstate .HELPER_FAMILIES : 950args += ["--mtp" ,mtp_word ]# round 8, N3: "--mtp off" never reached setup, which then fetched the 5.2 GB draft layer 951if resolved == "dflash2" and fam in modelstate .HELPER_FAMILIES and mtp_word != "off" : 952args += ["--drafter" ,"dflash2" ]# one drafter per run: a new install fetches DFlash2's pack (below), not the MTP layer 953data = s .data_dir or self .existing_data_dir () 954if data : 955args += ["--data-dir" ,str (data )] 956if self .move_data and s .data_dir :# only when the person said so: setup moves nothing otherwise 957args .append ("--move-data" ) 958if s .data_dir :# a folder the person chose is remembered for the next start and for the app 959args .append ("--set-default-data-dir" ) 960if s .model_path : 961p = Path (s .model_path ) 962args += ["--gguf-dir" ,str (p if p .is_dir ()else p .parent )] 963if self .feed :# --feed / STRATA_UPDATE_FEED: setup reads the signed feed from there too 964args += ["--feed" ,str (self .feed )] 965if s .gpu_roles : 966args += ["--gpu-roles" ,"," .join (f" { k } = { v } " for k ,v in sorted (s .gpu_roles .items (),key = lambda kv :int (kv [0 ])))] 967elif s .gpus : 968args += ["--gpus" ,"," .join (str (g )for g in s .gpus )]if len (s .gpus )> 1 else ["--gpu" ,str (s .gpus [0 ])] 969else : 970args += self .installed_card_args () 971if sys .platform == "darwin" : 972# a Mac's setup (Control mode, strata_control/mac_fit.py) takes fewer options (no --kv, --gpu, speed projection) 973keep = {"--yes" ,"--no-start" ,"--family" ,"--model" ,"--context" ,"--vision" ,"--data-dir" ,"--gguf-dir" ,"--move-data" , 974"--set-default-data-dir" ,"--feed" ,"--drafter" ,"--mtp" }# --drafter / --mtp: setup.py's Mac step fetches the draft layer only where the 975# start runs the MTP, and not after a Drafting Off (`--mtp off`) 976flags = ("--yes" ,"--no-start" ,"--move-data" ,"--set-default-data-dir" ) 977out ,i = [],0 978while i < len (args ): 979if args [i ]in keep : 980out .append (args [i ]) 981if args [i ]not in flags and i + 1 < len (args ): 982out .append (args [i + 1 ]) 983i += 2 if args [i ]not in flags else 1 984else : 985i += 2 if i + 1 < len (args )and not args [i + 1 ].startswith ("--" )else 1 986args = out 987return args 988 989def installed_card_args (self )-> list [str ]: 990"""--gpu-roles / --gpus of the installed config when the launch names no cards itself. A change of context or pictures runs setup again; 991without these it picked the cards and the Main/Helper roles afresh and reset an explicit choice (round 8, F3: 0=main,1=helper 992came back as 0=helper,1=main). Only a choice that was made ("gpus_asked" / roles) is forwarded, never the automatic pick.""" 993try : 994path ,_desc = self .installed_state () 995base = read_config (path )if path is not None else None 996if not isinstance (base ,dict ): 997return [] 998roles = base .get ("gpu_roles" ) 999if isinstance (roles ,dict )and roles : 1000return ["--gpu-roles" ,"," .join (f" { k } = { v } " for k ,v in sorted (roles .items (),key = lambda kv :int (kv [0 ])))] 1001try : 1002usable_now = self .catalog .computer ().usable_gpus 1003except Exception :# noqa: BLE001 1004usable_now = None 1005cards = installed_cards (base ,usable_now ) 1006if cards : 1007return ["--gpus" ,"," .join (str (g )for g in cards )]if len (cards )> 1 else ["--gpu" ,str (cards [0 ])] 1008except Exception :# noqa: BLE001 - never block a launch over remembering the cards 1009pass 1010return [] 1011 1012def installed_state (self )-> tuple [Path | None ,dict | None ]: 1013tag = self .catalog .tag_of (self .s .family ,self .s .model ) 1014path = self .catalog .installed_config (tag ) 1015if path is None : 1016return None ,None 1017desc = self .catalog .strata .describe_config (path ) 1018return path ,desc 1019 1020def layer_back (self ,path :Path | None = None )-> bool : 1021"""A drafter is named at this launch (Auto, MTP or DFlash2, not Off; no --mtp) while the installed config says "mtp": false: a Drafting Off launch hands 1022setup "--mtp off", and setup keeps that at every later run, so Auto read it as "the draft layer is off" and started without a drafter (0.2.13.1, REAL-USE-1). 1023Then setup runs again with "--mtp on", and the start is the one a first launch with that choice gets. A model the feed says has no draft layer stays off.""" 1024s = self .s 1025if s .mtp is not None or s .drafting is None or s .family not in modelstate .HELPER_FAMILIES : 1026return False # (a Mac's setup takes the --mtp word too: setup_args) 1027from strata_control import drafting 1028if drafting .normalize (s .drafting )== "off" or self .resolved_drafting (s .family )== "off" : 1029return False 1030try : 1031if path is None : 1032path = self .catalog .installed_config (self .catalog .tag_of (s .family ,s .model )) 1033return path is not None and read_config (path ).get ("mtp" )is False 1034except Exception :# noqa: BLE001 - an unreadable config is setup's to report; nothing changes here 1035return False 1036 1037def installed_serves_request (self ,path :Path )-> bool : 1038"""C08: the installed copy is what this launch asked for. A --model-path (or the Folder step's own files) and a --data-dir always win: 1039when the installed config names files outside them, it is not reused (that served another copy without a word) and setup runs with 1040the given folders, which rewrites the config so the profile follows.""" 1041s = self .s 1042if not (s .model_path or s .data_dir ): 1043return True 1044try : 1045cfg = read_config (path ) 1046args = [str (a )for a in cfg .get ("args" )or []] 1047if s .model_path : 1048want = Path (s .model_path ).expanduser ().resolve () 1049folder = want if want .is_dir ()else want .parent 1050ggufs = [Path (a )for a in args if a .lower ().endswith (".gguf" )] 1051if not ggufs or not all (_inside (g .resolve (),folder )for g in ggufs ): 1052return False 1053if s .data_dir : 1054packs = [Path (args [i + 1 ])for i ,a in enumerate (args [:- 1 ])if a == "--pack" ] 1055return all (_inside (pk .resolve (),Path (s .data_dir ).expanduser ().resolve ())for pk in packs ) 1056return True 1057from strata_control import discovery 1058found = discovery .footprint (cfg ,path ).data_dir 1059return found is not None and os .path .normcase (str (Path (found ).resolve ()))== os .path .normcase (str (Path (s .data_dir ).expanduser ().resolve ())) 1060except Exception :# noqa: BLE001 - when in doubt do what was asked: run setup with the given folders 1061return False 1062 1063def existing_data_dir (self )-> Path | None : 1064"""The data folder to give setup when the person chose none: the folder the model already lives in (its run config names its files), 1065else the folder the desktop app uses, so a helper file that is missing is fetched next to the rest, never into a second folder. 1066None: setup's own default is right.""" 1067s = self .s 1068try : 1069if s .model_path : 1070from strata_control import discovery 1071# the folder above the person's own files only when Strata may keep its files there (writable, not a Hugging Face cache); 1072# else setup's default data folder (lane NET item 5; beside_refused() says so) 1073found = discovery .writable_beside (self ._first_own_gguf ()) 1074return Path (found )if found else None 1075if s .family and s .model : 1076path = self .catalog .installed_config (self .catalog .tag_of (s .family ,s .model )) 1077if path is not None : 1078from strata_control import discovery 1079found = discovery .footprint (read_config (path ),path ).data_dir 1080if found is not None : 1081return found 1082found ,source = self .catalog .data_dir_choice () 1083return found if source != "default" else None 1084except Exception :# noqa: BLE001 1085return None 1086 1087def _first_own_gguf (self )-> Path | None : 1088s = self .s 1089if not s .model_path : 1090return None 1091try : 1092p = Path (s .model_path ) 1093return next (iter (sorted (p .glob ("*.gguf" ))),None )if p .is_dir ()else p 1094except OSError : 1095return None 1096 1097def beside_refused (self )-> Path | None : 1098"""The data folder guessed from the person's own files (the folder above a `models` folder) when Strata does not use it for its own files 1099because it cannot write there or it is inside a Hugging Face cache; None when it is used or there is none.""" 1100s = self .s 1101if not s .model_path or s .data_dir : 1102return None 1103try : 1104from strata_control import discovery 1105first = self ._first_own_gguf () 1106found = discovery .prepared_beside (first )["data_dir" ]if first else None 1107if found is None or discovery .writable_beside (first )is not None : 1108return None 1109return Path (found ) 1110except Exception :# noqa: BLE001 1111return None 1112 1113def model_state (self ): 1114"""What this launch still needs for the model, in numbers and words (strata_cli/launch/modelstate.py).""" 1115from strata_cli .launch import modelstate 1116s = self .s 1117self .resolved_vision () 1118path ,desc = (None ,None ) 1119installed = True 1120if s .family and s .model and not s .model_path : 1121path ,desc = self .installed_state () 1122if path is not None and self .other_copy ()is not None : 1123# the copy that is installed is not what this launch uses (another --data-dir): the start runs setup with the given folder, so 1124# the plan counts what setup fetches there, not the other copy (lane NET 4a) 1125path ,desc ,installed = None ,None ,False 1126return modelstate .assess (self .catalog ,s .family ,s .model ,vision = s .vision ,model_path = s .model_path ,data_dir = s .data_dir , 1127config = path ,desc = desc ,mtp = s .mtp ,drafting = self .resolved_drafting (s .family ),use_installed = installed ) 1128 1129def other_copy (self )-> Path | None : 1130"""The data folder of an installed copy of this model that this launch does not use, else None: another --data-dir was given, and the 1131copy is not in a folder setup itself takes model files from (setup.data_folder_for keeps the remembered data folder and Strata's own 1132folder as sources and uses complete files there where they are; any other folder it does not look at, so everything is fetched).""" 1133s = self .s 1134if not (s .family and s .model and s .data_dir )or s .model_path : 1135return None 1136try : 1137path ,_desc = self .installed_state () 1138if path is None or self .installed_serves_request (path ): 1139return None 1140from strata_control import discovery 1141found = discovery .footprint (read_config (path ),path ).data_dir 1142if found is None : 1143return None 1144here = Path (found ).resolve () 1145for source in (self .catalog .data_dir (),Path (self .catalog .root )): 1146try : 1147src = Path (source ).resolve () 1148except (OSError ,TypeError ): 1149continue 1150if here == src or here == src / "Strata-data" : 1151return None # setup reuses it: the plan's installed answer is the start's 1152return found 1153except Exception :# noqa: BLE001 - a plan line, never a reason to stop 1154return None 1155 1156def download_gb (self )-> float : 1157"""How much would be downloaded for this launch right now: 0 when everything is on disk (the model is installed with these choices 1158or is the person's own files). A model whose helper files are missing counts only those files, never the whole model.""" 1159s = self .s 1160if not (s .family and s .model )and not s .model_path : 1161return 0.0 1162try : 1163return float (self .model_state ().remaining_gb ) 1164except Exception :# noqa: BLE001 1165return 0.0 1166 1167def start_wait (self )-> int : 1168"""How long the start waits for the model to be ready (#3949 #3459): 10 minutes, more for a big model, which a slow disk needs 1169longer to read (about 8 more seconds per GB above 40 GB, at most 30 minutes). Automatic: nobody sets a variable for it.""" 1170gb = 0.0 1171try : 1172row = next ((r for r in self .catalog .rows ()if r .family == self .s .family and r .model == self .s .model ),None ) 1173gb = float (getattr (row ,"download_gb" ,0 )or 0 ) 1174except Exception :# noqa: BLE001 1175gb = 0.0 1176return int (min (runtime_max_wait (),max (600 ,600 + (gb - 40.0 )* 8.0 ))) 1177 1178def download_question (self )-> tuple [str ,str ]: 1179"""(title, text) of the question before a download starts, naming exactly what is fetched.""" 1180return self .model_state ().question () 1181 1182#: seconds of silence from setup before a "still working" line (packing a 40 GB model prints nothing for minutes) 1183HEARTBEAT_S = 30.0 1184 1185def _read_lines (self ,p :subprocess .Popen ): 1186"""The lines setup prints, and None whenever a second passes with none, so a silent step can say it is still going and a cancel is 1187seen at once.""" 1188import queue 1189q :queue .Queue = queue .Queue () 1190 1191def pump ()-> None : 1192try : 1193for ln in p .stdout :# type: ignore[union-attr] 1194q .put (ln ) 1195finally : 1196q .put (_END ) 1197threading .Thread (target = pump ,daemon = True ).start () 1198while True : 1199try : 1200ln = q .get (timeout = min (1.0 ,max (0.05 ,self .HEARTBEAT_S / 2 ))) 1201except queue .Empty : 1202yield None 1203continue 1204if ln is _END : 1205return 1206yield ln 1207 1208def progress_job (self )-> dict : 1209"""What the download figure is counted over: the folder setup writes the model into (the data folder it is GIVEN, which may be the 1210person's --data-dir and not the default one) and every file of the install with the catalog's total, so a model in several shards 1211shows 'of 66.4 GB' from the start and not the size of the file being fetched.""" 1212s ,cat = self .s ,self .catalog 1213data = Path (s .data_dir )if s .data_dir else (self .existing_data_dir ()or cat .data_dir ()) 1214models_dir = data / "models" 1215job = {"folder" :str (cat .model_folder (data ,s .family ,s .model )), 1216"total_gb" :float (next ((r .download_gb for r in cat .rows ()if r .family == s .family and r .model == s .model ),0 )or 0 )} 1217try : 1218setup_module = cat .strata .setup_module () 1219if setup_module is not None and not s .model_path : 1220job ["files" ]= cat .mcp .expected_files (setup_module ,str (s .family ),str (s .model ),models_dir ,self .vision_word ()!= "no" ) 1221first = next ((f for f in job ["files" ]if f .get ("role" )== "model" ),None ) 1222if first :# the folder setup names it (Q2_0), not the lower-case run-config tag (q2_0) 1223job ["folder" ]= str (Path (first ["path" ]).parent ) 1224except Exception :# noqa: BLE001 - progress is a convenience; the folder scan still counts 1225pass 1226return job 1227 1228def ensure_model (self )-> Path : 1229s ,cat = self .s ,self .catalog 1230self .check_own_files () 1231self .resolved_vision () 1232if not (s .family and s .model ): 1233raise LaunchError ("No model was chosen." ,"Choose a model, or use --model NAME (strata launch --help lists them)." ,2 ) 1234path ,desc = self .installed_state () 1235if path is not None and desc is not None and desc_matches (desc ,s )and not files_present (read_config (path ))and not self .layer_back (path ) \ 1236and not getattr (self ,"_layer_fetch" ,False ): 1237if self .installed_serves_request (path ): 1238self .emit ("model" ,f" { s . family } { s . model } is already installed with these choices." ,100 ) 1239return path 1240self .emit ("model" ,"The model already installed here is somewhere else than the folder you gave, so Strata uses the folder you gave " 1241"and points this launch at it." ,0 ) 1242title = f" { s . family } { s . model } " 1243try :# the name on screen 1244title = next ((r .title for r in self .catalog .rows ()if r .family == s .family and r .model == s .model ),title ) 1245except Exception :# noqa: BLE001 - a label only 1246pass 1247if sys .platform == "darwin" and not (cat .src / "strata_control" / "mac_fit.py" ).is_file (): 1248# a Terminal from before the Mac rules moved into strata_control/mac_fit.py: setup.py cannot install a Mac model in its Control 1249# mode (no source build, no setup_mac.py), so use model files prepared on this Mac. Every other Terminal installs through setup.py. 1250adopted = self .adopt_prepared_files ("no Mac model installer in this Terminal" ) 1251if adopted is not None : 1252return adopted 1253if self .intel_chosen (): 1254adopted = self .adopt_prepared_files ("" ,chosen = True ) 1255if adopted is not None : 1256return adopted 1257self .emit ("model" ,f"Preparing { title } from your model files…" if s .model_path else 1258f"Getting { title } ready (a download may be large; it continues where it stopped if interrupted)…" ,0 ) 1259refused = self .beside_refused () 1260if refused is not None :# lane NET item 5 (W9): the files stay, Strata's own go to the data folder 1261from strata_control import discovery 1262why = (f" { refused } is a Hugging Face download folder, so Strata" if discovery .in_hf_cache (refused )or discovery .in_hf_cache (refused / "models" ) 1263else f"Strata can't write in { refused } , so it" )# (W9 / W9b, owner 11-10) 1264note = (f"Your model files are used where they are. { why } keeps its own files (the prepared data and " 1265f"the picture reader) in { cat . data_dir () } ." ) 1266self .notices .append (note ) 1267self .emit ("model" ,note ,None ) 1268argv = [self .python ,str (cat .src / "setup.py" ),* self .setup_args ()] 1269env = self ._env () 1270env .update (STRATA_CONTROL_INSTALL = "1" ,STRATA_INSTALL_DIR = str (cat .root ),PYTHONNOUSERSITE = "1" ) 1271env .pop ("STRATA_NEED_ENGINE" ,None ) 1272if self .engine_problem : 1273env ["STRATA_ALLOW_NO_ENGINE" ]= "1" # the person said go on: setup warns about the engine instead of stopping 1274else : 1275env ["STRATA_NEED_ENGINE" ]= "1" 1276for k in ("PYTHONHOME" ,"PYTHONPATH" ,"VIRTUAL_ENV" ): 1277env .pop (k ,None ) 1278env ["PYTHONPATH" ]= str (cat .src ) 1279p = self ._spawn (argv ,env = env ,cwd = str (cat .src )) 1280lines :list [str ]= [] 1281already :bool | None = None # all the model's files were on disk before this run wrote anything 1282job = self .progress_job () 1283step_seen ,step_since ,quiet_since ,said = None ,time .monotonic (),time .monotonic (),None 1284for line in self ._read_lines (p ): 1285if self .cancel .is_set (): 1286self ._stop_children () 1287self .keep_setup_output (lines + [f"(you stopped it { ': ' + said [ 0 ] if said else '' } )" ])# the log says where it stood 1288raise Cancelled () 1289if line is None :# nothing printed for a while: the long steps (packing, converting) are silent 1290if said and time .monotonic ()- quiet_since >= self .HEARTBEAT_S :# (the download phase too: a server that does not answer is silent) 1291quiet_since = time .monotonic () 1292self .emit ("model" ,f" { said [ 0 ] } (still working, { _elapsed ( time . monotonic () - step_since ) } so far)" ,None ,step = step_seen ) 1293continue 1294quiet_since = time .monotonic () 1295line = line .rstrip () 1296if not line : 1297continue 1298lines .append (line ) 1299lines [:]= lines [- 1500 :] 1300prog = cat .mcp .install_progress (lines ) 1301prog = cat .mcp .combined_progress (prog ,job ) 1302dl ,phase ,label = prog .get ("download" ),prog .get ("phase" ),prog .get ("label" ) 1303if prog .get ("step" )!= step_seen : 1304step_seen ,step_since = prog .get ("step" ),time .monotonic () 1305said = (label ,phase )if label else None 1306if phase == "waiting" :# setup is waiting for a server to answer: say which one (netpolicy's line) 1307self .emit ("model" ,label ,None ,step = prog .get ("step" )) 1308elif dl and dl .get ("total_gb" ,0 )>= 0.05 and not (s .model_path and phase == "download" ): 1309if phase == "download" and already is None : 1310already = float (dl ["percent" ])>= 99.5 1311text = download_text (dl ,bool (already )and phase == "download" ,label ) 1312self .emit ("model" ,text ,float (dl ["percent" ]),step = prog .get ("step" )) 1313elif label : 1314self .emit ("model" ,label ,None ,step = prog .get ("step" )) 1315elif prog .get ("step" ): 1316self .emit ("model" ,f"Setup step { prog [ 'step' ] } " ,None ,step = prog .get ("step" )) 1317code = p .wait () 1318self .note_setup_lines (lines ) 1319if code != 0 : 1320err = "" 1321for line in reversed (lines ): 1322if line .strip ().startswith ("[X]" ): 1323err = line .strip ()[3 :].strip () 1324break 1325hint = "" 1326if err : 1327for i ,line in enumerate (lines ): 1328if err in line and i + 1 < len (lines )and lines [i + 1 ].startswith (" " ): 1329hint = lines [i + 1 ].strip () 1330adopted = self .adopt_prepared_files (err ) 1331if adopted is not None : 1332return adopted 1333raise setup_failure (lines ,err ,hint ,self .keep_setup_output (lines ),bool (s .model_path )) 1334path ,_desc = self .installed_state () 1335if path is None : 1336raise LaunchError ("Setup finished but no run config was written for this model." , 1337"Run `strata launch` again; if it repeats, the setup output above says why." ,6 ) 1338self .emit ("model" ,f" { title } is ready." ,100 ) 1339self .say_reused_data (path ) 1340self .check_pictures (path ) 1341return path 1342 1343def say_reused_data (self ,path :Path )-> None : 1344"""C08 note: your own model files are used where they are, and when the prepared pack or the draft layer are read from another data folder 1345than the one given, one line says where from.""" 1346s = self .s 1347if not (s .model_path and s .data_dir ): 1348return 1349try : 1350args = [str (a )for a in read_config (path ).get ("args" )or []] 1351want = Path (s .data_dir ).expanduser ().resolve () 1352elsewhere = [] 1353for flag ,label in (("--pack" ,"the prepared pack" ), ("--mtp" ,"the draft layer" )): 1354if flag in args and args .index (flag )+ 1 < len (args ): 1355value = args [args .index (flag )+ 1 ] 1356if value .isdigit (): 1357continue 1358place = Path (value ).expanduser ().resolve () 1359if not _inside (place ,want ): 1360elsewhere .append ((label ,place )) 1361if elsewhere : 1362folders = sorted ({str (pl .parent .parent if pl .parent .name in ("packs" ,"mtp" )else pl .parent )for _l ,pl in elsewhere }) 1363text = (f" { ' and ' . join ( l for l , _p in elsewhere ). capitalize () } { 'is' if len ( elsewhere ) == 1 else 'are' } read from " 1364f" { ', ' . join ( folders ) } , not from { want } ; nothing was copied." ) 1365self .notices .append (text ) 1366self .emit ("model" ,text ,100 ) 1367except (OSError ,ValueError ): 1368pass 1369 1370def keep_setup_output (self ,lines :list [str ])-> str | None : 1371"""The last lines setup.py printed, kept next to the launch's other logs so a failed install can be read afterwards (the message 1372shows one line; a traceback needs the rest). Best effort: None when it cannot be written.""" 1373try : 1374folder = launch_dir () 1375folder .mkdir (parents = True ,exist_ok = True ) 1376path = folder / f" { self . name } .setup.log" 1377path .write_text ("\n" .join (lines [- 400 :])+ "\n" ,encoding = "utf-8" ,errors = "replace" ) 1378return str (path ) 1379except (OSError ,ValueError ): 1380return None 1381 1382def intel_chosen (self )-> bool : 1383"""The engine for this launch is the Intel Arc one (chosen with --backend intel, saved, or the only make here), and the model is one 1384the built-in downloader sets up for NVIDIA and AMD only: Strata prepares the model files itself instead (adopt_prepared_files).""" 1385if sys .platform == "darwin" or WINDOWS : 1386return False 1387try : 1388from strata_control import engine_component 1389return engine_component .detect_backend ()[0 ]== "sycl" 1390except Exception :# noqa: BLE001 1391return False 1392 1393def prepare_pack (self ,model_dir :Path ,pack :Path ,shards :list )-> None : 1394"""Build the pack an Intel Arc run needs from the GGUF files (the step setup.py runs for NVIDIA and AMD cards): setup.py --prepare-pack 1395fetches llama.cpp's gguf-py by itself and runs tools/iq_pack.py. Takes seconds to a few minutes; the draft layer is not built.""" 1396cat = self .catalog 1397fam ,model = self .s .family ,self .s .model 1398try : 1399fam ,model = cat .resolve (str (model ),None if fam is None else str (fam ))# setup's own spelling (IQ2_XS, not iq2_xs) 1400except Exception :# noqa: BLE001 1401pass 1402self .emit ("model" ,"Preparing the model files for this graphics card (once, a few minutes; nothing is downloaded except a small helper)…" ,0 ) 1403argv = [self .python ,str (cat .src / "setup.py" ),"--prepare-pack" ,str (pack ),"--gguf-dir" ,str (model_dir ), 1404"--family" ,str (fam ),"--model" ,str (model )] 1405env = self ._env () 1406env .update (STRATA_CONTROL_INSTALL = "1" ,STRATA_INSTALL_DIR = str (cat .root ),PYTHONNOUSERSITE = "1" ) 1407for k in ("PYTHONHOME" ,"PYTHONPATH" ,"VIRTUAL_ENV" ): 1408env .pop (k ,None ) 1409env ["PYTHONPATH" ]= str (cat .src ) 1410p = self ._spawn (argv ,env = env ,cwd = str (cat .src )) 1411lines :list [str ]= [] 1412for line in self ._read_lines (p ): 1413if self .cancel .is_set (): 1414self ._stop_children () 1415raise Cancelled () 1416if line is None : 1417continue 1418line = line .rstrip () 1419if line : 1420lines .append (line ) 1421lines [:]= lines [- 400 :] 1422if p .wait ()!= 0 : 1423err = next ((ln .strip ()[3 :].strip ()for ln in reversed (lines )if ln .strip ().startswith ("[X]" )),"" ) 1424raise LaunchError ("Strata could not prepare the model files for this graphics card" + (f": { err } " if err else "." ), 1425"The last lines of the preparation are in " + (self .keep_setup_output (lines )or "the launch log" ) 1426+ ". If it says the helper could not be downloaded, check the internet connection (proxy: set HTTPS_PROXY) and try again." ,5 ) 1427 1428def adopt_prepared_files (self ,setup_error :str ,chosen :bool = False )-> Path | None : 1429"""The installer cannot set this graphics card up (Intel Arc, for one): if the model's files and prepared pack are already on disk, 1430write the run config here (strata_cli/launch/adopt.py); else say what is missing.""" 1431from strata_cli .launch import adopt 1432from strata_control import engine_component 1433s ,cat = self .s ,self .catalog 1434if not chosen and not adopt .setup_cannot_handle_this_card (setup_error ): 1435return None 1436_models ,families ,_ctx ,_src = cat .tables () 1437fam = families .get (s .family or "" , {}) 1438tag = cat .tag_of (s .family ,s .model ) 1439data_dir = Path (s .data_dir )if s .data_dir else cat .data_dir () 1440model_dir = Path (s .model_path )if s .model_path else data_dir / "models" / (fam .get ("tag" ,"" )+ s .model ) 1441if model_dir .is_file (): 1442model_dir = model_dir .parent 1443try : 1444backend = engine_component .detect_backend ()[0 ] 1445except Exception :# noqa: BLE001 1446backend = None 1447pack_dir = data_dir / "packs" / tag .lower () 1448files = adopt .model_files (model_dir ,s .family or "" ,fam )if fam .get ("feed" )else adopt .find_shards (model_dir )# a feed model can be one GGUF 1449if backend == "sycl" and files and not (pack_dir / "experts.bin" ).exists ()and not ( 1450 (pack_dir / "index.txt" ).exists ()and (pack_dir / "tokenizer" / "vocab.json" ).exists ()): 1451self .prepare_pack (model_dir ,pack_dir ,files ) 1452cfg ,problems = adopt .plan (family = s .family ,model = s .model ,model_dir = model_dir ,data_dir = data_dir ,src = cat .src , 1453context = s .context or 32768 ,kv = s .kv ,model_name = f" { fam . get ( 'name' , s . family ) } - { s . model . lower () } " ,family_def = fam , 1454log = cat .root / f"strata- { tag } .log" ,backend = backend , 1455vram_gb = float (cat .computer ().main_vram_gb or 0 ),notes = self .notices ,pack_name = tag .lower ()) 1456if cfg is None : 1457if backend == "sycl" : 1458raise LaunchError ("Strata cannot start this model on the Intel Arc card yet: " + "; " .join (problems )+ "." , 1459"Give the folder that holds the model's .gguf files with --model-path (Strata prepares them itself). " 1460"Intel cards do not download models yet; see docs/INTEL_ARC.md." ,5 ) 1461raise LaunchError ("The installer cannot set up this graphics card yet, and the files Strata would need to write the settings itself are not all there: " 1462+ "; " .join (problems )+ "." , 1463"Use model files that were prepared on this computer already (folder + pack): for an Intel Arc card the steps are in docs/INTEL_ARC.md (the Terminal carries tools/iq_pack.py for the pack). Or install on a computer with an NVIDIA or AMD card." ,5 ) 1464path = cat .root / f"strata- { tag } .json" 1465adopt .write (path ,cfg ) 1466self .notices .append ("The downloader built into this Terminal sets up NVIDIA and AMD cards only (Intel Arc cards have a separate installer), so Strata wrote the " 1467f"run settings itself from the prepared model files already on this computer ( { path . name } ). No model files were downloaded." ) 1468self .emit ("model" ,f"Used your prepared model files and wrote the run settings ( { path . name } ); this card is not one the built-in downloader sets up." ,100 ,level = "warn" ) 1469return path 1470 1471def check_own_files (self )-> None : 1472"""The person's own model files, looked at once: a path that is not there or holds no model is said in plain words first, and the 1473files are matched to the catalog model (resolve_own_files). Nothing else is done with a path that was already checked.""" 1474if self .s .model_path and not self ._own_checked : 1475self .resolve_own_files () 1476self ._own_checked = True 1477 1478def resolve_own_files (self )-> None : 1479""""Use model files I already have": the fingerprint table says which catalog model the files are, and which folder holds them (the 1480person may have named the folder above it). When the person also named the model (--model), the files are never refused here: setup 1481takes the files of that model out of the folder by name, as it always did (0.1.45), and says what is wrong when it cannot.""" 1482from strata_control import models 1483s = self .s 1484problem = models .own_path_problem (s .model_path ) 1485if problem :# before the engine or setup are touched, with the path as typed 1486raise LaunchError (problem [0 ],problem [1 ],2 ) 1487from strata_control import retired 1488if retired .folder_reason (models .absolute (s .model_path )):# DeepSeek files: named, never used (strata_control/retired.py) 1489raise LaunchError (retired .own_files (models .absolute (s .model_path )),"" ,2 ) 1490given = bool (s .family and s .model ) 1491try : 1492plan = models .plan_import (models .absolute (s .model_path )) 1493except Exception as e :# noqa: BLE001 1494if given : 1495return 1496raise LaunchError (f"These model files cannot be used: { e } ." ,"Pick the folder with every shard of one model, or a .gguf file of it." ,5 )from None 1497if given : 1498sel = plan .get ("candidate_selection" )or {} 1499if sel .get ("family" )and sel .get ("model" )and (sel ["family" ],sel ["model" ])!= (s .family ,s .model ): 1500# round 8, N8: --family swift was accepted for an IQ3_XXS file. The files are not refused (setup takes the named model's files 1501# out of the folder by name), but the person is told what the file header says. 1502words = (f"These files look like { sel [ 'family' ] } { sel [ 'model' ] } (by the file headers), not { s . family } { s . model } . " 1503f"Setup will look for { s . family } { s . model } files in that folder and may stop; to use these files, leave out --family and --model." ) 1504self .identity_notes .append (words ) 1505self .notices .append (words ) 1506hold = [h for h in plan .get ("folder_holds" )or []if (h .get ("family" ),h .get ("model" ))== (s .family ,s .model )] 1507if len (hold )== 1 and hold [0 ].get ("folder" ): 1508s .model_path = hold [0 ]["folder" ] 1509elif not plan .get ("issues" ): 1510s .model_path = models .import_target (s .model_path ,plan ) 1511return 1512sel = plan .get ("candidate_selection" )or {} 1513fam ,model = sel .get ("family" ),sel .get ("model" ) 1514if not (fam and model )or plan .get ("issues" ): 1515issues = models .problem_words (plan .get ("issues" )or [],missing = plan .get ("missing_shards" ))or "they are not a model Strata knows" 1516more = " " + next ((m for m in plan .get ("messages" )or []if "holds" in m ),"" ) 1517raise LaunchError (f"These files cannot be used as they are ( { issues } ). { more . rstrip () } " , 1518"Choose the matching model in the list, or check that every shard is in the folder." ,5 ) 1519s .family ,s .model = fam ,model 1520s .model_path = models .import_target (s .model_path ,plan ) 1521self .emit ("model" ,f"These files are { fam } { model } ." ,None ) 1522 1523# ---- 3. config and profile 1524def resolved_drafting (self ,family :str | None )-> str : 1525"""modelstate.resolved_drafting for this launch: Auto where the all-cards split engine will take the start is the MTP (it runs the model's draft layer and 1526nothing else), so the plan and the fetch include the draft layer and not DFlash2's drafter. A drafter the person chose is kept.""" 1527from strata_control import drafting 1528if self .feed_without_draft_layer (family ):# the model list says this model has no draft layer: no drafter is planned or fetched for it (G14, APP-LIN 0.2.14) 1529return "off" 1530r = modelstate .resolved_drafting (self .s .drafting ,family ,** auto_signals (self .catalog ,self .s ,family )) 1531if r == "dflash2" and drafting .normalize (self .s .drafting )== "auto" and self .split_expected (): 1532return "mtp" 1533return r 1534 1535def card_probe (self ): 1536"""The cards' facts for the split engine's rule: None (the engine's own probe, which counts each card's FREE memory), or, when a server of this launch's profile or on 1537its port is running, the same probe with the free memory left out: that server is stopped before the start and gives its memory back, so it is not "busy" memory.""" 1538try : 1539mine = any (r ["profile" ]== self .profile or r ["port" ]== int (self .s .port )for r in self .serving_launches ()) 1540except Exception :# noqa: BLE001 - a question asked early is never a reason to stop a launch 1541mine = False 1542if not mine : 1543return None 1544import dataclasses 1545from strata_control import split_engine as SE 1546return lambda indexes : [dataclasses .replace (c ,free_mib = None )for c in SE .probe_cards (indexes )] 1547 1548def split_expected (self ,cfg :dict | None = None )-> bool : 1549"""Would the all-cards split engine take this launch (strata_control/split_engine.expected: the rule apply_split_engine uses, asked before anything is on disk).""" 1550cached = getattr (self ,"_split_expected" ,None ) 1551if cached is not None : 1552return cached 1553got = False 1554try : 1555from strata_control import split_engine as SE 1556s = self .s 1557if s .family in modelstate .HELPER_FAMILIES and not self .intel_chosen (): 1558base = dict (cfg or {}) 1559if s .split_engine : 1560base ["split_engine" ]= s .split_engine 1561base ["drafting" ]= s .drafting if s .drafting is not None else base .get ("drafting" ) 1562native = None 1563if s .model_path : 1564p = Path (s .model_path ) 1565shards = sorted (p .glob ("*-00001-of-*.gguf" ))or sorted (p .glob ("*.gguf" ))if p .is_dir ()else [p ] 1566native = str (shards [0 ])if shards else None 1567else : 1568native = next ((str (a2 )for a1 ,a2 in zip (base .get ("args" )or [], (base .get ("args" )or [])[1 :])if a1 == "--native" ),None ) 1569if native is None and s .family not in ("qwen" ,"unsloth" ): 1570got = False # no file to look at and no reason to assume a Flash-Next shape 1571else : 1572cards = [int (g )for g in s .gpus ]if s .gpus else None 1573got = SE .expected (base ,indexes = cards ,native = native ,context = int (s .context or SE .TESTED_CONTEXT ), 1574kv = next ((str (a2 )for a1 ,a2 in zip (base .get ("args" )or [], (base .get ("args" )or [])[1 :])if a1 == "--kv" ),None ), 1575allow_untested = os .environ .get ("STRATA_SPLIT_ALLOW_UNTESTED" )== "1" ,probe = self .card_probe ()) 1576except Exception :# noqa: BLE001 - a question asked early is never a reason to stop a launch 1577got = False 1578self ._split_expected = got 1579return got 1580 1581def drafting_inputs (self ,cfg :dict )-> dict : 1582"""What strata_control/drafting.py needs to decide for this launch: the choice, the card class, the model and the data folder.""" 1583from strata_control import drafting 1584backend ,archs = drafting .detect_hardware () 1585mode = self .s .drafting if self .s .drafting is not None else cfg .get ("drafting" ) 1586args = cfg .get ("args" )or [] 1587if cfg .get ("mtp" )is False and drafting .normalize (mode )== "auto" : 1588mode = "off" # the Draft layer switch is off and no drafter was chosen since 1589elif drafting .normalize (mode )== "auto" and self .split_expected (cfg ): 1590mode = "mtp" # the all-cards split engine runs the MTP draft layer: the plan and the fetch are for that, not for DFlash2 1591name = cfg .get ("model_name" ) 1592if not name :# not installed yet (a first launch, --plan): the name setup will write, so the plan names the drafter Auto will really fetch 1593try : 1594name = self .catalog .model_name_of (self .s .family ,self .s .model ) 1595except Exception :# noqa: BLE001 - an unreadable table is only the old, generic plan 1596name = None 1597split = bool (self .s .gpus and len (self .s .gpus )> 1 ) 1598slot_drafts = False 1599if str (backend or "" ).lower ()== "cuda" and drafting .request_count (args ,int (self .s .parallel or 0 ))in drafting .SLOT_DRAFT_REQUESTS :# (the card is only read for a start that could be in the class) 1600sig = self .drafting_signals (cfg , {"backend" :backend ,"archs" :archs }) 1601slot_drafts = drafting .slot_drafts_by_default (mode ,backend = backend ,archs = archs ,vram_mib = sig ["vram_mib" ],args = sig ["args" ],slots = int (self .s .parallel or 0 ),split = split )# the drafter is fetched before the start (ensure_drafter) 1602return {"mode" :mode ,"klass" :drafting .card_class (archs ),"model_name" :name ,"family" :self .s .family , 1603"data_dir" :drafting .data_dir_of (args )or (Path (self .s .data_dir )if self .s .data_dir else None ), 1604"backend" :backend ,"archs" :archs ,"mtp_here" :drafting .mtp_ready (args )if cfg else None , 1605"blocked" :drafting .blocked_by (args ,split = split ,slots = int (self .s .parallel or 0 ),named = drafting .normalize (mode )== "dflash2" ,backend = backend ,slot_drafts = slot_drafts ), 1606"slots_none" :drafting .slots_draft_nothing (drafting .merged_args (cfg ),int (self .s .parallel or 0 ))} 1607 1608def drafting_signals (self ,cfg :dict ,want :dict )-> dict : 1609"""The two signals drafting.tuned_applies reads besides the backend and the card: the arguments (--expert-cache and the others the confidence reads, with the person's own 1610options over them as the server merges them) and the memory of the ONE card this launch uses (None: several cards, a shared-memory chip, or not readable).""" 1611return card_signals (cfg ,self .s .gpus ,want ) 1612 1613def one_request_for_dflash2 (self ,config :Path )-> bool : 1614"""DFlash2 chosen on purpose and the person gave no number of requests: one at a time, said once (drafting.wants_one_request).""" 1615try : 1616from strata_control import drafting 1617cfg = read_config (config ) 1618want = self .drafting_inputs (cfg ) 1619sig = self .drafting_signals (cfg ,want ) 1620if not drafting .wants_one_request (** want ,** sig )or not drafting .drafter_ready (want ["data_dir" ],want ["model_name" ],want ["backend" ]): 1621return False # (no drafter file after all, e.g. no internet: the MTP runs and the slots stay) 1622except Exception :# noqa: BLE001 - a note is never a reason to stop a launch 1623return False 1624if not getattr (self ,"_one_request_said" ,False ): 1625self ._one_request_said = True 1626self .notices .append (drafting .ONE_REQUEST_NOTE ) 1627return True 1628 1629def ensure_drafter (self ,base_path :Path )-> None : 1630"""Fetch the DFlash2 drafter when this launch will use it and it is not here yet. Never stops the launch: if it cannot be had, the model 1631starts with the MTP and the person is told (recommend, never force).""" 1632from strata_control import drafting ,drafting_fetch 1633want :dict = {} 1634try : 1635cfg = read_config (base_path ) 1636want = self .drafting_inputs (cfg ) 1637sig = self .drafting_signals (cfg ,want ) 1638if want ["data_dir" ]is not None and drafting .needs_conversion (** want )and drafting .engine_has_selector_q4 (): 1639drafting_fetch .convert_selector (want ["data_dir" ])# Load, not a start: the smaller selector (174 MiB), made here from the checked pack, no network 1640if want ["data_dir" ]is None or not (drafting .needs_pack (** want ,** sig )or drafting .needs_tuned (** want ,** sig )): 1641return 1642tuned = drafting .tuned_applies (want ["backend" ],want ["model_name" ],want ["archs" ],** sig ) 1643self .emit ("model" ,f"Downloading the DFlash2 drafter ( { drafting . tuned_pack ( drafting . tuned_variant ( want [ 'backend' ], want [ 'model_name' ])). gb if tuned else drafting . DOWNLOAD_GB :g } GB, once)…" ,0 ) 1644 1645def show (step :str ,done :int ,total :int )-> None : 1646self .check_cancel () 1647self .emit ("model" ,f" { step } { done / 1e9 :.2f } of { total / 1e9 :.2f } GB" if total > 1 and done < total else step , 1648100.0 * done / total if total > 0 else None ) 1649drafting_fetch .ensure_for (want ["data_dir" ],model_name = want ["model_name" ],backend = want ["backend" ],progress = show ,cancel = self .cancel ,throttle = True , 1650archs = want ["archs" ],** sig ) 1651except Cancelled : 1652raise 1653except Exception as e :# noqa: BLE001 - the MTP still runs 1654then = "starts with the MTP instead" if want .get ("mtp_here" )is not False else "starts without a drafter" 1655text = f" { e } The model { then } ." if isinstance (e ,drafting_fetch .DraftingError )else \ 1656f"The DFlash2 drafter could not be downloaded. The model { then } ." 1657self .notices .append (text ) 1658self .emit ("model" ,text ,None ,level = "warn" ) 1659 1660def check_saved_state_readable (self )-> None : 1661"""Before anything is written: a profile or run config of THIS launch that exists but cannot be read (permissions, a damaged profile) stops the 1662launch here. Writing the run config first replaced it with a new one holding a NEW API key (the apps set up with the old key broke without a word) and 1663only then failed on the profile (`profile 'x' already exists`). Wording approved by the owner 11-04.""" 1664from strata_control import profiles 1665try : 1666profiles .load (self .profile ) 1667except profiles .ProfileError as exc : 1668path = profiles ._path (self .profile ) 1669if path .exists ()or path .is_symlink (): 1670try : 1671path .read_bytes () 1672reason = str (exc )# readable, but not a profile: the load says why 1673except OSError as os_error : 1674reason = os_error .strerror or type (os_error ).__name__ 1675raise profiles .ProfileError (f"The profile of this launch ( { path } ) cannot be read ( { reason } ). " 1676"Fix its permissions or move it away, then run the launch again." ) 1677existing = launch_dir ()/ f" { self . name } .json" 1678try : 1679existing .read_bytes () 1680except FileNotFoundError : 1681pass 1682except OSError as exc : 1683raise LaunchError (f"The saved settings of this launch ( { existing } ) cannot be read ( { exc . strerror or type ( exc ). __name__ } )." , 1684"Fix its permissions or move it away, then run the launch again: writing a new one would drop its API key and your changes." ) 1685 1686def announce_key_written (self )-> None : 1687"""The run config (with the key in it) is on disk: now, and only now, say a new key was made.""" 1688if self .key_written_notice and not self .key_written : 1689self .key_written = True 1690self .emit ("config" ,self .key_written_notice ,None ,level = "warn" ) 1691 1692def build_config (self ,base_path :Path )-> Path : 1693from strata_control import tune_knobs 1694base = read_config (base_path ) 1695try : 1696previous = read_config (launch_dir ()/ f" { self . name } .json" ) 1697except (OSError ,ValueError ):# no earlier launch of this name, or an unreadable file: nothing to keep from it 1698previous = None 1699if not isinstance (previous ,dict ): 1700previous = None 1701cfg = derive_config (base ,self .s ,bool_flags = tune_knobs .BOOL_FLAGS , 1702log = str (launch_dir ()/ f" { self . name } .engine.log" ),gpus = cards_for_launch (self .s ,self .catalog ,base = base ), 1703prev = previous ) 1704self .say_remembered_cards (base ) 1705self .apply_four_card (cfg ) 1706self .apply_split_engine (cfg ) 1707wait = self .start_wait () 1708if wait > 600 and not cfg .get ("engine_ready_s" ):# the server's own wait for the engine (900 s) must not end before the start's 1709cfg ["engine_ready_s" ]= wait + 60 1710out = launch_dir ()/ f" { self . name } .json" 1711from strata_control import arg_layers 1712arg_layers .stamp (cfg )# what this launch wrote: a later change to "args" is a hand edit (kept next time) 1713write_private (out ,cfg ) 1714self .config_path = out 1715return out 1716 1717def apply_split_engine (self ,cfg :dict )-> None : 1718"""The all-cards split engine (docs/SPLIT_ENGINE.md): by itself ("auto", the default) for a Qwen model on this PC's NVIDIA or AMD (gfx1201) cards that passes 1719strata_control/split_engine.py's rule, never when the run config says "split_engine": "off" (`--split-engine off`, STRATA_SPLIT_ENGINE=0). 1720In auto a "no" is silent and the config stays as it is; with "on" it gets one plain line. It never stops a launch.""" 1721from strata_control import split_engine as SE 1722if SE .mode (cfg )== "off" : 1723return 1724exe_for = SE .exe_finder (cfg )# strata-split-N beside the run config's engine (shared with the app's start) 1725 1726# the split runs the model's own draft layer (--mtp) and refuses to start without it; the plan for Auto downloads DFlash2's drafter, not the draft layer, so 1727# a start whose draft-layer folder is not on disk stays on the layer split (Auto: silently, with DFlash2 as the plan said; "on": one line saying how to get it) 1728mtp_dir = next ((str (cfg ["args" ][i + 1 ])for i ,a in enumerate (cfg .get ("args" )or [])if a == "--mtp" and i + 1 < len (cfg ["args" ])),None ) 1729df2_split = str (cfg .get ("drafting" )or "" ).lower ()== "dflash2" and SE .mode (cfg )== "on" # DFlash2 chosen by name and the split engine asked for: its drafter is DFlash2's pack, the layer is not loaded 1730if mtp_dir and not df2_split and not self .draft_layer_present (mtp_dir ): 1731if SE .mode (cfg )== "on" : 1732text = ("The all-cards split engine needs the model's draft layer (the MTP), which is not downloaded. Add --drafting mtp to fetch it; " 1733"using the normal layer split." ) 1734self .notices .append (text ) 1735self .emit ("config" ,text ,None ,level = "warn" ) 1736return 1737# `--parallel N` is the split's lane count (split_config reads cfg["parallel"]); a refusal puts the run config back as it was 1738lanes_added = bool (self .s .parallel )and not cfg .get ("parallel" ) 1739if lanes_added : 1740cfg ["parallel" ]= int (self .s .parallel ) 1741try : 1742decision = SE .apply_to_config (cfg ,exe_for_cards = exe_for ,allow_untested = os .environ .get ("STRATA_SPLIT_ALLOW_UNTESTED" )== "1" ,probe = self .card_probe ()) 1743except Exception as e :# noqa: BLE001 - never stop a launch over an option 1744if lanes_added : 1745cfg .pop ("parallel" ,None ) 1746if SE .mode (cfg )== "on" : 1747text = f"The all-cards split engine was left out ( { type ( e ). __name__ } ). Using the normal layer split." 1748self .notices .append (text ) 1749self .emit ("config" ,text ,None ,level = "warn" ) 1750return 1751if lanes_added and not decision .use_split : 1752cfg .pop ("parallel" ,None ) 1753if decision .quiet : 1754return 1755line = decision .line + (" Turn it off with: strata launch --split-engine off." if decision .use_split else "" ) 1756self .notices .append (line ) 1757self .emit ("config" ,line ,None ) 1758 1759def say_remembered_cards (self ,base :dict )-> None : 1760"""A launch that names no cards keeps the cards the person chose earlier (`--gpu 0` is remembered by the model's settings). On a PC with more 1761cards than that, one line says so and how to use them all, so a one-card start is never a surprise (AMD says the same when the card is named).""" 1762s = self .s 1763if s .gpus or s .gpu_roles : 1764return 1765try : 1766usable = [int (g .get ("index" ,0 ))for g in self .catalog .computer ().usable_gpus ] 1767kept = installed_cards (base ,self .catalog .computer ().usable_gpus ) 1768except Exception :# noqa: BLE001 - a note only: never stop a launch over it 1769return 1770if not kept or len (usable )<= len (set (kept )& set (usable )): 1771return 1772where = f"card { kept [ 0 ] } " if len (kept )== 1 else "cards " + ", " .join (str (k )for k in kept ) 1773text = (f"This model stays on { where } , the { 'card' if len ( kept ) == 1 else 'cards' } you chose earlier; this PC has { len ( usable ) } usable cards. " 1774f"To use them all: strata launch --gpu { ',' . join ( str ( u ) for u in sorted ( usable )) } (it is remembered from then on)." ) 1775self .notices .append (text ) 1776self .emit ("config" ,text ,None ) 1777 1778def apply_four_card (self ,cfg :dict )-> None : 1779"""Four Radeon AI PRO R9700 cards and Qwen3.8-Flash-Next IQ3_S: the measured serving profile (strata_control/amd_four_card.py), filled 1780in where the person chose nothing. Never stops a launch.""" 1781self .four_card_parallel = None 1782try : 1783from strata_control import amd_four_card 1784picked = cfg .get ("gpu" ) 1785if not (isinstance (picked ,list )and len (picked )== amd_four_card .CARDS ): 1786return 1787want = {int (i )for i in picked } 1788cards = [c for c in self .catalog .computer ().usable_gpus if int (c .get ("index" ,- 1 ))in want ] 1789before = cfg .get ("parallel" ) 1790notes = amd_four_card .apply (cards ,cfg ,parallel_given = bool (self .s .parallel )) 1791if notes : 1792self .four_card_parallel = cfg .get ("parallel" )if before is None and cfg .get ("parallel" )else None # (only a number the profile set) 1793self .emit ("model" ,"Four " + str (cards [0 ].get ("name" ,"AMD" )).replace ("AMD Radeon " ,"" )+ " cards: " + "; " .join (notes )+ "." ,None ) 1794except Exception :# noqa: BLE001 - a profile is never a reason to stop a launch 1795self .four_card_parallel = None 1796 1797def ensure_profile (self ,config :Path )-> None : 1798from strata_control import profiles 1799name = self .profile 1800parallel = self .s .parallel if self .s .parallel else (getattr (self ,"four_card_parallel" ,None )or self .catalog_parallel ()) 1801if parallel and not self .s .parallel and self .one_request_for_dflash2 (config ): 1802parallel = None # the slots Strata fills in by itself would keep the MTP: DFlash2 answers one request at a time 1803if parallel and self .run_config_owns_slots (config ): 1804parallel = None # the all-cards split engine's run config carries its lanes (--batch N, from --parallel N or its default): a profile override would only collide with them 1805sets = [f"host= { acc . host_for ( self . s . access ) } " ,f"port= { int ( self . s . port ) } " ]+ ([f"parallel= { parallel } " ]if parallel else []) 1806try : 1807current ,_rev = profiles .load (name ) 1808except profiles .ProfileError : 1809profiles .create (name ,str (config )) 1810else : 1811if current .get ("source_config" )!= str (config .resolve ()): 1812proposed ,rev = profiles .propose_source (name ,str (config )) 1813profiles .save (name ,proposed ,expected_revision = rev ) 1814# the overrides are replaced as a set: a launch's host/port/parallel are exactly these 1815cur ,rev = profiles .load (name ) 1816want = {k :v for k ,v in (profiles .parse_assignment (x )for x in sets )} 1817if cur .get ("overrides" )!= want : 1818profiles .save (name , {** cur ,"overrides" :want },expected_revision = rev ) 1819 1820@staticmethod 1821def draft_layer_present (folder :str )-> bool : 1822"""The draft layer's folder (mtp/rt) exists and holds files.""" 1823try : 1824return Path (folder ).is_dir ()and any (Path (folder ).iterdir ()) 1825except OSError : 1826return False 1827 1828@staticmethod 1829def run_config_owns_slots (config :Path )-> bool : 1830"""The run config already names its batch slots (--batch / --slots in its args): the all-cards split engine's does, always.""" 1831try : 1832args = [str (a )for a in read_config (config ).get ("args" )or []] 1833except Exception :# noqa: BLE001 - a config that cannot be read is not a reason to stop a launch 1834return False 1835return "--batch" in args or "--slots" in args 1836 1837def catalog_parallel (self )-> int | None : 1838try : 1839comp = self .catalog .computer () 1840return S .fit_parallel (comp .main_vram_gb )if comp .usable_gpus else None 1841except Exception :# noqa: BLE001 1842return None 1843 1844# ---- 4. tuning 1845def tune (self )-> None : 1846s = self .s 1847if s .tune == "skip" : 1848return 1849from strata_control import presets 1850if not self .retune : 1851if s .tuned_preset : 1852try : 1853presets .find (s .tuned_preset ) 1854self .emit ("tune" ,"This preset is already tuned for this computer. Add --retune to measure again." ,100 ) 1855return 1856except presets .PresetError : 1857pass 1858elif s .tuned_at :# measured before: the standard settings were already the fastest, nothing was saved 1859self .emit ("tune" ,f"Already tuned on { s . tuned_at } : this computer runs best with the standard settings. Nothing to do; add --retune to measure again." ,100 ) 1860return 1861stored = self .stored_tuning () 1862if stored :# the same model and choices were tuned on this computer before (a run by flags, no preset) 1863s .tuned_preset ,s .tuned_at = stored ["id" ],stored ["date" ] 1864self .emit ("tune" ,f"This model was already tuned for this computer on { stored [ 'date' ] } (' { stored [ 'name' ] } '), so that result is used " 1865"and nothing is measured again. Add --retune to measure again." ,100 ) 1866return 1867mode = "thorough" if s .tune == "thorough" else "quick" 1868status_file = launch_dir ()/ f" { self . name } .tune.json" 1869try : 1870status_file .unlink () 1871except OSError : 1872pass 1873argv = self ._cli ("tune" ,"auto" ,self .profile ,"--mode" ,mode ,"--output" ,"json" ,"--status-file" ,str (status_file ), 1874"--name" , (s .name or self .name )) 1875if s .tune_allow_small : 1876argv .append ("--allow-small-differences" ) 1877self .stop_own_server_for_tuning () 1878self .emit ("tune" ,"Tuning for the best speed. Close other heavy programs while it measures." ,0 ) 1879p = self ._spawn (argv ) 1880out_lines :list [str ]= [] 1881reader = threading .Thread (target = lambda :out_lines .extend (p .stdout .readlines ()),daemon = True )# type: ignore[union-attr] 1882reader .start () 1883while p .poll ()is None : 1884if self .cancel .is_set (): 1885self ._stop_children () 1886raise Cancelled () 1887st = _read_json (status_file ) 1888if st : 1889done ,planned = st .get ("runs_done" )or 0 ,st .get ("runs_planned" )or 0 1890pct = (100.0 * done / planned )if planned else None 1891left = st .get ("minutes_left" ) 1892self .emit ("tune" ,st .get ("message" )or "Measuring…" ,pct ,speeds = st .get ("speeds" )or [], 1893round = (done ,planned ),minutes_left = left ) 1894time .sleep (1.0 ) 1895reader .join (timeout = 3 ) 1896result = None 1897for line in reversed (out_lines ): 1898try : 1899result = json .loads (line ).get ("result" ) 1900break 1901except (ValueError ,AttributeError ): 1902continue 1903self .tune_result = result 1904word ,sentence = tune_words (result ,p .returncode ) 1905self .tune_word = word 1906preset = (result or {}).get ("preset" )or {} 1907if preset .get ("id" ): 1908s .tuned_preset ,s .tuned_at = preset ["id" ],time .strftime ("%Y-%m-%d" ) 1909elif result and result .get ("outcome" )== "default_confirmed" : 1910s .tuned_at = time .strftime ("%Y-%m-%d" ) 1911self .emit ("tune" ,f"Tuning result: { word } . { sentence } " ,100 ,level = "info" if word in ("faster" ,"already fastest" )else "warn" ,word = word ) 1912 1913restart_after = True # run(start=False) measures only: nothing starts the model again 1914 1915def stop_own_server_for_tuning (self )-> None : 1916"""The measuring engine needs the card, so this launch's own server (the same profile) is stopped first and `start()` brings it back with 1917the result (E07). Other engines are never touched here; the tuner says plainly when another program holds the card.""" 1918from strata_control import runtime 1919from strata_control .profiles import ProfileError 1920self .stop_others () 1921try : 1922state = runtime .status (self .profile ).get ("state" ) 1923except Exception :# noqa: BLE001 - no state to read: nothing of ours is running 1924return 1925if state not in LEFTOVER_STATES : 1926return 1927if state in ("ready" ,"starting" ): 1928self .emit ("tune" ,"Stopping the model to measure; it starts again afterwards." if self .restart_after 1929else "Stopping the model to measure." ,0 ) 1930else : 1931# a server that already stopped but whose manager is still open (#4824): it would refuse the start that comes after the measuring 1932self .emit ("tune" ,"Clearing a stopped server of this preset before measuring." ,0 ) 1933try : 1934runtime .stop (self .profile ,timeout = 120 ) 1935except ProfileError as e : 1936raise LaunchError (f"The running model could not be stopped to measure: { e } ." ,"Run `strata launch --stop` first, then measure again." ,6 )from None 1937 1938def stored_tuning (self )-> dict | None : 1939"""The tuning result stored for this launch's model, choices and computer (the active preset of its slot in the shared presets store, 1940which the start applies), or None. A result whose computer changed in a way that matters (a different card, processor or memory, 1941another model file) is not reused: it is measured again.""" 1942if self .config_path is None : 1943return None 1944from strata_control import presets 1945try : 1946_cfg ,info = presets .overlay (read_config (self .config_path )) 1947if not info .get ("applied" )or not info .get ("preset" ): 1948return None 1949made = str (presets .load (info ["preset" ]["id" ]).get ("created" )or "" )[:10 ] 1950return {"id" :info ["preset" ]["id" ],"name" :info ["preset" ]["name" ],"date" :made or time .strftime ("%Y-%m-%d" )} 1951except Exception :# noqa: BLE001 - an unreadable store means: measure 1952return None 1953 1954tune_word :str | None = None 1955 1956# ---- 0. a server is already running 1957CHOICE_SKIP = ("schema" ,"name" ,"tuned_preset" ,"tuned_at" ,"last_used" ,"created" ,"api_key" ) 1958 1959def choices (self )-> dict : 1960"""The choices that make one server different from another (not the bookkeeping, and the key only as a fingerprint).""" 1961import hashlib 1962d = {k :v for k ,v in self .s .to_dict (with_key = False ).items ()if k not in self .CHOICE_SKIP } 1963d ["key" ]= hashlib .sha256 (("none" if self .s .no_key and not self .s .api_key else self .s .api_key or "" ).encode ("utf-8" )).hexdigest ()[:16 ] 1964return json .loads (json .dumps (d ,sort_keys = True )) 1965 1966def _choices_file (self ,profile :str | None = None )-> Path : 1967return launch_dir ()/ f" { ( profile or self . profile )[ 7 :] } .choices.json" 1968 1969def save_choices (self )-> None : 1970try : 1971write_private (self ._choices_file (),self .choices ()) 1972except OSError : 1973pass 1974 1975def _saved_choices (self ,profile :str )-> dict | None : 1976try : 1977return json .loads (self ._choices_file (profile ).read_text (encoding = "utf-8" )) 1978except (OSError ,ValueError ): 1979return None 1980 1981def serving_launches (self )-> list [dict ]: 1982"""Launch servers that are up now (this one included): [{profile, name, port, choices}].""" 1983from strata_control import profiles ,runtime 1984out = [] 1985try : 1986listing = profiles .list_profiles () 1987except Exception :# noqa: BLE001 1988return out 1989for row in listing : 1990pid = row ["id" ] 1991if not pid .startswith ("launch-" ): 1992continue 1993try : 1994if runtime .status (pid ).get ("state" )not in ("ready" ,"starting" ): 1995continue 1996prof ,_rev = profiles .load (pid ) 1997except Exception :# noqa: BLE001 1998continue 1999port = int ((prof .get ("overrides" )or {}).get ("port" ,S .DEFAULT_PORT )) 2000out .append ({"profile" :pid ,"name" :pid [7 :],"port" :port ,"choices" :self ._saved_choices (pid )}) 2001return out 2002 2003def running_phrase (self ,row :dict )-> str : 2004"""`Gyro-S is running on port 8080 with 32K` for the restart question.""" 2005c = row .get ("choices" )or {} 2006title = None 2007try : 2008title = next ((r .title for r in self .catalog .rows ()if r .family == c .get ("family" )and r .model == c .get ("model" )),None ) 2009except Exception :# noqa: BLE001 2010title = None 2011title = title or ("Your model files" if c .get ("model_path" )else row ["name" ]) 2012return f" { title } is running on port { row [ 'port' ] } " + (f" with { S . context_label ( c [ 'context' ]) } " if c .get ("context" )else "" ) 2013 2014@staticmethod 2015def describe_running (row :dict )-> str : 2016c = row .get ("choices" )or {} 2017bits = [] 2018if c .get ("context" ): 2019bits .append (f"context { S . context_label ( c [ 'context' ]) } " ) 2020if c .get ("vision" ): 2021bits .append (f"pictures { c [ 'vision' ] } " ) 2022if c .get ("access" ): 2023bits .append (f"access { S . ACCESS_WORDS . get ( c [ 'access' ], c [ 'access' ]) } " ) 2024return f" { row [ 'name' ] } is serving on port { row [ 'port' ] } " + (f" ( { ', ' . join ( bits ) } )" if bits else "" ) 2025 2026def check_serving (self )-> "Result | None" : 2027"""G04/E01. The same choices already serving: return that server (nothing stops or starts). Other choices on this profile, or another 2028launch on this port: ask once on the screens, go on with --restart, else refuse in one line and change nothing. A launch on another port 2029runs beside the others (the person asked for two), with a warning about graphics memory.""" 2030running = self .serving_launches () 2031if not running : 2032self .checked () 2033return None 2034own = next ((r for r in running if r ["profile" ]== self .profile ),None ) 2035same_port = [r for r in running if r ["profile" ]!= self .profile and r ["port" ]== int (self .s .port )] 2036beside = [r for r in running if r ["profile" ]!= self .profile and r ["port" ]!= int (self .s .port )] 2037if own and not self .retune and not same_port and own ["choices" ]== self .choices ()and own ["port" ]== int (self .s .port ): 2038self .checked () 2039self .config_path = launch_dir ()/ f" { self . name } .json" 2040urls = acc .urls_for (self .s ,tunnel_url = (acc .tunnel_info (self .profile )or {}).get ("url" )) 2041self .emit ("done" ,"Already serving these choices; nothing was restarted." ,100 ,urls = urls ) 2042return Result (self .profile ,urls ,self .s .api_key ,None ,self .notices ,str (self .config_path ),reused = True ) 2043for r in beside : 2044self .notices .append (f" { r [ 'name' ] } is already loaded on port { r [ 'port' ] } . Two models at once may not fit in the graphics memory; " 2045"the new one can fail to start. Stop the first with `strata launch --stop` if it does." ) 2046blocking = ([own ]if own and not self .retune else [])+ same_port 2047if not blocking : 2048self .checked () 2049return None 2050what = "; " .join (self .describe_running (r )for r in blocking ) 2051if not self .restart : 2052if self .confirm_restart is not None : 2053if not self .confirm_restart (f" { self . running_phrase ( blocking [ 0 ]) } . Restart it with these settings?" ,"Answers in progress stop." ): 2054raise LaunchError ("Left as it is: the running model keeps serving." ,"" ,130 ) 2055else : 2056raise LaunchError (f"A model is already running: { what } . These choices are different." , 2057"Add --restart to stop it and start these, or run `strata launch --stop` first." ,6 ) 2058self ._stop_first = [r ["profile" ]for r in same_port ] 2059self .checked () 2060return None 2061 2062def checked (self )-> None : 2063cb ,self .after_check = self .after_check ,None 2064if cb is not None : 2065cb () 2066 2067def stop_others (self )-> None : 2068"""Stop the other launch servers that hold this port, so the new one gets it (no "port already in use").""" 2069from strata_control import runtime 2070from strata_control .profiles import ProfileError 2071for pid in self ._stop_first : 2072self .emit ("start" ,f"Stopping { pid [ 7 :] } so the new choices can use port { int ( self . s . port ) } …" ,None ) 2073try : 2074runtime .stop (pid ,timeout = 120 ) 2075acc .stop_tunnel (pid ) 2076except ProfileError as e : 2077raise LaunchError (f"The running server { pid [ 7 :] } could not be stopped: { e } ." ,"Run `strata launch --stop` first." ,6 )from None 2078self ._stop_first = [] 2079 2080# ---- 5. start 2081def start (self )-> None : 2082from strata_control import runtime 2083from strata_control .profiles import ProfileError 2084name = self .profile 2085self .stop_others () 2086st = runtime .status (name ) 2087if st .get ("state" )in LEFTOVER_STATES : 2088if st .get ("state" )in ("ready" ,"starting" ): 2089self .emit ("start" ,"A server for this preset is already running; restarting it with these choices…" ) 2090else : 2091self .emit ("start" ,"A server of this preset stopped earlier and was never cleared; clearing it before the start…" ) 2092try : 2093runtime .stop (name ,timeout = 120 ) 2094except ProfileError as e : 2095raise LaunchError (f"The running server could not be stopped: { e } ." ,"Run `strata launch --stop` first." ,6 )from None 2096self .check_port_free () 2097self ._marks = self .log_marks ()# what the logs already held: only this attempt's lines are ever quoted 2098self .emit ("start" ,"Starting the engine and loading the model. The first start can take a few minutes." ,None ) 2099done = threading .Event () 2100box :dict [str ,Any ]= {} 2101 2102def go ()-> None : 2103try : 2104box ["r" ]= runtime .start (name ,wait = self .start_wait ()) 2105except Exception as e :# noqa: BLE001 2106box ["e" ]= e 2107finally : 2108done .set () 2109 2110threading .Thread (target = go ,daemon = True ).start () 2111t0 = time .monotonic () 2112while not done .wait (1.0 ): 2113if self .cancel .is_set (): 2114try : 2115runtime .stop (name ,timeout = 60 ) 2116except Exception :# noqa: BLE001 2117pass 2118raise Cancelled () 2119self .emit ("start" ,f"Loading the model… { int ( time . monotonic () - t0 ) } s" ,None ) 2120if "e" in box : 2121self .end_failed_start () 2122raise LaunchError (f"The server could not start: { box [ 'e' ] } " ,_log_hint (self .config_path ,box ["e" ]),6 ) 2123r = box ["r" ] 2124if not r .get ("ok" ): 2125text ,nxt = explain_engine_exit (r ,self .config_path ,marks = self ._marks ,server_log = self .server_log_path (), 2126shared_memory = self .shares_memory ()) 2127self .end_failed_start () 2128raise LaunchError (text ,nxt ,6 ) 2129self .emit ("start" ,"The model is loaded and answering." ,100 ) 2130self .report_drafting () 2131 2132_marks :dict | None = None 2133 2134def shares_memory (self )-> bool : 2135"""Does this launch run on a graphics chip that shares the RAM (Strix Halo)? Only used to explain a stop.""" 2136try : 2137return uses_integrated_gpu (self .catalog .computer (),self .s ) 2138except Exception :# noqa: BLE001 - an explanation only 2139return False 2140 2141def server_log_path (self )-> Path | None : 2142try : 2143from strata_control import runtime 2144return runtime .runtime_dir ()/ f" { self . profile } .server.log" 2145except Exception :# noqa: BLE001 2146return None 2147 2148def log_marks (self )-> dict : 2149"""{log path: size now} for the engine log and the runtime's server log, so a failed start quotes only what this attempt wrote.""" 2150marks = {} 2151paths = [self .server_log_path ()] 2152try : 2153paths .append (Path (read_config (self .config_path ).get ("log" )))if self .config_path else None 2154except (OSError ,ValueError ,TypeError ): 2155pass 2156for path in paths : 2157try : 2158marks [str (path )]= Path (path ).stat ().st_size if path else 0 2159except OSError : 2160if path : 2161marks [str (path )]= 0 2162return marks 2163 2164def check_port_free (self )-> None : 2165"""Before the host starts: a port another program holds is said at once, in words (X01), and nothing is left running.""" 2166import socket 2167port = int (self .s .port ) 2168busy = False 2169for host in ("127.0.0.1" ,): 2170try : 2171with socket .create_connection ((host ,port ),timeout = 1.0 ): 2172busy = True 2173except OSError : 2174pass 2175if not busy : 2176return 2177raise LaunchError (f"Port { port } is already in use by another program." , 2178f"Close it, or start with a different port (for example --port { port + 1 } )." ,6 ) 2179 2180def end_failed_start (self )-> None : 2181"""A start that failed leaves nothing alive: the runtime host of this attempt is stopped, or ended by its recorded identity.""" 2182from strata_control import runtime 2183try : 2184runtime .stop (self .profile ,timeout = 30 ) 2185except Exception :# noqa: BLE001 2186pass 2187try : 2188runtime .cleanup (self .profile ) 2189except Exception :# noqa: BLE001 2190pass 2191 2192def report_drafting (self )-> None : 2193"""Say which drafter runs when the engine fell back from the one that was asked for ("Drafting: MTP (DFlash2 didn't fit)"). Best effort.""" 2194try : 2195import urllib .request 2196headers = {"Authorization" :f"Bearer { self . s . api_key } " }if self .s .api_key else {} 2197with urllib .request .urlopen (urllib .request .Request (f"http://127.0.0.1: { int ( self . s . port ) } /metrics" ,headers = headers ),timeout = 4 )as resp : 2198info = (json .loads (resp .read ().decode ("utf-8" ,"replace" )).get ("engine" )or {}) 2199except Exception :# noqa: BLE001 - the line is a convenience 2200return 2201self .report_split_fallback (info ) 2202self .report_vision (info ) 2203note = str (info .get ("drafting_note" )or "" ) 2204if note : 2205self .notices .append (note ) 2206self .emit ("start" ,note ,None ) 2207 2208def report_vision (self ,info :dict )-> None : 2209"""The server read pictures on the processor because the card had no room for the picture reader: its /metrics carries the sentence (vision_note; 2210strata_control/reader_room.py), and the summary shows it.""" 2211note = str (info .get ("vision_note" )or "" ) 2212if note and note not in self .notices : 2213self .notices .append (note ) 2214self .emit ("start" ,note ,None ,level = "warn" ) 2215 2216def report_split_fallback (self ,info :dict )-> None : 2217"""The server started the normal layer split because the all-cards split engine would not come up (its metrics say split_fallback; serve/server.py 2218start_engine_or_fallback): the summary then says what runs, not the line written before the start ("Using the all-cards split engine on N cards").""" 2219if not info .get ("split_fallback" ): 2220return 2221why = "" 2222try : 2223log = read_config (self .config_path ).get ("log" )if self .config_path else None 2224lines = Path (str (log )+ ".split-engine" ).read_text (encoding = "utf-8" ,errors = "replace" ).splitlines ()if log else [] 2225why = next ((ln .strip ()for ln in reversed (lines )if ln .lstrip ().startswith ("sfnx:" )),"" ) 2226except Exception :# noqa: BLE001 - the reason is a convenience 2227why = "" 2228text = "The all-cards split engine could not start" + (f" ( { why } )" if why else "" )+ "; running the normal layer split." 2229self .notices [:]= [n for n in self .notices if not n .startswith ("Using the all-cards split engine" )] 2230self .notices .append (text ) 2231self .emit ("start" ,text ,None ,level = "warn" ) 2232 2233# ---- 6. access 2234def open_access (self )-> str | None : 2235s = self .s 2236missing = acc .missing_helper (s .access ) 2237tunnel = None 2238if s .access == "cloudflare" : 2239if missing : 2240self .notices .append (missing + " The server is running on this computer meanwhile." ) 2241self .emit ("access" ,missing ,level = "warn" ) 2242else : 2243self .emit ("access" ,"Opening a Cloudflare quick tunnel…" ) 2244tunnel ,msg = acc .start_tunnel (self .profile ,int (s .port )) 2245if tunnel is None : 2246self .notices .append (msg ) 2247self .emit ("access" ,msg ,level = "info" if tunnel else "warn" ,url = tunnel ) 2248elif missing : 2249self .notices .append (missing ) 2250self .emit ("access" ,missing ,level = "warn" ) 2251else : 2252self .emit ("access" ,"Ready: " + ", " .join (acc .urls_for (s )),100 ) 2253return tunnel 2254 2255# ---- all of it 2256def row (self ): 2257"""The catalog row of the chosen model (None for a model the list does not carry).""" 2258s = self .s 2259return next ((r for r in self .catalog .rows ()if (r .family ,r .model )== (s .family ,s .model )),None ) 2260 2261def download_plan (self )-> dict : 2262"""What this launch would download, in numbers and words (nothing is changed): the model's missing files, and for a model that is 2263not on this computer yet also the draft layer and the picture reader that setup fetches after it. 0 when everything is here.""" 2264from strata_control import engine_component 2265from strata_control import discovery 2266from strata_control .discovery import MMPROJ_GB ,MTP_FETCH_GB 2267s = self .s 2268st = self .model_state () 2269parts = [{"kind" :p .kind ,"label" :p .label ,"gb" :round (p .gb ,1 )}for p in st .parts if p .gb >= 0.05 ]# a part already on disk is not a download 2270row = self .row () 2271helpers = s .family in modelstate .HELPER_FAMILIES 2272wants_pictures = s .vision not in (None ,"off" )and row is not None and bool (row .images ) 2273if helpers and (st .own_files or not st .installed ): 2274# a model that is not set up yet (or the person's own files) comes without the draft layer and the picture reader: setup fetches them 2275# next to the prepared data, unless they are there already 2276have = {p ["kind" ]for p in parts } 2277try : 2278data = Path (st .folder )if st .folder else (Path (s .data_dir )if s .data_dir else (self .existing_data_dir ()or self .catalog .data_dir ())) 2279# the data folder the model sits in, then --data-dir and the remembered folder: setup writes the draft layer to <data-dir>/mtp/rt even when the model folder is elsewhere 2280homes = [data ,* [d for d in modelstate .data_places (self .catalog ,Path (s .data_dir )if s .data_dir else None )if d != data ]] 2281if modelstate .mtp_choice (s .mtp ,self .resolved_drafting (s .family ))!= "off" and "mtp" not in have and discovery .mtp_layer_in (* homes )is None : 2282parts .append ({"kind" :"mtp" ,"label" :"the draft layer" ,"gb" :MTP_FETCH_GB }) 2283own = None 2284if s .model_path :# setup uses a reader that sits with the person's own files (setup.py --gguf-dir) 2285own = Path (s .model_path ) 2286own = own if own .is_dir ()else own .parent 2287# setup's rule, not any mmproj*.gguf: the pinned name (lane NET 4b; which file setup accepts is unchanged) 2288has_reader = modelstate .reader_present (self .catalog ,s .family ,homes ,own = own ) 2289if wants_pictures and "mmproj" not in have and not has_reader : 2290parts .append ({"kind" :"mmproj" ,"label" :"the picture reader" ,"gb" :MMPROJ_GB }) 2291except OSError : 2292pass 2293try : 2294from strata_control import drafting 2295_b ,_cfg = self .installed_state () 2296if _b is not None and self .other_copy ()is not None : 2297_cfg = None # another data folder's copy: its drafter is not the one this launch uses 2298want = self .drafting_inputs (_cfg or {}) 2299want ["data_dir" ]= want ["data_dir" ]or self .existing_data_dir ()or self .catalog .data_dir () 2300sig = self .drafting_signals (_cfg or {},want ) 2301if drafting .needs_pack (** want ,** sig )or drafting .needs_tuned (** want ,** sig ):# chosen DFlash2 (or Auto picking it) and the drafter (the tuned one, where the set has it) is not here: it is part of the download 2302parts .append ({"kind" :"dflash2" ,"label" :"the DFlash2 drafter" , 2303"gb" :drafting .tuned_pack (drafting .tuned_variant (want ["backend" ],want ["model_name" ])).gb if drafting .tuned_applies (want ["backend" ],want ["model_name" ],want ["archs" ],** sig )else drafting .DOWNLOAD_GB }) 2304except Exception :# noqa: BLE001 - the plan still shows the rest 2305pass 2306gap = self .ready_pack_gap ()if st .own_files else None 2307if gap : 2308# a ready-made pack (NVFP4) is taken from setup's own models folder, not from where the person's files are (round 8, N2: the plan 2309# said "nothing to download" and setup then asked for 129 GB): count what setup will fetch 2310parts = [p for p in parts if p ["kind" ]!= "weights" ]+ [{"kind" :"weights" ,"label" :"the ready-made pack" ,"gb" :gap ["gb" ]}] 2311intel = self .intel_chosen () 2312if intel :# the Intel route builds the pack from the files and fetches no draft layer, picture reader or drafter 2313parts = [p for p in parts if p ["kind" ]not in ("mtp" ,"mmproj" ,"dflash2" )] 2314gb = round (sum (p ["gb" ]for p in parts ),1 ) 2315engine ,here = True , [] 2316try : 2317report = engine_component .status (Path (self .components_dir )if self .components_dir else None ) 2318engine = bool (report .get ("usable" )) 2319here = [str (i .get ("version" ))for i in report .get ("installed" )or []if i .get ("version" )] 2320except Exception :# noqa: BLE001 - the plan must not fail on this 2321pass 2322if gb < 0.05 : 2323text = ("Nothing to download: your model files are used where they are." if st .own_files 2324else "Nothing to download: the model is already on this computer." ) 2325else : 2326names = [f" { p [ 'label' ] } ( { p [ 'gb' ]:.2f } GB)" if p ["kind" ]== "dflash2" and p ["gb" ]< 1 else f" { p [ 'label' ] } ( { p [ 'gb' ]:.1f } GB)" for p in parts ]# (the tuned drafter is 0.34 / 0.52 GB: one decimal said 0.3 / 0.5) 2327what = names [0 ]if len (names )== 1 else ", " .join (names [:- 1 ])+ " and " + names [- 1 ] 2328other = self .other_copy () 2329text = (f"About { gb :.1f } GB to download into { Path ( s . data_dir ). expanduser () } : { what } ." if other is not None else 2330f"About { gb :.1f } GB to download: { what } ." ) 2331if other is not None :# lane NET 4a: the start uses --data-dir, not the copy installed elsewhere 2332text += f" The copy in { other } is not used with this --data-dir." 2333if st .on_disk_gb >= 1 : 2334text += f" { st . on_disk_gb :.0f } GB of the model is already in its folder." 2335if st .own_files : 2336text += " Your model files are used where they are." 2337if gap : 2338text += (f" This is a ready-made pack, and setup takes it from its own folder ( { gap [ 'folder' ] } ), not from where your files are. " 2339"Copy or link your pack there to use it as it is" + 2340 (f"; only { gap [ 'free_gb' ]:.0f } GB are free on that drive, so choose a bigger drive with --data-dir" if gap .get ("free_gb" )is not None and gap ["free_gb" ]< gap ["gb" ]else "" )+ "." ) 2341if any (p ["kind" ]== "mmproj" for p in parts ): 2342text += " To skip the picture reader (the model then answers text only), add --vision off; or put its mmproj file next to your model files." 2343if any (p ["kind" ]== "mtp" for p in parts ): 2344text += " To skip the draft layer (a little slower, less memory), add --mtp off." 2345if any (p ["kind" ]== "dflash2" for p in parts ): 2346text += " To skip the DFlash2 drafter, add --drafting mtp." 2347if not engine and here : 2348# B03: an engine IS installed, but this plan cannot use it (its signature cannot be checked here, or it is for another card): not "missing" 2349text += (f" An engine ( { ', ' . join ( here [: 3 ]) } ) is installed, but it did not pass Strata's check on this computer, so Strata looks for a working one " 2350"first. `strata components engine` says why." ) 2351elif not engine : 2352text += " The engine for your graphics card is downloaded first (from the update source; its size is shown when it starts)." 2353if intel : 2354text += (" For the Intel card Strata builds the model's pack from your files itself (once, a few minutes); the first time it fetches " 2355"a small helper (llama.cpp's gguf-py) from GitHub. No draft layer or picture reader is used on Intel cards yet." ) 2356return {"gb" :gb ,"parts" :parts ,"engine_missing" :not engine and not here ,"engine_usable" :engine ,"own_files" :st .own_files ,"text" :text } 2357 2358def ready_pack_gap (self )-> dict | None : 2359"""For a ready-made pack family (NVFP4): what setup would still fetch into its models folder for these choices, {gb, folder, free_gb}, or None.""" 2360s = self .s 2361try : 2362mod = self .catalog .strata .setup_module () 2363_m ,families ,_c ,_src = self .catalog .tables () 2364if mod is None or not (families .get (s .family or "" )or {}).get ("ready" )or not hasattr (mod ,"ready_needed" ): 2365return None 2366data = Path (s .data_dir )if s .data_dir else (self .existing_data_dir ()or self .catalog .data_dir ()) 2367models_dir = data / "models" 2368need = 0 2369for f in mod .ready_needed (s .model ,models_dir ): 2370if not mod .ready_verified (mod .ready_where (models_dir ,f ),f [5 ]): 2371need += int (f [4 ]) 2372if need <= 0 : 2373return None 2374probe = next ((q for q in (models_dir ,* models_dir .parents )if q .exists ()),None ) 2375free = self .catalog .disk_free (probe )if probe is not None else None 2376return {"gb" :round (need / 1e9 ,1 ),"folder" :str (models_dir ),"free_gb" :free } 2377except Exception :# noqa: BLE001 - a plan that cannot work this out still shows the rest 2378return None 2379 2380def preflight_words (self )-> list [str ]: 2381"""Plain warnings for `--plan` that the run itself would meet: an engine older than the model needs, an earlier install taking the 2382place of a clean one, files that are not the model that was named. Nothing is changed.""" 2383out :list [str ]= list (self .identity_notes ) 2384try : 2385from strata_control import engine_component as ec 2386report = ec .status (Path (self .components_dir )if self .components_dir else None ) 2387if report .get ("usable" ): 2388stale = self .stale_engine (report ["engine" ].get ("version" )) 2389if stale : 2390out .append (stale + " Strata will ask before updating it (`strata update` does it now)." ) 2391except Exception :# noqa: BLE001 2392pass 2393try : 2394out += install_isolation_words (self .catalog ,self .s .data_dir ) 2395except Exception :# noqa: BLE001 2396pass 2397return out 2398 2399def plan (self )-> dict : 2400s = self .s 2401self .keep_saved_off ()# the plan names the drafter the start will run 2402self .keep_saved_word () 2403self .check_own_files () 2404warns = [n .line ()for n in (* S .check_access (s ),)] 2405warns += self .preflight_words () 2406row = self .row () 2407try : 2408self .resolved_vision () 2409except Exception :# noqa: BLE001 2410pass 2411try : 2412download = self .download_plan () 2413except Exception :# noqa: BLE001 - a plan that cannot count the download still shows the rest 2414download = {"gb" :None ,"parts" : [],"engine_missing" :None ,"own_files" :bool (s .model_path ), 2415"text" :"How much would be downloaded could not be worked out here." } 2416title = row .title if row is not None else (f" { s . family } { s . model } " if s .model else None ) 2417model = {"title" :title ,"family" :s .family ,"model" :s .model ,"model_gb" :row .download_gb if row is not None else None , 2418"own_files" :bool (s .model_path ),"folder" :s .model_path } 2419out = {"profile" :self .profile ,"settings" :s .to_dict (with_key = False ),"warnings" :warns , 2420"flags" :S .flags_text (s ),"steps" :list (STAGES ),"model" :model ,"download" :download ,"drafting" :self .drafting_plan_line ()} 2421return out 2422 2423def feed_without_draft_layer (self ,family :str | None = None )-> bool : 2424"""A model of the signed feed whose entry says `drafter: none` (strata_control/feed_models.py puts it on the family): nothing drafts, whatever Auto would pick for a Flash-Next model. 2425`family`: another family than this launch's (None: this launch's).""" 2426try : 2427fam = self .catalog .tables ()[1 ].get (family or self .s .family )or {} 2428return bool (fam .get ("feed" ))and fam .get ("drafter" )== "none" 2429except Exception :# noqa: BLE001 - an unreadable table is only the generic plan line 2430return False 2431 2432def fetch_missing_drafter (self ,base_path :Path )-> Path : 2433"""The start's safety net: a model never starts without a drafter unless the person chose Off. When the start's decision (drafting.decide on the installed 2434config) is no drafter although Off was not chosen, the drafter it falls back to is the MTP layer and that is not here (DFlash2 blocked by several requests; 2435a card near a class line where setup and the start read the context differently): setup runs again and fetches the layer with its own download 2436lines, then the start decides again. Offline (setup goes on without the layer) or a server that does not answer: the start goes on without, with 2437the start's own line. Never stops the launch.""" 2438from strata_control import drafting 2439try : 2440cfg = read_config (base_path ) 2441want = self .drafting_inputs (cfg ) 2442if not cfg or drafting .normalize (want ["mode" ])== "off" or want .get ("mtp_here" )is not False or self .feed_without_draft_layer () \ 2443or self .s .family not in modelstate .HELPER_FAMILIES or drafting .decide (** want ,** self .drafting_signals (cfg ,want )).drafter != "off" : 2444return base_path 2445except Exception :# noqa: BLE001 - a question asked early is never a reason to stop a launch 2446return base_path 2447self ._layer_fetch = True 2448try : 2449return self .ensure_model () 2450except Cancelled : 2451raise 2452except LaunchError :# the layer could not be had: the start goes on without it and says so 2453return base_path 2454finally : 2455self ._layer_fetch = False 2456 2457def note_setup_lines (self ,lines :list [str ])-> None : 2458"""Remember that setup could not fetch the draft layer because this computer is offline: tools/mtp_fetch.py's own line (netpolicy "offline"), 2459after which setup goes on without the layer (setup.fetch_mtp, mtp_fetch exit 5).""" 2460from strata_control import netpolicy 2461tail = netpolicy .WORDS ["offline" ].split ("{host}" ,1 )[1 ].format (what = "the draft layer" ) 2462if any (tail in str (line )for line in lines or []): 2463self ._mtp_offline = True 2464 2465def say_mtp_offline (self ,base_path :Path )-> None : 2466"""Once per launch: the draft layer could not be downloaded offline and the start has no other drafter (drafting.MTP_OFFLINE_NOTE, shown like the 2467DFlash2 drafter's offline line). The start's own "Drafting: off (no drafter is downloaded yet)" stays as it is.""" 2468if not getattr (self ,"_mtp_offline" ,False )or getattr (self ,"_mtp_offline_said" ,False ): 2469return 2470from strata_control import drafting 2471try : 2472cfg = read_config (base_path ) 2473want = self .drafting_inputs (cfg ) 2474if drafting .normalize (want ["mode" ])== "off" or drafting .decide (** want ,** self .drafting_signals (cfg ,want )).drafter != "off" : 2475return # Off was chosen, or another drafter runs: nothing to say 2476except Exception :# noqa: BLE001 - a note is never a reason to stop a launch 2477return 2478self ._mtp_offline_said = True 2479self .notices .append (drafting .MTP_OFFLINE_NOTE ) 2480self .emit ("model" ,drafting .MTP_OFFLINE_NOTE ,None ,level = "warn" ) 2481 2482def keep_saved_off (self )-> None : 2483"""A launch without a Drafting word keeps the Off this launch ran with last time (its own run config, launch/<name>.json), unless the model's installed 2484config holds a Drafting choice of its own (the app's Models screen). Off is only ever the person's choice, and a chosen Off holds: where setup does not run 2485again the Off was only in that file, and the next start ran Auto's drafter (0.2.14 real-use run, Strix T6).""" 2486s = self .s 2487if s .drafting is not None : 2488return 2489try : 2490from strata_control import drafting 2491prev = read_config (launch_dir ()/ f" { self . name } .json" ) 2492if not isinstance (prev ,dict )or drafting .normalize (prev .get ("drafting" ))!= "off" : 2493return 2494path = self .catalog .installed_config (self .catalog .tag_of (s .family ,s .model )) 2495if path is not None and read_config (path ).get ("drafting" )is not None : 2496return 2497s .drafting = "off" 2498except Exception :# noqa: BLE001 - an unreadable file keeps the launch as it was 2499return 2500 2501def keep_saved_word (self )-> None : 2502"""A launch without a Drafting word keeps the word this launch was given last time (Auto, MTP or DFlash2; Off is keep_saved_off's and is never touched here). 2503Owner 11-15: a drafter the person chose stays chosen, the way Off does; only a new explicit choice changes it, Auto included. (boxia d3d and l620 C2, 25040.2.14.1: the restart with no word wrote null where "auto" was, and a chosen MTP or DFlash2 went back to Auto.) The saved word is what the person chose, 2505never the drafter a start fell back to (drafting.decide: a chosen drafter whose file is not here starts the other one when it is on disk and safe on the 2506card, with its note). Not carried over: when the model's installed config holds a Drafting choice of its own (the app's Models screen, a later choice) 2507or has its draft layer switched off with no choice (also later than the launch's word), and for a model with no Drafting choice.""" 2508s = self .s 2509if s .drafting is not None : 2510return 2511try : 2512from strata_control import drafting 2513word = saved_launch_word (self .name ) 2514if word is None or word == "off" or modelstate .drafting_for_family (word ,s .family )is None : 2515return 2516path = self .catalog .installed_config (self .catalog .tag_of (s .family ,s .model )) 2517installed = read_config (path )if path is not None else {} 2518if isinstance (installed ,dict )and (installed .get ("drafting" )is not None or installed .get ("mtp" )is False ): 2519return 2520s .drafting = drafting .normalize (word ) 2521except Exception :# noqa: BLE001 - an unreadable file keeps the launch as it was 2522return 2523 2524def drafting_plan_line (self )-> str : 2525"""The drafting line of --plan: what drafts, or why not what was asked for. Nothing is changed or downloaded.""" 2526from strata_control import drafting 2527if self .feed_without_draft_layer ():# the model list says this model has no draft layer: setup fetches none and the engine starts without a drafter 2528return drafting .summary_line (drafting .Decision ("off" ,"off" )) 2529try : 2530base ,cfg = self .installed_state () 2531want = self .drafting_inputs (cfg or {}) 2532if self .split_expected (cfg )and drafting .normalize (want .get ("mode" ))== "mtp" : 2533from strata_control .discovery import MTP_FETCH_GB 2534from strata_control import split_engine as SE 2535return SE .split_plan_line (MTP_FETCH_GB ) 2536sig = self .drafting_signals (cfg or {},want ) 2537if drafting .needs_pack (** want ,** sig )or drafting .needs_tuned (** want ,** sig ):# the launch fetches the drafter first (ensure_drafter), so that is what will run 2538return "Drafting: DFlash2 (its drafter is downloaded first)" 2539return drafting .summary_line (drafting .decide (** want ,** sig )) 2540except Exception :# noqa: BLE001 2541return "" 2542 2543def run (self ,* ,start :bool = True )-> Result : 2544self .restart_after = start 2545self .keep_saved_off () 2546self .keep_saved_word ()# a restart with no word keeps the saved one (it was written as null before) 2547try : 2548self .check_own_files ()# a wrong --model-path is said before the engine is downloaded 2549if start : 2550reused = self .check_serving ()# before anything is downloaded or stopped 2551if reused is not None : 2552return reused 2553self .ensure_engine () 2554self .check_cancel () 2555base = self .ensure_model () 2556self .check_cancel () 2557self .ensure_drafter (base ) 2558base = self .fetch_missing_drafter (base ) 2559self .say_mtp_offline (base ) 2560self .check_cancel () 2561self .check_saved_state_readable () 2562self .emit ("config" ,"Writing this launch's settings…" ) 2563cfg = self .build_config (base ) 2564self .announce_key_written () 2565self .ensure_profile (cfg ) 2566self .emit ("config" ,"Settings are saved." ,100 ) 2567if self .engine_problem : 2568text = no_engine_final (self .engine_problem ,self .s .name or self .name ) 2569self .emit ("done" ,text ,100 ,level = "warn" ) 2570return Result (self .profile , [],self .s .api_key ,None ,self .notices + [text ],str (cfg ),serving = False , 2571engine_problem = self .engine_problem ,final_text = text ) 2572self .tune () 2573self .check_cancel () 2574if not start : 2575return Result (self .profile , [],self .s .api_key ,self .tune_word ,self .notices ,str (cfg )) 2576self .start () 2577self .save_choices () 2578tunnel = self .open_access () 2579urls = acc .urls_for (self .s ,tunnel_url = tunnel ) 2580res = Result (self .profile ,urls ,self .s .api_key ,self .tune_word ,self .notices ,str (cfg ),tunnel ) 2581self .emit ("done" ,"Strata is serving." ,100 ,urls = urls ) 2582return res 2583except Cancelled : 2584self ._stop_children () 2585raise 2586except LaunchError : 2587self ._stop_children () 2588raise 2589 2590def stop (self )-> dict : 2591from strata_control import runtime 2592out = runtime .stop (self .profile ,timeout = 180 ) 2593acc .stop_tunnel (self .profile ) 2594return out 2595 2596 2597from strata_control .models import ISSUE_WORDS ,plain_issue # noqa: E402,F401 (one wording for the app, the Terminal and `models import`) 2598 2599 2600def _read_json (path :Path )-> dict | None : 2601try : 2602return json .loads (Path (path ).read_text (encoding = "utf-8" )) 2603except (OSError ,ValueError ): 2604return None 2605 2606 2607#: lines of an engine log that say why it stopped (the last one wins), and a plain next step for the causes we know. Recommend, never force. 2608CAUSE_LINE = re .compile (r"error|exception|failed|cannot|can't|could not|no device|not found|out of memory|unsupported|abort|invalid|missing|" 2609r"no kernel|illegal|denied|refus" ,re .I ) 2610# The GPU runtime (ROCm) failed while the card was being set up, often right after another engine exited: the runtime's own text 2611# ("terminate called after throwing an instance of 'rocr::AMD::hsa_exception'") stays in the log, not in the sentence shown. 2612HSA_START = re .compile (r"hsa_exception|HSA_STATUS_ERROR" ,re .I ) 2613HSA_START_NEXT = ("The graphics card was not ready yet; wait a few seconds and run it again. If it keeps happening, restart the PC " 2614"and report the log." ) 2615VRAM_STOP_NEXT = ("A graphics card is too full for this start, even after Strata moved what it could to the processor and the RAM. Close other programs that use the " 2616"cards, or start on fewer cards (--gpu), or turn pictures off (--vision off); the context and the number of requests were not changed." ) 2617KNOWN_CAUSES = ( 2618 (re .compile (r"cannot run the expert kernel|needs AVX-?512" ,re .I ), 2619"This model folder holds the pack for CPUs with AVX-512, and this PC's CPU does not have it. Run `strata setup` again: on a CPU " 2620"without AVX-512 it builds the pack that runs on AVX2 CPUs (Ryzen 3000-5000, Intel Core 12th-14th generation)." ), 2621 (re .compile (r"no device of requested type|device not found|no (gpu|sycl|level.zero) device|permission denied.*(dri|render)" ,re .I ), 2622"The engine could not open the graphics card. On Linux the account must be allowed to use it: add it to the render group " 2623"(`sudo usermod -aG render $USER`), log in again and start it again." ), 2624 (re .compile (r"out of memory|not enough (gpu |video |free )?memory|cudaerrormemory|allocation failed" ,re .I ), 2625"The card or memory ran out. Close other programs that use the card, or choose a smaller context (`--context 16k`) and start again." ), 2626 (re .compile (r"tqk\d|no kernel|unsupported (quant|type|model)|unknown (quant|tensor) type" ,re .I ), 2627"This engine is too old for this model. Update it with `strata update` and start again." ), 2628 (re .compile (r"dll|libcu|cannot open shared object|0xc0000135" ,re .I ), 2629"A library the engine needs is missing. Update the engine (`strata update`) or install the graphics driver again." ), 2630# a Strix Halo with --batch N: the engine's own line after a failed start (src/program/generate.cpp); it must stay the LAST entry (explain_engine_exit reads KNOWN_CAUSES[-1]) 2631 (re .compile (r"requests at once do not fit" ,re .I ), 2632"This PC's memory cannot hold that many requests at once. Lower Concurrent requests in the app (or `--parallel` in the Terminal) by one and start again." ), 2633) 2634 2635 2636def _lines_since (path :str | os .PathLike | None ,mark :int | None ,limit :int = 65536 )-> list [str ]: 2637"""Lines written to a log after `mark` bytes (the whole tail when there is no mark); a log that got shorter was started over.""" 2638if not path : 2639return [] 2640try : 2641with open (path ,"rb" )as stream : 2642stream .seek (0 ,os .SEEK_END ) 2643size = stream .tell () 2644start = 0 if (mark is None or mark > size )else mark 2645stream .seek (max (start ,size - limit )) 2646data = stream .read ().decode ("utf-8" ,"replace" ) 2647except OSError : 2648return [] 2649return [x .rstrip ()for x in data .splitlines ()if x .strip ()] 2650 2651 2652def engine_log_tail (config :Path | None ,limit :int = 65536 ,since :dict | None = None )-> tuple [list [str ],str | None ]: 2653"""(last lines of the engine log, its path); ([], path-or-None) when it cannot be read. With `since` (log sizes before the attempt) 2654only this attempt's lines are returned.""" 2655log = None 2656if config : 2657try : 2658log = read_config (config ).get ("log" ) 2659except (OSError ,ValueError ): 2660log = None 2661if not log : 2662return [],None 2663if since is not None : 2664return _lines_since (log ,since .get (str (log )),limit ),str (log ) 2665try : 2666with open (log ,"rb" )as stream : 2667stream .seek (0 ,os .SEEK_END ) 2668stream .seek (max (0 ,stream .tell ()- limit )) 2669data = stream .read ().decode ("utf-8" ,"replace" ) 2670except OSError : 2671return [],str (log ) 2672return [x .rstrip ()for x in data .splitlines ()if x .strip ()],str (log ) 2673 2674 2675def _reader_token_limit (config :Path | None )-> int | None : 2676"""The picture reader's image limit in the run config (vision.max_tokens; 0 = no limit); None when the config does not say (the default limit).""" 2677try : 2678value = (read_config (config ).get ("vision" )or {}).get ("max_tokens" )if config else None 2679return int (value )if value is not None else None 2680except (OSError ,ValueError ,TypeError ,AttributeError ): 2681return None 2682 2683 2684def _reader_room_facts (config :Path | None ,room :reader_room .NoRoom )-> tuple [int | None ,int | None ]: 2685"""(the card as nvidia-smi numbers it, its free memory in MiB) for a picture reader that found no room; None for what cannot be said. The reader counts 2686the cards its environment shows it, so its number is looked up in the list the server gave it (the config's cards in the engine's order, or the one card 2687named by vision.cuda_device); the free memory is read after the failure, when the reader is gone, so it is what the reader had.""" 2688card = free = None 2689try : 2690cfg = read_config (config )if config else {} 2691vision = cfg .get ("vision" )or {} 2692if vision .get ("cuda_device" )is not None : 2693visible = [vision ["cuda_device" ]] 2694else : 2695from serve import server as _server 2696visible = _server .hip_visible (cfg )if cfg .get ("backend" )== "hip" else _server .ordered_gpus (cfg ) 2697card = reader_room .physical_card (room .device ,visible ) 2698except Exception :# noqa: BLE001 - the figures are a convenience; the sentence is complete without them 2699card = None 2700if card is not None : 2701try : 2702from strata_control import split_engine as SE 2703cards = SE .probe_cards ([card ]) 2704free = cards [0 ].free_mib if cards else None 2705except Exception :# noqa: BLE001 2706free = None 2707return card ,free 2708 2709 2710def explain_engine_exit (result :dict ,config :Path | None ,marks :dict | None = None ,server_log :Path | None = None , 2711shared_memory :bool = False )-> tuple [str ,str ]: 2712"""(text, next) for a start that did not reach ready: the stage, the cause line from the engine log, the next step and the log path 2713(round 8, L3: an Arc engine died with 'No device of requested type available' and the person saw only 'server_exited').""" 2714server_lines = _lines_since (server_log , (marks or {}).get (str (server_log )))if (server_log and marks is not None )else [] 2715for x in server_lines :# the server's own refusal (server.py: error: ...) is the cause when there is one 2716busy = re .search (r"port (\d+) is already in use" ,x ) 2717if busy : 2718return (f"Port { busy . group ( 1 ) } is already in use by another program." , 2719f"Close it, or start with a different port (for example --port { int ( busy . group ( 1 )) + 1 } ). The server's log: { server_log } " ) 2720lines ,log = engine_log_tail (config ,since = marks ) 2721if marks is not None and not lines : 2722own = [x for x in server_lines if re .search (r"server\.py: error:|error:" ,x ,re .I )] 2723if own : 2724lines ,log = own ,str (server_log ) 2725lines = lines or [x .strip ()for x in str (result .get ("log_tail" )or "" ).split (" | " )if x .strip ()] 2726# a card that ran out of memory: the engine's own line is the cause (the picture reader's "ggml_cuda_init: ... no CUDA-capable device", which it prints when the 2727# cards are full and it runs on the processor, matched "failed" and used to be the last line shown) 2728vram_cause = vram_fit .engine_stop_reason (lines ) 2729reader = None if vram_cause else reader_room .find (lines )# the picture reader found no room on its card (ggml prints it, then aborts): not the engine's line, so a search of its own 2730cause = vram_cause or next ((x for x in reversed (lines )if CAUSE_LINE .search (x )and not x .lstrip ().startswith (("strata generate: " ,"strata serve: expert" ))),None ) 2731cause = (cause or (lines [- 1 ]if lines else "" )).strip () 2732cause = re .sub (r"^(\[strata\]\s*)?(\d{4}-\d\d-\d\d[ T][\d:.]+\s*)?" ,"" ,cause )[:240 ] 2733state ,why = result .get ("state" ),result .get ("error" )or result .get ("message" ) 2734if why == "startup_wait_expired" : 2735stage = "The model did not finish loading in time" 2736elif why == "server_exited" or result .get ("engine_exit_code" )is not None : 2737code = result .get ("engine_exit_code" ) 2738stage = "The engine stopped while it was loading the model" + (f" (exit code { code } )" if code not in (None ,0 )else "" ) 2739else : 2740stage = f"The server did not become ready ( { state } : { why or 'see the engine log' } )" 2741hsa = HSA_START .search (" " .join (lines + [str (why or "" )]))# the runtime's own text is kept out of the sentence (it is in the log) 2742if hsa : 2743# a real cause in the same log (out of memory, no permission on the card ...) wins: its line is the cause shown 2744real = next ((x for x in reversed (lines )if any (p .search (x )for p ,_ in KNOWN_CAUSES )),None ) 2745if real : 2746hsa = None 2747cause = re .sub (r"^(\[strata\]\s*)?(\d{4}-\d\d-\d\d[ T][\d:.]+\s*)?" ,"" ,real .strip ())[:240 ] 2748else : 2749cause = "" 2750if reader is not None and not hsa :# the plain sentence: which card, what the reader needs, what is free, and the next step 2751card ,free = _reader_room_facts (config ,reader ) 2752said ,nxt = reader_room .could_not_start (card ,reader_room .whole_need_mib (reader .need_mib ,_reader_token_limit (config )),free ) 2753return said ,nxt + _log_sentence (log ) 2754text = stage + (f": { cause } " if cause else "." ) 2755if not text .endswith (("." ,"!" )): 2756text += "." 2757step = HSA_START_NEXT if hsa else (VRAM_STOP_NEXT if vram_cause else next ((words for pattern ,words in KNOWN_CAUSES if pattern .search (" " .join ([cause ,str (why or "" )]))),"Run it again; if it repeats, report the log." )) 2758if shared_memory and not hsa and not any (p .search (" " .join ([cause ,str (why or "" )]))for p ,_ in (* KNOWN_CAUSES [:2 ],KNOWN_CAUSES [- 1 ])): 2759# a Strix Halo: the settings fix the expert cache beside a RAM budget, and the engine ended with no error text of its own (STRIX-2Q, 11-01) 2760try : 2761from strata_control import uma_pool ,user_args as _ua 2762cfg = read_config (config )if config else {} 2763effective = {"args" :list (cfg .get ("args" )or []),_ua .USER_KEY :cfg .get (_ua .USER_KEY )} 2764_ua .apply (effective ) 2765advice = uma_pool .stop_advice (effective ["args" ]) 2766except Exception :# noqa: BLE001 - the plain sentence below is enough 2767advice = None 2768if advice : 2769if cause and not CAUSE_LINE .search (cause ):# the last log line was a progress line ("prefill: copy stream"), not a reason 2770text = stage + "." 2771return text ,advice + _log_sentence (log ) 2772return text ,step + _log_sentence (log ) 2773 2774 2775def _log_sentence (log :str | None )-> str : 2776"""The sentence that points at the engine's log. A log that does not exist is not pointed at: a start that stopped before the engine 2777existed (a profile whose runtime is still live, a missing engine package) never wrote one (#3714).""" 2778if log and os .path .isfile (log ): 2779return f" The engine's log: { log } " 2780if log : 2781return " The engine did not get as far as writing its log, so the reason is in the lines above (`strata logs` has the server's own)." 2782return " The engine's log has the reason (strata logs, or the log named in the run config)." 2783 2784 2785#: the states of a launch's own runtime that must be ended before a new start: a server that runs, and one that stopped but whose host is still 2786#: alive ("failed", "stale"); `strata launch --stop` ends all four, and a start refuses the profile while any of them is left (#4824). 2787LEFTOVER_STATES = ("ready" ,"starting" ,"failed" ,"stale" ) 2788 2789#: what the runtime says when another host still owns the profile: the start never began, so there is no engine log to read. 2790PROFILE_BUSY = re .compile (r"already has a live managed runtime" ,re .I ) 2791 2792 2793def _log_hint (config :Path | None ,error :object = None )-> str : 2794if PROFILE_BUSY .search (str (error or "" )): 2795return ("Another Strata server for this preset is still running or starting, or one that stopped has not been cleared, so this start never began " 2796"and there is no engine log for it. Run `strata launch --stop`, then start again without --retune: a tuning that finished is kept and is not measured again." ) 2797log = None 2798if config : 2799try : 2800log = read_config (config ).get ("log" ) 2801except (OSError ,ValueError ): 2802log = None 2803if log and os .path .isfile (log ): 2804return f"The engine's log has the reason: { log } " 2805if log : 2806return "The engine did not get as far as writing its log, so the reason is the message above (`strata logs` has the server's own)." 2807return "The engine's log has the reason (strata logs, or the log named in the run config)."