okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""What a launch is made of, as plain data: the choices of the setup screens, the rules that turn them into warnings, and the 2flags that say the same thing without the TUI. 3 4No Textual, no network, standard library only: the screens, the flags and the saved presets all use this one description, 5so `strata launch --preset X` and clicking through the screens cannot drift apart. 6 7Rules of this file: recommend, never force. A choice that does not fit this computer is a warning with the reason; only 8a value that cannot be run at all (a port that is not a number, an unknown access kind) is an error. 9""" 10 11from __future__import annotations 12 13import difflib 14import re 15from dataclasses import asdict ,dataclass ,field ,fields 16from typing import Any 17 18SCHEMA = "strata.launch/1" 19 20#: setup.py's CONTEXTS (kept here only as the fallback when the installer files are not next to this terminal). 21FALLBACK_CONTEXTS = (8192 ,32768 ,65536 ,131072 ,204800 ,262144 ,393216 ,524288 ) 22 23ACCESS_KINDS = ("local" ,"lan" ,"cloudflare" ,"tailscale" ) 24ACCESS_WORDS = {"local" :"This computer only" ,"lan" :"My local network" ,"cloudflare" :"Cloudflare tunnel" , 25"tailscale" :"Tailscale" } 26TUNE_MODES = ("quick" ,"thorough" ,"skip" ) 27VISION_MODES = ("off" ,"on" ,"gpu" ,"cpu" ) 28MTP_MODES = ("on" ,"off" ) 29#: strata_control/split_engine.py MODES: the all-cards split engine on NVIDIA and AMD gfx1201 cards (auto = by itself where it is supported, the default) 30SPLIT_MODES = ("auto" ,"on" ,"off" ) 31#: strata_control/drafting.py MODES (tests/terminal/test_drafting.py keeps the two the same) 32DRAFTING_MODES = ("auto" ,"mtp" ,"dflash2" ,"off" ) 33KV_MODES = ("int8" ,"q4_0" ,"k8v4" ,"fp16" ) 34DEFAULT_PORT = 8080 35 36#: How many requests the card can answer at once (the spec's "fit to card" default): by graphics memory. 37PARALLEL_BY_VRAM = ((32.0 ,4 ), (24.0 ,3 ), (20.0 ,2 ), (0.0 ,1 )) 38 39 40def fit_parallel (vram_gb :float | None )-> int : 41"""12 GB -> 1, 20 -> 2, 24 -> 3, 32 and more -> 4 (each step starts at the listed size).""" 42gb = float (vram_gb or 0.0 ) 43for floor ,n in PARALLEL_BY_VRAM : 44if gb >= floor - 0.5 : 45return n 46return 1 47 48 49def parse_context (text :Any )-> int : 50"""`128k`, `128K`, `131072` or `64 K` -> tokens. 1K is 1024 tokens (the engine's and setup's unit).""" 51raw = str (text ).strip ().lower ().replace (" " ,"" ).replace ("_" ,"" ).replace ("," ,"" ) 52m = re .fullmatch (r"(\d+(?:\.\d+)?)(k|m)?" ,raw ) 53if not m : 54raise ValueError (f"' { text } ' is not a context size. Use a number of tokens or a size such as 32k, 64k, 128k, 256k." ) 55value = float (m .group (1 ))* {"k" :1024 ,"m" :1024 * 1024 ,None :1 }[m .group (2 )] 56n = int (round (value )) 57if n < 1024 : 58raise ValueError (f"A context of { n } tokens is too small to be useful; the smallest size offered is 8k." ) 59return n 60 61 62def context_label (tokens :int | None )-> str : 63if not tokens : 64return "default" 65if tokens >= 1048576 and tokens % 1048576 == 0 :# 1,048,576 positions: "1M" 66return f" { tokens // 1048576 } M" 67if tokens % 1024 == 0 : 68return f" { tokens // 1024 } K" 69if tokens >= 1000 : 70return f" { tokens / 1000 :g } K" 71return str (tokens ) 72 73 74def words_for (tokens :int )-> str : 75"""About how many English words fit (0.75 words per token, rounded to two figures).""" 76words = tokens * 0.75 77mag = 10 ** max (0 ,len (str (int (words )))- 2 ) 78return f"about { int ( round ( words / mag ) * mag ):, } words" 79 80 81@dataclass 82class LaunchSettings : 83"""Every choice of `strata launch`. `None` means "the recommendation for this computer".""" 84 85name :str | None = None # the saved preset's name 86family :str | None = None # catalog family id (qwen, swift, coder, unsloth, gyro, nvfp4...) 87model :str | None = None # catalog size (IQ3_XXS ...) 88model_path :str | None = None # "Use model files I already have": a .gguf file or a folder 89data_dir :str | None = None # where model files are stored (None: the Strata default) 90gpus :list [int ]| None = None # None = the engine's choice (all usable cards) 91gpu_roles :dict [str ,str ]| None = None # {"1": "main", "0": "helper", "2": "off"}: a role for every card; None = the recommendation 92context :int | None = None 93kv :str | None = None # None = int8 above 8K, as setup 94vision :str | None = None # None = the default (on when the model can read pictures and the engine has the reader), off | on | gpu | cpu 95parallel :int | None = None # None = fit to the card 96drafting :str | None = None # None = Auto (recommended): the table in strata_control/drafting.py; mtp | dflash2 | off choose one. Saved in the launch config 97split_engine :str | None = None # None = auto (the all-cards split engine runs by itself where it is supported); on | off. Saved in the preset and the launch config 98mtp :str | None = None # None = as installed (draft layer on); "off" starts without it (less graphics memory and RAM, slower); "on" overrides an installed "off" 99tune :str = "skip" # quick | thorough | skip 100tune_allow_small :bool = False # the "answer-changing" tick, off by default, as in the app 101access :str = "local" 102port :int = DEFAULT_PORT 103api_key :str | None = None # never shown whole; stored only in the private preset file 104no_key :bool = False # served beyond this computer without a key, on purpose (--no-api-key); a warning, never a refusal 105extra :dict [str ,str ]= field (default_factory = dict )# Advanced: --set key=value (flags and STRATA_* variables) 106# filled in by the run, kept in the preset 107tuned_preset :str | None = None # id of the tuning preset the tuner saved 108tuned_at :str | None = None 109last_used :str | None = None 110created :str | None = None 111 112@property 113def is_tuned (self )-> bool : 114"""Tuning was done for this preset: it saved faster settings (tuned_preset), or it measured that the standard settings are already the 115fastest (only tuned_at is set). Either way the next start must not tune again.""" 116return bool (self .tuned_preset or self .tuned_at ) 117 118def to_dict (self ,* ,with_key :bool = True )-> dict [str ,Any ]: 119d = {"schema" :SCHEMA ,** asdict (self )} 120if not with_key : 121d ["api_key" ]= "set" if self .api_key else None 122return d 123 124@classmethod 125def from_dict (cls ,data :dict [str ,Any ])-> "LaunchSettings" : 126known = {f .name for f in fields (cls )} 127clean = {k :v for k ,v in (data or {}).items ()if k in known } 128if isinstance (clean .get ("extra" ),dict ): 129clean ["extra" ]= {str (k ):str (v )for k ,v in clean ["extra" ].items ()} 130else : 131clean .pop ("extra" ,None ) 132return cls (** clean ) 133 134def copy (self ,** changes :Any )-> "LaunchSettings" : 135d = asdict (self ) 136d .update (changes ) 137return LaunchSettings .from_dict (d ) 138 139 140# ----------------------------------------------------------------------------------------------------- checks 141 142@dataclass 143class Notice : 144level :str # "warn" | "error" 145text :str # plain words: what it means 146next :str = "" # plain words: what to do 147after_write :bool = False # true only once the thing it reports has really been written: the launch says it then (Runner.announce_key_written), not in the plan or before a refusal 148 149def line (self )-> str : 150return self .text + (f" { self . next } " if self .next else "" ) 151 152 153def closest (word :str ,options :list [str ])-> str | None : 154hit = difflib .get_close_matches (word .lower (), [o .lower ()for o in options ],n = 1 ,cutoff = 0.5 ) 155if not hit : 156return None 157return next (o for o in options if o .lower ()== hit [0 ]) 158 159 160def check_port (port :Any )-> Notice | None : 161try : 162p = int (port ) 163except (TypeError ,ValueError ): 164return Notice ("error" ,f"' { port } ' is not a port number." ,"Use a number from 1 to 65535, for example 8080." ) 165if not 1 <= p <= 65535 : 166return Notice ("error" ,f"Port { p } does not exist." ,"Use a number from 1 to 65535, for example 8080." ) 167if p < 1024 : 168return Notice ("warn" ,f"Port { p } is below 1024; on many computers only an administrator can use it." , 169"8080 works without special rights." ) 170return None 171 172 173NO_KEY_NETWORK = "No API key: anyone who can reach this port can use the model and its tools (they can read and change files on this computer)." 174NO_KEY_PUBLIC = ("No API key on a public address: anyone on the internet who finds it can use the model and its tools " 175"(they can read and change files on this computer)." ) 176 177 178def check_access (s :LaunchSettings )-> list [Notice ]: 179out :list [Notice ]= [] 180if s .access not in ACCESS_KINDS : 181near = closest (s .access ,list (ACCESS_KINDS )) 182out .append (Notice ("error" ,f"' { s . access } ' is not a way to share Strata." , 183f"Choose one of: { ', ' . join ( ACCESS_KINDS ) } ." + (f" Did you mean ' { near } '?" if near else "" ))) 184return out 185port = check_port (s .port ) 186if port : 187out .append (port ) 188if s .access != "local" and not s .api_key : 189if s .access == "cloudflare" : 190out .append (Notice ("warn" ,NO_KEY_PUBLIC ,"Leave --no-api-key out to get a key." )) 191elif s .no_key : 192out .append (Notice ("warn" ,NO_KEY_NETWORK ,"Leave --no-api-key out to get a key." )) 193else : 194out .append (Notice ("warn" ,f" { ACCESS_WORDS [ s . access ] } without an API key lets anyone who can reach it use your computer's model." , 195"Add an API key (Strata makes one for you in the Access step)." )) 196return out 197 198 199def check_parallel (s :LaunchSettings ,* ,vram_gb :float | None ,fitted :int | None = None )-> list [Notice ]: 200out :list [Notice ]= [] 201if s .parallel is None : 202return out 203if not 1 <= int (s .parallel )<= 8 : 204out .append (Notice ("error" ,f" { s . parallel } requests at once is outside what the engine can do (1 to 8)." , 205"Pick a number from 1 to 8." )) 206return out 207fitted = fit_parallel (vram_gb )if fitted is None else fitted 208if vram_gb and s .parallel > fitted : 209out .append (Notice ("warn" ,f" { s . parallel } requests at once is more than a { vram_gb :.0f } GB card usually holds " 210f"(it fits { fitted } )." , 211"It can still start; the engine keeps less of the model in graphics memory, so each answer is slower." )) 212return out 213 214 215def check_context (s :LaunchSettings ,* ,max_fit_tokens :int | None = None )-> list [Notice ]: 216out :list [Notice ]= [] 217if s .context is not None and s .context > 262144 : 218out .append (Notice ("warn" ,f" { context_label ( s . context ) } is more than the model was trained on (256K)." , 219"Setup adds rope scaling for it (experimental); answers may get less reliable." )) 220if max_fit_tokens and s .context and s .context > max_fit_tokens : 221out .append (Notice ("warn" ,f" { context_label ( s . context ) } is bigger than this computer's memory comfortably holds." , 222f" { context_label ( max_fit_tokens ) } is the recommended size." )) 223return out 224 225 226# ----------------------------------------------------------------------------------------------------- advanced settings 227 228_ENV_NAME = re .compile (r"^(?=[A-Za-z0-9_]*[A-Z])[A-Za-z_][A-Za-z0-9_]*$" )# any name with a capital letter: STRATA_X, IGC_EnableDPEmulation, ZES_ENABLE_SYSMAN 229_FLAG_NAME = re .compile (r"^[a-z][a-z0-9-]*$" ) 230 231 232def split_setting (text :str )-> tuple [str ,str ]: 233"""`prefill=65536`, `--prefill=65536`, `STRATA_PIN_BY_NEED=1` -> (key, value); the key is a `--flag` or an ENV name.""" 234key ,sep ,value = text .partition ("=" ) 235key = key .strip () 236if not key : 237raise ValueError ("an empty setting name" ) 238if _ENV_NAME .match (key ): 239return key ,value .strip () 240flag = key [2 :]if key .startswith ("--" )else key 241flag = flag .replace ("_" ,"-" ) 242if not _FLAG_NAME .match (flag ): 243raise ValueError (f"' { text } ' is not a setting name. Write it like prefill=65536 or STRATA_PIN_BY_NEED=1." ) 244return "--" + flag ,value .strip () 245 246 247def settings_from_pairs (pairs :list [str ])-> dict [str ,str ]: 248out :dict [str ,str ]= {} 249for p in pairs or []: 250k ,v = split_setting (p ) 251out [k ]= v 252return out 253 254 255#: Options whose value is a WORD the engine reads (on, off, auto, none): the word goes through as typed (none since DeepSeek's --dspark left, #3959). 256WORD_VALUE_FLAGS :frozenset [str ]= frozenset () 257 258 259def as_argv_changes (extra :dict [str ,str ],bool_flags :frozenset [str ], 260word_flags :frozenset [str ]= WORD_VALUE_FLAGS )-> tuple [dict [str ,Any ],dict [str ,str | None ]]: 261"""Turn the Advanced table's values into `tune_knobs.apply_to_argv` changes and environment changes. 262 263A flag without a value (or on/true/yes) is "present"; off/false/no/none removes it; anything else is a value. 264A word-valued option (WORD_VALUE_FLAGS) keeps its word.""" 265args :dict [str ,Any ]= {} 266env :dict [str ,str | None ]= {} 267for key ,value in extra .items (): 268if key .startswith ("--" ): 269low = value .lower () 270if key in word_flags and key not in bool_flags : 271if low : 272args [key ]= low 273continue # an empty value is no change, as for every option that takes one (#3504) 274if low == "" and key not in bool_flags : 275continue # an empty value for an option that takes one is no change, never a bare flag (#3504) 276if key in bool_flags or low in ("on" ,"true" ,"yes" ,"" ): 277args [key ]= None if low in ("off" ,"false" ,"no" ,"none" )else True 278elif low in ("off" ,"false" ,"no" ,"none" ): 279args [key ]= None 280else : 281args [key ]= value 282else : 283env [key ]= None if value .lower ()in ("off" ,"unset" ,"none" )else value 284return args ,env 285 286 287def flags_text (s :LaunchSettings ,* ,preset :str | None = None )-> str : 288"""The `strata launch ...` line that says the same as these choices (copyable).""" 289parts = ["strata launch" ] 290if preset : 291parts .append (f'--preset " { preset } "' ) 292else : 293if s .model_path : 294parts .append (f'--model-path " { s . model_path } "' ) 295if s .model :# own files the table recognised say which model they are, so the line stays exact 296parts .append (f"--model { s . model . lower () } " + (f" --family { s . family } " if s .family and s .family != "qwen" else "" )) 297if s .data_dir : 298parts .append (f'--data-dir " { s . data_dir } "' ) 299if s .context : 300parts .append (f"--context { context_label ( s . context ). lower () } " ) 301if s .kv : 302parts .append (f"--kv { s . kv } " ) 303if s .vision : 304parts .append (f"--vision { s . vision } " ) 305if s .parallel : 306parts .append (f"--parallel { s . parallel } " ) 307if s .mtp : 308parts .append (f"--mtp { s . mtp } " ) 309if s .drafting : 310parts .append (f"--drafting { s . drafting } " ) 311if s .split_engine : 312parts .append (f"--split-engine { s . split_engine } " ) 313parts .append (f"--tune { s . tune } " ) 314if s .tune_allow_small : 315parts .append ("--tune-allow-small" ) 316parts .append (f"--access { s . access } " ) 317parts .append (f"--port { s . port } " ) 318if s .gpu_roles : 319parts .append ("--gpu-roles " + "," .join (f" { k } = { v } " for k ,v in sorted (s .gpu_roles .items (),key = lambda kv :int (kv [0 ])))) 320elif s .gpus : 321parts .append ("--gpu " + "," .join (str (g )for g in s .gpus )) 322for k ,v in sorted (s .extra .items ()): 323parts .append (f"--set { k [ 2 :] if k . startswith ( '--' ) else k } = { v } " if v else f"--set { k [ 2 :] if k . startswith ( '--' ) else k } " ) 324return " " .join (parts ) 325 326 327def slug (name :str )-> str : 328"""A name safe for profile ids and file names: lowercase letters, digits, - and _, starting with a letter.""" 329text = re .sub (r"-{2,}" ,"-" ,re .sub (r"[^a-z0-9_-]+" ,"-" ,name .lower ())).strip ("-_" )or "launch" 330if not text [0 ].isalpha (): 331text = "l" + text 332return text [:48 ]