okami.mom/strata

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

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

main
11.0 KiB177 linesraw
1"""The speed features of 0.2.7 that have a switch in the app's Expert settings and in the Terminal's Advanced table.
2
3A switch has a default (``on`` or ``off``).  In its other state it writes exactly the engine environment below into the model's run config ("env"); back in
4its default it removes those entries, so a default launch carries none of them and is byte for byte what 0.2.6 started.  The names are the engine switch
5contract (phaseA-tests/notes-027-plan.md).  The app does the same in apps/host/server/native-settings.mjs (SPEED_SWITCHES); tests/terminal/test_speed_switches.py
6reads that file and fails when the two disagree, so the Terminal and the app cannot drift apart.
7
8- "Faster long prompts" (Qwen KVA) is OFF by default (owner decision, 26 October): ``STRATA_KVA=1`` turns it on.  A file that holds ``STRATA_KVA=0`` (the
9  off switch of an earlier 0.2.7 test build) reads as off, which is what it is now.
10- "Faster answers on 12 GB NVIDIA cards" (residency-biased routing) is OFF by default since 0.2.8 (owner decision, 29 October; #4402: it can repeat itself
11  and give weaker results in long agent sessions): ``STRATA_ROUTE_PRIOR=1.5`` turns it on.  The ``STRATA_ROUTE_PRIOR=0`` that 0.2.7's Off wrote is the default state now.
12- "Faster answers on Radeon RX 9000 / AI PRO R9700" is ON by default; turning it off writes its entry.
13
14The Terminal shows the switches as rows of its Advanced table (strata_cli/launch/params.py), only where they apply: ``strata launch --set STRATA_KVA=1``
15turns "Faster long prompts" on, ``--set STRATA_KVA=off`` puts the default back (the same as removing the row).
16"""
17
18from __future__ import annotations
19
20import re
21from dataclasses import dataclass
22from typing import Any, Iterable, Mapping
23
24
25@dataclass(frozen=True)
26class Switch:
27    id: str
28    label: str                    # the words the app shows
29    effect: str                   # one plain sentence: what it does and what the other choice does
30    env: tuple[tuple[str, str], ...]   # the environment entries written when the switch is NOT in its default state
31    only: str                     # "qwen-gpu" | "qwen-cuda-12gb" | "qwen-radeon-9000" | "qwen-any": where it applies
32    default: str = "on"           # "on" | "off": what a launch without the entries does
33    legacy: tuple[tuple[str, str], ...] = ()    # entries an earlier 0.2.7 test build wrote for the same state: they read as the switch being set, and are removed with it
34    terminal_only: bool = False   # shown in the Terminal's Advanced table only, never in the app
35    group: str = "Speed"          # the app's group of Expert settings the row is shown in
36    words: tuple[tuple[str, str], ...] = ()   # ("on", ...), ("off", ...): the app's two option names instead of On / Off (the default one says "(recommended)")
37    terminal_default: str = ""    # the Terminal's Default cell for the row, when "on" / "off" would not say it
38
39
40SWITCHES: tuple[Switch, ...] = (
41    Switch("faster_long_prompts", "Faster long prompts",
42           "Reads very long prompts faster by approximating part of the work. Off by default: answers about long documents can miss or mix up details.",
43           (("STRATA_KVA", "1"),), "qwen-gpu", default="off"),
44    Switch("faster_12gb_nvidia", "Faster answers on 12 GB NVIDIA cards",
45           "Prefers the parts of the model already on the graphics card, which makes answers faster on 12 GB cards. Off by default: in long agent sessions it can repeat itself and give weaker results. Turn on if you mostly chat and want the speed.",
46           (("STRATA_ROUTE_PRIOR", "1.5"),), "qwen-cuda-12gb", default="off"),
47    Switch("faster_radeon_9000", "Faster answers on Radeon RX 9000 / AI PRO R9700",
48           "Shares the work between the graphics card and the processor in a way that makes answers faster on these cards. "
49           "Turn off to go back to the previous setting, which is slower.",
50           (("STRATA_PCIE_FRAC_DEFAULT", "old"),), "qwen-radeon-9000"),
51    # The picture reader (owner 11-11: "Our tower, the other selectable"): Strata's own by default (strata-vision's `auto`: ours where it was measured no slower
52    # and correct, llama.cpp's by itself where it was measured slower or does not start); STRATA_VISION_TOWER=mtmd picks llama.cpp's mtmd reader.  The server
53    # hands the run config's env to the reader, and an older strata-vision ignores the name.  Label, options and help line approved by the owner 11-11 morning
54    # (par/OWNER-WORDING-1111.md); the Terminal row's frame (env_words) is still [DRAFT].
55    Switch("picture_reader", "Picture reader",
56           "Which program turns pictures into something the model can read. Strata's own is faster on most computers and reads very large pictures correctly; "
57           "on a few graphics cards where it is still slower, Strata uses llama.cpp's by itself. Choose llama.cpp's if pictures look misread.",
58           (("STRATA_VISION_TOWER", "mtmd"),), "qwen-pictures", group="Image reading",
59           words=(("on", "Strata's own (recommended)"), ("off", "llama.cpp's")), terminal_default="auto"),
60    # Troubleshooting only, in the Terminal's Advanced table and nowhere else: every Qwen 0.2.7 default back to its 0.2.6 behaviour.
61    Switch("qwen_defaults_026", "Qwen: 0.2.6 behaviour",
62           "Starts every Qwen speed setting new in 0.2.7 the way 0.2.6 did, for troubleshooting. Use it if something that worked before no longer does.",
63           (("STRATA_DEFAULTS", "026"),), "qwen-any", default="off", terminal_only=True),
64)
65
66BY_ID = {s.id: s for s in SWITCHES}
67
68_GFX12 = re.compile(r"^gfx120[01]$", re.IGNORECASE)
69_RADEON_9000 = re.compile(r"\b(?:RX\s*9\d{3}|AI\s*PRO\s*R97\d{2}|R97\d{2})\b", re.IGNORECASE)
70
71
72def _small_nvidia(gpus: Iterable[Mapping[str, Any]] | None) -> bool:
73    """A discrete NVIDIA card of 13 GiB or less (the engine's rule for residency-biased routing: not an integrated chip, not a card that shares system memory)."""
74    for g in gpus or []:
75        if g.get("usable") is False or g.get("uma") or g.get("integrated") or (g.get("unified_gb") or 0) > 0:
76            continue
77        vendor = str(g.get("vendor") or "").lower()
78        if vendor not in ("nvidia", "") or (vendor == "" and not re.search(r"nvidia|geforce|\brtx\b|\bgtx\b|quadro|tesla", str(g.get("name") or ""), re.IGNORECASE)):
79            continue
80        vram = float(g.get("vram_gb") or 0)
81        if 0 < vram <= 13.0:
82            return True
83    return False
84
85
86def _radeon_9000(gpus: Iterable[Mapping[str, Any]] | None) -> bool:
87    for g in gpus or []:
88        if g.get("vendor") not in (None, "", "amd"):
89            continue
90        arch = str(g.get("arch") or "")
91        if _GFX12.match(arch) or (not arch and _RADEON_9000.search(str(g.get("name") or ""))):
92            return True
93    return False
94
95
96def applies(switch: Switch | str, cfg: Mapping[str, Any] | None, gpus: Iterable[Mapping[str, Any]] | None, backend: str | None = None) -> bool:
97    """Does the switch make sense for this model on this PC? ``backend`` is the engine's (cuda, hip, sycl, metal, cpu); the run config's own wins.
98    "Faster long prompts" is for Qwen3.8-Flash-Next models only (a config without an "arch")."""
99    sw = BY_ID[switch] if isinstance(switch, str) else switch
100    from strata_control import retired
101    if retired.config_reason(cfg):                   # a DeepSeek config (strata_control/retired.py): this Strata does not run it
102        return False
103    if sw.only == "qwen-any":
104        return True
105    if sw.only == "qwen-pictures":
106        # a Qwen run config that reads pictures (its "vision" section starts strata-vision)
107        return bool((cfg or {}).get("vision"))
108    backend = (cfg or {}).get("backend") or backend
109    if sw.only == "qwen-gpu":
110        # KVA was measured on the Qwen3.8-Flash-Next shape (48 layers, 512 experts); the engine declines any other.  Setup writes "arch" only for the
111        # families with an engine path of their own (Qwen3.6-35B-A3B: qwen35moe), so a Flash-Next config (the original, Swift, Coder, Unsloth, Gyro, NVFP4) has none.
112        return not (cfg or {}).get("arch") and backend in ("cuda", "hip")
113    if sw.only == "qwen-cuda-12gb":
114        # the engine's residency-biased routing needs the Flash-Next shape (512 experts, top-10) and a CUDA build; a Qwen3.6 config has an "arch"
115        return not (cfg or {}).get("arch") and backend == "cuda" and _small_nvidia(gpus)
116    if sw.only == "qwen-radeon-9000":
117        return backend == "hip" and _radeon_9000(gpus)
118    return False
119
120
121def applicable(cfg: Mapping[str, Any] | None, gpus: Iterable[Mapping[str, Any]] | None, backend: str | None = None) -> list[Switch]:
122    gpus = list(gpus or [])
123    return [s for s in SWITCHES if applies(s, cfg, gpus, backend)]
124
125
126def app_switches() -> list[Switch]:
127    """The switches the app shows (apps/host/server/native-settings.mjs SPEED_SWITCHES): all but the Terminal-only ones."""
128    return [s for s in SWITCHES if not s.terminal_only]
129
130
131def is_set(env: Mapping[str, Any] | None, switch: Switch | str) -> bool:
132    """Every entry the switch writes is there with its value (the switch is out of its default).  A file with only some of them, or other values
133    (``STRATA_KVA=0``), is in the default state and is left alone."""
134    sw = BY_ID[switch] if isinstance(switch, str) else switch
135    have = lambda entries: bool(entries) and all((env or {}).get(name) == value for name, value in entries)   # noqa: E731
136    return have(sw.env) or have(sw.legacy)
137
138
139def is_on(env: Mapping[str, Any] | None, switch: Switch | str) -> bool:
140    """Is the feature on for a launch with this environment?"""
141    sw = BY_ID[switch] if isinstance(switch, str) else switch
142    return is_set(env, sw) != (sw.default == "on")
143
144
145def set_switch(env: Mapping[str, Any] | None, switch: Switch | str, on: bool) -> dict[str, Any]:
146    """The environment with the feature on or off: the default state removes the switch's entries, the other one writes them. Nothing else changes."""
147    sw = BY_ID[switch] if isinstance(switch, str) else switch
148    out = dict(env or {})
149    write = on != (sw.default == "on")
150    for name, value in sw.env:
151        if write:
152            out[name] = value
153        else:
154            out.pop(name, None)
155    if not write:
156        for name, _ in sw.legacy:
157            out.pop(name, None)
158    return out
159
160
161def env_names() -> dict[str, Switch]:
162    """Every environment name a switch writes -> its switch."""
163    return {name: sw for sw in SWITCHES for name, _ in sw.env}
164
165
166def env_words(name: str) -> str:
167    """The plain sentence of one environment row of the Terminal's Advanced table."""
168    sw = env_names()[name]
169    value = dict(sw.env)[name]
170    together = f"; all {len(sw.env)} speed-up rows go together" if len(sw.env) > 1 else ""
171    if sw.words:
172        names = {state: word.replace(" (recommended)", "") for state, word in sw.words}
173        other = "off" if sw.default == "on" else "on"
174        return f"{sw.label} ({names[sw.default]} by default; set {value} to use {names[other]}). {sw.effect}"   # [DRAFT] frame, not yet seen by the owner
175    if sw.default == "off":
176        return f"{sw.label} (off by default; set {value} to turn on{together}). {sw.effect}"
177    return f"{sw.label} (on by default; set {value} to turn off{together}). {sw.effect}"