okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
16.0 KiB332 linesraw
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)."""
42    gb = float(vram_gb or 0.0)
43    for floor, n in PARALLEL_BY_VRAM:
44        if gb >= floor - 0.5:
45            return n
46    return 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)."""
51    raw = str(text).strip().lower().replace(" ", "").replace("_", "").replace(",", "")
52    m = re.fullmatch(r"(\d+(?:\.\d+)?)(k|m)?", raw)
53    if not m:
54        raise ValueError(f"'{text}' is not a context size. Use a number of tokens or a size such as 32k, 64k, 128k, 256k.")
55    value = float(m.group(1)) * {"k": 1024, "m": 1024 * 1024, None: 1}[m.group(2)]
56    n = int(round(value))
57    if n < 1024:
58        raise ValueError(f"A context of {n} tokens is too small to be useful; the smallest size offered is 8k.")
59    return n
60
61
62def context_label(tokens: int | None) -> str:
63    if not tokens:
64        return "default"
65    if tokens >= 1048576 and tokens % 1048576 == 0:        # 1,048,576 positions: "1M"
66        return f"{tokens // 1048576}M"
67    if tokens % 1024 == 0:
68        return f"{tokens // 1024}K"
69    if tokens >= 1000:
70        return f"{tokens / 1000:g}K"
71    return 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)."""
76    words = tokens * 0.75
77    mag = 10 ** max(0, len(str(int(words))) - 2)
78    return 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
85    name: str | None = None                    # the saved preset's name
86    family: str | None = None                  # catalog family id (qwen, swift, coder, unsloth, gyro, nvfp4...)
87    model: str | None = None                   # catalog size (IQ3_XXS ...)
88    model_path: str | None = None              # "Use model files I already have": a .gguf file or a folder
89    data_dir: str | None = None                # where model files are stored (None: the Strata default)
90    gpus: list[int] | None = None              # None = the engine's choice (all usable cards)
91    gpu_roles: dict[str, str] | None = None    # {"1": "main", "0": "helper", "2": "off"}: a role for every card; None = the recommendation
92    context: int | None = None
93    kv: str | None = None                      # None = int8 above 8K, as setup
94    vision: str | None = None                  # None = the default (on when the model can read pictures and the engine has the reader), off | on | gpu | cpu
95    parallel: int | None = None                # None = fit to the card
96    drafting: str | None = None                # None = Auto (recommended): the table in strata_control/drafting.py; mtp | dflash2 | off choose one. Saved in the launch config
97    split_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
98    mtp: str | None = None                     # None = as installed (draft layer on); "off" starts without it (less graphics memory and RAM, slower); "on" overrides an installed "off"
99    tune: str = "skip"                         # quick | thorough | skip
100    tune_allow_small: bool = False             # the "answer-changing" tick, off by default, as in the app
101    access: str = "local"
102    port: int = DEFAULT_PORT
103    api_key: str | None = None                 # never shown whole; stored only in the private preset file
104    no_key: bool = False                       # served beyond this computer without a key, on purpose (--no-api-key); a warning, never a refusal
105    extra: 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
107    tuned_preset: str | None = None            # id of the tuning preset the tuner saved
108    tuned_at: str | None = None
109    last_used: str | None = None
110    created: str | None = None
111
112    @property
113    def 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
115        fastest (only tuned_at is set). Either way the next start must not tune again."""
116        return bool(self.tuned_preset or self.tuned_at)
117
118    def to_dict(self, *, with_key: bool = True) -> dict[str, Any]:
119        d = {"schema": SCHEMA, **asdict(self)}
120        if not with_key:
121            d["api_key"] = "set" if self.api_key else None
122        return d
123
124    @classmethod
125    def from_dict(cls, data: dict[str, Any]) -> "LaunchSettings":
126        known = {f.name for f in fields(cls)}
127        clean = {k: v for k, v in (data or {}).items() if k in known}
128        if isinstance(clean.get("extra"), dict):
129            clean["extra"] = {str(k): str(v) for k, v in clean["extra"].items()}
130        else:
131            clean.pop("extra", None)
132        return cls(**clean)
133
134    def copy(self, **changes: Any) -> "LaunchSettings":
135        d = asdict(self)
136        d.update(changes)
137        return LaunchSettings.from_dict(d)
138
139
140# ----------------------------------------------------------------------------------------------------- checks
141
142@dataclass
143class Notice:
144    level: str        # "warn" | "error"
145    text: str         # plain words: what it means
146    next: str = ""    # plain words: what to do
147    after_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
149    def line(self) -> str:
150        return self.text + (f" {self.next}" if self.next else "")
151
152
153def closest(word: str, options: list[str]) -> str | None:
154    hit = difflib.get_close_matches(word.lower(), [o.lower() for o in options], n=1, cutoff=0.5)
155    if not hit:
156        return None
157    return next(o for o in options if o.lower() == hit[0])
158
159
160def check_port(port: Any) -> Notice | None:
161    try:
162        p = int(port)
163    except (TypeError, ValueError):
164        return Notice("error", f"'{port}' is not a port number.", "Use a number from 1 to 65535, for example 8080.")
165    if not 1 <= p <= 65535:
166        return Notice("error", f"Port {p} does not exist.", "Use a number from 1 to 65535, for example 8080.")
167    if p < 1024:
168        return Notice("warn", f"Port {p} is below 1024; on many computers only an administrator can use it.",
169                      "8080 works without special rights.")
170    return 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]:
179    out: list[Notice] = []
180    if s.access not in ACCESS_KINDS:
181        near = closest(s.access, list(ACCESS_KINDS))
182        out.append(Notice("error", f"'{s.access}' is not a way to share Strata.",
183                          f"Choose one of: {', '.join(ACCESS_KINDS)}." + (f" Did you mean '{near}'?" if near else "")))
184        return out
185    port = check_port(s.port)
186    if port:
187        out.append(port)
188    if s.access != "local" and not s.api_key:
189        if s.access == "cloudflare":
190            out.append(Notice("warn", NO_KEY_PUBLIC, "Leave --no-api-key out to get a key."))
191        elif s.no_key:
192            out.append(Notice("warn", NO_KEY_NETWORK, "Leave --no-api-key out to get a key."))
193        else:
194            out.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)."))
196    return out
197
198
199def check_parallel(s: LaunchSettings, *, vram_gb: float | None, fitted: int | None = None) -> list[Notice]:
200    out: list[Notice] = []
201    if s.parallel is None:
202        return out
203    if not 1 <= int(s.parallel) <= 8:
204        out.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."))
206        return out
207    fitted = fit_parallel(vram_gb) if fitted is None else fitted
208    if vram_gb and s.parallel > fitted:
209        out.append(Notice("warn", f"{s.parallel} requests at once is more than a {vram_gb:.0f} GB card usually holds "
210                                  f"(it fits {fitted}).",
211                          "It can still start; the engine keeps less of the model in graphics memory, so each answer is slower."))
212    return out
213
214
215def check_context(s: LaunchSettings, *, max_fit_tokens: int | None = None) -> list[Notice]:
216    out: list[Notice] = []
217    if s.context is not None and s.context > 262144:
218        out.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."))
220    if max_fit_tokens and s.context and s.context > max_fit_tokens:
221        out.append(Notice("warn", f"{context_label(s.context)} is bigger than this computer's memory comfortably holds.",
222                          f"{context_label(max_fit_tokens)} is the recommended size."))
223    return 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."""
234    key, sep, value = text.partition("=")
235    key = key.strip()
236    if not key:
237        raise ValueError("an empty setting name")
238    if _ENV_NAME.match(key):
239        return key, value.strip()
240    flag = key[2:] if key.startswith("--") else key
241    flag = flag.replace("_", "-")
242    if not _FLAG_NAME.match(flag):
243        raise ValueError(f"'{text}' is not a setting name. Write it like prefill=65536 or STRATA_PIN_BY_NEED=1.")
244    return "--" + flag, value.strip()
245
246
247def settings_from_pairs(pairs: list[str]) -> dict[str, str]:
248    out: dict[str, str] = {}
249    for p in pairs or []:
250        k, v = split_setting(p)
251        out[k] = v
252    return 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],
260                    word_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
263    A flag without a value (or on/true/yes) is "present"; off/false/no/none removes it; anything else is a value.
264    A word-valued option (WORD_VALUE_FLAGS) keeps its word."""
265    args: dict[str, Any] = {}
266    env: dict[str, str | None] = {}
267    for key, value in extra.items():
268        if key.startswith("--"):
269            low = value.lower()
270            if key in word_flags and key not in bool_flags:
271                if low:
272                    args[key] = low
273                continue                          # an empty value is no change, as for every option that takes one (#3504)
274            if low == "" and key not in bool_flags:
275                continue                          # an empty value for an option that takes one is no change, never a bare flag (#3504)
276            if key in bool_flags or low in ("on", "true", "yes", ""):
277                args[key] = None if low in ("off", "false", "no", "none") else True
278            elif low in ("off", "false", "no", "none"):
279                args[key] = None
280            else:
281                args[key] = value
282        else:
283            env[key] = None if value.lower() in ("off", "unset", "none") else value
284    return 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)."""
289    parts = ["strata launch"]
290    if preset:
291        parts.append(f'--preset "{preset}"')
292    else:
293        if s.model_path:
294            parts.append(f'--model-path "{s.model_path}"')
295        if s.model:                                   # own files the table recognised say which model they are, so the line stays exact
296            parts.append(f"--model {s.model.lower()}" + (f" --family {s.family}" if s.family and s.family != "qwen" else ""))
297        if s.data_dir:
298            parts.append(f'--data-dir "{s.data_dir}"')
299        if s.context:
300            parts.append(f"--context {context_label(s.context).lower()}")
301        if s.kv:
302            parts.append(f"--kv {s.kv}")
303        if s.vision:
304            parts.append(f"--vision {s.vision}")
305        if s.parallel:
306            parts.append(f"--parallel {s.parallel}")
307        if s.mtp:
308            parts.append(f"--mtp {s.mtp}")
309        if s.drafting:
310            parts.append(f"--drafting {s.drafting}")
311        if s.split_engine:
312            parts.append(f"--split-engine {s.split_engine}")
313        parts.append(f"--tune {s.tune}")
314        if s.tune_allow_small:
315            parts.append("--tune-allow-small")
316        parts.append(f"--access {s.access}")
317        parts.append(f"--port {s.port}")
318        if s.gpu_roles:
319            parts.append("--gpu-roles " + ",".join(f"{k}={v}" for k, v in sorted(s.gpu_roles.items(), key=lambda kv: int(kv[0]))))
320        elif s.gpus:
321            parts.append("--gpu " + ",".join(str(g) for g in s.gpus))
322    for k, v in sorted(s.extra.items()):
323        parts.append(f"--set {k[2:] if k.startswith('--') else k}={v}" if v else f"--set {k[2:] if k.startswith('--') else k}")
324    return " ".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."""
329    text = re.sub(r"-{2,}", "-", re.sub(r"[^a-z0-9_-]+", "-", name.lower())).strip("-_") or "launch"
330    if not text[0].isalpha():
331        text = "l" + text
332    return text[:48]