okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""The Advanced table: every engine setting with its default, the tuned value and the person's own value. 2 3The list comes from the engine itself (its `--help`, the same read `strata tune` uses), plus the environment variables the tuner 4knows (strata_control/tune_knobs.py). Nothing is invented here: a setting the engine does not list is shown as unknown, with a 5warning and never a refusal, because newer engines have flags this one has not heard of. 6""" 7 8from __future__import annotations 9 10import re 11from dataclasses import dataclass ,field 12from pathlib import Path 13from typing import Any 14 15from strata_control .user_args import MULTI_VALUE_FLAGS 16 17_ENTRY = re .compile (r"^ (--[A-Za-z0-9][A-Za-z0-9-]*)( +)?(.*)$" ) 18_EXPERIMENTAL = re .compile (r"experimental|diagnostic|A/B arm|fault injection|oracle" ,re .I ) 19_DEFAULT = re .compile (r"\(\s*default[: ]\s*([^)]*)\)" ,re .I ) 20_PARENS = re .compile (r"\([^)]*\)" ) 21 22 23# Plain words for the settings people meet most. The engine's own help text is written for its developers (round codes like "R4", internal 24# names); these lines say what the setting does for a person. A setting not listed here keeps the engine's sentence with the codes removed. 25PLAIN = { 26"--expert-cache" :"How many of the model's experts stay in graphics memory (auto picks the most that fit your card)." , 27"--prefill" :"How many prompt tokens are read in one go (auto picks for your card)." , 28"--spec" :"How many words the draft layer guesses ahead to speed up answers." , 29"--spec-min-p" :"How sure the draft layer must be before a guess is used." , 30"--mtp" :"The draft layer that makes answers faster." , 31"--pack" :"The folder with the model's prepared data." , 32"--native" :"The model file." , 33"--ple-gguf" :"The model file that holds the word-embedding table." , 34"--expert-profile" :"A table of which experts are used most, to decide what stays in graphics memory." , 35"--max-context" :"How much text the model remembers at once." , 36"--kv" :"The format of the conversation memory (int8 uses half of fp16; q4_0 uses less still)." , 37"--kv-resident" :"How much of the conversation memory stays in graphics memory." , 38"--vision" :"Let the model read pictures." , 39"--vram-reserve-mib" :"Graphics memory (in MiB) kept free for other programs." , 40"--adapt-every" :"How often the engine re-chooses which experts stay in graphics memory." , 41"--pcie-frac" :"How much of the link to the graphics card is used for moving experts." , 42"--suffix-draft" :"Guess the next words from text already in the conversation." , 43"--port" :"The network port the server listens on." , 44"--gpu" :"Which graphics card to use." , 45"--gpu-roles" :"A role for each graphics card: main, helper or off." , 46"--gpus" :"Which graphics cards to use together." , 47} 48_CODE = re .compile (r"\b[RTS]\d{1,2}\b[:,)]?\s*" ) 49 50 51def plain_description (name :str ,text :str )-> str : 52"""A person's sentence for a setting: ours when we have one, else the engine's with its internal round codes ("R4", "T2") taken out.""" 53if name in PLAIN : 54return PLAIN [name ] 55cleaned = _CODE .sub ("" ,text or "" ).strip (" :;,-" ) 56cleaned = re .sub (r"\(\s*\)" ,"" ,cleaned ).strip () 57cleaned = re .sub (r"\s{2,}" ," " ,cleaned ) 58return cleaned [:1 ].upper ()+ cleaned [1 :]if cleaned else "An engine setting (the engine's help has no sentence for it)." 59 60 61@dataclass 62class Param : 63name :str # --flag or ENV_NAME 64kind :str # "flag" | "env" 65metavar :str = "" 66description :str = "" 67help_default :str | None = None 68experimental :bool = False 69values :list [str ]= field (default_factory = list ) 70full :str = "" # a sentence that is shown whole (the speed switches); empty: the first sentence of the description 71 72@property 73def short (self )-> str : 74"""One line: the first sentence, cut at 70 characters.""" 75text = re .sub (r"\s+" ," " ,re .sub (r"\([^)]*\)" ,"" ,self .description )).strip () 76cut = re .split (r"(?<=[.;:])\s" ,text ,maxsplit = 1 )[0 ]if text else "" 77cut = plain_description (self .name ,cut .rstrip (".;:" )).rstrip (".;:" ) 78return cut if len (cut )<= 70 else cut [:67 ].rstrip ()+ "..." 79 80 81def parse_help (text :str )-> list [Param ]: 82"""The engine's usage text -> parameters, one per flag (a flag listed twice, like --kv, keeps all of its descriptions).""" 83params :dict [str ,Param ]= {} 84current :Param | None = None 85for line in text .splitlines (): 86m = _ENTRY .match (line ) 87if m and not line .startswith (" " ): 88name ,gap ,rest = m .group (1 ),m .group (2 )or "" ,m .group (3 )or "" 89meta ,desc = "" ,rest 90if len (gap )== 1 :# "--pack DIR the pack": one space, a value name, a gap 91parts = re .split (r" {2,}" ,rest ,maxsplit = 1 ) 92meta ,desc = (parts [0 ],parts [1 ])if len (parts )== 2 else (parts [0 ],"" ) 93p = params .get (name ) 94if p is None : 95p = params [name ]= Param (name = name ,kind = "flag" ,metavar = meta ,description = desc .strip ()) 96else : 97p .description = (p .description + " " + desc .strip ()).strip () 98p .metavar = p .metavar or meta 99if meta and "|" in meta : 100p .values = sorted (set (p .values + meta .split ("|" ))) 101current = p 102elif current is not None and line .startswith (" " )and line .strip (): 103current .description += " " + line .strip () 104elif not line .strip (): 105current = None 106for p in params .values (): 107p .description = re .sub (r"\s+" ," " ,p .description ).strip () 108p .experimental = bool (_EXPERIMENTAL .search (p .description )) 109d = _DEFAULT .search (p .description ) 110if d : 111p .help_default = (d .group (1 )or "" ).strip ().rstrip (".,;" )or None 112return list (params .values ()) 113 114 115def env_params ()-> list [Param ]: 116"""The environment settings the tuner knows (from tune_knobs.ARMS), with the tuner's own plain label.""" 117try : 118from strata_control import tune_knobs 119except ImportError : 120return [] 121out :dict [str ,Param ]= {} 122for arm in tune_knobs .ARMS : 123for key in arm .env : 124if key not in out : 125out [key ]= Param (name = key ,kind = "env" ,description = arm .label ,experimental = arm .answer != "exact" ) 126return list (out .values ()) 127 128 129def switch_params (applicable :list [Any ])-> list [Param ]: 130"""The rows of the speed switches that apply to this launch (strata_control/speed_switches.py): the environment each one writes outside its default, 131shown as the default ("off" for Faster long prompts, "on" for the others) until the person types the value. The same features as the app's Expert settings.""" 132from strata_control import speed_switches as sw 133return [Param (name = name ,kind = "env" ,description = sw .env_words (name ),help_default = switch .terminal_default or switch .default ,full = sw .env_words (name )) 134for switch in applicable for name ,_ in switch .env ] 135 136 137def argv_to_dict (argv :list [Any ])-> dict [str ,str ]: 138"""`["--kv", "int8", "--kv-grow"]` -> {"--kv": "int8", "--kv-grow": ""}.""" 139out :dict [str ,str ]= {} 140items = [str (x )for x in argv ] 141i = 0 142while i < len (items ): 143tok = items [i ] 144if tok .startswith ("--" ): 145if i + 1 < len (items )and not items [i + 1 ].startswith ("--" ): 146n = 1 147while n < MULTI_VALUE_FLAGS .get (tok ,1 )and i + 1 + n < len (items )and not items [i + 1 + n ].startswith ("--" ): 148n += 1 149out [tok ]= " " .join (items [i + 1 :i + 1 + n ]) 150i += 1 + n 151continue 152out [tok ]= "" 153i += 1 154return out 155 156 157@dataclass 158class Row : 159name :str 160default :str 161tuned :str 162yours :str 163description :str 164experimental :bool 165known :bool = True 166 167def cells (self )-> tuple [str ,str ,str ,str ]: 168return (self .name ,self .default or "-" ,self .tuned or "-" ,self .yours or "-" ) 169 170 171def build_rows (engine_help :str | None ,base_args :list [Any ],tuned_args :list [Any ]| None ,base_env :dict | None , 172tuned_env :dict | None ,extra :dict [str ,str ],switches :list [Param ]| None = None )-> list [Row ]: 173"""The table. Settings the run config or the tuner use come first (what this launch really runs), then the rest.""" 174base ,tuned = argv_to_dict (base_args ),argv_to_dict (tuned_args if tuned_args is not None else base_args ) 175params = {p .name :p for p in (parse_help (engine_help )if engine_help else [])} 176for p in env_params (): 177params .setdefault (p .name ,p ) 178for p in switches or []: 179params [p .name ]= p 180switch_order = {p .name :i for i ,p in enumerate (switches or [])} 181names = list (dict .fromkeys ([* base ,* tuned ,* (base_env or {}),* (tuned_env or {}),* extra ,* params ])) 182rows :list [Row ]= [] 183for name in names : 184p = params .get (name ) 185is_env = not name .startswith ("--" ) 186d = (base_env or {}).get (name )if is_env else base .get (name ) 187t = (tuned_env or {}).get (name )if is_env else tuned .get (name ) 188if d is None : 189d = (p .help_default if p and p .help_default else ("off" if is_env else "" )) 190if is_env : 191t = t if t is not None else d 192else : 193t = t if t is not None else "" 194shown = lambda v :"on" if v == "" and not is_env and name in (base if v is d else tuned )else v # noqa: E731 195y = extra .get (name ,"" ) 196rows .append (Row (name = name ,default = str (d )if d else "" ,tuned = str (t )if t else "" ,yours = str (y ), 197description = ((p .full or p .short )if p else "(not in this engine's list: newer flag or a typing mistake)" ), 198experimental = bool (p and p .experimental ),known = bool (p )or not params )) 199in_use = lambda r : (r .name in base or r .name in tuned or r .name in extra or r .name in (base_env or {})or r .name in (tuned_env or {}))# noqa: E731 200rows .sort (key = lambda r : (not in_use (r ),switch_order .get (r .name ,len (switch_order )),r .name )) 201return rows 202 203 204def check_name (name :str ,engine_flags :list [str ]| None )-> str | None : 205"""A warning (never a refusal) for a flag the engine's list does not have.""" 206if not name .startswith ("--" )or not engine_flags : 207return None 208if name in engine_flags : 209return None 210from strata_cli .launch .settings import closest 211near = closest (name ,engine_flags ) 212return (f"This engine does not list { name } . " + (f"Did you mean { near } ? " if near else "" ) 213+ "It is kept as you typed it; a newer engine may know it, and this one may refuse to start with it." ) 214 215 216def flag_list (engine :str | Path | None )-> list [str ]| None : 217"""The engine's flags (the tuner's own read), or None when no engine can be run here.""" 218if not engine : 219return None 220try : 221from strata_control import tuning 222return tuning .engine_flag_inventory (Path (engine )) 223except Exception :# noqa: BLE001 224return None 225 226def engine_help_text (engine :str | Path | None )-> str | None : 227if not engine : 228return None 229import subprocess 230try : 231from strata_control import tuning 232proc = subprocess .run ([* tuning .engine_command (Path (engine )),"--help" ],capture_output = True ,text = True ,errors = "replace" ,timeout = 20 , 233env = tuning .engine_env (Path (engine ))) 234except Exception :# noqa: BLE001 235return None 236text = f" { proc . stdout or '' } \n { proc . stderr or '' } " 237return text if "--" in text else None