okami.mom/strata

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

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

main
11.4 KiB237 linesraw
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."""
53    if name in PLAIN:
54        return PLAIN[name]
55    cleaned = _CODE.sub("", text or "").strip(" :;,-")
56    cleaned = re.sub(r"\(\s*\)", "", cleaned).strip()
57    cleaned = re.sub(r"\s{2,}", " ", cleaned)
58    return 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:
63    name: str                       # --flag or ENV_NAME
64    kind: str                       # "flag" | "env"
65    metavar: str = ""
66    description: str = ""
67    help_default: str | None = None
68    experimental: bool = False
69    values: list[str] = field(default_factory=list)
70    full: str = ""                  # a sentence that is shown whole (the speed switches); empty: the first sentence of the description
71
72    @property
73    def short(self) -> str:
74        """One line: the first sentence, cut at 70 characters."""
75        text = re.sub(r"\s+", " ", re.sub(r"\([^)]*\)", "", self.description)).strip()
76        cut = re.split(r"(?<=[.;:])\s", text, maxsplit=1)[0] if text else ""
77        cut = plain_description(self.name, cut.rstrip(".;:")).rstrip(".;:")
78        return 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)."""
83    params: dict[str, Param] = {}
84    current: Param | None = None
85    for line in text.splitlines():
86        m = _ENTRY.match(line)
87        if m and not line.startswith("   "):
88            name, gap, rest = m.group(1), m.group(2) or "", m.group(3) or ""
89            meta, desc = "", rest
90            if len(gap) == 1:                              # "--pack DIR      the pack": one space, a value name, a gap
91                parts = re.split(r" {2,}", rest, maxsplit=1)
92                meta, desc = (parts[0], parts[1]) if len(parts) == 2 else (parts[0], "")
93            p = params.get(name)
94            if p is None:
95                p = params[name] = Param(name=name, kind="flag", metavar=meta, description=desc.strip())
96            else:
97                p.description = (p.description + " " + desc.strip()).strip()
98                p.metavar = p.metavar or meta
99            if meta and "|" in meta:
100                p.values = sorted(set(p.values + meta.split("|")))
101            current = p
102        elif current is not None and line.startswith("    ") and line.strip():
103            current.description += " " + line.strip()
104        elif not line.strip():
105            current = None
106    for p in params.values():
107        p.description = re.sub(r"\s+", " ", p.description).strip()
108        p.experimental = bool(_EXPERIMENTAL.search(p.description))
109        d = _DEFAULT.search(p.description)
110        if d:
111            p.help_default = (d.group(1) or "").strip().rstrip(".,;") or None
112    return 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."""
117    try:
118        from strata_control import tune_knobs
119    except ImportError:
120        return []
121    out: dict[str, Param] = {}
122    for arm in tune_knobs.ARMS:
123        for key in arm.env:
124            if key not in out:
125                out[key] = Param(name=key, kind="env", description=arm.label, experimental=arm.answer != "exact")
126    return 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,
131    shown 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."""
132    from strata_control import speed_switches as sw
133    return [Param(name=name, kind="env", description=sw.env_words(name), help_default=switch.terminal_default or switch.default, full=sw.env_words(name))
134            for 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": ""}."""
139    out: dict[str, str] = {}
140    items = [str(x) for x in argv]
141    i = 0
142    while i < len(items):
143        tok = items[i]
144        if tok.startswith("--"):
145            if i + 1 < len(items) and not items[i + 1].startswith("--"):
146                n = 1
147                while n < MULTI_VALUE_FLAGS.get(tok, 1) and i + 1 + n < len(items) and not items[i + 1 + n].startswith("--"):
148                    n += 1
149                out[tok] = " ".join(items[i + 1:i + 1 + n])
150                i += 1 + n
151                continue
152            out[tok] = ""
153        i += 1
154    return out
155
156
157@dataclass
158class Row:
159    name: str
160    default: str
161    tuned: str
162    yours: str
163    description: str
164    experimental: bool
165    known: bool = True
166
167    def cells(self) -> tuple[str, str, str, str]:
168        return (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,
172               tuned_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."""
174    base, tuned = argv_to_dict(base_args), argv_to_dict(tuned_args if tuned_args is not None else base_args)
175    params = {p.name: p for p in (parse_help(engine_help) if engine_help else [])}
176    for p in env_params():
177        params.setdefault(p.name, p)
178    for p in switches or []:
179        params[p.name] = p
180    switch_order = {p.name: i for i, p in enumerate(switches or [])}
181    names = list(dict.fromkeys([*base, *tuned, *(base_env or {}), *(tuned_env or {}), *extra, *params]))
182    rows: list[Row] = []
183    for name in names:
184        p = params.get(name)
185        is_env = not name.startswith("--")
186        d = (base_env or {}).get(name) if is_env else base.get(name)
187        t = (tuned_env or {}).get(name) if is_env else tuned.get(name)
188        if d is None:
189            d = (p.help_default if p and p.help_default else ("off" if is_env else ""))
190        if is_env:
191            t = t if t is not None else d
192        else:
193            t = t if t is not None else ""
194        shown = lambda v: "on" if v == "" and not is_env and name in (base if v is d else tuned) else v     # noqa: E731
195        y = extra.get(name, "")
196        rows.append(Row(name=name, default=str(d) if d else "", tuned=str(t) if t else "", yours=str(y),
197                        description=((p.full or p.short) if p else "(not in this engine's list: newer flag or a typing mistake)"),
198                        experimental=bool(p and p.experimental), known=bool(p) or not params))
199    in_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
200    rows.sort(key=lambda r: (not in_use(r), switch_order.get(r.name, len(switch_order)), r.name))
201    return 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."""
206    if not name.startswith("--") or not engine_flags:
207        return None
208    if name in engine_flags:
209        return None
210    from strata_cli.launch.settings import closest
211    near = closest(name, engine_flags)
212    return (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."""
218    if not engine:
219        return None
220    try:
221        from strata_control import tuning
222        return tuning.engine_flag_inventory(Path(engine))
223    except Exception:                                        # noqa: BLE001
224        return None
225
226def engine_help_text(engine: str | Path | None) -> str | None:
227    if not engine:
228        return None
229    import subprocess
230    try:
231        from strata_control import tuning
232        proc = subprocess.run([*tuning.engine_command(Path(engine)), "--help"], capture_output=True, text=True, errors="replace", timeout=20,
233                              env=tuning.engine_env(Path(engine)))
234    except Exception:                                        # noqa: BLE001
235        return None
236    text = f"{proc.stdout or ''}\n{proc.stderr or ''}"
237    return text if "--" in text else None