okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6b63729a9
main
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 16but 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 18one 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, 20512 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 21Q2_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, 22any 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 24experts in RAM) and the RAM that stays (the 27.5 GiB locked embedding table, a few GiB of buffers and the conversation cache) 25is 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 : 90index :int 91name :str 92vram_mib :int 93cc :int # NVIDIA: compute capability as a number, 86 for 8.6; AMD: 0 94vendor :str = "nvidia" # "nvidia" or "amd" 95arch :str = "" # "sm_86", "gfx1201"; empty: derived from cc (NVIDIA) 96free_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 99def 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.""" 101if self .free_mib is None : 102return self .vram_mib 103return max (0 ,min (self .vram_mib ,self .free_mib )- FREE_RESERVE_MIB ) 104 105@property 106def arch_name (self )-> str : 107return self .arch or (f"sm_ { self . cc } " if self .vendor == "nvidia" else "?" ) 108 109 110@ dataclasses . dataclass 111class ModelFacts : 112routed_types :dict [str ,int ]# type name -> tensors, for the routed experts (gate/up/down, all layers) 113routed_bytes :int 114embd_type :str | None # token_embd.weight 115shexp_types :dict [str ,int ]# shared-expert tensors 116embd_ram_bytes :int # token_embd + per_layer_token_embd: locked in RAM 117layers :int 118experts :int 119ple_type :str | None = "IQ4_NL" # per_layer_token_embd.weight 120output_type :str | None = "Q8_0" # output.weight 121 122 123@ dataclasses . dataclass 124class Decision : 125use_split :bool 126reasons :list [str ]# why not (plain words), empty when use_split 127cards :int = 0 128untested :list [str ]= dataclasses .field (default_factory = list )# what about this setup nobody has run 129need_vram_gib :float = 0.0 130need_ram_gib :float = 0.0 131quiet :bool = False # auto mode and a "no": the launch says nothing and starts the normal layer split 132arch :str = "" # the cards' architecture ("sm_86", "gfx1201"); empty when no card was probed (the run manifest records it) 133routed_types :tuple = ()# the model's routed-expert types, sorted (the run manifest records them) 134 135@property 136def line (self )-> str : 137if self .use_split : 138note = f" ( { '; ' . join ( self . untested ) } : not tested)" if self .untested else "" 139return f"Using the all-cards split engine on { self . cards } cards { note } ." 140return "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).""" 148from tools .gguf_reader import GGUFFile 149 150first = pathlib .Path (first_shard ) 151shards = [first ] 152m = re .match (r"^(.*)-(\d{5})-of-(\d{5})\.gguf$" ,first .name ) 153if m : 154total = int (m .group (3 )) 155shards = [first .with_name (f" { m . group ( 1 ) } - { i :05d } -of- { m . group ( 3 ) } .gguf" )for i in range (1 ,total + 1 )] 156routed_types :dict [str ,int ]= {} 157routed_bytes = 0 158shexp :dict [str ,int ]= {} 159embd_type = None 160ple_type = None 161output_type = None 162embd_ram = 0 163layers = 0 164experts = 0 165for shard in shards : 166g = GGUFFile (shard ) 167for t in g .tensors : 168n = t .name 169b = t .expected_bytes ()or 0 170if "_exps" in n and n .endswith (".weight" )and "shexp" not in n : 171routed_types [t .type_name ]= routed_types .get (t .type_name ,0 )+ 1 172routed_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 173if len (t .shape )>= 3 : 174experts = max (experts ,t .shape [- 1 ]) 175mm = re .search (r"blk\.(\d+)\." ,n ) 176if mm : 177layers = max (layers ,int (mm .group (1 ))+ 1 ) 178elif "shexp" in n and n .endswith (".weight" ): 179shexp [t .type_name ]= shexp .get (t .type_name ,0 )+ 1 180elif n == "token_embd.weight" : 181embd_type = t .type_name 182embd_ram += b 183elif n == "per_layer_token_embd.weight" : 184ple_type = t .type_name 185embd_ram += b 186elif n == "output.weight" : 187output_type = t .type_name 188return 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 , 192context :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.""" 194if not enabled : 195return Decision (False , ["the all-cards split engine is off (it is opt-in)" ]) 196why :list [str ]= [] 197untested :list [str ]= [] 198if system != "linux" : 199why .append ("the all-cards split engine runs on Linux only" ) 200n = len (cards ) 201if n < 2 : 202why .append ("it needs two or more cards" ) 203elif n > MAX_CARDS : 204why .append (f"it handles at most { MAX_CARDS } cards, this PC offers { n } " ) 205make = cards [0 ].vendor if cards else "nvidia" 206if cards : 207if len ({c .vendor for c in cards })!= 1 : 208why .append ("the cards are of different makes" ) 209if len ({(c .name ,c .vram_mib )for c in cards })!= 1 : 210why .append ("the cards are not all the same model and size" ) 211if make == "nvidia" and not all (c .cc >= 70 for c in cards ): 212why .append ("a card is too old for it" ) 213if make == "amd" and not all (c .arch_name in BUILT_ARCHS ["amd" ]for c in cards ): 214why .append ("the AMD engine is built for RDNA4 cards (gfx1201: Radeon AI PRO R9700, RX 9070), not " + cards [0 ].arch_name ) 215tested = TESTED .get (make , {}) 216archs = sorted ({c .arch_name for c in cards }) 217counts = sorted ({k for a in archs for k in tested .get (a , ())}) 218if 2 <= n <= MAX_CARDS and make in TESTED and n not in counts and not (len (archs )== 1 and archs [0 ]not in tested ): 219if allow_untested : 220untested .append (f" { n } cards" ) 221else : 222ran = " and " .join (str (k )for k in counts )if counts else "no number of" 223why .append (f"it has only been run on { ran } cards, not { n } " ) 224if cards and not all (c .arch_name in tested for c in cards ): 225if allow_untested : 226untested .append (f"card architecture { cards [ 0 ]. arch_name } " ) 227else : 228ran = "/" .join (tested )if tested else "no" 229why .append (f"it has only been run on { ran } cards, not { cards [ 0 ]. arch_name } " ) 230if context > TESTED_CONTEXT : 231if allow_untested : 232untested .append (f"context { context } " ) 233else : 234why .append (f"it has only been run up to a context of { TESTED_CONTEXT } " ) 235bad = sorted (t for t in model .routed_types if t not in EXPERT_TYPES ) 236if not model .routed_types : 237why .append ("this is not a model it knows (no routed experts)" ) 238elif bad : 239why .append ("the model's routed experts use " + "/" .join (bad )+ ", which it does not read" ) 240converts = bool (CONVERT_TRIGGERS & set (model .routed_types ))# the loader then converts the dense tensors it does not read 241readable = CONVERTED_FROM if converts else {"Q8_0" } 242if model .embd_type not in readable : 243why .append (f"the token embeddings are { model . embd_type } , it needs Q8_0" if not converts else 244f"the token embeddings are { model . embd_type } , which it cannot convert to Q8_0" ) 245if model .shexp_types and not set (model .shexp_types )- {"F32" }<= readable :# the router gate vector beside the shared expert is F32 246why .append ("the shared expert is " + "/" .join (sorted (set (model .shexp_types )- readable - {"F32" }))+ ", which it cannot read" + ("" if converts else " (it needs Q8_0)" )) 247if model .output_type is not None and model .output_type not in readable : 248why .append (f"the output head is { model . output_type } , which it cannot read" + ("" if converts else " (it needs Q8_0)" )) 249if model .ple_type is not None and model .ple_type not in PLE_TYPES : 250why .append (f"the per-layer embedding table is { model . ple_type } , it needs IQ4_NL or Q8_0" ) 251if (model .layers ,model .experts )!= (LAYERS ,EXPERTS ): 252why .append ("it only knows Qwen3.8-Flash-Next (48 layers, 512 experts)" ) 253need_vram = model .routed_bytes / GIB / max (n ,1 )+ CARD_OVERHEAD_GIB 254need_ram = model .embd_ram_bytes / GIB + RAM_PINNED_BUFFERS_GIB + cache_mib / 1024 255if cards and n >= 2 and min (c .room_mib for c in cards )/ 1024 < need_vram : 256has = 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 257why .append (f"all the experts do not fit in the cards' memory (each card needs about { need_vram :.0f } GiB, has { has } )" ) 258if ram_available_gib < need_ram + RAM_SPARE_GIB : 259why .append (f"there is not enough free RAM (about { need_ram + RAM_SPARE_GIB :.0f } GiB needed, { ram_available_gib :.0f } GiB free)" ) 260facts = dict (arch = "/" .join (archs ),routed_types = tuple (sorted (model .routed_types ))) 261if why : 262return Decision (False ,why ,n ,untested ,need_vram ,need_ram ,** facts ) 263return 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 , 267lanes :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 269stay), and it is kept whole under "split_fallback" so the server can start the normal layer split if this engine refuses.""" 270if not decision .use_split : 271raise ValueError ("split_config: the decision is not to use the split engine" ) 272cfg = {k :v for k ,v in base .items ()if k not in ("exe" ,"args" ,"env" ,"layer_split" ,"replicas" ,"user_args" ,"drafting" )} 273cfg ["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) 276drafter = ["--draft" ,"dflash2" ,"--draft-model" ,dflash2_pack ]if dflash2_pack else ["--mtp" ,mtp_dir ] 277cfg ["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 )))] 279if vision : 280cfg ["args" ].append ("--vision" ) 281# every expert in the cards' memory, no expert cache, no arena: the engine reads these two at start 282cfg ["env" ]= {** (base .get ("env" )or {}),"FNX_ARENA" :"0" ,"FNX_EXPERT_RAM_GIB" :"off" } 283cfg ["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. 288cfg ["drafting" ]= "dflash2" if dflash2_pack else "mtp" # (drafting.apply leaves a split run config with --draft dflash2 as it is) 289cfg ["split_engine_note" ]= decision .line 290return 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.""" 296cards = probe_nvidia_cards (indexes ) 297return 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 302memory 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 303tools needed. [] when there is no /sys/class/kfd.""" 304import pathlib 305 306nodes = pathlib .Path (root )/ "class/kfd/kfd/topology/nodes" 307cards :list [Card ]= [] 308try : 309dirs = sorted ((d for d in nodes .iterdir ()if d .name .isdigit ()),key = lambda d :int (d .name )) 310except OSError : 311return [] 312idx = 0 313for d in dirs : 314try : 315props = dict (line .split (None ,1 )for line in (d / "properties" ).read_text ().splitlines ()if line .strip ()) 316if int (props .get ("simd_count" ,"0" ))<= 0 : 317continue # the CPU node 318gv = int (props .get ("gfx_target_version" ,"0" )) 319arch = f"gfx { gv // 10000 } {( gv // 100 ) % 100 :x } { gv % 100 :x } " if gv else "?" 320name = props .get ("marketing_name" ,"" ).strip ()or "AMD GPU" 321mem = 0 322bank = d / "mem_banks/0/properties" 323if bank .is_file (): 324bp = dict (line .split (None ,1 )for line in bank .read_text ().splitlines ()if line .strip ()) 325mem = int (bp .get ("size_in_bytes" ,"0" ))>> 20 326except (OSError ,ValueError ): 327continue 328free = None 329try :# what is in use: the card's render node, found by the topology node's drm_render_minor 330minor = int (props .get ("drm_render_minor" ,"0" )) 331if minor > 0 and mem : 332used = int ((pathlib .Path (root )/ f"class/drm/renderD { minor } /device/mem_info_vram_used" ).read_text ())>> 20 333free = max (0 ,mem - used ) 334except (OSError ,ValueError ): 335free = None 336cards .append (Card (idx ,name ,mem ,0 ,"amd" ,arch ,free_mib = free )) 337idx += 1 338return _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.""" 343import subprocess 344 345try : 346out = subprocess .run (["nvidia-smi" ,"--query-gpu=index,name,memory.total,compute_cap,memory.free" ,"--format=csv,noheader,nounits" ], 347capture_output = True ,text = True ,timeout = 20 ).stdout 348except (OSError ,subprocess .SubprocessError ): 349return [] 350cards = [] 351for line in out .splitlines (): 352parts = [p .strip ()for p in line .split ("," )] 353if len (parts )not in (4 ,5 ): 354continue 355try : 356idx ,mem = int (parts [0 ]),int (float (parts [2 ])) 357cc = int (round (float (parts [3 ])* 10 )) 358except ValueError : 359continue 360try : 361free = int (float (parts [4 ]))if len (parts )== 5 else None 362except ValueError : 363free = None # "[N/A]", or an answer without the column: the size counts 364cards .append (Card (idx ,parts [1 ],mem ,cc ,free_mib = free )) 365return _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 370card 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.""" 371if indexes is not None : 372return [c for c in cards if c .index in indexes ] 373if not cards : 374return cards 375from strata_control import gpu_roles 376vis = 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 ) 377return 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.""" 383from strata_control import cgroup_memory 384total ,available = cgroup_memory .ram_bytes () 385return (total or 0 )/ (1 << 30 ), (available or 0 )/ (1 << 30 ) 386 387 388def _flag (args :list ,name :str )-> str | None : 389return 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) 394and, over it, STRATA_SPLIT_ENGINE in the environment (testers). Anything it does not know is auto.""" 395import os 396 397env = environ if environ is not None else os .environ 398raw = env .get ("STRATA_SPLIT_ENGINE" ) 399if raw is None or not str (raw ).strip (): 400raw = cfg .get ("split_engine" ) 401if raw is True : 402return "on" 403if raw is False : 404return "off" 405return {"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).""" 410return 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). 415None: they pass.""" 416amd = cards [0 ].vendor == "amd" 417if amd and mode_ != "on" and not set (model .routed_types )<= AUTO_SPLIT_AMD_EXPERT_TYPES : 418return 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 ) 419if amd and mode_ != "on" and d .cards not in AUTO_SPLIT_AMD_CARD_COUNTS : 420return 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 ) 421if 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 423return 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 ) 424if not amd and chosen == "auto" and not all (c .cc in AUTO_SPLIT_BEATS_DFLASH2 for c in cards ): 425return Decision (False , ["on this card the layer split with DFlash2 has not been measured slower than the all-cards split engine" ],d .cards ) 426return 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 , 435allow_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 437draft 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 438DFlash2'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 439package (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 440replicas say no, as in apply_to_config. Never raises.""" 441import os 442import sys 443 444try : 445m = mode (cfg ) 446if m == "off" : 447return False 448chosen = str (cfg .get ("drafting" )or "auto" ).lower () 449if chosen == "off" or (chosen == "dflash2" and m != "on" )or cfg .get ("user_args" )or cfg .get ("replicas" ): 450return False 451if kv not in (None ,"int8" ):# the split keeps int8 (apply_to_config says the same) 452return False 453system = system or ("linux" if sys .platform .startswith ("linux" )else sys .platform ) 454cards = (probe or probe_cards )(indexes )if system == "linux" else [] 455total ,avail = (ram or ram_gib )() 456model = ASSUMED_MODEL 457if native and os .path .isfile (native ): 458model = (scan or scan_model )(native ) 459experimental_ok = m == "on" and bool (cards )and cards [0 ].vendor == "amd" 460d = decide (enabled = True ,system = system ,cards = cards ,ram_total_gib = total ,ram_available_gib = avail ,model = model ,context = context , 461allow_untested = allow_untested or experimental_ok ) 462if not d .use_split or _auto_gates (d ,cards ,model ,chosen ,m )is not None : 463return False 464if exe_for_cards is not None : 465amd = cards [0 ].vendor == "amd" 466if not (exe_for_cards (d .cards ,cards [0 ].cc ,cards [0 ].arch_name )if amd else exe_for_cards (d .cards ,cards [0 ].cc )): 467return False 468return True 469except Exception :# noqa: BLE001 - a question asked early is never a reason to stop a launch 470return False 471 472 473def apply_to_config (cfg :dict ,* ,exe_for_cards ,system :str | None = None ,allow_untested :bool = False ,probe = None ,ram = None , 474scan = 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. 476exe_for_cards(n, cc) -> the path of the strata-split-n built for compute capability cc, or None (the engine package has none); 477probe(indexes) -> [Card]; ram() -> (total, available) GiB; scan(first_shard) -> ModelFacts: the facts of this PC and model, replaceable 478for tests. Mode "off": nothing happens, silently. Mode "auto": a refusal is `quiet` (the normal layer split starts without a word).""" 479m = mode_ or mode (cfg ) 480if m == "off" : 481return Decision (False , ["the all-cards split engine is turned off" ],quiet = True ) 482d = _apply (cfg ,exe_for_cards = exe_for_cards ,system = system ,allow_untested = allow_untested ,probe = probe ,ram = ram ,scan = scan ,data_dir = data_dir , 483mode_ = m ) 484if m == "auto" and not d .use_split : 485d .quiet = True 486record_launch_manifest (d ,m ) 487return 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 492setup 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.""" 493if not d .arch or "/" in d .arch or not d .arch .startswith ("gfx" ): 494return None 495return {"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 501timestamps, so two matched launches give the same text. Never raises and never changes the launch. True when a file was written.""" 502import json 503import os 504 505target = (os .environ if environ is None else environ ).get ("STRATA_MANIFEST" ) 506if not target : 507return False 508try : 509doc = {"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 )}} 513path = target + ".launch.json" 514tmp = path + ".tmp" 515with open (tmp ,"w" ,encoding = "utf-8" ,newline = "\n" )as f : 516json .dump (doc ,f ,indent = 2 ,sort_keys = True ) 517f .write ("\n" ) 518os .replace (tmp ,path ) 519return True 520except Exception :# noqa: BLE001 - a diagnostic never stops a start 521return False 522 523 524def _apply (cfg :dict ,* ,exe_for_cards ,system ,allow_untested ,probe ,ram ,scan ,data_dir ,mode_ :str = "auto" )-> Decision : 525import pathlib 526import sys 527 528system = system or ("linux" if sys .platform .startswith ("linux" )else sys .platform ) 529args = [str (a )for a in cfg .get ("args" )or []] 530native = _flag (args ,"--native" ) 531if not native : 532return 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. 537chosen = 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) 540if chosen == "dflash2" and mode_ != "on" : 541return Decision (False , ["DFlash2 drafting was chosen, which the all-cards split engine does not run" ]) 542if chosen == "off" : 543return Decision (False , ["drafting is off, and the all-cards split engine needs the draft layer" ]) 544if cfg .get ("user_args" )or cfg .get ("replicas" ): 545return Decision (False , ["this run config has engine arguments of its own or replicas, which the all-cards split engine does not take" ]) 546kv = _flag (args ,"--kv" ) 547if kv not in (None ,"int8" ): 548return Decision (False , [f"the conversation memory format is { kv } , the all-cards split engine keeps int8" ]) 549gpus = cfg .get ("gpu" ) 550indexes = [int (g )for g in gpus ]if isinstance (gpus ,list )else ([int (gpus )]if isinstance (gpus ,int )else None ) 551cards = (probe or probe_cards )(indexes )if system == "linux" else [] 552total ,avail = (ram or ram_gib )() 553try : 554model = (scan or scan_model )(native ) 555except Exception as e :# noqa: BLE001 - a file it cannot read is a reason, not a failed start 556return Decision (False , [f"the model file could not be read ( { type ( e ). __name__ } )" ]) 557context = 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 559experimental_ok = mode_ == "on" and bool (cards )and cards [0 ].vendor == "amd" 560d = decide (enabled = True ,system = system ,cards = cards ,ram_total_gib = total ,ram_available_gib = avail ,model = model ,context = context , 561allow_untested = allow_untested or experimental_ok ) 562if not d .use_split : 563return d 564gate = _auto_gates (d ,cards ,model ,chosen ,mode_ ) 565if gate is not None : 566return gate 567amd = cards [0 ].vendor == "amd" 568# NVIDIA: strata-split-N-sm<cc> or strata-split-N; AMD: strata-split-N-<arch> (gfx1201), the third argument 569exe = exe_for_cards (d .cards ,cards [0 ].cc ,cards [0 ].arch_name )if amd else exe_for_cards (d .cards ,cards [0 ].cc ) 570if not exe : 571return Decision (False , [f"this engine package has no strata-split- { d . cards } " + (f"- { cards [ 0 ]. arch_name } " if amd else "" )],d .cards ) 572df2_pack = None 573mtp = _flag (args ,"--mtp" ) 574if chosen == "dflash2" :# (mode "on"): the drafter is DFlash2's pack, the MTP layer is not loaded and not needed 575if not exe_takes_dflash2 (exe ): 576return Decision (False , ["DFlash2 drafting was chosen, which the all-cards split engine does not run" ],d .cards ) 577from strata_control import drafting 578folder = data_dir or drafting .data_dir_of (args ) 579if not folder or not drafting .pack_ready (folder ): 580return Decision (False , [NO_DF2_PACK ],d .cards ) 581df2_pack = str (drafting .pack_path (folder )) 582elif not mtp : 583return Decision (False , ["the model has no draft layer files (--mtp)" ],d .cards ) 584vocab = None 585for folder in (pathlib .Path (exe ).parent ,pathlib .Path (data_dir )if data_dir else None ,pathlib .Path (cfg .get ("cwd" )or "." )/ "data" ): 586if folder and (folder / "draft_vocab_en.bin" ).is_file (): 587vocab = str (folder / "draft_vocab_en.bin" ) 588break 589if not vocab : 590return Decision (False , ["draft_vocab_en.bin is missing" ],d .cards ) 591lanes = int (cfg .get ("parallel" )or _flag (args ,"--batch" )or (AMD_DEFAULT_LANES if amd else DEFAULT_LANES )) 592new = split_config (cfg ,d ,exe = exe ,native = native ,mtp_dir = mtp ,draft_vocab = vocab ,context = context ,lanes = lanes , 593vision = bool (cfg .get ("vision" ))or "--vision" in args ,dflash2_pack = df2_pack ) 594cfg .clear () 595cfg .update (new ) 596return 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.""" 608import mmap 609 610if not exe : 611return False 612try : 613path = pathlib .Path (exe ) 614st = path .stat () 615key = (str (path ),st .st_size ,st .st_mtime_ns ) 616if key not in _split_df2 : 617with 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 619return _split_df2 [key ] 620except (OSError ,ValueError ): 621return 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. 627One 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).""" 629import pathlib 630 631def exe_for (n :int ,cc :int | None = None ,arch :str | None = None ): 632from strata_control import engine_component as EC 633exe = cfg .get ("exe" ) 634try : 635real = EC .expand (exe ,cfg ,full = False )if EC .is_reference (exe )else exe 636except Exception :# noqa: BLE001 - no engine to look beside: no split 637return None 638for 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 } " ,)): 639p = pathlib .Path (str (real )).parent / name 640if p .is_file (): 641return str (p ) 642return None 643 644return 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.""" 649return "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.""" 654import pathlib 655 656try : 657return pathlib .Path (folder ).is_dir ()and any (pathlib .Path (folder ).iterdir ()) 658except OSError : 659return 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 664config 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). 665Auto 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 666hooks of apply_to_config (system, probe, ram, scan, data_dir), replaceable for tests.""" 667m = mode (cfg ) 668if m == "off" : 669return Decision (False , ["the all-cards split engine is turned off" ],quiet = True ),"" ,False 670args = [str (a )for a in cfg .get ("args" )or []] 671mtp_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) 674if mtp_dir and not draft_layer_present (mtp_dir )and not (str (cfg .get ("drafting" )or "" ).lower ()== "dflash2" and m == "on" ): 675line = "The all-cards split engine needs the model's draft layer (the MTP), which is not downloaded; using the normal layer split." 676return Decision (False , [line ],quiet = m != "on" ), (line if m == "on" else "" ),True 677before = dict (cfg ) 678try : 679d = apply_to_config (cfg ,exe_for_cards = exe_for_cards or exe_finder (cfg ),allow_untested = allow_untested ,** facts ) 680except Exception as e :# noqa: BLE001 - never stop a start over an option 681cfg .clear () 682cfg .update (before ) 683line = f"The all-cards split engine was left out ( { type ( e ). __name__ } ). Using the normal layer split." 684return Decision (False , [line ],quiet = m != "on" ), (line if m == "on" else "" ),True 685if d .quiet : 686return d ,"" ,False 687return d ,d .line ,not d .use_split