okami.mom/strata

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

Niko1221Merge f-container-mem-core: memory checks that read a container's limit correctly6b63729a9

main
43.2 KiB687 linesraw
1"""strata-split: when the all-cards split engine may run, and the run config for it. AUTOMATIC by default (mode "auto"), with an off switch.
2
3`strata-split-N` (src/split, from sFNX, MIT, Copyright (c) 2026 John Fink) gives every card a share of EVERY layer instead of some
4layers, and the cards exchange the layer sums through page-locked host memory (no peer access anywhere). On two RTX A6000 with
5UD-Q4_K_XL it decodes 40-95% faster than the normal layer split (phaseA-tests/sfnx/RESULTS.md). The owner's decision: it runs by itself whenever the
6rule below says yes ("auto", the default), and `strata launch --split-engine off` (or "split_engine": "off" in the run config, or
7STRATA_SPLIT_ENGINE=0) turns it off; "on" asks for it and says why in one line when it cannot run. In auto a "no" is silent: the normal
8layer split starts, as before.
9
10This module is pure (no I/O besides reading GGUF directories): the launcher passes it facts and gets a Decision. The rule, from what
11has actually been run:
12
13  - not turned off (mode(): "auto" by default; "on" is the same rule but a refusal is reported; "off" never);
14  - Linux, 2 to 4 cards of ONE make (NVIDIA, or AMD RDNA4 gfx1201: the R9700 and RX 9070), all the same model of card and memory size;
15  - a card architecture and card count that have been run (TESTED, per make): NVIDIA sm_86 on 2 cards, AMD gfx1201 on 4 cards. Others build
16    but stay off unless the caller says allow_untested (testers); the Decision says which part is untested in plain words;
17  - AMD gfx1201 is automatic like NVIDIA (the owner's decision: default on for two or more cards, off with `--split-engine off`); AUTO_SPLIT_AMD_ARCHS is the
18    one constant that says which AMD architectures start it by themselves, every other AMD architecture keeps the layer split silently;
19  - the GGUF is a set the engine reads (checked from the file's tensor types, not its name), the Qwen3.8-Flash-Next shapes (48 layers,
20    512 experts): routed experts Q4_K/Q5_K/Q5_1/Q8_0/Q4_0 (UD-Q4_K_XL, Q8_0) or the i-quants IQ2_S/IQ3_XXS/IQ3_S/IQ4_XS/IQ4_NL and Strata's
21    Q2_0 (UD-IQ4_XS, the IQ3_S set); token embeddings, shared expert, output head Q8_0, or, in a set with i-quant or Q2_0 experts,
22    any type the loader converts to Q8_0/F32 when it reads the file (src/split/src/tensor_convert.hpp);
23  - ALL routed experts fit in the cards' memory (the expert cache is off: with it the engine keeps a 74 GiB pinned copy of the
24    experts in RAM) and the RAM that stays (the 27.5 GiB locked embedding table, a few GiB of buffers and the conversation cache)
25    is available with room to spare;
26  - context at most TESTED_CONTEXT (128K).
27Anything else: use_split False and one plain line saying why. The server also falls back to the normal layer split if the split
28engine refuses or fails to start (serve/server.py, "split_fallback").
29"""
30
31from __future__ import annotations
32
33import dataclasses
34import pathlib
35import re
36
37# What has been run with the host exchange, per make: {make: {architecture: card counts}}.  NVIDIA: 2x RTX A6000 (boston, sm_86), 2x RTX PRO 6000 (srv118, sm_120).
38# AMD: 4x Radeon AI PRO R9700 (r9700, gfx1201; phaseA-tests/sfnx/RESULTS-HIP.md): 4 cards with UD-Q4_K_XL, 3 cards with the IQ3_S set, 2 cards with the IQ3_S set at 8K context and 2 slots only
39# (the memory rule below refuses that by its estimate; the counts here say the engine has run on them).
40TESTED = {"nvidia": {"sm_86": (2,), "sm_120": (2,)}, "amd": {"gfx1201": (2, 3, 4)}}
41# the engine package's kernels (one binary per card count with a code object for each AMD architecture): any other card is refused. AMD beyond gfx1201 is EXPERIMENTAL: only an explicit
42# `--split-engine on` starts it there (never auto), and the engine runs its kernel self-test on the card before it loads the model (src/split/src/hip/selftest_policy.hpp)
43BUILT_ARCHS = {"nvidia": ("sm_86", "sm_120"), "amd": ("gfx1100", "gfx1101", "gfx1102", "gfx1103", "gfx1200", "gfx1201")}
44TESTED_CARD_COUNTS = (2,)          # run with the host exchange: 2 cards (boston, 2x RTX A6000; srv118, 2x RTX PRO 6000)
45TESTED_ARCHS = (86, 120)           # compute capability: sm_86 (the 61-task suite, pictures, hashes) and sm_120 (decode, prompts, parallel, hashes,
46                                   # pictures; no suite there)
47MODES = ("auto", "on", "off")
48#: cards (compute capability) on which Auto drafting resolves to split + MTP rather than layer split + DFlash2: the split decodes faster there
49#: (phaseA-tests/sfnx/RESULTS.md section 17). Another card is not auto-split at all (TESTED_ARCHS), so it keeps Auto = layer split + DFlash2.
50AUTO_SPLIT_BEATS_DFLASH2 = (86, 120)
51#: AMD architectures on which mode "auto" starts the split engine (owner, 2026-11-02: default on for two or more cards, `--split-engine off` turns it off). The one flip: take an
52#: architecture out of this tuple and auto keeps the layer split there while `--split-engine on` still runs the split.
53AUTO_SPLIT_AMD_ARCHS: tuple = ("gfx1201",)
54#: card counts on which mode "auto" starts it on those architectures. Four: on 2 and 3 R9700 with the IQ3_S set the split is slower than the layer split today (RESULTS-HIP.md
55#: section 7), and Auto must not pick a slower path. `--split-engine on` is not limited by this.
56AUTO_SPLIT_AMD_CARD_COUNTS: tuple = (4,)
57#: routed-expert types for which mode "auto" starts it on AMD: the UD-Q4_K_XL family and the IQ3_S set (i-quant and Q2_0 experts). With the shared expert fused into the routed launches
58#: (round 0212) the split beats the layer split on 4 x R9700 with the IQ3_S set: 1 user 187 against 104 tok/s, 8 users 365 against 321 (phaseA-tests/round0212/RESULTS-AMDSPLIT.md).
59AUTO_SPLIT_AMD_EXPERT_TYPES: frozenset = frozenset({"Q4_K", "Q5_K", "Q5_1", "Q8_0", "Q2_0", "IQ2_S", "IQ3_XXS", "IQ3_S", "IQ4_XS", "IQ4_NL"})
60TESTED_CONTEXT = 131072
61MAX_CARDS = 4
62LAYERS, EXPERTS = 48, 512          # Qwen3.8-Flash-Next
63EXPERT_TYPES = {"Q4_K", "Q5_K", "Q5_1", "Q8_0", "Q4_0",           # the routed-expert kernels (decode and prompt)
64                "IQ2_S", "IQ3_XXS", "IQ3_S", "IQ4_XS", "IQ4_NL",  # ggml's i-quant vec_dots; prompt tiles in src/moe_mma_iq.cuh
65                "Q2_0"}                                           # Strata's 2-bit type: the loader repacks it to Q4_0 blocks (twice the bytes)
66# the loader (Gguf::convert_small_tensors) converts the dense tensors to Q8_0/F32 only when the file has one of these routed types
67CONVERT_TRIGGERS = {"IQ2_S", "IQ3_XXS", "IQ3_S", "Q2_0"}
68# and can read these types to do it
69CONVERTED_FROM = {"Q8_0", "Q4_K", "Q5_K", "Q6_K", "IQ4_XS", "IQ4_NL", "BF16", "F16", "F32"}
70PLE_TYPES = {"IQ4_NL", "Q8_0"}     # per_layer_token_embd.weight as the host's row reader takes it
71# measured on 2x RTX A6000 48 GB at 128K context, 6 lanes (phaseA-tests/sfnx/RESULTS.md section 8): a card held half the experts plus
72# 8.4 GiB of dense weights, buffers and the K/V pool, with 3.6 GiB left free. 9 GiB per card is that plus a little.
73CARD_OVERHEAD_GIB = 9.0
74# What a card must have FREE, not just own: other programs on a shared box or a desktop hold part of it (srv118, 2 x RTX PRO 6000 held to 8 GB free: the plan still
75# said "all-cards split" and would have fetched the 5.2 GB draft layer). The fit counts free memory minus the engine's own default reserve (--vram-reserve-mib 700,
76# strata_control.drafting.SLOT_RESERVE_MIB); a card whose free memory is not known is counted by its size, as before.
77FREE_RESERVE_MIB = 700
78RAM_SPARE_GIB = 8.0                # left over beside the engine's own RAM
79RAM_PINNED_BUFFERS_GIB = 3.0       # the exchange buffers and heap (smaps: 1.7 GiB pinned + 0.9 heap)
80CONVERSATION_CACHE_MIB = 4096      # parked conversations (host RAM); the engine's own default is 32-128 GiB
81DEFAULT_LANES = 6
82# AMD (4 x R9700, 32 GB): the K/V pool and buffers of 8 lanes at 128K context leave 7.2 GiB free on each card (phaseA-tests/round0211/RESULTS-R9700SPLIT.md), and 8 users
83# at once run in one wave: 350 tok/s against 255 with 6 lanes (two waves). Same arithmetic, only the scheduling differs
84AMD_DEFAULT_LANES = 8
85MAX_LANES = 8                       # the engine: "--batch must be 1..8" (lanes above it, e.g. the AMD four-card default of 32, are cut to it)
86
87
88@dataclasses.dataclass
89class Card:
90    index: int
91    name: str
92    vram_mib: int
93    cc: int                         # NVIDIA: compute capability as a number, 86 for 8.6; AMD: 0
94    vendor: str = "nvidia"          # "nvidia" or "amd"
95    arch: str = ""                  # "sm_86", "gfx1201"; empty: derived from cc (NVIDIA)
96    free_mib: int | None = None     # memory nobody holds right now (nvidia-smi memory.free, the kernel's vram_used); None: not known, the card's size counts
97
98    @property
99    def room_mib(self) -> int:
100        """What the fit may count on this card: its free memory minus the reserve (never more than its size); the whole size when the free memory is not known."""
101        if self.free_mib is None:
102            return self.vram_mib
103        return max(0, min(self.vram_mib, self.free_mib) - FREE_RESERVE_MIB)
104
105    @property
106    def arch_name(self) -> str:
107        return self.arch or (f"sm_{self.cc}" if self.vendor == "nvidia" else "?")
108
109
110@dataclasses.dataclass
111class ModelFacts:
112    routed_types: dict[str, int]    # type name -> tensors, for the routed experts (gate/up/down, all layers)
113    routed_bytes: int
114    embd_type: str | None           # token_embd.weight
115    shexp_types: dict[str, int]     # shared-expert tensors
116    embd_ram_bytes: int             # token_embd + per_layer_token_embd: locked in RAM
117    layers: int
118    experts: int
119    ple_type: str | None = "IQ4_NL"     # per_layer_token_embd.weight
120    output_type: str | None = "Q8_0"    # output.weight
121
122
123@dataclasses.dataclass
124class Decision:
125    use_split: bool
126    reasons: list[str]              # why not (plain words), empty when use_split
127    cards: int = 0
128    untested: list[str] = dataclasses.field(default_factory=list)   # what about this setup nobody has run
129    need_vram_gib: float = 0.0
130    need_ram_gib: float = 0.0
131    quiet: bool = False             # auto mode and a "no": the launch says nothing and starts the normal layer split
132    arch: str = ""                  # the cards' architecture ("sm_86", "gfx1201"); empty when no card was probed (the run manifest records it)
133    routed_types: tuple = ()        # the model's routed-expert types, sorted (the run manifest records them)
134
135    @property
136    def line(self) -> str:
137        if self.use_split:
138            note = f" ({'; '.join(self.untested)}: not tested)" if self.untested else ""
139            return f"Using the all-cards split engine on {self.cards} cards{note}."
140        return "Using the normal layer split: " + "; ".join(self.reasons) + "."
141
142
143GIB = 1 << 30
144
145
146def scan_model(first_shard: str | pathlib.Path) -> ModelFacts:
147    """The facts the rule needs from the GGUF set whose first shard is named (all shards of the -0000N-of-0000M set are read)."""
148    from tools.gguf_reader import GGUFFile
149
150    first = pathlib.Path(first_shard)
151    shards = [first]
152    m = re.match(r"^(.*)-(\d{5})-of-(\d{5})\.gguf$", first.name)
153    if m:
154        total = int(m.group(3))
155        shards = [first.with_name(f"{m.group(1)}-{i:05d}-of-{m.group(3)}.gguf") for i in range(1, total + 1)]
156    routed_types: dict[str, int] = {}
157    routed_bytes = 0
158    shexp: dict[str, int] = {}
159    embd_type = None
160    ple_type = None
161    output_type = None
162    embd_ram = 0
163    layers = 0
164    experts = 0
165    for shard in shards:
166        g = GGUFFile(shard)
167        for t in g.tensors:
168            n = t.name
169            b = t.expected_bytes() or 0
170            if "_exps" in n and n.endswith(".weight") and "shexp" not in n:
171                routed_types[t.type_name] = routed_types.get(t.type_name, 0) + 1
172                routed_bytes += b * 2 if t.type_name == "Q2_0" else b     # the loader repacks Q2_0 to Q4_0: twice the bytes in the cards
173                if len(t.shape) >= 3:
174                    experts = max(experts, t.shape[-1])
175                mm = re.search(r"blk\.(\d+)\.", n)
176                if mm:
177                    layers = max(layers, int(mm.group(1)) + 1)
178            elif "shexp" in n and n.endswith(".weight"):
179                shexp[t.type_name] = shexp.get(t.type_name, 0) + 1
180            elif n == "token_embd.weight":
181                embd_type = t.type_name
182                embd_ram += b
183            elif n == "per_layer_token_embd.weight":
184                ple_type = t.type_name
185                embd_ram += b
186            elif n == "output.weight":
187                output_type = t.type_name
188    return ModelFacts(routed_types, routed_bytes, embd_type, shexp, embd_ram, layers, experts, ple_type, output_type)
189
190
191def decide(*, enabled: bool, system: str, cards: list[Card], ram_total_gib: float, ram_available_gib: float, model: ModelFacts,
192           context: int = TESTED_CONTEXT, allow_untested: bool = False, cache_mib: int = CONVERSATION_CACHE_MIB) -> Decision:
193    """Whether the all-cards split engine runs this launch, with plain reasons when not."""
194    if not enabled:
195        return Decision(False, ["the all-cards split engine is off (it is opt-in)"])
196    why: list[str] = []
197    untested: list[str] = []
198    if system != "linux":
199        why.append("the all-cards split engine runs on Linux only")
200    n = len(cards)
201    if n < 2:
202        why.append("it needs two or more cards")
203    elif n > MAX_CARDS:
204        why.append(f"it handles at most {MAX_CARDS} cards, this PC offers {n}")
205    make = cards[0].vendor if cards else "nvidia"
206    if cards:
207        if len({c.vendor for c in cards}) != 1:
208            why.append("the cards are of different makes")
209        if len({(c.name, c.vram_mib) for c in cards}) != 1:
210            why.append("the cards are not all the same model and size")
211        if make == "nvidia" and not all(c.cc >= 70 for c in cards):
212            why.append("a card is too old for it")
213        if make == "amd" and not all(c.arch_name in BUILT_ARCHS["amd"] for c in cards):
214            why.append("the AMD engine is built for RDNA4 cards (gfx1201: Radeon AI PRO R9700, RX 9070), not " + cards[0].arch_name)
215    tested = TESTED.get(make, {})
216    archs = sorted({c.arch_name for c in cards})
217    counts = sorted({k for a in archs for k in tested.get(a, ())})
218    if 2 <= n <= MAX_CARDS and make in TESTED and n not in counts and not (len(archs) == 1 and archs[0] not in tested):
219        if allow_untested:
220            untested.append(f"{n} cards")
221        else:
222            ran = " and ".join(str(k) for k in counts) if counts else "no number of"
223            why.append(f"it has only been run on {ran} cards, not {n}")
224    if cards and not all(c.arch_name in tested for c in cards):
225        if allow_untested:
226            untested.append(f"card architecture {cards[0].arch_name}")
227        else:
228            ran = "/".join(tested) if tested else "no"
229            why.append(f"it has only been run on {ran} cards, not {cards[0].arch_name}")
230    if context > TESTED_CONTEXT:
231        if allow_untested:
232            untested.append(f"context {context}")
233        else:
234            why.append(f"it has only been run up to a context of {TESTED_CONTEXT}")
235    bad = sorted(t for t in model.routed_types if t not in EXPERT_TYPES)
236    if not model.routed_types:
237        why.append("this is not a model it knows (no routed experts)")
238    elif bad:
239        why.append("the model's routed experts use " + "/".join(bad) + ", which it does not read")
240    converts = bool(CONVERT_TRIGGERS & set(model.routed_types))       # the loader then converts the dense tensors it does not read
241    readable = CONVERTED_FROM if converts else {"Q8_0"}
242    if model.embd_type not in readable:
243        why.append(f"the token embeddings are {model.embd_type}, it needs Q8_0" if not converts else
244                   f"the token embeddings are {model.embd_type}, which it cannot convert to Q8_0")
245    if model.shexp_types and not set(model.shexp_types) - {"F32"} <= readable:   # the router gate vector beside the shared expert is F32
246        why.append("the shared expert is " + "/".join(sorted(set(model.shexp_types) - readable - {"F32"})) + ", which it cannot read" + ("" if converts else " (it needs Q8_0)"))
247    if model.output_type is not None and model.output_type not in readable:
248        why.append(f"the output head is {model.output_type}, which it cannot read" + ("" if converts else " (it needs Q8_0)"))
249    if model.ple_type is not None and model.ple_type not in PLE_TYPES:
250        why.append(f"the per-layer embedding table is {model.ple_type}, it needs IQ4_NL or Q8_0")
251    if (model.layers, model.experts) != (LAYERS, EXPERTS):
252        why.append("it only knows Qwen3.8-Flash-Next (48 layers, 512 experts)")
253    need_vram = model.routed_bytes / GIB / max(n, 1) + CARD_OVERHEAD_GIB
254    need_ram = model.embd_ram_bytes / GIB + RAM_PINNED_BUFFERS_GIB + cache_mib / 1024
255    if cards and n >= 2 and min(c.room_mib for c in cards) / 1024 < need_vram:
256        has = f"{min(c.room_mib for c in cards) / 1024:.0f} GiB" + (" free" if any(c.free_mib is not None for c in cards) else "")   # free memory when it was read, else the size
257        why.append(f"all the experts do not fit in the cards' memory (each card needs about {need_vram:.0f} GiB, has {has})")
258    if ram_available_gib < need_ram + RAM_SPARE_GIB:
259        why.append(f"there is not enough free RAM (about {need_ram + RAM_SPARE_GIB:.0f} GiB needed, {ram_available_gib:.0f} GiB free)")
260    facts = dict(arch="/".join(archs), routed_types=tuple(sorted(model.routed_types)))
261    if why:
262        return Decision(False, why, n, untested, need_vram, need_ram, **facts)
263    return Decision(True, [], n, untested, need_vram, need_ram, **facts)
264
265
266def split_config(base: dict, decision: Decision, *, exe: str, native: str, mtp_dir: str | None, draft_vocab: str, context: int,
267                 lanes: int = DEFAULT_LANES, vision: bool = False, cache_mib: int = CONVERSATION_CACHE_MIB, dflash2_pack: str | None = None) -> dict:
268    """The run config for strata-split: `base` is the normal run config (its tokenizer, port, log, model name, GPUs and everything else
269    stay), and it is kept whole under "split_fallback" so the server can start the normal layer split if this engine refuses."""
270    if not decision.use_split:
271        raise ValueError("split_config: the decision is not to use the split engine")
272    cfg = {k: v for k, v in base.items() if k not in ("exe", "args", "env", "layer_split", "replicas", "user_args", "drafting")}
273    cfg["exe"] = exe
274    # the drafter: the model's draft layer (--mtp), or, when the person chose DFlash2 by name, DFlash2's pack (--draft dflash2 --draft-model PACK; one drafter a lane on the
275    # first card, the MTP layer is not loaded)
276    drafter = ["--draft", "dflash2", "--draft-model", dflash2_pack] if dflash2_pack else ["--mtp", mtp_dir]
277    cfg["args"] = ["--native", native, *drafter, "--draft-vocab", draft_vocab, "--max-context", str(context),
278                   "--spec", "6", "--lookup", "15", "--conversation-cache-mib", str(cache_mib), "--batch", str(min(MAX_LANES, max(lanes, 1)))]
279    if vision:
280        cfg["args"].append("--vision")
281    # every expert in the cards' memory, no expert cache, no arena: the engine reads these two at start
282    cfg["env"] = {**(base.get("env") or {}), "FNX_ARENA": "0", "FNX_EXPERT_RAM_GIB": "off"}
283    cfg["split_fallback"] = {k: base[k] for k in ("exe", "args", "env", "layer_split", "replicas", "user_args", "drafting", "cwd") if k in base}
284    # The split engine runs the model's own draft layer (the MTP) and nothing else. Saying so in the config ("drafting": "mtp") keeps serve/server.py's
285    # drafter step, which resolves Auto to DFlash2 where the engine has it, from adding DFlash2 flags to the split engine's arguments (it would refuse them
286    # and every start would fall back to the layer split). The fallback keeps the person's own choice (or none: Auto), so the layer split that starts
287    # instead gets DFlash2 as usual.
288    cfg["drafting"] = "dflash2" if dflash2_pack else "mtp"   # (drafting.apply leaves a split run config with --draft dflash2 as it is)
289    cfg["split_engine_note"] = decision.line
290    return cfg
291
292
293# ---- the launcher side: facts from this PC, then the config ----------------------------------------------------------------------------
294def probe_cards(indexes: list[int] | None = None) -> list[Card]:
295    """The cards (all, or the named ones): NVIDIA from nvidia-smi, else AMD from the kernel's KFD topology and sysfs; [] when neither says."""
296    cards = probe_nvidia_cards(indexes)
297    return cards or probe_amd_cards(indexes)
298
299
300def probe_amd_cards(indexes: list[int] | None = None, root: str = "/sys") -> list[Card]:
301    """AMD GPUs the compute stack counts, in HIP's order: the KFD topology nodes with SIMDs (gfx_target_version 120001 = gfx1201), their
302    memory from the node's VRAM bank (properties "size_in_bytes" of its memory bank 0) or the drm card's mem_info_vram_total. No ROCm
303    tools needed. [] when there is no /sys/class/kfd."""
304    import pathlib
305
306    nodes = pathlib.Path(root) / "class/kfd/kfd/topology/nodes"
307    cards: list[Card] = []
308    try:
309        dirs = sorted((d for d in nodes.iterdir() if d.name.isdigit()), key=lambda d: int(d.name))
310    except OSError:
311        return []
312    idx = 0
313    for d in dirs:
314        try:
315            props = dict(line.split(None, 1) for line in (d / "properties").read_text().splitlines() if line.strip())
316            if int(props.get("simd_count", "0")) <= 0:
317                continue                                     # the CPU node
318            gv = int(props.get("gfx_target_version", "0"))
319            arch = f"gfx{gv // 10000}{(gv // 100) % 100:x}{gv % 100:x}" if gv else "?"
320            name = props.get("marketing_name", "").strip() or "AMD GPU"
321            mem = 0
322            bank = d / "mem_banks/0/properties"
323            if bank.is_file():
324                bp = dict(line.split(None, 1) for line in bank.read_text().splitlines() if line.strip())
325                mem = int(bp.get("size_in_bytes", "0")) >> 20
326        except (OSError, ValueError):
327            continue
328        free = None
329        try:                                                 # what is in use: the card's render node, found by the topology node's drm_render_minor
330            minor = int(props.get("drm_render_minor", "0"))
331            if minor > 0 and mem:
332                used = int((pathlib.Path(root) / f"class/drm/renderD{minor}/device/mem_info_vram_used").read_text()) >> 20
333                free = max(0, mem - used)
334        except (OSError, ValueError):
335            free = None
336        cards.append(Card(idx, name, mem, 0, "amd", arch, free_mib=free))
337        idx += 1
338    return _named_or_visible(cards, indexes)
339
340
341def probe_nvidia_cards(indexes: list[int] | None = None) -> list[Card]:
342    """The NVIDIA cards (all, or the named ones) with their name, memory and compute capability, from nvidia-smi; [] when it cannot say."""
343    import subprocess
344
345    try:
346        out = subprocess.run(["nvidia-smi", "--query-gpu=index,name,memory.total,compute_cap,memory.free", "--format=csv,noheader,nounits"],
347                             capture_output=True, text=True, timeout=20).stdout
348    except (OSError, subprocess.SubprocessError):
349        return []
350    cards = []
351    for line in out.splitlines():
352        parts = [p.strip() for p in line.split(",")]
353        if len(parts) not in (4, 5):
354            continue
355        try:
356            idx, mem = int(parts[0]), int(float(parts[2]))
357            cc = int(round(float(parts[3]) * 10))
358        except ValueError:
359            continue
360        try:
361            free = int(float(parts[4])) if len(parts) == 5 else None
362        except ValueError:
363            free = None                                      # "[N/A]", or an answer without the column: the size counts
364        cards.append(Card(idx, parts[1], mem, cc, free_mib=free))
365    return _named_or_visible(cards, indexes)
366
367
368def _named_or_visible(cards: list[Card], indexes: list[int] | None) -> list[Card]:
369    """The cards the launch named; with none named, the ones the environment leaves visible (CUDA_VISIBLE_DEVICES, AMD: ROCR_VISIBLE_DEVICES then HIP_VISIBLE_DEVICES): a
370    card the engine will not see is not one the split can use. Named cards are the server's own visibility list (it sets it from them), so they are kept as named."""
371    if indexes is not None:
372        return [c for c in cards if c.index in indexes]
373    if not cards:
374        return cards
375    from strata_control import gpu_roles
376    vis = gpu_roles.env_visible([c.index for c in cards], cards[0].vendor, alike=len({(c.name, c.vram_mib) for c in cards}) == 1)
377    return cards if vis is None else [c for c in cards if c.index in vis]
378
379
380def ram_gib() -> tuple[float, float]:
381    """(total, available) GiB of this PC's RAM from /proc/meminfo, inside a container its memory limit
382    (strata_control/cgroup_memory.py); (0, 0) where there is none."""
383    from strata_control import cgroup_memory
384    total, available = cgroup_memory.ram_bytes()
385    return (total or 0) / (1 << 30), (available or 0) / (1 << 30)
386
387
388def _flag(args: list, name: str) -> str | None:
389    return str(args[args.index(name) + 1]) if name in args and args.index(name) + 1 < len(args) else None
390
391
392def mode(cfg: dict, environ: dict | None = None) -> str:
393    """"auto" (the default), "on" or "off". The run config's "split_engine" (true/false or the word; `strata launch --split-engine X` writes it)
394    and, over it, STRATA_SPLIT_ENGINE in the environment (testers). Anything it does not know is auto."""
395    import os
396
397    env = environ if environ is not None else os.environ
398    raw = env.get("STRATA_SPLIT_ENGINE")
399    if raw is None or not str(raw).strip():
400        raw = cfg.get("split_engine")
401    if raw is True:
402        return "on"
403    if raw is False:
404        return "off"
405    return {"on": "on", "1": "on", "true": "on", "yes": "on", "off": "off", "0": "off", "false": "off", "no": "off"}.get(str(raw).strip().lower(), "auto")
406
407
408def wanted(cfg: dict, environ: dict | None = None) -> bool:
409    """The split engine may be tried for this launch (anything but off)."""
410    return mode(cfg, environ) != "off"
411
412
413def _auto_gates(d: Decision, cards: list[Card], model: ModelFacts, chosen: str, mode_: str) -> Decision | None:
414    """The rules that apply to Auto after the general rule said yes (AMD: expert types, card counts, architectures; NVIDIA: the split must beat DFlash2 on the card).
415    None: they pass."""
416    amd = cards[0].vendor == "amd"
417    if amd and mode_ != "on" and not set(model.routed_types) <= AUTO_SPLIT_AMD_EXPERT_TYPES:
418        return Decision(False, ["this model's experts (" + "/".join(sorted(set(model.routed_types) - AUTO_SPLIT_AMD_EXPERT_TYPES)) + ") run faster on the layer split on AMD today; the all-cards split engine starts for them only with --split-engine on"], d.cards)
419    if amd and mode_ != "on" and d.cards not in AUTO_SPLIT_AMD_CARD_COUNTS:
420        return Decision(False, [f"the all-cards split engine is not automatic on {d.cards} {cards[0].arch_name} cards; it starts only with --split-engine on"], d.cards)
421    if amd and mode_ != "on" and not all(c.arch_name in AUTO_SPLIT_AMD_ARCHS for c in cards):
422        # opt-in on AMD: auto keeps the layer split (quiet), `--split-engine on` runs the split
423        return Decision(False, [f"the all-cards split engine is not automatic on {cards[0].arch_name} yet; it starts only with --split-engine on"], d.cards)
424    if not amd and chosen == "auto" and not all(c.cc in AUTO_SPLIT_BEATS_DFLASH2 for c in cards):
425        return Decision(False, ["on this card the layer split with DFlash2 has not been measured slower than the all-cards split engine"], d.cards)
426    return None
427
428
429#: what the rule assumes of a model that is not on this computer yet (a download still to come): a Qwen3.8-Flash-Next set the engine reads, small enough
430#: for the memory rule; the real files are looked at when they are there
431ASSUMED_MODEL = ModelFacts(routed_types={"Q4_K": 1}, routed_bytes=0, embd_type="Q8_0", shexp_types={"Q8_0": 1}, embd_ram_bytes=0, layers=LAYERS, experts=EXPERTS)
432
433
434def expected(cfg: dict, *, indexes: list[int] | None = None, native: str | None = None, context: int = TESTED_CONTEXT, system: str | None = None,
435             allow_untested: bool = False, probe=None, ram=None, scan=None, exe_for_cards=None, kv: str | None = None) -> bool:
436    """Would the launch start the all-cards split engine? The answer of the rule apply_to_config uses, asked BEFORE the model's files, the engine package or the
437    draft layer are on the computer (the plan and the fetch: the split runs the model's draft layer, the MTP, so a start that will use it has to fetch that and not
438    DFlash2's drafter). Facts that are not there yet are assumed in the split's favour: the model (ASSUMED_MODEL, unless `native` is a readable file), the engine
439    package (unless exe_for_cards is given and finds no strata-split-N). Mode "off", a person's own DFlash2 / off choice, engine arguments of their own and
440    replicas say no, as in apply_to_config. Never raises."""
441    import os
442    import sys
443
444    try:
445        m = mode(cfg)
446        if m == "off":
447            return False
448        chosen = str(cfg.get("drafting") or "auto").lower()
449        if chosen == "off" or (chosen == "dflash2" and m != "on") or cfg.get("user_args") or cfg.get("replicas"):
450            return False
451        if kv not in (None, "int8"):                         # the split keeps int8 (apply_to_config says the same)
452            return False
453        system = system or ("linux" if sys.platform.startswith("linux") else sys.platform)
454        cards = (probe or probe_cards)(indexes) if system == "linux" else []
455        total, avail = (ram or ram_gib)()
456        model = ASSUMED_MODEL
457        if native and os.path.isfile(native):
458            model = (scan or scan_model)(native)
459        experimental_ok = m == "on" and bool(cards) and cards[0].vendor == "amd"
460        d = decide(enabled=True, system=system, cards=cards, ram_total_gib=total, ram_available_gib=avail, model=model, context=context,
461                   allow_untested=allow_untested or experimental_ok)
462        if not d.use_split or _auto_gates(d, cards, model, chosen, m) is not None:
463            return False
464        if exe_for_cards is not None:
465            amd = cards[0].vendor == "amd"
466            if not (exe_for_cards(d.cards, cards[0].cc, cards[0].arch_name) if amd else exe_for_cards(d.cards, cards[0].cc)):
467                return False
468        return True
469    except Exception:                                        # noqa: BLE001 - a question asked early is never a reason to stop a launch
470        return False
471
472
473def apply_to_config(cfg: dict, *, exe_for_cards, system: str | None = None, allow_untested: bool = False, probe=None, ram=None,
474                    scan=None, data_dir: str | None = None, mode_: str | None = None) -> Decision:
475    """Turn a normal run config into the split engine's config IN PLACE when the mode and the rule say yes, and say what was decided.
476    exe_for_cards(n, cc) -> the path of the strata-split-n built for compute capability cc, or None (the engine package has none);
477    probe(indexes) -> [Card]; ram() -> (total, available) GiB; scan(first_shard) -> ModelFacts: the facts of this PC and model, replaceable
478    for tests. Mode "off": nothing happens, silently. Mode "auto": a refusal is `quiet` (the normal layer split starts without a word)."""
479    m = mode_ or mode(cfg)
480    if m == "off":
481        return Decision(False, ["the all-cards split engine is turned off"], quiet=True)
482    d = _apply(cfg, exe_for_cards=exe_for_cards, system=system, allow_untested=allow_untested, probe=probe, ram=ram, scan=scan, data_dir=data_dir,
483               mode_=m)
484    if m == "auto" and not d.use_split:
485        d.quiet = True
486    record_launch_manifest(d, m)
487    return d
488
489
490def auto_rule(d: Decision) -> dict | None:
491    """AMD only: the three conditions mode "auto" starts the split on (architecture, card count, expert types), each on its own, so a manifest says which one a
492    setup misses. A two- or three-card setup is never promoted by the four-card rule: its `card_count` is false. None for another make or no card."""
493    if not d.arch or "/" in d.arch or not d.arch.startswith("gfx"):
494        return None
495    return {"architecture": d.arch in AUTO_SPLIT_AMD_ARCHS, "card_count": d.cards in AUTO_SPLIT_AMD_CARD_COUNTS,
496            "expert_types": bool(d.routed_types) and set(d.routed_types) <= AUTO_SPLIT_AMD_EXPERT_TYPES}
497
498
499def record_launch_manifest(d: Decision, mode_: str, environ: dict | None = None) -> bool:
500    """STRATA_MANIFEST=<file> (a diagnostic, off unless set): the engine choice and why, in <file>.launch.json, next to the engine's own <file>. Sorted keys, no
501    timestamps, so two matched launches give the same text. Never raises and never changes the launch. True when a file was written."""
502    import json
503    import os
504
505    target = (os.environ if environ is None else environ).get("STRATA_MANIFEST")
506    if not target:
507        return False
508    try:
509        doc = {"manifest_version": 1, "launch": {
510            "split_engine_mode": mode_, "engine": "all-cards-split" if d.use_split else "native-layer-split", "reasons": list(d.reasons),
511            "cards": d.cards, "card_arch": d.arch, "routed_types": list(d.routed_types), "untested": list(d.untested),
512            "need_vram_gib": round(d.need_vram_gib, 1), "need_ram_gib": round(d.need_ram_gib, 1), "amd_auto_rule": auto_rule(d)}}
513        path = target + ".launch.json"
514        tmp = path + ".tmp"
515        with open(tmp, "w", encoding="utf-8", newline="\n") as f:
516            json.dump(doc, f, indent=2, sort_keys=True)
517            f.write("\n")
518        os.replace(tmp, path)
519        return True
520    except Exception:                                        # noqa: BLE001 - a diagnostic never stops a start
521        return False
522
523
524def _apply(cfg: dict, *, exe_for_cards, system, allow_untested, probe, ram, scan, data_dir, mode_: str = "auto") -> Decision:
525    import pathlib
526    import sys
527
528    system = system or ("linux" if sys.platform.startswith("linux") else sys.platform)
529    args = [str(a) for a in cfg.get("args") or []]
530    native = _flag(args, "--native")
531    if not native:
532        return Decision(False, ["this model is not a single GGUF file set"])
533    # choices the split engine does not honour: the normal layer split keeps them
534    # Drafting: Auto (nothing written, or "auto") on a setup the split accepts runs the split with its MTP: measured faster to decode than the layer
535    # split with DFlash2 on both tested cards (AUTO_SPLIT_BEATS_DFLASH2, numbers in docs/SPLIT_ENGINE.md). The person's own "dflash2" (or "off", which the
536    # split cannot do: it needs the draft layer) keeps the layer split; "mtp" is what the split runs.
537    chosen = str(cfg.get("drafting") or "auto").lower()
538    # DFlash2 chosen by name runs on the split engine only when the person asked for the split engine too (--split-engine on): Auto keeps the layer split with DFlash2
539    # (the split engine with DFlash2 was not faster than with the MTP draft layer at 4 users or on sampled text, RESULTS-SPLITDF2.md, so nothing picks it by itself)
540    if chosen == "dflash2" and mode_ != "on":
541        return Decision(False, ["DFlash2 drafting was chosen, which the all-cards split engine does not run"])
542    if chosen == "off":
543        return Decision(False, ["drafting is off, and the all-cards split engine needs the draft layer"])
544    if cfg.get("user_args") or cfg.get("replicas"):
545        return Decision(False, ["this run config has engine arguments of its own or replicas, which the all-cards split engine does not take"])
546    kv = _flag(args, "--kv")
547    if kv not in (None, "int8"):
548        return Decision(False, [f"the conversation memory format is {kv}, the all-cards split engine keeps int8"])
549    gpus = cfg.get("gpu")
550    indexes = [int(g) for g in gpus] if isinstance(gpus, list) else ([int(gpus)] if isinstance(gpus, int) else None)
551    cards = (probe or probe_cards)(indexes) if system == "linux" else []
552    total, avail = (ram or ram_gib)()
553    try:
554        model = (scan or scan_model)(native)
555    except Exception as e:                                   # noqa: BLE001 - a file it cannot read is a reason, not a failed start
556        return Decision(False, [f"the model file could not be read ({type(e).__name__})"])
557    context = int(_flag(args, "--max-context") or 8192)
558    # an AMD architecture nobody has run (gfx1100..1103, gfx1200) starts only on the person's explicit "on", with the engine's own self-test as the guard
559    experimental_ok = mode_ == "on" and bool(cards) and cards[0].vendor == "amd"
560    d = decide(enabled=True, system=system, cards=cards, ram_total_gib=total, ram_available_gib=avail, model=model, context=context,
561               allow_untested=allow_untested or experimental_ok)
562    if not d.use_split:
563        return d
564    gate = _auto_gates(d, cards, model, chosen, mode_)
565    if gate is not None:
566        return gate
567    amd = cards[0].vendor == "amd"
568    # NVIDIA: strata-split-N-sm<cc> or strata-split-N; AMD: strata-split-N-<arch> (gfx1201), the third argument
569    exe = exe_for_cards(d.cards, cards[0].cc, cards[0].arch_name) if amd else exe_for_cards(d.cards, cards[0].cc)
570    if not exe:
571        return Decision(False, [f"this engine package has no strata-split-{d.cards}" + (f"-{cards[0].arch_name}" if amd else "")], d.cards)
572    df2_pack = None
573    mtp = _flag(args, "--mtp")
574    if chosen == "dflash2":                                  # (mode "on"): the drafter is DFlash2's pack, the MTP layer is not loaded and not needed
575        if not exe_takes_dflash2(exe):
576            return Decision(False, ["DFlash2 drafting was chosen, which the all-cards split engine does not run"], d.cards)
577        from strata_control import drafting
578        folder = data_dir or drafting.data_dir_of(args)
579        if not folder or not drafting.pack_ready(folder):
580            return Decision(False, [NO_DF2_PACK], d.cards)
581        df2_pack = str(drafting.pack_path(folder))
582    elif not mtp:
583        return Decision(False, ["the model has no draft layer files (--mtp)"], d.cards)
584    vocab = None
585    for folder in (pathlib.Path(exe).parent, pathlib.Path(data_dir) if data_dir else None, pathlib.Path(cfg.get("cwd") or ".") / "data"):
586        if folder and (folder / "draft_vocab_en.bin").is_file():
587            vocab = str(folder / "draft_vocab_en.bin")
588            break
589    if not vocab:
590        return Decision(False, ["draft_vocab_en.bin is missing"], d.cards)
591    lanes = int(cfg.get("parallel") or _flag(args, "--batch") or (AMD_DEFAULT_LANES if amd else DEFAULT_LANES))
592    new = split_config(cfg, d, exe=exe, native=native, mtp_dir=mtp, draft_vocab=vocab, context=context, lanes=lanes,
593                       vision=bool(cfg.get("vision")) or "--vision" in args, dflash2_pack=df2_pack)
594    cfg.clear()
595    cfg.update(new)
596    return d
597
598
599#: Why the split engine is not started when DFlash2 was chosen by name with --split-engine on and its drafter file is not on this computer.
600NO_DF2_PACK = "the DFlash2 drafter isn't downloaded yet"       # (the same words as drafting.NOT_DOWNLOADED, already in the catalog)
601#: Text the split engine program carries when it takes `--draft dflash2` (src/split/tools/sfnx.cpp); an older strata-split-N has none and would stop at start on the flag.
602_MARK_SPLIT_DF2 = b"--draft dflash2 needs --native, --draft-model PACK"
603_split_df2: dict[tuple[str, int, int], bool] = {}
604
605
606def exe_takes_dflash2(exe) -> bool:
607    """Does the strata-split-N program at `exe` take `--draft dflash2 --draft-model PACK`? Read from the file's text (it is never started for this), once per path, size and time."""
608    import mmap
609
610    if not exe:
611        return False
612    try:
613        path = pathlib.Path(exe)
614        st = path.stat()
615        key = (str(path), st.st_size, st.st_mtime_ns)
616        if key not in _split_df2:
617            with open(path, "rb") as handle, mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as data:
618                _split_df2[key] = data.find(_MARK_SPLIT_DF2) >= 0
619        return _split_df2[key]
620    except (OSError, ValueError):
621        return False
622
623
624# ---- the engine package and the draft layer (the Terminal's launcher and the app's start share these) ---------------------------------------
625def exe_finder(cfg: dict):
626    """exe_for_cards(n, cc=None, arch=None) for a run config: the strata-split-N build that sits beside the run config's engine, or None.
627    One build per architecture (FNX_ARCH is compile time): NVIDIA strata-split-N-sm<cc> then strata-split-N; AMD strata-split-N-<arch>, then strata-split-N-amd
628    (one binary with a code object for each RDNA architecture)."""
629    import pathlib
630
631    def exe_for(n: int, cc: int | None = None, arch: str | None = None):
632        from strata_control import engine_component as EC
633        exe = cfg.get("exe")
634        try:
635            real = EC.expand(exe, cfg, full=False) if EC.is_reference(exe) else exe
636        except Exception:                                    # noqa: BLE001 - no engine to look beside: no split
637            return None
638        for name in ((f"strata-split-{n}-{arch}", f"strata-split-{n}-amd") if arch else ((f"strata-split-{n}-sm{cc}",) if cc else ()) + (f"strata-split-{n}",)):
639            p = pathlib.Path(str(real)).parent / name
640            if p.is_file():
641                return str(p)
642        return None
643
644    return exe_for
645
646
647def split_plan_line(gb: float | None = None) -> str:
648    """The drafting line of a plan that says split (the Terminal's --plan and the app's drafting plan): the MTP draft layer is what drafts, with its download size when it is still to come."""
649    return "Drafting: MTP (the all-cards split engine uses the MTP draft layer" + (f", {gb:g} GB)" if gb else ")")
650
651
652def draft_layer_present(folder: str) -> bool:
653    """The draft layer's folder (mtp/rt) exists and holds files."""
654    import pathlib
655
656    try:
657        return pathlib.Path(folder).is_dir() and any(pathlib.Path(folder).iterdir())
658    except OSError:
659        return False
660
661
662def apply_run_config(cfg: dict, *, allow_untested: bool = False, exe_for_cards=None, **facts) -> tuple[Decision, str, bool]:
663    """The app's side of the start (the Terminal's is strata_cli/launch/runner.py apply_split_engine, the same steps): turn a normal run config into the split engine's
664    config IN PLACE when the mode and the rule say yes. Returns (decision, the one plain line to show or "", whether that line is a warning).
665    Auto and a "no" (also a missing draft layer or engine package): nothing changes and no line. "on" and a "no": one line. Never raises. `facts` are the
666    hooks of apply_to_config (system, probe, ram, scan, data_dir), replaceable for tests."""
667    m = mode(cfg)
668    if m == "off":
669        return Decision(False, ["the all-cards split engine is turned off"], quiet=True), "", False
670    args = [str(a) for a in cfg.get("args") or []]
671    mtp_dir = _flag(args, "--mtp")
672    # the split runs the model's own draft layer (--mtp) and refuses to start without it: a start whose draft-layer folder is not on disk stays on the layer split
673    # (not for DFlash2 chosen by name with --split-engine on: that drafter is DFlash2's pack, the layer is not loaded)
674    if mtp_dir and not draft_layer_present(mtp_dir) and not (str(cfg.get("drafting") or "").lower() == "dflash2" and m == "on"):
675        line = "The all-cards split engine needs the model's draft layer (the MTP), which is not downloaded; using the normal layer split."
676        return Decision(False, [line], quiet=m != "on"), (line if m == "on" else ""), True
677    before = dict(cfg)
678    try:
679        d = apply_to_config(cfg, exe_for_cards=exe_for_cards or exe_finder(cfg), allow_untested=allow_untested, **facts)
680    except Exception as e:                                   # noqa: BLE001 - never stop a start over an option
681        cfg.clear()
682        cfg.update(before)
683        line = f"The all-cards split engine was left out ({type(e).__name__}). Using the normal layer split."
684        return Decision(False, [line], quiet=m != "on"), (line if m == "on" else ""), True
685    if d.quiet:
686        return d, "", False
687    return d, d.line, not d.use_split