okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1b4018870
main
1"""Which drafter a model uses to guess ahead: DFlash2, MTP or none. One place, read by the Terminal and the app. 2 3One drafter per run. The engine is started with the DFlash2 drafter or with the MTP layer, never with both (owner, 2026-11-02): the one that is not 4chosen is not loaded, so its graphics memory goes to the expert cache. 5 6The choice is the person's, and it is saved in the model's run config as ``"drafting"``: ``auto`` (the default), ``mtp``, ``dflash2`` or ``off``. 7``strata launch --drafting ...`` writes it, the app's Models screen writes it, and ``serve/server.py`` applies it at every start (like ``"mtp": false``, 8strata_control/draft_layer.py), so a setup run that rewrites the engine arguments cannot undo it. An older config that names both drafters (``--mtp`` and 9``--draft dflash2``) starts with the one chosen. 10 11dflash2 ``--draft dflash2 --draft-model <pack> --draft-fallback none --mtp-draft-vocab <file> --spec 6 --draft-conf 0.35`` (``--spec 8`` on Strix Halo and on Blackwell cc 12.0 with >= 48 GB, whose conf is 0.55: window_for / big_blackwell) and no ``--mtp``: the DFlash2 12block drafter (incoai/Qwen3.8-Flash-Next-DFlash2, Q4_0 pack) for Qwen3.8-Flash-Next, Gyro and Unsloth's quantizations, with the window and confidence that measured best 13(RESULTS-DRAFT.md section 4); a ``--spec`` or ``--draft-conf`` the person set by hand (``user_args``) stays 14mtp the model's own draft layer (``--mtp <folder>``) and none of the DFlash2 flags 15off no draft layer and no DFlash2 (the same as ``"mtp": false``: the engine still looks ahead in the text with ``--spec``) 16auto DFlash2 wherever the engine has it (DFLASH2_BACKENDS) and the model is Qwen3.8-Flash-Next, Gyro or an Unsloth quantization, the MTP everywhere else 17 18Recommend, never force: a choice that cannot be applied (DFlash2 with several requests at once, no drafter file yet) does not stop the 19start. The other drafter runs if it is on this computer, else none, and ``Decision.note`` says why in one short line. Nothing is loaded twice and the 20engine never switches drafter mid-run. 21""" 22 23from __future__import annotations 24 25import hashlib 26import json 27import mmap 28import os 29import re 30import struct 31import sys 32import time 33from dataclasses import dataclass 34from pathlib import Path 35from typing import Any 36 37MODES = ("auto" ,"mtp" ,"dflash2" ,"off" ) 38DEFAULT_MODE = "auto" 39LABELS = {"auto" :"Auto (recommended)" ,"mtp" :"MTP" ,"dflash2" :"DFlash2" ,"off" :"Off" } 40DRAFTERS = ("mtp" ,"dflash2" ,"off" ) 41 42#: The engine families that have the DFlash2 code (CMakeLists.txt STRATA_HAVE_DFLASH2). Auto picks DFlash2 on these; a computer with any other engine keeps the 43#: MTP. Intel SYCL joined with the DF2-SYCL engine (Arc A750 measured: a tie with the MTP, section 8-9 of phaseA-tests/blackwell/RESULTS-DF2SYCL.md). Metal: the DF2-METAL engine. 44DFLASH2_BACKENDS = ("cuda" ,"hip" ,"metal" ,"sycl" ) 45 46#: Graphics memory each drafter takes on Qwen3.8-Flash-Next IQ3_S (GB; phaseA-tests/blackwell/RESULTS-DF2MEM.md section 1, l620, engine free memory at 47#: the first graph capture): DFlash2 alone 890 MiB, the MTP layer 1082 MiB. The fit, the plan and the slot estimates use the one that is chosen. 48#: `dflash2_selq4` is DFlash2 alone with the converted pack (the selector's codebooks as Q4_0 rows, 175 MiB less: the engine's drafter line 800 -> 625 MiB, section 16): 49#: 715 MiB. vram_gb() says which of the two is the true figure on this computer. The apps keep copies of these numbers (apps/host/server/native-parallel.mjs and 50#: apps/host/src/lib/native-fit.ts); apps/host/tests/drafting.test.mjs reads this table and fails when they differ. 51DRAFTER_MIB = {"dflash2" :890 ,"dflash2_selq4" :715 ,"mtp" :1082 ,"off" :0 } 52DRAFTER_GB = {name :int (mib / 10 + 0.5 )/ 100 for name ,mib in DRAFTER_MIB .items ()}# 0.89, 0.72, 1.08, the figures the apps show (mib rounded half up to 10 MiB) 53 54#: GPU architecture (what nvidia-smi's compute capability and the kernel driver report) -> card class 55ARCH_CLASS = ( 56 (re .compile (r"^gfx1151$" ),"strix_halo" ), 57 (re .compile (r"^gfx120[01]$" ),"rdna4" ), 58 (re .compile (r"^sm_12\d$" ),"blackwell" ), 59 (re .compile (r"^sm_86$" ),"ampere" ), 60) 61 62 63def card_class (archs :Any )-> str : 64"""The class of the first card whose architecture the table knows (``sm_120``, ``gfx1151``...); ``other`` for an unknown or empty list.""" 65for arch in ([archs ]if isinstance (archs ,str )else list (archs or [])): 66for pattern ,name in ARCH_CLASS : 67if pattern .match (str (arch ).strip ().lower ()): 68return name 69return "other" 70 71 72# --------------------------------------------------------------------------------------------------- where the engine can run it 73# 74# The DFlash2 code (src/core/dflash2.cpp, src/kernels/cuda/dflash2.cu) is compiled into the engines of DFLASH2_BACKENDS (CMakeLists.txt, STRATA_HAVE_DFLASH2); 75# the others have none, and a PC with no supported graphics card has no engine to run it. Where the code exists, three words say what was 76# measured (DFlash2 against MTP, same prompts, same flags; the numbers are in the comment above SUGGESTED and in phaseA-tests/blackwell/RESULTS-DRAFT.md): 77# tested measured on this kind of card: faster on some kinds of text, slower on others 78# slower measured on this kind of card: slower on every prompt 79# untested the engine has the code for this card but it was never measured on it 80 81#: What the Terminal's Drafting step and the app's paragraph under the dropdown say (the same words; apps/host/src/locales/df2-en.json, tests keep them equal). 82#: The numbers are measured: l620, RTX PRO 5000, Qwen3.8-Flash-Next IQ3_S, DFlash2 `--spec 6 --draft-conf 0.35` against MTP (phaseA-tests/blackwell/RESULTS-DRAFT.md section 4). 83EXPLAIN_NUMBERS = ("MTP is the default. DFlash2 is another way to guess the next words ahead, for Qwen3.8-Flash-Next only. On an RTX PRO 5000 it was 7.8% faster than MTP " 84"on 19 short prompts and 1.1% faster on long thinking, and faster on 21 of 23 prompts. On the short prompts the answers were identical." ) 85EXPLAIN_LIMITS = "It downloads about 1.2 GB once, works with one graphics card and one request at a time, and uses MTP otherwise." 86 87LINE_TESTED = "On graphics cards like yours, DFlash2 was faster than MTP on some kinds of text and slower on others in our tests." 88LINE_SLOWER = "On graphics cards like yours, DFlash2 was slower than MTP in our tests." 89LINE_UNTESTED = "DFlash2 has not been tested on your graphics card yet." 90LINE_AUTO_MTP = "DFlash2 is off by default on this graphics card for now; choose it in Drafting to use it." # a card in AUTO_MTP: Auto starts the MTP 91LINE_METAL = "On your Mac, DFlash2 was faster than MTP on this model in our tests." # a Mac and a set in SET_DEFAULTS whose default is DFlash2 (replaces "not tested" there) 92 93 94@dataclass( frozen = True ) 95class Support : 96can_run :bool # this engine build has the DFlash2 code for the card 97level :str # none | tested | slower | untested 98line :str # plain words for the person ("" when there is nothing to say) 99 100 101_TESTED = {("cuda" ,"sm_120" ), ("cuda" ,"sm_121" ), ("hip" ,"gfx1151" ), ("hip" ,"gfx1201" ), ("sycl" ,"arc_a" )} 102_SLOWER = {("cuda" ,"sm_86" )} 103 104 105_HARDWARE :list = [] 106 107# --- Intel: the SYCL path gives no architecture, so the card is told by its name (Windows display adapters) or its PCI id (Linux sysfs). 108# arc_a Arc A-series, Alchemist: A3xx / A5xx / A7xx (the A750 was measured: RESULTS-DF2SYCL.md), PCI ids 0x56A0..0x56AF and the mobile 0x5690..0x5692 109# arc_a_pro Arc Pro A-series (A40, A50, A60): not measured 110# arc_b Arc B-series, Battlemage (B580, Pro B60, B65, B70...): not measured 111# intel_igpu integrated graphics (UHD, Iris Xe, "Arc Graphics" of Core Ultra): not measured 112_ARC_NAME = re .compile (r"\bArc\b(?:\(TM\))?\s*(Pro\s+)?([AB])\s?(\d{2,3})(?!\d)" ,re .I ) 113 114 115def sycl_arch_of_name (name :str )-> str : 116"""The class of an Intel adapter from its Windows name: ``Intel(R) Arc(TM) A750 Graphics`` is ``arc_a``; ``intel_igpu`` for any other Intel name.""" 117m = _ARC_NAME .search (str (name or "" )) 118if not m : 119return "intel_igpu" 120pro ,letter ,number = bool (m .group (1 )),m .group (2 ).upper (),int (m .group (3 )) 121if letter == "B" : 122return "arc_b" 123return "arc_a" if not pro and number >= 300 else "arc_a_pro" # A310 / A380 / A580 / A750 / A770 and the mobile A3xx-A7xx; A40 / A50 / A60 and every Pro are not measured 124 125 126def sycl_arch_of_pci (driver :str ,devid :str )-> str : 127"""The class of an Intel card from its Linux driver and PCI device id (strata_control/intel_spec.py's cards): i915 ids 0x56A0.. are Alchemist, 0x56B0.. the Pro 128A-series, xe ids 0xE2xx Battlemage.""" 129try : 130n = int (str (devid ).lower ().replace ("0x" ,"" ),16 ) 131except ValueError : 132return "intel_igpu" 133if driver == "xe" and 0xE200 <= n <= 0xE2FF : 134return "arc_b" 135if driver == "i915" and 0x5690 <= n <= 0x56AF : 136return "arc_a" 137if driver == "i915" and 0x56B0 <= n <= 0x56BF : 138return "arc_a_pro" 139return "intel_igpu" 140 141 142def sycl_archs_present ()-> list [str ]: 143"""One class (``arc_a`` ...) per Intel card: from the display adapters on Windows, from sysfs on Linux. Empty when neither can say.""" 144from strata_control import engine_component ,intel_spec 145found :list [str ]= [] 146if os .name == "nt" : 147for adapter in engine_component .windows_display_adapters (): 148if str (adapter .get ("vendor" ,"" )).lower ()== "8086" : 149found .append (sycl_arch_of_name (adapter .get ("name" ,"" ))) 150else : 151for card in intel_spec .sysfs_cards (): 152found .append (sycl_arch_of_pci (card .get ("driver" ,"" ),card .get ("devid" ,"" ))) 153return found 154 155 156def detect_hardware ()-> tuple [str | None ,list [str ]]: 157"""(engine family, card architectures) of this computer, looked up once: ``("cuda", ["sm_120"])``, ``("hip", ["gfx1151"])``, ``("metal", [])``; 158``(None, [])`` when nothing answers. Read-only probes of tools that are already installed; never raises, never downloads.""" 159if not _HARDWARE : 160backend :str | None = None 161archs :list [str ]= [] 162try : 163from strata_control import engine_component 164backend = engine_component .detect_backend ()[0 ] 165archs = list (engine_component .cuda_archs_present ())+ list (engine_component .hip_archs_present ()) 166if backend == "sycl" and not archs : 167archs = sycl_archs_present () 168except Exception :# noqa: BLE001 - an unknown computer is "no DFlash2", never an error 169pass 170_HARDWARE .append ((backend ,archs )) 171return _HARDWARE [0 ] 172 173 174def hardware_support (backend :str | None ,archs :Any = None ,model_name :str | None = None )-> Support : 175"""Can the engine for this backend and card run DFlash2, and what was measured on it. ``backend`` is the engine family (cuda | hip | sycl | metal); 176``archs`` the cards' architectures (``sm_120``, ``gfx1151``...), the first one counts like card_class does. ``model_name``: on Metal the answer is 177per set (SET_DEFAULTS): a set whose default is DFlash2 was measured; the others keep "not tested".""" 178make = str (backend or "" ).strip ().lower () 179if make not in DFLASH2_BACKENDS : 180return Support (False ,"none" ,"" ) 181first = ([archs ]if isinstance (archs ,str )else list (archs or [])) 182arch = str (first [0 ]).strip ().lower ()if first else "" 183if (make ,arch )in AUTO_MTP : 184return Support (True ,"tested" ,LINE_AUTO_MTP ) 185if make == "metal" : 186entry = default_for (make ,model_name ) 187if entry is not None and entry .drafter == "dflash2" : 188return Support (True ,"tested" ,LINE_METAL ) 189if (make ,arch )in _TESTED : 190return Support (True ,"tested" ,LINE_TESTED ) 191if (make ,arch )in _SLOWER and any (k [0 ]== make and k [1 ]== set_of (model_name )and v .drafter == "dflash2" for k ,v in CLASS_DEFAULTS .items ()): 192return Support (True ,"tested" ,LINE_TESTED )# a set whose default on this class of card is DFlash2 (CLASS_DEFAULTS): faster on some kinds of text, slower on others 193if (make ,arch )in _SLOWER : 194return Support (True ,"slower" ,LINE_SLOWER ) 195return Support (True ,"untested" ,LINE_UNTESTED ) 196 197 198# --------------------------------------------------------------------------------------------------- the drafter file 199# 200# incoai/Qwen3.8-Flash-Next-DFlash2 (Apache-2.0), pinned to one revision. The safetensors file is 1.2 GB; tools/dflash2_pack.py --q4_0 turns it, on the 201# person's own computer, into the engine's runtime file (a Q4_0 pack, 522,458,112 bytes; the repository publishes only the bf16 file and we host nothing). 202# The sizes and hashes are the repository's own for that revision: a download is refused if either differs. The pack itself is checked too: the same 203# bytes come out on x86 Windows, x86 Linux and aarch64 Linux (numpy 2.3.3 and 2.5.3), so its size and SHA-256 are pinned and a pack that differs is deleted. 204# A Q8 pack (760,353,792 bytes) made by an earlier Strata keeps working and is never fetched again; Q4_0 and Q8 ran the same speed (-0.3%, RESULTS-DRAFT.md). 205 206REPO = "incoai/Qwen3.8-Flash-Next-DFlash2" 207REVISION = "a22a1744e85c17364dcc54a6a420af7135d4c7f6" 208LICENSE = "Apache-2.0" 209BASE_URL = f"https://huggingface.co/ { REPO } /resolve/ { REVISION } /" 210FILES = ( 211 ("config.json" ,1236 ,"2409575986f9ea24d455343eb469c0e6940def5edab1d1be503bb8eb4cc3b1b9" ), 212 ("model.safetensors" ,1206140008 ,"d6723f2a359eaf33ec0c95f22ae8edda896774020c552296a85e1913b4d3186f" ), 213) 214DOWNLOAD_GB = 1.2 # what is fetched (the safetensors file) 215PACK_GB = 0.52 # what stays on disk (the source file is removed after packing) 216PACK_NAME = "qwen3.8-flash-next-dflash2.q4_0.pack" 217PACK_BYTES = 522458112 # the Q4_0 pack tools/dflash2_pack.py --q4_0 makes from the pinned safetensors file, and its SHA-256 218PACK_SHA256 = "cda40d62d0eb8f37ed6e272142641a1d2f0de4a32f9e14d0416e7a71534849f1" 219# The same pack with the selector's two codebooks as Q4_0 rows (174 MiB less in graphics memory, ~88 expert slots; draft ms, acceptance and the committed text equal: RESULTS-DF2MEM.md 220# section 15). The idea and the bytes are nazeshinjite's: the community GGUF https://huggingface.co/nazeshinjite/Qwen3.8-Flash-Next-DFlash2-GGUF (Apache-2.0) stores the codebooks 221# as Q4_0, and tools/dflash2_pack.py --q4_0-selector / --convert-selector writes exactly those bytes (selector_predecessor sha256 55f70049...ffd28, selector_successor 222# 3b596669...a72d2 over the tensor bytes; checked equal to the GGUF's). We host nothing: setup / Load converts the verified Q4_0 pack above on this computer 223# (drafting_fetch.convert_selector, no network, a second or two); the engine reads either pack and says "selector codebooks: Q4_0 rows" when it loads the converted one. 224CONVERTED_NAME = "qwen3.8-flash-next-dflash2.q4_0-selq4.pack" 225CONVERTED_BYTES = 339694592 226CONVERTED_SHA256 = "4a42b98220ea7880664002c8edda1563aecbae754b762a2e2f31b2b91ee93ecd" 227_MARK_SELQ4 = b"selector codebooks: Q4_0 rows" # text of an engine that reads such a pack (src/core/dflash2.cpp) 228# The tuned drafter (round 0216, DF-SHIP; phaseA-tests/round0215/RESULTS-DF2WS.md sections 15-20): the published weights, fine-tuned by Strata on the 4-bit targets' own 229# outputs and packed as the Q4_0 + Q4_0-selector pack (the same format and size as CONVERTED_NAME, so no engine change). +11.4% accepted drafts on UD-Q4_K_XL and UD-IQ4_XS-v31; 230# on Metal +4.5% / +3.4% output tokens per second against the stock pack at 0.5, greedy identity 120 of 120 per set, WITH --draft-conf 0.7 (at 0.5 it is a wash, and the 231# stock pack is 5% worse at 0.7: the setting belongs to the pack). It is a file Strata hosts (the repository publishes only the bf16 file). 232# Apache-2.0, modified by Strata: data/dflash2-tuned/ (LICENSE, NOTICE.md) ships with Strata and is copied beside the file when it is fetched. 233TUNED_NAME = "qwen3.8-flash-next-dflash2.strata1.q4_0-selq4.pack" 234TUNED_BYTES = 339694592 235TUNED_SHA256 = "4df2e5ab2b47c064afbe662e16e4f06569877125c2d0e2123a4ac755266c664c" 236TUNED_GB = 0.34 237# The same tuned weights for an engine that reads only the bf16 selector codebooks (the SYCL 0.2.11 engine refuses the Q4_0-selector pack above): the Q4_0 pack of tools/dflash2_pack.py 238# --q4_0 (the tool reproduces the stock Arc pack cda40d62... exactly from the stock weights). Its own name, size and SHA-256; the feed lists it for ["sycl"] only. 239TUNED_BF16_NAME = "qwen3.8-flash-next-dflash2.strata1.q4_0-bf16sel.pack" 240TUNED_BF16_BYTES = 522458112 241TUNED_BF16_SHA256 = "34ca17fee701ff088b6069acc35a26661d237953f5d114be0a3f7dae3ec5cda9" 242TUNED_BF16_GB = 0.52 243#: Where it is hosted (owner 11-06, recommendation of the coordinator): a GitHub release asset of Niko1221/Strata, listed in the signed feed (strata-feed.json, feed key 5d1bc23a) as a 244#: `drafters` entry (packaging/feed_tool.py pack-drafter, build-feed --drafters), so the app gets the feed's signature, offline handling and updates the same way as engine packages. 245#: The entry's url is relative to the feed (flat release assets); the size and SHA-256 above are pinned in the code as well, so the feed can move the file but never swap its bytes. 246#: Written alternative, not implemented: a Hugging Face repository under the owner's account (a resolve address of the pinned commit), fetched with the 247#: same pins; it would need the one address below and loses the feed's signature. 248TUNED_FEED_MEMBER = "drafters" 249TUNED_BACKEND = "metal" # the engine family the feed entry must list 250TUNED_URL_ENV = "STRATA_DFLASH2_TUNED_URL" # tests and mirrors: a direct address (https, file:) of the same pinned bytes, instead of the feed 251TUNED_LICENCE_FOLDER = "data/dflash2-tuned" # LICENSE (Apache-2.0) and NOTICE.md, shipped in data/ with the draft vocabularies 252TUNED_BASE = "incoai/Qwen3.8-Flash-Next-DFlash2 revision a22a1744e85c17364dcc54a6a420af7135d4c7f6" 253LEGACY_PACK_NAME = "qwen3.8-flash-next-dflash2.q8.pack" # what Strata 0.2.9 test builds packed: still used when it is the one on disk 254VRAM_GB = DRAFTER_GB ["dflash2" ]# graphics memory with the MTP layer not loaded and the bf16-selector pack: 890 MiB (RESULTS-DF2MEM.md); vram_gb() has the true figure for this computer 255FOLDER = "dflash2" # under the model data folder, next to ``mtp`` 256SPEC_WINDOW = 6 # --spec with DFlash2: the widest window of drafted words per round (measured best on Blackwell; the engine caps it per card) 257WIDE_WINDOW = 8 # --spec on the two card classes whose engine cap (include/strata/core/draft_cap.hpp dflash2_auto_cap) is 8: Strix Halo and Blackwell cc 12.0 with >= 48 GB (window_for). The engine only ever lowers --spec to its cap, so every other card keeps SPEC_WINDOW 258MTP_WINDOW = 4 # the MTP's usual --spec: the window it runs when DFlash2 falls back to it, unless the config names another 259DRAFT_CONF = 0.35 # --draft-conf with DFlash2: the window ends where the chance that every draft so far holds falls below this (the card holds most experts) 260 261# --draft-conf by how many expert slots the card holds once the drafter is on. THE UNIT IS THE ENGINE'S SLOT (the "expert cache N slots" line of its log, one slot 262# averaging 1.95 MiB of IQ3_S): an explicit --expert-cache N is a budget of N x the largest blob (2.54 MiB), which the engine turns into about 1.3 N slots 263# (measured N = 300 .. 12,000 -> 384 .. 15,667 slots, ratio 1.28 .. 1.31; EXPERT_CACHE_SLOTS_PER_N below). 264# Measured with DFlash2 ALONE (no MTP layer loaded: the drafter is the only one, as it is by default now) against the MTP at spec 4, equal VRAM, l620 mimic, 265# IQ3_S, 6-turn chat with a rewind + 4 cold prompts, 300 greedy tokens, prompt cache 6, 3 paired rounds (RESULTS-DF2MEM.md section 12). Gain over MTP by 266# confidence 0.35 / 0.5 / 0.65 / 0.8 / 0.9, at the DFlash2 engine's slot count: 267# 1,383 slots: -4.2 / +3.1 / +7.1 / +9.3 / +8.7% 3,337: -1.8 / +4.3 / +7.1 / +7.7 / +5.8% 6,629: -0.5 / +3.6 / +6.9 / +5.2 / +2.6% 268# 9,248 slots: -0.5 / +5.9 / +3.9 / +2.6 / -0.1% 15,766: +4.9 / +5.6 / +3.5 / -0.6 / -6.5% (0.5 and 0.35 are level there: 3 of 3 pairs each) 269# The older table here (DFlash2 +0.2 .. -10% against the MTP) charged the MTP layer's VRAM to the DFlash2 engine. 270# Steps, rounded: the more experts come over PCIe, the dearer a row, the shorter the window should be. 271CONF_STEPS = ((12000 ,0.35 ), (7500 ,0.5 ), (3000 ,0.7 ), (0 ,0.8 ))# (engine slots at least, --draft-conf) 272EXPERT_CACHE_SLOTS_PER_N = 1.3 # an explicit --expert-cache N holds about this many engine slots per N on the IQ3_S pack (1.28 at N = 1,000 .. 1.31 at N = 12,000) 273MAX_SLOTS = 24576 # every (layer, expert) pair of Qwen3.8-Flash-Next 274# A backend whose card class was measured on its own has ONE value that replaces the slot steps (they were calibrated on CUDA cards with 300 to 9,300 slots): 275# Intel Arc (SYCL, A750 with 298 expert slots, IQ3_XXS, serve sweeps with suffix drafting on): 0.6 was the best of 0.35 / 0.6 / 0.8 and the other two lost 4 to 10% 276# (RESULTS-DF2SYCL.md sections 6-8). 277# Metal (M5 Max 128 GB, UD-Q4_K_XL, all experts mapped: the expert-cache slot count the CUDA steps read means nothing there), greedy 300 tokens, serve path, fresh engine per run, 278# DFlash2 --spec 6 against MTP --spec 2, 3 interleaved rounds x 2 reps, six request kinds (phaseA-tests/round0215/RESULTS-MAC-OUT.md): conf 0.35 / 0.5 / 0.6 = +10.0 / +14.3 / +12.4% over all 279# six kinds (0.5 faster than MTP on every kind in 3 of 3 rounds; the slot rule would have written 0.8 for the Mac's --expert-cache 64). 280BACKEND_CONF = {"sycl" :0.6 ,"metal" :0.5 } 281# Large-VRAM Blackwell (cc 12.0 = sm_120, at least 48 GB: l620's RTX PRO 5000 72 GB; NOT the DGX Spark, sm_121, and not a consumer card under 48 GB, which were not measured): a window of 8 for every 282# set (the engine cap is 8 there too, set-independent: window 8 alone at conf 0.35 was +0.5% on IQ3_S) and, for IQ3_S only (SetDefault.big_blackwell_conf in SET_DEFAULTS, owner/coordinator 11-08), 283# conf 0.55. 11-08 sweep (phaseA-tests/df2r2/RESULTS-CONF.md), IQ3_S, 36 requests, 300 greedy tokens, 5 interleaved pairs against conf 0.35 / window 6: +2.4%, 5 of 5 pairs faster, output identical 284# (conf 0.55 alone +1.1%). Only where every expert is resident (the first CONF_STEPS step), the case that was measured; the other sets on that card were not measured and keep 0.35. 285BIG_CARD_BYTES = 48_000_000_000 # "48 GB" the way cards are sold (a 48 GB card reports about 47.5 GiB); the engine's kDflash2BigCardBytes is the same number 286 287 288@dataclass( frozen = True ) 289class TunedPack : 290"""One tuned file: ``key`` is what SetDefault.pack names (``selq4`` = Q4_0 selector codebooks, the CUDA / HIP / Metal engines; ``bf16sel`` = bf16 selector codebooks, the SYCL engine).""" 291key :str 292name :str 293size :int 294sha256 :str 295gb :float 296selector_q4 :bool 297 298 299def tuned_pack (variant :str | None = None )-> TunedPack : 300"""The pin of a tuned file, read from the module's constants at call time.""" 301if variant == "bf16sel" : 302return TunedPack ("bf16sel" ,TUNED_BF16_NAME ,TUNED_BF16_BYTES ,TUNED_BF16_SHA256 ,TUNED_BF16_GB ,False ) 303return TunedPack ("selq4" ,TUNED_NAME ,TUNED_BYTES ,TUNED_SHA256 ,TUNED_GB ,True ) 304 305 306@dataclass( frozen = True ) 307class SetDefault : 308"""What Auto does for one model set on one engine family. ``drafter``: ``dflash2`` or ``mtp``. ``tuned``: DFlash2 starts with Strata's tuned pack (TUNED_NAME) where the pack is here and 309``where`` holds. ``tuned_conf``: the ``--draft-conf`` that goes with the tuned pack, or None = the backend's OWN conf stays (CONF_STEPS / BACKEND_CONF: only the pack changes). ``where``: 310"" always (Metal); "resident" CUDA with every expert resident = the card the first CONF_STEPS step (conf 0.35) is for, or a shared-memory chip (sm_121, the Spark class); "gfx1151" Strix Halo; 311"arc_a" Intel Arc A-series (the class the A750 stands for). ``pack``: which tuned file (tuned_pack): ``selq4`` or, for the SYCL engine, ``bf16sel``.""" 312drafter :str 313tuned :bool = False 314tuned_conf :float | None = None 315where :str = "" 316pack :str = "selq4" 317big_blackwell_conf :float | None = None # the ``--draft-conf`` on the large-VRAM Blackwell class (big_blackwell: cc 12.0, >= 48 GB) with the tuned pack, for the sets measured there; None = the backend's own conf 318 319 320#: Per (engine family, set) defaults, measured. THE ONE TABLE to switch a set either way. The set is the model_name without its "qwen3.8-flash-next-" prefix. 321#: METAL (M5 Max, RESULTS-MAC-OUT.md / RESULTS-MAC-INT.md / RESULTS-DF2WS.md): DFlash2 --spec 6 over MTP --spec 2 is +12.7% on UD-Q4_K_XL and +9.2% on UD-IQ4_XS-v31 (5 interleaved pairs); 322#: the tuned pack at conf 0.7 adds +4.5% / +3.4% over the stock pack at 0.5 (6 pairs per set, greedy identity 120/120). IQ3_S stays on the MTP until the owner says otherwise; to switch it: 323#: ("metal", "iq3_s"): SetDefault("dflash2") (the stock pack at conf 0.5; the Mac setup then fetches the drafter for it too). 324#: CUDA / HIP (owner 11-06 ~10:00; RESULTS-DFVAL.md, tuned pack at the box's CURRENT conf against the stock pack, 3 interleaved rounds, 24 requests an arm and round; DFlash2 is already their 325#: Auto drafter, so only the pack changes and the conf stays what CONF_STEPS / the card class give): ONLY the cells that were measured are enabled: 326#: cuda "resident" (conf 0.35): IQ3_S l620 (RTX PRO 5000) x1.021 (3/3 rounds) and DGX Spark x1.032 / x1.048 (3/3, two runs); UD-IQ4_XS-v31 DGX Spark x1.050 (3/3). CUDA ids identical. 327#: hip gfx1151 (Strix Halo, conf 0.35): IQ3_S x1.037, UD-Q4_K_XL x1.043, UD-IQ4_XS x1.045 (3/3 each; the text differs by window length on HIP, as with any conf change); UD-IQ4_XS-v31 x1.046 (setup's config, budget 38, 3 rounds, 3/3: agent 1.075, chat 1.013, code 1.073, creative 1.030, json 1.066, tool 1.055). 328#: SYCL / Intel Arc (owner 11-06 ~11:30 "Yes for Arc"; DF-VAL, A750 8 GB on p1006, SYCL 0.2.11, IQ3_XXS, 3 rounds, against the stock pack at Arc's 0.6 = 18.8 tok/s): the bf16-selector tuned pack 329#: at 0.6 x1.054 (3/3 rounds), at 0.5 x1.063; MTP x0.995; the stock pack against itself x1.011. The SYCL engine refuses the selq4 pack, so Arc has its OWN file (``pack`` "bf16sel", TUNED_BF16_*) 330#: and keeps BACKEND_CONF["sycl"] = 0.6. ONLY IQ3_XXS, the measured set; every other Arc set stays on the stock pack until it is measured. 331#: NOT enabled: a 12 GB / streaming card (the CONF_STEPS 0.8 step: P2003 is still being measured), gfx1201 / R9700 (the DFlash2 prompt stall is open), SYCL / Arc (untested), several cards (not measured), 332#: and the sets nobody measured on that platform (CUDA UD-Q4_K_XL, CUDA UD-IQ4_XS): each is one more line here once DF-VAL has the cell. 333SET_DEFAULTS = { 334 ("metal" ,"unsloth-ud-q4_k_xl" ):SetDefault ("dflash2" ,True ,0.7 ), 335 ("metal" ,"unsloth-ud-iq4_xs-v31" ):SetDefault ("dflash2" ,True ,0.7 ), 336 ("metal" ,"iq3_s" ):SetDefault ("mtp" ), 337 ("cuda" ,"iq3_s" ):SetDefault ("dflash2" ,True ,None ,"resident" ,big_blackwell_conf = 0.55 ), 338 ("cuda" ,"unsloth-ud-iq4_xs-v31" ):SetDefault ("dflash2" ,True ,None ,"resident" ), 339 ("hip" ,"iq3_s" ):SetDefault ("dflash2" ,True ,None ,"gfx1151" ), 340 ("hip" ,"unsloth-ud-q4_k_xl" ):SetDefault ("dflash2" ,True ,None ,"gfx1151" ), 341 ("hip" ,"unsloth-ud-iq4_xs" ):SetDefault ("dflash2" ,True ,None ,"gfx1151" ), 342 ("hip" ,"unsloth-ud-iq4_xs-v31" ):SetDefault ("dflash2" ,True ,None ,"gfx1151" ), 343 ("sycl" ,"iq3_xxs" ):SetDefault ("dflash2" ,True ,None ,"arc_a" ,"bf16sel" ), 344} 345#: Per (engine family, set, card class) defaults for a class of CARD, read from the same slot count the confidence reads (owner 11-06 ~15:30 "1 yes"). Today one class: "streaming" = a CUDA card whose 346#: engine slots are under the last-but-one CONF_STEPS step (3000), i.e. the step that gives conf 0.8: the 12 GB class (P2003, RTX 3060), where the experts stream and IQ3_S runs from the file cache. 347#: A class entry beats the (backend, set) entry above for the cards of its class and changes nothing for any other card; ONE REMOVABLE ENTRY PER SET: 348#: IQ3_S -> Auto is the MTP: on the 12 GB card with the file cache the MTP beats DFlash2 by 12-44% (RTX2 t4b), DF-VAL saw up to 3.1x. 349#: UD-IQ4_XS-v31 -> Auto is DFlash2 with the tuned selq4 pack at the class's CURRENT conf (0.8, unchanged): with RTX2's file-tier fix (unbuffered reads) DFlash2 beats the MTP by about 6.5% (t8, 3 starts: 350#: agent +14.2%, code +12.9%, chat +7.3%, tool +2.1%, json -3.5%); DF-VAL, forced-fast: tuned at 0.8 x1.037 against the stock pack. THIS ENTRY DEPENDS ON RTX2's FILE-TIER FIX BEING IN THE SAME RELEASE. 351#: Other sets on that class: unchanged (the general rule). Anything chosen by name (a saved "drafting", `--drafting`, the app's dropdown) wins over both. 352CLASS_DEFAULTS = { 353 ("cuda" ,"iq3_s" ,"streaming" ):SetDefault ("mtp" ,where = "streaming" ), 354 ("cuda" ,"unsloth-ud-iq4_xs-v31" ,"streaming" ):SetDefault ("dflash2" ,True ,None ,"streaming" ), 355} 356MODEL_PREFIX = "qwen3.8-flash-next-" 357 358#: Cards where Auto starts the MTP instead of DFlash2 (owner 11-06 ~10:30), keyed (engine family, first architecture); the value is why. ONE ENTRY, delete it to put Auto back. 359#: gfx1201 (RX 9070 / R9700 class): the open DFlash2 PROMPT STALL, 11 of 50 engines on 0.2.11 never got past the prompt, until PE-RDNA4's fix lands. Only Auto is affected: DFlash2 chosen 360#: by name (the Drafting step, the app's dropdown, `--drafting dflash2`, a saved "drafting": "dflash2") still starts DFlash2, and every other card and platform is unchanged. 361AUTO_MTP = {("hip" ,"gfx1201" ):"the DFlash2 prompt stall (11 of 50 engines on 0.2.11); PE-RDNA4's fix is pending" } 362 363 364def set_of (model_name :str | None )-> str : 365"""The set a run config's model_name names: ``qwen3.8-flash-next-unsloth-ud-q4_k_xl`` is ``unsloth-ud-q4_k_xl``.""" 366name = str (model_name or "" ).strip ().lower () 367return name [len (MODEL_PREFIX ):]if name .startswith (MODEL_PREFIX )else name 368 369 370def default_for (backend :str | None ,model_name :str | None )-> SetDefault | None : 371"""The measured default of this set on this engine family (SET_DEFAULTS), or None when it was not decided (the general rule applies).""" 372return SET_DEFAULTS .get ((str (backend or "" ).strip ().lower (),set_of (model_name ))) 373 374 375def tuned_entry (backend :str | None ,model_name :str | None )-> SetDefault | None : 376"""The table entry when this set on this engine family uses the tuned pack at all (whether THIS card qualifies is tuned_applies).""" 377entry = default_for (backend ,model_name ) 378return entry if entry is not None and entry .drafter == "dflash2" and entry .tuned else None 379 380 381def tuned_variant (backend :str | None ,model_name :str | None )-> str | None : 382"""Which tuned file this set on this engine family uses (``selq4`` / ``bf16sel``), or None: no tuned entry.""" 383entry = tuned_entry (backend ,model_name ) 384return entry .pack if entry is not None else None 385 386 387def tuned_conf_for (backend :str | None ,model_name :str | None )-> float | None : 388"""The ``--draft-conf`` the tuned pack runs at for this set (Metal 0.7), or None: no tuned entry, or the entry keeps the backend's own conf.""" 389entry = tuned_entry (backend ,model_name ) 390return entry .tuned_conf if entry is not None else None 391 392 393def first_arch (archs :Any )-> str : 394first = [archs ]if isinstance (archs ,str )else list (archs or []) 395return str (first [0 ]).strip ().lower ()if first else "" 396 397 398def streaming_class (backend :str | None ,archs :Any = None ,* ,args :list [Any ]| None = None ,vram_mib :float | None = None )-> bool : 399"""Is this a CUDA card of the 12 GB / streaming class: the one card's memory is known (or the person gave an --expert-cache) and slots_of() is under the last-but-one CONF_STEPS step, so the 400confidence is the last step's (0.8)? The Spark (one memory pool) and several cards are not.""" 401if str (backend or "" ).strip ().lower ()!= "cuda" or first_arch (archs )== "sm_121" : 402return False 403slots = slots_of (list (args or []),vram_mib ) 404return slots is not None and slots < CONF_STEPS [- 2 ][0 ] 405 406 407def class_entry (backend :str | None ,model_name :str | None ,archs :Any = None ,* ,args :list [Any ]| None = None ,vram_mib :float | None = None )-> SetDefault | None : 408"""The CLASS_DEFAULTS entry that holds for this start (the set on this engine family and the card's class), or None.""" 409key = (str (backend or "" ).strip ().lower (),set_of (model_name ),"streaming" ) 410entry = CLASS_DEFAULTS .get (key ) 411if entry is not None and streaming_class (backend ,archs ,args = args ,vram_mib = vram_mib ): 412return entry 413return None 414 415 416def auto_mtp_only (backend :str | None ,archs :Any = None )-> bool : 417"""Is this card one where Auto starts the MTP (AUTO_MTP)? Auto only: a DFlash2 asked for by name is not looked at here.""" 418return (str (backend or "" ).strip ().lower (),first_arch (archs ))in AUTO_MTP 419 420 421def tuned_applies (backend :str | None ,model_name :str | None ,archs :Any = None ,* ,args :list [Any ]| None = None ,vram_mib :float | None = None )-> bool : 422"""Does THIS start use the tuned pack? The set has a tuned entry and the entry's ``where`` holds, read from the signals the confidence already reads: CUDA "resident" = the engine slots of 423slots_of() (the person's --expert-cache, else the one card's memory ``vram_mib``) reach the first CONF_STEPS step (the step that gives 0.35), or the chip is the Spark (sm_121: one 424pool of memory, vram_mib is None by design); "gfx1151" = the first architecture is Strix Halo. A card whose memory is not known (several cards, a driver that does not answer) is not 425resident. Nothing here looks at the disk or the network.""" 426klass = class_entry (backend ,model_name ,archs ,args = args ,vram_mib = vram_mib ) 427if klass is not None : 428return klass .drafter == "dflash2" and klass .tuned # the card class has its own rule for this set 429entry = tuned_entry (backend ,model_name ) 430if entry is None : 431return False 432if entry .where == "" : 433return True 434arch = first_arch (archs ) 435if entry .where == "gfx1151" : 436return arch == "gfx1151" 437if entry .where == "arc_a" : 438return arch == "arc_a" 439if entry .where == "resident" : 440if arch == "sm_121" : 441return True 442slots = slots_of (list (args or []),vram_mib ) 443return slots is not None and slots >= CONF_STEPS [0 ][0 ] 444return False 445 446 447SLOT_MIB = 1.95 # one expert slot of Qwen3.8-Flash-Next IQ3_S: the engine's "46.84 GiB for 24576 slots" (l620) and 23.87 GiB for 12570 (R9700) 448SLOT_BASE_MIB = 3800 # dense weights and the engine's fixed buffers beyond vram_fit's own terms, from the R9700 start (128K context, 12570 slots on 32 GiB); it holds the draft layer's 449# allowance, which is the DFlash2's own now that it is the only drafter (expected_slots takes nothing more off) 450SLOT_RESERVE_MIB = 700 # the engine's default --vram-reserve-mib 451DEFAULT_CONTEXT = 131072 # --max-context when the arguments name none (the 128K default) 452 453#: model families (strata launch --family) the drafter was trained for and measured on: Qwen3.8-Flash-Next, its Gyro build and Unsloth's quantizations of the same weights 454#: (UD-IQ4_XS, UD-Q4_K_XL...; DFlash2 numbers measured on UD-Q4_K_XL on Strix, R9700 and M5 Max). Not Swift (UkisAI's fine-tune), Coder (ISTA-DASLab's coding version) or NVFP4: 455#: no DFlash2 acceptance numbers for them, they start the MTP. 456SUPPORTED_FAMILIES = ("qwen" ,"gyro" ,"unsloth" ) 457#: The model_name setup.py (and metal/setup_mac.py) write: f"{family name}-{model.lower()}": qwen3.8-flash-next-iq3_s, qwen3.8-flash-next-gyro-gyro-s, 458#: qwen3.8-flash-next-unsloth-ud-q4_k_xl. (Coder is qwen3.8-flash-next-coder-iq1_m, NVFP4 qwen3.8-flash-next-nvfp4-nvfp4: neither matches.) Mirrored in 459#: apps/host/server/native-settings.mjs; tests/drafting.test.mjs keeps the two the same. 460_SUPPORTED_NAME = re .compile (r"^qwen3\.8-flash-next(-gyro-[a-z0-9._-]+|-unsloth-[a-z0-9._-]+|-(q|iq|tq)\d[a-z0-9_.]*)?$" ,re .IGNORECASE ) 461 462 463def supported_model (model_name :str | None = None ,family :str | None = None )-> bool : 464"""DFlash2 is for Qwen3.8-Flash-Next only: by family when it is known (the Terminal), else by the run config's model name.""" 465if family is not None : 466return family .lower ()in SUPPORTED_FAMILIES 467return bool (model_name and _SUPPORTED_NAME .match (str (model_name ))) 468 469 470# --------------------------------------------------------------------------------------------------- the model file itself 471# 472# A run config whose model_name does not match _SUPPORTED_NAME (a renamed file, a hand-written config, a feed model under its own name, no name at all) used to start the MTP with 473# no word said, also when the file is Qwen3.8-Flash-Next and DFlash2 was the default for it. What decides now is what the file is: the architecture, the layer count, the hidden 474# size and the vocabulary size in its GGUF header against what the drafter pack records (its ``cfg hidden / vocab / taps`` lines, tools/dflash2_pack.py). 475 476TARGET_ARCH = "qwen4exp" # general.architecture of the Qwen3.8-Flash-Next GGUFs (tools/gguf_writer.py) 477#: What the drafter pack was made for, used when no pack is on this computer yet to read it from: ``cfg hidden 2560``, ``cfg vocab 248320``, ``cfg taps 5,15,25,35,45`` 478#: (the layers of the target it reads; the model needs more layers than the last tap). 479PACK_TARGET = {"hidden" :2560 ,"vocab" :248320 ,"taps" : (5 ,15 ,25 ,35 ,45 )} 480#: The model name a file that fits is treated as (the plain family name: no quantization, so no per-quantization table entry applies). 481FILE_FITS_AS = "qwen3.8-flash-next" 482#: Names the DFlash2 exclusions above stand for (Coder, NVFP4, Swift): a file under such a name stays out whatever its header says. 483_EXCLUDED_NAME = re .compile (r"coder|nvfp4|swift" ,re .IGNORECASE ) 484_GGUF_HEAD = 1 << 20 # bytes of a GGUF read for its header (the keys are in the first few KB; the vocabulary's words are never read) 485_PACK_HEAD = 1 << 16 486_GGUF_SCALAR = {0 :1 ,1 :1 ,2 :2 ,3 :2 ,4 :4 ,5 :4 ,6 :4 ,7 :1 ,10 :8 ,11 :8 ,12 :8 } 487 488 489def gguf_facts (path :Any )-> dict [str ,Any ]| None : 490"""What a GGUF file says about itself, from its first megabyte: ``arch`` (general.architecture), ``layers`` (<arch>.block_count), ``hidden`` (<arch>.embedding_length) and 491``vocab`` (the number of tokenizer.ggml.tokens, read from the array's header: the words are not read). A part that is not there is None; None when the file is not a GGUF 492or cannot be read.""" 493try : 494with open (path ,"rb" )as f : 495head = f .read (_GGUF_HEAD ) 496except (OSError ,TypeError ,ValueError ): 497return None 498if len (head )< 24 or head [:4 ]!= b"GGUF" : 499return None 500facts :dict [str ,Any ]= {"arch" :None ,"layers" :None ,"hidden" :None ,"vocab" :None } 501try : 502pos = 16 503 (n_kv ,)= struct .unpack_from ("<Q" ,head ,pos ) 504pos += 8 505for _ in range (min (n_kv ,4096 )): 506 (klen ,)= struct .unpack_from ("<Q" ,head ,pos ) 507pos += 8 508key = head [pos :pos + klen ].decode ("utf-8" ,"replace" ) 509pos += klen 510 (vtype ,)= struct .unpack_from ("<I" ,head ,pos ) 511pos += 4 512if vtype == 8 :# a string 513 (slen ,)= struct .unpack_from ("<Q" ,head ,pos ) 514pos += 8 515if key == "general.architecture" : 516facts ["arch" ]= head [pos :pos + slen ].decode ("utf-8" ,"replace" ) 517pos += slen 518elif vtype in (4 ,5 )and (key .endswith (".block_count" )or key .endswith (".embedding_length" )): 519 (value ,)= struct .unpack_from ("<I" if vtype == 4 else "<i" ,head ,pos ) 520facts ["layers" if key .endswith (".block_count" )else "hidden" ]= value 521pos += 4 522elif vtype in _GGUF_SCALAR : 523pos += _GGUF_SCALAR [vtype ] 524elif vtype == 9 :# an array: element type, count 525etype ,count = struct .unpack_from ("<IQ" ,head ,pos ) 526pos += 12 527if key == "tokenizer.ggml.tokens" : 528facts ["vocab" ]= count 529break # the words follow: everything wanted comes before them 530if etype in _GGUF_SCALAR : 531pos += count * _GGUF_SCALAR [etype ] 532else : 533break # an array of words before the tokens: not looked into 534else : 535break 536if pos > len (head ): 537break 538except (struct .error ,ValueError ,OverflowError ,MemoryError ):# a damaged header: no answer 539return None 540return facts if facts ["arch" ]else None 541 542 543#: The model_name setup writes for a set of each family (setup.py's family names): f"{name}-{model.lower()}". Coder, Swift and NVFP4 are left out on purpose (no DFlash2 numbers). 544_SET_NAME_PREFIX = {"qwen" :"qwen3.8-flash-next" ,"unsloth" :"qwen3.8-flash-next-unsloth" ,"gyro" :"qwen3.8-flash-next-gyro" } 545_known_names :dict [tuple [str ,int ,int ],str | None ]= {} 546 547 548def known_name_of_file (args :list [Any ])-> str | None : 549"""The model_name setup would have written for the file in --native when its header is EXACTLY one set of data/gguf_fingerprints.json (strata_control/models.py known_set_by_header: tensor count, 550payload bytes and expert formats over all shards; never the layout guess), so a renamed copy gets that set's table entry (tuned pack, confidence) as under its own name; None otherwise. 551Read once per file, size and time (the tensor directory of every shard is read: about a second).""" 552path = _flag_value (args ,"--native" ) 553if not path : 554return None 555try : 556stat = Path (path ).stat () 557key = (str (path ),stat .st_size ,stat .st_mtime_ns ) 558if key not in _known_names : 559from strata_control import models 560found = models .known_set_by_header (path ) 561prefix = _SET_NAME_PREFIX .get (found .split ("/" ,1 )[0 ])if found else None 562name = f" { prefix } - { found . split ( '/' , 1 )[ 1 ]. lower () } " if prefix and found else None 563_known_names [key ]= name if name and supported_model (name )else None 564return _known_names [key ] 565except Exception :# noqa: BLE001 - not known is the general defaults 566return None 567 568 569def pack_target (data_dir :str | Path | None = None )-> dict [str ,Any ]: 570"""What the drafter pack on this computer says it was made for (``hidden``, ``vocab``, ``taps`` from its ``cfg`` lines), else PACK_TARGET.""" 571want = dict (PACK_TARGET ) 572if data_dir : 573base = Path (data_dir )/ FOLDER 574for name in (TUNED_NAME ,TUNED_BF16_NAME ,CONVERTED_NAME ,PACK_NAME ): 575try : 576with open (base / name ,"rb" )as f : 577head = f .read (_PACK_HEAD ) 578except OSError : 579continue 580if len (head )< 12 or head [:4 ]!= b"DF2P" : 581continue 582 (n ,)= struct .unpack_from ("<I" ,head ,8 ) 583for ln in head [12 :12 + n ].decode ("utf-8" ,"replace" ).splitlines (): 584parts = ln .split () 585if len (parts )>= 3 and parts [0 ]== "cfg" : 586try : 587if parts [1 ]in ("hidden" ,"vocab" ): 588want [parts [1 ]]= int (parts [2 ]) 589elif parts [1 ]== "taps" : 590want ["taps" ]= tuple (int (x )for x in parts [2 ].split ("," )) 591except ValueError : 592pass 593break 594return want 595 596 597def file_fit (args :list [Any ],data_dir :str | Path | None = None )-> str : 598"""Is the model file in the engine arguments (``--native``) the one the drafter pack was made for? ``fits`` (Qwen3.8-Flash-Next's architecture, the pack's hidden size and 599vocabulary, more layers than the last tap), ``family`` (the same architecture, other sizes: a different model of that family), ``other`` (another architecture) or 600``unknown`` (no file in the arguments, not a GGUF, or not readable).""" 601path = _flag_value (args ,"--native" ) 602facts = gguf_facts (path )if path else None 603if not facts : 604return "unknown" 605if facts ["arch" ]!= TARGET_ARCH : 606return "other" 607want = pack_target (data_dir ) 608if facts ["hidden" ]== want ["hidden" ]and (facts ["layers" ]or 0 )> max (want ["taps" ])and facts ["vocab" ]in (None ,want ["vocab" ]): 609return "fits" 610return "family" 611 612 613def _here (path :Path )-> bool : 614try : 615return path .is_file ()and path .stat ().st_size > (1 << 20 ) 616except OSError : 617return False 618 619 620def target_path (data_dir :str | Path )-> Path : 621"""Where a fetch writes the Q4_0 pack.""" 622return Path (data_dir )/ FOLDER / PACK_NAME 623 624 625def converted_path (data_dir :str | Path )-> Path : 626"""Where setup / Load writes the pack with the Q4_0 selector (beside the Q4_0 pack it was made from).""" 627return Path (data_dir )/ FOLDER / CONVERTED_NAME 628 629 630def tuned_path (data_dir :str | Path ,variant :str | None = None )-> Path : 631"""Where the tuned drafter lives (next to the stock packs); ``variant``: selq4 (default) or bf16sel.""" 632return Path (data_dir )/ FOLDER / tuned_pack (variant ).name 633 634 635def sha256_of (path :Path )-> str : 636digest = hashlib .sha256 () 637with Path (path ).open ("rb" )as stream : 638for block in iter (lambda :stream .read (1 << 22 ),b"" ): 639digest .update (block ) 640return digest .hexdigest () 641 642 643def converted_ok (data_dir :str | Path | None ,* ,size :int | None = None ,sha256 :str | None = None ,name :str | None = None )-> bool : 644"""Is the converted pack here and exactly the pinned bytes? A file of another size is refused at once; the SHA-256 (about a second) is checked when the 645file is new to us, and the answer is kept in a small marker beside it (size, time, hash) so a start reads one tiny file, not 340 MB. A missing, short, 646changed or corrupt file is simply "no": the Q4_0 pack with the bf16 selector is used. Reads only; nothing is written when the marker cannot be.""" 647if not data_dir : 648return False 649want_size = CONVERTED_BYTES if size is None else size 650want_sha = CONVERTED_SHA256 if sha256 is None else sha256 651path = Path (data_dir )/ FOLDER / (name or CONVERTED_NAME ) 652try : 653stat = path .stat () 654if not path .is_file ()or stat .st_size != want_size : 655return False 656marker = path .with_name (path .name + ".ok" ) 657try : 658known = json .loads (marker .read_text (encoding = "utf-8" )) 659if known .get ("size" )== stat .st_size and known .get ("mtime_ns" )== stat .st_mtime_ns and known .get ("sha256" )== want_sha : 660return True 661except (OSError ,ValueError ): 662pass 663if sha256_of (path )!= want_sha : 664return False 665try : 666marker .write_text (json .dumps ({"size" :stat .st_size ,"mtime_ns" :stat .st_mtime_ns ,"sha256" :want_sha }),encoding = "utf-8" ) 667except OSError : 668pass 669return True 670except OSError : 671return False 672 673 674def tuned_ok (data_dir :str | Path | None ,variant :str | None = None )-> bool : 675"""Is the tuned drafter here and exactly the pinned bytes (size, then SHA-256 once; the answer is kept in a marker beside it, as for the converted pack)? A short, 676changed or corrupt file is simply "no": the stock pack (or the MTP) is used. ``variant``: selq4 (default) or bf16sel.""" 677pin = tuned_pack (variant ) 678return converted_ok (data_dir ,size = pin .size ,sha256 = pin .sha256 ,name = pin .name ) 679 680 681def uses_tuned (backend :str | None ,model_name :str | None )-> bool : 682"""Does this set on this engine family have a tuned-drafter entry (SET_DEFAULTS)? Entry level: whether this card qualifies is tuned_applies().""" 683return tuned_entry (backend ,model_name )is not None 684 685 686_selq4 :dict [tuple [str ,int ,int ],bool ]= {} 687 688 689def engine_reads_selector_q4 (exe :str | os .PathLike [str ]| None )-> bool : 690"""Does the engine program at `exe` read a pack with Q4_0 selector codebooks? Read from the file's text (it is never started for this), once per path, size 691and time. An engine that is not known (no path) or that lacks the text gets the bf16-selector pack: an older engine would read the rows as garbage.""" 692if not exe : 693return False 694try : 695path = Path (exe ) 696stat = path .stat () 697except (OSError ,ValueError ): 698return False 699key = (str (path ),stat .st_size ,stat .st_mtime_ns ) 700if key not in _selq4 : 701try : 702with open (path ,"rb" )as handle ,mmap .mmap (handle .fileno (),0 ,access = mmap .ACCESS_READ )as data : 703_selq4 [key ]= data .find (_MARK_SELQ4 )>= 0 704except (OSError ,ValueError ): 705_selq4 [key ]= False 706return _selq4 [key ] 707 708 709def uses_selector_q4 (data_dir :str | Path | None ,engine :str | os .PathLike [str ]| None = None )-> bool : 710"""Is this computer's DFlash2 start the one with the Q4_0 selector (the converted pack, 175 MiB less)? True when the installed engine reads such a pack and the drafter is 711(or will be, at setup / Load) the Q4_0 pack it is made from; a Q8 pack an earlier Strata made is never converted. An engine that is not known: False (the larger figure).""" 712if not engine or not engine_reads_selector_q4 (engine ): 713return False 714if data_dir and not _here (Path (data_dir )/ FOLDER / PACK_NAME )and _here (Path (data_dir )/ FOLDER / LEGACY_PACK_NAME ): 715return False 716return True 717 718 719def engine_has_selector_q4 ()-> bool : 720"""Does the engine installed on this computer read the Q4_0-selector pack ("selector codebooks: Q4_0 rows": CUDA, HIP and Metal engines; not the SYCL one)? Setup, Load and 721`strata drafting fetch` make that pack only then: where the engine cannot read it the 340 MB file would never be used. No engine installed yet: False (made at the next Load).""" 722return engine_reads_selector_q4 (installed_engine_exe ()) 723 724 725def vram_gb (data_dir :str | Path | None = None ,engine :str | os .PathLike [str ]| None = None )-> float : 726"""Graphics memory of DFlash2 alone on this computer, in GB: DRAFTER_GB["dflash2_selq4"] (0.72) with the converted pack, DRAFTER_GB["dflash2"] (0.89) otherwise. The fit, 727the plan text and the slot estimates say this number.""" 728return DRAFTER_GB ["dflash2_selq4" if uses_selector_q4 (data_dir ,engine )else "dflash2" ] 729 730 731def installed_engine_exe ()-> Path | None : 732"""The engine program of the newest installed engine component for this computer's backend (None: not found). A quick folder scan, nothing is hashed or started.""" 733try : 734from strata_control import engine_component as ec 735found ,_ = ec .scan (None ) 736backend = (detect_hardware ()[0 ]or "" ).lower () 737best = [c for c in found if not backend or str (c .backend ).split (":" )[0 ].lower ()== backend ]or list (found ) 738best .sort (key = lambda c :ec ._version_key (c .version ),reverse = True ) 739return best [0 ].exe if best and best [0 ].exe .is_file ()else None 740except Exception :# noqa: BLE001 - informational: an unknown engine means the larger figure 741return None 742 743 744def pack_path (data_dir :str | Path ,engine :str | os .PathLike [str ]| None = None ,* ,model_name :str | None = None ,backend :str | None = None ,tuned :bool | None = None )-> Path : 745"""The pack the engine is started with: the converted pack (Q4_0 selector) when it is here, verified, and `engine` is a program that reads it; else the Q4_0 pack, else 746a Q8 pack an earlier Strata made (no download for it), else where the Q4_0 pack will be. The tuned pack comes first where this set has one (SET_DEFAULTS), it is here and 747verified, and `engine` reads the Q4_0 selector (it is that format): the stock pack stays the fallback. `tuned`: whether this card qualifies (tuned_applies; None = the entry alone).""" 748if tuned is None : 749tuned = uses_tuned (backend ,model_name ) 750variant = tuned_variant (backend ,model_name )or "selq4" 751if tuned and variant == "bf16sel" and tuned_ok (data_dir ,variant ): 752return tuned_path (data_dir ,variant )# the bf16-selector file: any engine that runs DFlash2 reads it 753if engine is not None and tuned and variant == "selq4" and tuned_ok (data_dir )and engine_reads_selector_q4 (engine ): 754return tuned_path (data_dir ) 755if engine is not None and converted_ok (data_dir )and engine_reads_selector_q4 (engine ): 756return converted_path (data_dir ) 757for name in (PACK_NAME ,LEGACY_PACK_NAME ): 758if _here (Path (data_dir )/ FOLDER / name ): 759return Path (data_dir )/ FOLDER / name 760return target_path (data_dir ) 761 762 763def pack_ready (data_dir :str | Path | None )-> bool : 764try : 765return bool (data_dir )and _here (pack_path (data_dir )) 766except OSError : 767return False 768 769 770#: AMD chips that share the system memory (serve/server.py HIP_IGPU_ARCHS: the same list): no card memory to read. 771IGPU_ARCHS = ("gfx1035" ,"gfx1036" ,"gfx1037" ,"gfx1103" ,"gfx1150" ,"gfx1151" ,"gfx1152" ,"gfx90c" ) 772 773 774def card_vram_mib (cfg :dict [str ,Any ],backend :str | None ,archs :Any = None )-> float | None : 775"""Memory in MiB of the ONE card a start of this run config would use (NVML / amdgpu sysfs), for tuned_applies at fetch time (setup, Load, the app's plan): the same answer as serve/server.py 776drafting_vram_mib gives the start. None for several cards, a shared-memory chip (sm_121, Strix Halo and the other APUs) or a card that does not answer. Never raises.""" 777try : 778arch = first_arch (archs ) 779if arch == "sm_121" or arch in IGPU_ARCHS : 780return None 781from strata_control import gpu_roles 782roles ,_ = gpu_roles .saved_roles (cfg ) 783raw = cfg .get ("gpu" ) 784numbers = [int (str (x ).strip ())for x in (raw if isinstance (raw , (list ,tuple ))else str (raw ).split ("," ))if raw not in (None ,"" )and str (x ).strip ()!= "" ] 785indices = numbers if (roles is None or numbers )else list (gpu_roles .engine_order (roles )) 786if len (indices )> 1 : 787return None 788from serve .telemetry import gpu_reader 789reader = gpu_reader ((indices or [0 ])[0 ],amd = (backend == "hip" )) 790if not reader .ok (): 791return None 792total = reader .read ().get ("mem_total" ) 793return float (int (total )>> 20 )if total else None 794except Exception :# noqa: BLE001 - an unreadable card means "not known to be resident" 795return None 796 797 798def drafter_ready (data_dir :str | Path | None ,model_name :str | None = None ,backend :str | None = None )-> bool : 799"""Is a drafter file for this start on the computer: a stock pack (pack_ready), or, where the set has a tuned entry, the verified tuned pack.""" 800try : 801return pack_ready (data_dir )or (bool (data_dir )and uses_tuned (backend ,model_name )and tuned_ok (data_dir ,tuned_variant (backend ,model_name ))) 802except OSError : 803return False 804 805 806# --------------------------------------------------------------------------------------------------- a decision 807 808 809@dataclass 810class Decision : 811asked :str # what the person chose (auto | mtp | dflash2 | off) 812drafter :str # what the engine is started with: mtp | dflash2 | off 813note :str = "" # plain words when the choice could not be applied; "" otherwise 814flags :tuple [str , ...]= ()# engine flags added 815vocab :str = "" # log line (not shown to the person): which draft vocabulary file a DFlash2 start uses and why; "" for the other drafters 816 817 818def normalize (value :Any )-> str : 819text = str (value if value is not None else DEFAULT_MODE ).strip ().lower () 820return text if text in MODES else DEFAULT_MODE 821 822 823#: Does the engine in this release run DFlash2 when it serves (the app and `strata launch`)? On this branch it does: `--draft dflash2` works with --serve for one 824#: card or a layer split over several cards, one request at a time (src/program/generate.cpp); --batch (several requests at once on one card) and --pipeline-windows cannot. A parked or 825#: edited conversation starts the drafter with an empty context (a log line; the answers are the same). Flip back to False to hide the choice again. 826ENGINE_SERVES_DFLASH2 = True 827 828#: Why another drafter (or none) runs when the one chosen cannot: a closed set of short reasons, each one is a sentence in the interface catalog in all 829#: nine languages (the line is "Drafting: MTP (<reason>)", apps/host/src/locales/df2-<lang>.json and en.json). 830DIDNT_FIT = "DFlash2 didn't fit" 831NOT_HERE = "DFlash2 isn't available in this mode" 832NOT_SUPPORTED = "DFlash2 is for Qwen3.8-Flash-Next only" 833NOT_DOWNLOADED = "the DFlash2 drafter isn't downloaded yet" 834NOT_THIS_CARD = "DFlash2 isn't available on this graphics card" 835NO_MTP = "the MTP drafter isn't downloaded yet" 836NONE_HERE = "no drafter is downloaded yet" 837FETCH_HINT = "Run strata drafting fetch to get the DFlash2 drafter now." 838DIDNT_START = "DFlash2 didn't start" # Auto picked DFlash2, the engine ended before it was ready, and the start was repeated once with the MTP (serve/server.py) 839NOT_SERVED = NOT_HERE 840SHORT_OF_VRAM = "the cards were short of memory" # the engine ended before it was ready for lack of graphics memory: the start was repeated once with no drafter (serve/server.py), never with the MTP 841#: Request slots (2 or more requests at once) with the MTP layer loaded but no ``--batch-mtp``: the slots draft nothing and only a single request drafts. This reason is the whole line after 842#: "Drafting: " (``line`` prints it as it is, not inside "MTP (...)"); ``slots_draft_nothing`` says when it is true. 843NONE_IN_SLOTS = "none in parallel slots (one token per request and step); a single request still drafts" 844REASONS = (DIDNT_FIT ,NOT_HERE ,NOT_SUPPORTED ,NOT_DOWNLOADED ,NOT_THIS_CARD ,NO_MTP ,NONE_HERE ,DIDNT_START ,SHORT_OF_VRAM ,NONE_IN_SLOTS ) 845#: The server's line for a DFlash2 start whose request slots draft too (a drafter per request slot, guesses only in the rows the slots leave spare); ``slot_drafts_run`` says when. 846SLOT_DRAFTS_LINE = "Drafting: DFlash2, one guess window per request slot (spare rows only)" 847 848 849def line (drafter :str ,reason :str = "" )-> str : 850"""``Drafting: DFlash2``, ``Drafting: MTP (DFlash2 isn't available in this mode)``, ``Drafting: off (no drafter is downloaded yet)``, ``Drafting: none in parallel slots (...)``.""" 851if reason == NONE_IN_SLOTS : 852return f"Drafting: { NONE_IN_SLOTS } " 853word = {"mtp" :"MTP" ,"dflash2" :"DFlash2" ,"off" :"off" }.get (drafter ,drafter ) 854return f"Drafting: { word } ( { reason } )" if reason else f"Drafting: { word } " 855 856 857def merged_args (cfg :dict [str ,Any ])-> list [str ]: 858"""The config's engine arguments with the person's own ``user_args`` over them, as the server merges them at a start (what slots_draft_nothing reads).""" 859args = [str (a )for a in cfg .get ("args" )or []] 860if cfg .get ("user_args" ): 861from strata_control import user_args 862args = user_args .merge (args ,cfg ["user_args" ]) 863return args 864 865 866def slots_draft_nothing (args :list [Any ],slots :int | float | None = 0 )-> bool : 867"""Do this start's request slots draft nothing? Yes for 2 or more requests at once with no ``--batch-mtp`` (and no ``STRATA_BATCH_MTP``, no ``--pipeline-windows``) in the arguments: 868the engine runs the slots with one token per request and step, and only a single request drafts. (Called for a start that runs the MTP layer: the slots' own DFlash2 drafts are 869``slot_drafts_run``; with ``--batch-mtp`` the slots carry MTP drafts and the usual line stays.)""" 870items = [str (a )for a in args or []] 871if request_count (items ,slots )< 2 or "--batch-mtp" in items or "--pipeline-windows" in items : 872return False 873return os .environ .get ("STRATA_BATCH_MTP" ,"0" )in ("" ,"0" ) 874 875 876def slot_drafts_run (args :list [Any ],slots :int | float | None = 0 ,split :bool = False )-> bool : 877"""Does a DFlash2 start draft in its request slots too (``--draft dflash2 --batch N``, a drafter per slot)? Yes for 2 or more requests at once, unless ``STRATA_BATCH_DF2=0`` (the way back, 878as the engine reads it), a layer split (``split`` or ``--layer-split``: its slots draft only where they run as one group, not decided here) or ``--pipeline-windows``.""" 879items = [str (a )for a in args or []] 880if split or request_count (items ,slots )< 2 or "--layer-split" in items or "--pipeline-windows" in items : 881return False 882return os .environ .get ("STRATA_BATCH_DF2" ,"" )!= "0" 883 884 885def mtp_line (reason :str )-> str : 886return line ("mtp" ,reason ) 887 888 889# --------------------------------------------------------------------------------------------------- what the installed engine takes 890 891#: How an engine wants the draft vocabulary of a DFlash2-alone start (no MTP layer). The app must never send a flag the engine it starts does not have 892#: (the Gyro-S start on engine 0.1.55.2 ended with exit code 2: that engine takes `--mtp DIR` for DIR/draft_vocab.bin and does not accept `--mtp-draft-vocab` alone). 893FORM_FILE = "vocab-file" # --mtp-draft-vocab FILE is enough (rc1 and later) 894FORM_DIR = "mtp-dir" # --mtp DIR, for DIR/draft_vocab.bin; the MTP layer is still not loaded (--draft-fallback none) 895FORM_NONE = "unsupported" # no --draft-fallback in the engine: it cannot run DFlash2 without the MTP layer at all 896#: Text the engine program carries, read from the file (it is never started for this): the start message of --draft dflash2 names what it needs. 897_MARK_FILE = b"--mtp-draft-vocab FILE (or --mtp DIR" 898_MARK_DIR = b"--spec 2 or more and --mtp DIR (for DIR/draft_vocab.bin)" 899_MARK_FALLBACK = b"--draft-fallback" 900_forms :dict [tuple [str ,int ,int ],str | None ]= {} 901 902 903def engine_form (exe :str | os .PathLike [str ]| None )-> str | None : 904"""How the engine program at `exe` takes the DFlash2-alone vocabulary: FORM_FILE, FORM_DIR, FORM_NONE, or None when it cannot be told (no path, the file is 905unreadable, or it has the flag but says nothing we know: the usual form is used then). The program is read once per path, size and time and the answer kept.""" 906if not exe : 907return None 908try : 909path = Path (exe ) 910stat = path .stat () 911except (OSError ,ValueError ): 912return None 913key = (str (path ),stat .st_size ,stat .st_mtime_ns ) 914if key not in _forms : 915_forms [key ]= _read_form (path ) 916return _forms [key ] 917 918 919def _read_form (path :Path )-> str | None : 920try : 921with open (path ,"rb" )as handle ,mmap .mmap (handle .fileno (),0 ,access = mmap .ACCESS_READ )as data : 922if data .find (_MARK_FILE )>= 0 : 923return FORM_FILE 924if data .find (_MARK_DIR )>= 0 : 925return FORM_DIR 926return None if data .find (_MARK_FALLBACK )>= 0 else FORM_NONE 927except (OSError ,ValueError ):# unreadable, or an empty file (mmap refuses it) 928return None 929 930 931def engine_flags (pack :str | Path ,vocab :str | Path | None = None ,form :str | None = None )-> tuple [str , ...]: 932"""The engine arguments of a DFlash2 start: the drafter, its file, no MTP layer, the draft vocabulary, the window and the confidence. The vocabulary is 933`--mtp-draft-vocab FILE`, or for an engine that only knows `--mtp DIR` (`form` FORM_DIR) the folder that holds it: the MTP layer is still not loaded.""" 934where :tuple [str , ...]= () 935if vocab : 936where = ("--mtp" ,str (Path (vocab ).parent ))if form == FORM_DIR else ("--mtp-draft-vocab" ,str (vocab )) 937return ("--draft" ,"dflash2" ,"--draft-model" ,str (pack ),"--draft-fallback" ,"none" ,* where ,"--spec" ,str (SPEC_WINDOW ),"--draft-conf" ,f" { DRAFT_CONF :g } " ) 938 939 940def big_blackwell (backend :str | None ,archs :Any = None ,vram_mib :float | None = None ,slots :int | float | None = None )-> bool : 941"""Is this start on the large-VRAM Blackwell class (the window of 8, and the sets' big_blackwell_conf): CUDA, the first card's architecture sm_120 (cc 12.0; the Spark is sm_121), the one card's memory ``vram_mib`` 942at least BIG_CARD_BYTES (None = several cards or unknown: no), and ``slots`` in the all-resident step (None counts as unknown: no)? Mirrors the engine's dflash2_big_blackwell.""" 943if str (backend or "" ).strip ().lower ()!= "cuda" or first_arch (archs )!= "sm_120" or not vram_mib or slots is None : 944return False 945return vram_mib * 1048576 >= BIG_CARD_BYTES and slots >= CONF_STEPS [0 ][0 ] 946 947 948def big_blackwell_conf_for (backend :str | None ,model_name :str | None ,archs :Any = None ,vram_mib :float | None = None ,slots :int | float | None = None )-> float | None : 949"""The ``--draft-conf`` this set has on the large-VRAM Blackwell class (SetDefault.big_blackwell_conf), or None: not that class, or a set nobody measured there (it keeps the slot rule's 0.35).""" 950entry = tuned_entry (backend ,model_name ) 951return entry .big_blackwell_conf if entry is not None and big_blackwell (backend ,archs ,vram_mib ,slots )else None 952 953 954def window_for (backend :str | None ,archs :Any = None ,vram_mib :float | None = None ,slots :int | float | None = None )-> int : 955"""The ``--spec`` of a DFlash2 start: WIDE_WINDOW (8) on Strix Halo (HIP gfx1151, engine cap 8) and on the large-VRAM Blackwell class (big_blackwell), SPEC_WINDOW (6) everywhere else, so no other 956card's effective window changes (the engine caps 6 on the Spark and the smaller Blackwell cards, and does not cap the rest).""" 957if str (backend or "" ).strip ().lower ()== "hip" and first_arch (archs )== "gfx1151" : 958return WIDE_WINDOW 959return WIDE_WINDOW if big_blackwell (backend ,archs ,vram_mib ,slots )else SPEC_WINDOW 960 961 962def conf_for (backend :str | None ,slots :int | float | None )-> float : 963"""The ``--draft-conf`` for this engine family and a card that holds ``slots`` experts: the backend's own value (BACKEND_CONF) when it has one, else the slot steps.""" 964own = BACKEND_CONF .get (str (backend or "" ).strip ().lower ()) 965return own if own is not None else conf_for_slots (slots ) 966 967 968def conf_for_slots (slots :int | float | None )-> float : 969"""The ``--draft-conf`` for a card that holds ``slots`` experts (CONF_STEPS); DRAFT_CONF when the number is unknown.""" 970if slots is None : 971return DRAFT_CONF 972for at_least ,conf in CONF_STEPS : 973if slots >= at_least : 974return conf 975return CONF_STEPS [- 1 ][1 ] 976 977 978def expected_slots (vram_mib :float ,args :list [Any ])-> int : 979"""The ENGINE slots a card of ``vram_mib`` MiB is expected to hold with the drafter on, the same arithmetic as strata_control/vram_fit.py (the card, the 980runtime's gap, the dense weights, the KV session of ``--max-context`` / ``--kv``, the prompt buffers, the reserve; the draft layer's allowance in the base 981is the DFlash2's own now, it is the only drafter), over one slot. An estimate good to about 10% (two engine starts); the steps of CONF_STEPS are wider.""" 982from strata_control import vram_fit 983ctx = _flag_value (args ,"--max-context" ) 984ctx = int (ctx )if ctx and ctx .isdigit ()else DEFAULT_CONTEXT 985kv = _flag_value (args ,"--kv" )or "int8" 986reserve = _flag_value (args ,"--vram-reserve-mib" ) 987reserve = int (reserve )if reserve and reserve .isdigit ()else SLOT_RESERVE_MIB 988prefill = _flag_value (args ,"--prefill" ) 989chunk = vram_fit .chunk_of (prefill .split (":" )[- 1 ]if prefill else "auto" ) 990# SLOT_BASE_MIB is the baseline that holds the draft layer (the MTP's ~1.08 GiB, measured); DFlash2 is now the ONLY drafter, so that allowance pays for its own 991# 0.89 GiB (measured: "drafter 799 MiB" + its head's staging, 890 MiB beside the engine without one; 192 MiB less than the MTP layer): nothing more is taken off. 992free = (float (vram_mib )- vram_fit .GAP_OTHER_MIB - SLOT_BASE_MIB - vram_fit .session_mib (ctx ,kv )- vram_fit .HEAD_MIB - reserve 993- (vram_fit .PROMPT_BASE_MIB + vram_fit .PROMPT_PER_TOKEN_MIB * chunk )) 994return max (0 ,min (MAX_SLOTS ,int (free / SLOT_MIB ))) 995 996 997def slots_of (args :list [Any ],vram_mib :float | None = None )-> int | None : 998"""How many expert slots this start holds: the person's own ``--expert-cache N``, else the estimate for the card (``vram_mib``), else None.""" 999given = _flag_value (args ,"--expert-cache" ) 1000if given is not None and given .isdigit (): 1001return min (MAX_SLOTS ,int (int (given )* EXPERT_CACHE_SLOTS_PER_N ))# N is a budget of largest blobs; the steps are in the engine's slots 1002if vram_mib : 1003return expected_slots (vram_mib ,args ) 1004return None 1005 1006 1007#: How many requests at once get DFlash2 slot drafts by default (see slot_drafts_by_default). l620, RTX PRO 5000 72 GB, IQ3_S, every expert resident, 32 requests x 3 passes a start 1008#: (phaseA-tests/par/RESULTS-PAR-DRAFT.md, blocks 4 and 5), requests per minute: 2 clients: queued on one stream 65.4, slots with no drafts 60.0, MTP slot drafts 68.4, DFlash2 slot drafts 69.1; 1009#: 3 clients (two starts each): queued 64.3, slots with no drafts 74.1 / 73.3, DFlash2 slot drafts 73.5 / 74.5 (level, so 3 is not in the list); 1010#: 4 clients: queued 64.5, slots with no drafts 82.9, MTP slot drafts 80.6, DFlash2 slot drafts 78.8. From 3 requests on, plain slots stay what a start gets. 1011SLOT_DRAFT_REQUESTS = (2 ,) 1012 1013 1014def request_count (args :list [Any ],slots :int | float | None = 0 )-> int : 1015"""How many requests at once this start serves: ``slots`` (the config's ``parallel``) or the number after ``--batch`` / ``--slots`` / ``--parallel``, whichever is larger; 0 = one at a time.""" 1016n = int (slots )if isinstance (slots , (int ,float ))and not isinstance (slots ,bool )else 0 1017for flag in ("--batch" ,"--slots" ,"--parallel" ): 1018value = _flag_value (args ,flag ) 1019if value is not None and value .isdigit (): 1020n = max (n ,int (value )) 1021return n 1022 1023 1024def slot_drafts_by_default (mode :Any ,* ,backend :str | None ,archs :Any = None ,vram_mib :float | None = None ,args :list [Any ]| None = None ,slots :int | float | None = 0 , 1025split :bool = False ,drafter_here :bool = True )-> bool : 1026"""Does Auto start the request slots with DFlash2 slot drafts (``--draft dflash2 --draft-model <pack> --batch N``, one drafter per slot, no MTP layer loaded) instead of the MTP 1027and slots with no drafts? Yes when ALL of these hold, the class that was measured and nothing else: the choice is Auto; the start serves 2 requests at once (SLOT_DRAFT_REQUESTS); 1028one CUDA card of the large-VRAM Blackwell class holding every expert (big_blackwell: sm_120, at least 48 GB, the first CONF_STEPS step; None for several cards and for the Spark's 1029shared memory); no layer split; the DFlash2 drafter is on this computer (``drafter_here``); and the person has not chosen otherwise: no ``--batch-mtp`` or ``--pipeline-windows`` in 1030the arguments, ``STRATA_BATCH_MTP`` not set, ``STRATA_BATCH_DF2=0`` not set (the way back, as the engine reads it). Every other class (AMD, the Spark, Strix, Metal, Arc, several 1031cards, a streaming card) and every other request count keep their rule as it was: the MTP loaded and slots with no drafts, or what the person named. A start that serves one request 1032at a time never comes here.""" 1033if normalize (mode )!= "auto" or split or not drafter_here : 1034return False 1035items = [str (a )for a in args or []] 1036if any (a in items for a in ("--layer-split" ,"--batch-mtp" ,"--pipeline-windows" )): 1037return False 1038if os .environ .get ("STRATA_BATCH_MTP" ,"0" )not in ("" ,"0" )or os .environ .get ("STRATA_BATCH_DF2" ,"" )== "0" : 1039return False 1040if request_count (items ,slots )not in SLOT_DRAFT_REQUESTS : 1041return False 1042return big_blackwell (backend ,archs ,vram_mib ,slots_of (strip_mtp_flags (strip_draft_flags (items )),vram_mib )) 1043 1044 1045def blocked_by (args :list [Any ],* ,split :bool = False ,slots :int = 0 ,named :bool = False ,backend :str | None = None ,slot_drafts :bool = False )-> bool : 1046"""Does this start have something DFlash2 does not run beside: several requests at once (``--batch``, ``--slots``, ``--parallel``; per-slot DFlash2 drafts are on by 1047default only for a layer split whose slots run as one group and are opt-in on one card, so the MTP's ``--batch-mtp`` is the measured choice there) or 1048``--pipeline-windows``. A layer split over several cards is NOT in the list any more (owner, 2026-11-02: the 0.1.56 engine runs ``--draft dflash2 1049--draft-fallback none`` on a layer split, one request at a time; paired decode 1.014 against the MTP, CI 0.994-1.033, 2 x RTX PRO 6000, RESULTS-DF2MGPU.md): 1050``split`` and a ``--layer-split`` argument are accepted and ignored so the callers keep working. The caller says what it adds later (``slots``); the arguments are looked at too. 1051 1052``named``: the person chose DFlash2 by name (owner, 2026-11-03: "we want users to have a choice to pick whatever they want"). Several requests at once are then their word 1053too, and the engine serves them with a drafter per request (``--draft dflash2 --batch N``, the slot drafts); only ``--pipeline-windows`` (the MTP's speculative next window, 1054which DFlash2 has no counterpart for) still blocks. Auto never passes ``named``: it keeps the MTP for several requests. 1055The Metal engine has no per-request drafters (generate.cpp batch_df2_wanted), so DFlash2 beside request slots there would draft nothing and the person would not know: on 1056Metal (``backend``) the old rule stays and a DFlash2 chosen with several requests is the MTP with the usual reason. 1057 1058``slot_drafts``: Auto on the class whose slot drafts are the default (slot_drafts_by_default says so; the caller asks it): the same as ``named`` for the request slots.""" 1059items = [str (a )for a in args or []] 1060if (named or slot_drafts )and str (backend or "" ).lower ()!= "metal" : 1061return "--pipeline-windows" in items 1062return bool (slots > 1 or any (a in items for a in ("--batch" ,"--slots" ,"--pipeline-windows" ,"--parallel" ))) 1063 1064 1065def mtp_ready (args :list [Any ])-> bool | None : 1066"""Is the MTP layer this start would load on this computer? ``--mtp <folder>`` with its ``experts.bin`` (or, on a Mac, ``mtp-q2_0.gguf`` beside the folder). 1067None (not known, taken as there) when the arguments name no layer at all (an Intel route, or a layer switched off) or a draft depth instead of a folder (Qwen3.6's 1068``--mtp 4``: that layer is its own). A DFlash2-only install keeps ``--mtp <folder>`` in the saved arguments for a later switch to the MTP, so the folder is looked at.""" 1069items = [str (a )for a in args or []] 1070if "--mtp" not in items : 1071return None 1072value = _flag_value (args ,"--mtp" ) 1073if value is None or value .isdigit (): 1074return None 1075folder = Path (value ) 1076try : 1077return (folder / "experts.bin" ).is_file ()or (folder .parent / "mtp-q2_0.gguf" ).is_file () 1078except OSError : 1079return False 1080 1081 1082VOCAB_NAME = "draft_vocab.bin" 1083 1084 1085#: The subsets a person can choose in setup (``--draft-vocab``), by name: the files Strata ships in data/ (setup.DRAFT_VOCABS names the same ones). 1086VOCAB_FILES = {"cjk" :VOCAB_NAME ,"en" :"draft_vocab_en.bin" ,"cyrillic" :"draft_vocab_cyrillic.bin" ,"fr" :"draft_vocab_fr.bin" ,"latin" :"draft_vocab_latin.bin" } 1087#: The sha256 of the 27-Han-token subset up to 0.1.26 (setup.OLD_DRAFT_VOCABS): a copy that is any shipped subset may be replaced by the person's later choice, a made-by-hand one never. 1088OLD_VOCAB_SHA256 = {"369151522226a5edaa5f12cfd1e2ae7db8f4fbdbd222f3dcf327dced9597fb25" } 1089 1090 1091def shipped_vocab (choice :str | None = None )-> Path : 1092"""The draft vocabulary Strata ships with (``data/draft_vocab.bin``, also in the packaged Control), or the shipped subset named ``choice`` (cjk, en, cyrillic, fr).""" 1093return Path (__file__ ).resolve ().parents [1 ]/ "data" / VOCAB_FILES .get (choice or "cjk" ,VOCAB_NAME ) 1094 1095 1096# --------------------------------------------------------------------------------------------------- the vocabulary by the computer's language 1097# 1098# DFlash2 proposes tokens only from the draft vocabulary. The default one (cjk) holds English, code and every Chinese / Japanese / Korean token and misses 46% of the tokens of a Russian answer 1099# and 20-26% of German, Spanish, French and Polish ones. Measured on l620 (RESULTS-DRAFT-VOCAB.md): `cyrillic` gives Russian +26%, `latin` (English + the tokens of de / es / fr / pl text) +8 to +12% 1100# on those four, both within 0.3% of the default on English and code; either file costs 12-16% on Chinese and Japanese. So with no choice saved, the file follows the computer's languages, and 1101# anything that could mean Chinese, Japanese or Korean keeps the default (the costs are lopsided: the wrong file on CJK text costs far more than the right one gains elsewhere). 1102 1103#: Language codes by the script their text is written in (the ones the vocabulary files cover: Cyrillic, and the Latin script beyond English). Anything else (English, Arabic, Hebrew, Hindi, Thai, 1104#: Greek...) says nothing. 1105_CJK_LANGS = frozenset ("zh ja ko yue cmn wuu hak nan gan lzh" .split ()) 1106_CYRILLIC_LANGS = frozenset ("ru uk be bg mk sr kk ky tg mn tt ba cv ce os sah ab av kv udm" .split ()) 1107_LATIN_LANGS = frozenset (("de fr es pt it nl pl cs sk sl hr bs ro hu sv da nb nn no fi et lv lt tr vi id ms ca gl eu af sq is ga cy mt fil tl sw " 1108"lb fo gd br oc rm eo la uz az tk hsb dsb ast an co fy sc se smn nds wa ln zu xh st tn yo ig ha so mg haw mi sm to" ).split ()) 1109_CJK_SCRIPTS = frozenset ("hans hant hani jpan kore hang hira kana bopo" .split ()) 1110 1111 1112def script_of_language (tag :Any )-> str : 1113"""The script group a language tag (``ru-RU``, ``sr-Latn-RS``, ``de_DE.UTF-8``, ``sr_RS@latin``, ``zh-Hans``) says: ``cjk``, ``cyrillic``, ``latin`` (a Latin-script language other than English) or ``""`` (English, another 1114script, ``C`` / ``POSIX``, nothing readable).""" 1115text = str (tag or "" ).strip () 1116if not text : 1117return "" 1118low = text .lower () 1119if low in ("c" ,"posix" )or low .startswith (("c." ,"posix." )): 1120return "" 1121modifier = "" 1122if "@" in low : 1123low ,modifier = low .split ("@" ,1 ) 1124low = low .split ("." ,1 )[0 ] 1125parts = [p for p in low .replace ("_" ,"-" ).split ("-" )if p ] 1126if not parts : 1127return "" 1128lang ,scripts = parts [0 ],parts [1 :] 1129if any (p in _CJK_SCRIPTS for p in scripts )or lang in _CJK_LANGS : 1130return "cjk" 1131if "cyrl" in scripts or modifier == "cyrillic" : 1132return "cyrillic" 1133if "latn" in scripts or modifier == "latin" : 1134return "" if lang == "en" else "latin" 1135if lang in _CYRILLIC_LANGS : 1136return "cyrillic" 1137if lang in _LATIN_LANGS : 1138return "latin" 1139return "" 1140 1141 1142def vocab_for_languages (ui :Any = (),region :Any = (),keyboards :Any = ())-> tuple [str ,str ]: 1143"""(choice, language): the draft vocabulary for the computer's language signals, ``cjk`` (the default file) or ``cyrillic`` or ``latin``, and the language that decided ("" for the default). Each argument is a list of 1144language tags: ``ui`` the display / interface languages, ``region`` the regional format (user locale), ``keyboards`` the installed keyboard-layout languages. 1145any Chinese, Japanese or Korean signal anywhere -> the default; 1146else a Cyrillic signal, or a Latin-script non-English signal, picks that file; when both kinds are present the first one in the UI languages wins, then the regional format, then the keyboards; 1147no signal at all, English only, ``C`` / ``POSIX``, other scripts -> the default.""" 1148groups = [[(script_of_language (t ),str (t ))for t in (g or ())]for g in (ui ,region ,keyboards )] 1149seen = {s for g in groups for s ,_ in g if s } 1150if not seen or "cjk" in seen : 1151return "cjk" ,"" 1152for g in groups : 1153for script ,tag in g : 1154if script : 1155return script ,tag .replace ("_" ,"-" ).split ("." ,1 )[0 ].split ("@" ,1 )[0 ].split ("-" ,1 )[0 ].lower () 1156return "cjk" ,"" 1157 1158 1159def _windows_names (call )-> list [str ]: 1160try : 1161return [x for x in call ()if x ] 1162except Exception :# noqa: BLE001 - a signal that cannot be read says nothing 1163return [] 1164 1165 1166def os_language_signals (env :Any = None ,system :str | None = None )-> dict [str ,list [str ]]: 1167"""Every language signal this computer gives cheaply and locally: ``ui``, ``region``, ``keyboards`` (lists of tags). Linux and anywhere an environment is set: LANGUAGE, LC_ALL, LC_MESSAGES, LANG (display) and 1168LC_CTYPE, LC_TIME, LC_NUMERIC, LC_MONETARY (regional); Windows: the preferred UI languages, the user locale and the installed keyboard layouts (kernel32 / user32 through ctypes); the Mac: the preferred 1169languages and the locale from the user's global preferences file. A read that fails gives nothing for that signal; there is no waiting and no network.""" 1170from strata_control import sysinfo # (the platform module's own call asks WMI with no timeout on Windows) 1171env = os .environ if env is None else env 1172system = system or sysinfo .system () 1173ui :list [str ]= [] 1174region :list [str ]= [] 1175keyboards :list [str ]= [] 1176try : 1177ui += [x for x in str (env .get ("LANGUAGE" ,"" )).split (":" )if x ] 1178ui += [str (env .get (k ,"" ))for k in ("LC_ALL" ,"LC_MESSAGES" ,"LANG" )if env .get (k )] 1179region += [str (env .get (k ,"" ))for k in ("LC_CTYPE" ,"LC_TIME" ,"LC_NUMERIC" ,"LC_MONETARY" )if env .get (k )] 1180except Exception :# noqa: BLE001 1181pass 1182if system == "Windows" : 1183ui_w ,region_w ,kb_w = _windows_languages () 1184ui ,region ,keyboards = ui_w + ui ,region_w + region ,kb_w 1185elif system == "Darwin" : 1186try : 1187import plistlib 1188with open (Path .home ()/ "Library" / "Preferences" / ".GlobalPreferences.plist" ,"rb" )as fh : 1189prefs = plistlib .load (fh ) 1190ui = [str (x )for x in prefs .get ("AppleLanguages" )or []]+ ui 1191if prefs .get ("AppleLocale" ): 1192region = [str (prefs ["AppleLocale" ])]+ region 1193except Exception :# noqa: BLE001 1194pass 1195return {"ui" :ui ,"region" :region ,"keyboards" :keyboards } 1196 1197 1198def computer_language_signals ()-> dict [str ,list [str ]]: 1199"""The signals of THIS computer (os_language_signals with its own environment); the one name the tests replace so that no result depends on the language of the box that runs them.""" 1200return os_language_signals () 1201 1202 1203def _windows_languages ()-> tuple [list [str ],list [str ],list [str ]]: 1204"""(UI languages, user locale, keyboard-layout languages) as locale names on Windows, each read on its own so one failure leaves the others.""" 1205ui :list [str ]= [] 1206region :list [str ]= [] 1207keyboards :list [str ]= [] 1208try : 1209import ctypes 1210from ctypes import wintypes 1211k32 = ctypes .windll .kernel32 1212except Exception :# noqa: BLE001 1213return ui ,region ,keyboards 1214 1215def locale_name (langid :int )-> str : 1216buf = ctypes .create_unicode_buffer (85 ) 1217return buf .value if k32 .LCIDToLocaleName (langid & 0xFFFF ,buf ,85 ,0 )> 0 else "" 1218 1219try : 1220count = wintypes .ULONG (0 ) 1221size = wintypes .ULONG (0 ) 1222if k32 .GetUserPreferredUILanguages (0x8 ,ctypes .byref (count ),None ,ctypes .byref (size ))and size .value : 1223raw = ctypes .create_unicode_buffer (size .value ) 1224if k32 .GetUserPreferredUILanguages (0x8 ,ctypes .byref (count ),raw ,ctypes .byref (size )): 1225ui = [x for x in ctypes .wstring_at (ctypes .addressof (raw ),size .value ).split ("\x00" )if x ] 1226except Exception :# noqa: BLE001 1227pass 1228if not ui : 1229try : 1230ui = [x for x in (locale_name (k32 .GetUserDefaultUILanguage ()),)if x ] 1231except Exception :# noqa: BLE001 1232pass 1233try : 1234buf = ctypes .create_unicode_buffer (85 ) 1235if k32 .GetUserDefaultLocaleName (buf ,85 )> 0 and buf .value : 1236region = [buf .value ] 1237except Exception :# noqa: BLE001 1238pass 1239try : 1240u32 = ctypes .windll .user32 1241u32 .GetKeyboardLayoutList .restype = ctypes .c_int 1242n = u32 .GetKeyboardLayoutList (0 ,None ) 1243if 0 < n <= 64 : 1244layouts = (ctypes .c_void_p * n )() 1245got = u32 .GetKeyboardLayoutList (n ,layouts ) 1246keyboards = [x for x in (locale_name (int (layouts [i ]or 0 )& 0xFFFF )for i in range (max (0 ,got )))if x ] 1247except Exception :# noqa: BLE001 1248pass 1249return ui ,region ,keyboards 1250 1251 1252def vocab_ids_fit (path :Path ,n_vocab :int | None = None )-> bool : 1253"""Is this file a draft vocabulary of the model's tokenizer: whole int32 ids, none below zero or past the vocabulary (the drafter pack's own vocabulary size, 248,320 for Qwen3.8-Flash-Next)?""" 1254import array 1255try : 1256data = Path (path ).read_bytes () 1257except OSError : 1258return False 1259if not data or len (data )% 4 : 1260return False 1261ids = array .array ("i" ) 1262ids .frombytes (data ) 1263if sys .byteorder == "big" : 1264ids .byteswap () 1265return min (ids )>= 0 and max (ids )< (n_vocab or PACK_TARGET ["vocab" ]) 1266 1267 1268def auto_vocab (cfg :dict ,args :list [str ],current :Path | None ,form :str | None ,data_dir :str | Path | None = None , 1269signals :dict [str ,list [str ]]| None = None )-> tuple [Path | None ,str ]: 1270"""(file, line) for a DFlash2 start: the draft vocabulary file and one log line saying which and why. The person's own choice always wins and is kept as it was: ``draft_vocab`` saved in the run config (setup 1271``--draft-vocab``, also when it is the default one) or ``--mtp-draft-vocab`` in the arguments. Otherwise the file follows the computer's languages (vocab_for_languages) when the engine takes the file by name 1272(FORM_FILE, or an engine nobody can tell: the usual form), the shipped file is here and fits this model's vocabulary; anything else is today's default, said nothing about. Nothing is written to the config: it is worked out at every start.""" 1273name = lambda p :Path (p ).name if p else "none" # noqa: E731 1274saved = cfg .get ("draft_vocab" ) 1275if saved or _flag_value (args ,"--mtp-draft-vocab" )or _flag_value (cfg .get ("user_args" )or [],"--mtp-draft-vocab" ): 1276return current ,f"draft vocabulary: { name ( current ) } (set by you)" 1277if form not in (None ,FORM_FILE )or current is None :# (None: the engine program is not known: the usual form, the file by name) 1278return current ,f"draft vocabulary: { name ( current ) } (the default)" 1279try : 1280sig = signals if signals is not None else computer_language_signals () 1281choice ,language = vocab_for_languages (sig .get ("ui" ),sig .get ("region" ),sig .get ("keyboards" )) 1282except Exception :# noqa: BLE001 - no answer means the default 1283choice ,language = "cjk" ,"" 1284if choice != "cjk" : 1285picked = shipped_vocab (choice ) 1286if picked .is_file ()and vocab_ids_fit (picked ,pack_target (data_dir )["vocab" ]): 1287return picked ,f"draft vocabulary: { picked . name } (by this computer's language: { language } )" 1288return current ,f"draft vocabulary: { name ( current ) } (the default)" 1289 1290 1291def _sha256 (path :Path )-> str : 1292return hashlib .sha256 (path .read_bytes ()).hexdigest () 1293 1294 1295def vocab_target (data_dir :str | Path )-> Path : 1296"""Where the DFlash2 install keeps its copy of the draft vocabulary: next to the pack, so an install that never downloaded the MTP layer has one.""" 1297return Path (data_dir )/ FOLDER / VOCAB_NAME 1298 1299 1300def refresh_vocab (data_dir :str | Path | None ,choice :str = "cjk" )-> Path | None : 1301"""Put the subset the person chose in setup (``--draft-vocab``) beside the DFlash2 pack, where a DFlash2 start reads it when the MTP folder has none. The copy is made when 1302it is missing and replaced when it is a shipped subset other than the chosen one (a later choice, or an install from before the choice reached DFlash2); a subset made by hand 1303stays. Same rule as setup.refresh_draft_vocab for the MTP folder. None when it cannot be had.""" 1304if not data_dir : 1305return None 1306target = vocab_target (data_dir ) 1307try : 1308new = shipped_vocab (choice ) 1309if not new .is_file (): 1310return provide_vocab (data_dir ) 1311if target .is_file ()and target .stat ().st_size > 0 : 1312old = _sha256 (target ) 1313shipped_hashes = OLD_VOCAB_SHA256 | {_sha256 (shipped_vocab (c ))for c in VOCAB_FILES if shipped_vocab (c ).is_file ()} 1314if old == _sha256 (new )or old not in shipped_hashes : 1315return target 1316target .parent .mkdir (parents = True ,exist_ok = True ) 1317tmp = target .with_suffix (".tmp" ) 1318tmp .write_bytes (new .read_bytes ()) 1319tmp .replace (target ) 1320return target 1321except OSError : 1322return None 1323 1324 1325def provide_vocab (data_dir :str | Path | None ,choice :str | None = None )-> Path | None : 1326"""Make sure the DFlash2 folder holds the draft vocabulary (a local copy of the file Strata ships; no network). Called by the drafter's fetch and by 1327setup's DFlash2 step, so a fresh install that selected only DFlash2 has everything the engine needs. None when it cannot be had. 1328Without ``choice`` a copy that is there is never touched (the fetch must not undo the person's setup choice); with it (setup) see refresh_vocab.""" 1329if not data_dir : 1330return None 1331if choice is not None : 1332return refresh_vocab (data_dir ,choice ) 1333target = vocab_target (data_dir ) 1334try : 1335if target .is_file ()and target .stat ().st_size > 0 : 1336return target 1337source = shipped_vocab () 1338if not source .is_file (): 1339return None 1340target .parent .mkdir (parents = True ,exist_ok = True ) 1341tmp = target .with_suffix (".tmp" ) 1342tmp .write_bytes (source .read_bytes ()) 1343tmp .replace (target ) 1344return target 1345except OSError : 1346return None 1347 1348 1349def vocab_path (args :list [Any ],data_dir :str | Path | None = None )-> Path | None : 1350"""The draft vocabulary DFlash2 reads its draft head from: the person's own ``--mtp-draft-vocab``, else the one in the model's MTP folder (the subset the 1351person chose in setup), else the copy the DFlash2 install keeps, else the default subset Strata ships. None when none of them is on this computer.""" 1352given = _flag_value (args ,"--mtp-draft-vocab" ) 1353if given and Path (given ).is_file (): 1354return Path (given ) 1355folder = _flag_value (args ,"--mtp" ) 1356if folder and not folder .isdigit ()and (Path (folder )/ VOCAB_NAME ).is_file (): 1357return Path (folder )/ VOCAB_NAME 1358if data_dir and vocab_target (data_dir ).is_file (): 1359return vocab_target (data_dir ) 1360shipped = shipped_vocab () 1361return shipped if shipped .is_file ()else None 1362 1363 1364def can_run_dflash2 (model_name :str | None ,family :str | None ,backend :str | None ,archs :Any = None )-> bool : 1365"""Is this model one the drafter was made for, and does this computer's engine have the DFlash2 code? (The disk and the mode of the start are not looked at.)""" 1366return bool (supported_model (model_name ,family )and ENGINE_SERVES_DFLASH2 and backend is not None and hardware_support (backend ,archs ).can_run ) 1367 1368 1369def choice_of (mode :Any ,* ,model_name :str | None = None ,family :str | None = None ,backend :str | None = None ,archs :Any = None , 1370args :list [Any ]| None = None ,vram_mib :float | None = None )-> str : 1371"""The drafter the choice means for this model on this computer, before anything is looked up on disk: ``dflash2``, ``mtp`` or ``off``. Auto is DFlash2 wherever 1372the engine has it (DFLASH2_BACKENDS) and the model is one it was made for, the MTP everywhere else and for a set whose entry in SET_DEFAULTS says MTP; DFlash2 asked for by name 1373where it cannot run is MTP.""" 1374asked = normalize (mode ) 1375if asked == "off" : 1376return "off" 1377if asked == "mtp" : 1378return "mtp" 1379entry = default_for (backend ,model_name ) 1380if asked == "auto" and entry is not None and entry .drafter == "mtp" : 1381return "mtp" # a set whose measured default on this engine family is the MTP (SET_DEFAULTS) 1382if asked == "auto" and auto_mtp_only (backend ,archs ): 1383return "mtp" # a card where Auto keeps the MTP for now (AUTO_MTP) 1384klass = class_entry (backend ,model_name ,archs ,args = args ,vram_mib = vram_mib ) 1385if asked == "auto" and klass is not None and klass .drafter == "mtp" : 1386return "mtp" # this set on this class of card (CLASS_DEFAULTS) 1387return "dflash2" if can_run_dflash2 (model_name ,family ,backend ,archs )else "mtp" 1388 1389 1390def decide (mode :Any ,* ,klass :str = "other" ,model_name :str | None = None ,family :str | None = None ,data_dir :str | Path | None = None , 1391backend :str | None = None ,archs :Any = None ,mtp_here :bool | None = None ,blocked :bool = False ,vocab_here :bool = True , 1392args :list [Any ]| None = None ,vram_mib :float | None = None ,slots_none :bool = False )-> Decision : 1393"""The drafter a start uses. Never raises. ``slots_none`` (slots_draft_nothing of the start's arguments and request count; False when the caller cannot know it): the reason for a 1394DFlash2 that is not available here is NONE_IN_SLOTS instead of NOT_HERE, so the plan says what the server says. One drafter, never two. A choice that cannot be applied becomes the other drafter when that one is on this computer, 1395else none, with a note in plain words. ``mtp_here`` says whether the MTP layer is on disk (None: not known, taken as there), ``blocked`` that this start is a layer 1396split or has several requests at once (see blocked_by), ``vocab_here`` that the draft vocabulary DFlash2 needs is there. ``klass`` is not used any more (Auto 1397does not depend on the kind of card) and stays only so the callers keep working.""" 1398asked = normalize (mode ) 1399if asked == "off" : 1400return Decision (asked ,"off" ) 1401want = choice_of (asked ,model_name = model_name ,family = family ,backend = backend ,archs = archs ,args = args ,vram_mib = vram_mib ) 1402have_mtp = mtp_here is not False 1403# DFlash2 stands in for a missing MTP layer wherever it may run on this card: also where Auto picks the MTP for the card class (the 12 GB card with IQ3_S), so a 1404# start never goes without a drafter while one is on disk; not where Auto keeps the MTP because DFlash2 stalls there (AUTO_MTP, gfx1201) 1405# (and never as the stand-in for a chosen MTP either: owner 11-15, a chosen drafter stays chosen and its fallback must be safe on the card; DFlash2 named by 1406# itself is the person's own choice and is not looked at here) 1407runnable = can_run_dflash2 (model_name ,family ,backend ,archs )and not (asked != "dflash2" and auto_mtp_only (backend ,archs )) 1408 1409if want == "dflash2" : 1410reason = NOT_HERE if (blocked or not vocab_here )else NOT_DOWNLOADED if not drafter_ready (data_dir ,model_name ,backend )else "" 1411if reason == NOT_HERE and slots_none : 1412reason = NONE_IN_SLOTS 1413if not reason : 1414return Decision (asked ,"dflash2" ,flags = engine_flags (pack_path (data_dir ))) 1415return Decision (asked ,"mtp" ,reason )if have_mtp else Decision (asked ,"off" ,NONE_HERE ) 1416# the MTP: asked for, or all there is where DFlash2 cannot run 1417if have_mtp : 1418why = "" 1419if asked == "dflash2" :# named, and it cannot run on this model or this computer 1420why = NOT_SUPPORTED if not supported_model (model_name ,family )else NOT_SERVED if not ENGINE_SERVES_DFLASH2 else NOT_THIS_CARD 1421return Decision (asked ,"mtp" ,why ) 1422# the layer is not on this computer: DFlash2 instead when it can run and its pack is here (said), else none (said) 1423if runnable and not blocked and vocab_here and drafter_ready (data_dir ,model_name ,backend ): 1424return Decision (asked ,"dflash2" ,NO_MTP ,engine_flags (pack_path (data_dir ))) 1425return Decision (asked ,"off" ,NONE_HERE ) 1426 1427 1428ONE_REQUEST_NOTE = "DFlash2 answers one request at a time, so Strata set this model to one request at a time." 1429#: setup could not fetch the MTP layer because the computer is offline (tools/mtp_fetch.py OFFLINE) and the start has no other drafter (owner, 11-15). 1430#: The app shows the same words (apps/host/server/native-control.mjs installMtpLayer). 1431MTP_OFFLINE_NOTE = "There is no internet connection, so the draft layer can't be downloaded now. The model starts without a drafter." 1432 1433 1434def wants_one_request (mode :Any ,* ,klass :str = "other" ,model_name :str | None = None ,family :str | None = None ,backend :str | None = None , 1435archs :Any = None ,args :list [Any ]| None = None ,vram_mib :float | None = None ,** _ignored :Any )-> bool : 1436"""The choice means DFlash2 on this model and computer (named, or Auto where the engine has it): the model then starts with one request at a time, because the 1437engine's request slots (``--batch``, which Strata fills in by itself on a card with room) are not filled in beside it. A number of requests the person chose stays as 1438they chose it: with DFlash2 named the start runs DFlash2 with that many (a drafter per request), with Auto it loads the MTP and says so; the callers check that.""" 1439return choice_of (mode ,model_name = model_name ,family = family ,backend = backend ,archs = archs ,args = args ,vram_mib = vram_mib )== "dflash2" 1440 1441 1442def needs_conversion (mode :Any ,* ,klass :str = "other" ,model_name :str | None = None ,family :str | None = None ,data_dir :str | Path | None = None , 1443backend :str | None = None ,archs :Any = None ,args :list [Any ]| None = None ,vram_mib :float | None = None ,** _ignored :Any )-> bool : 1444"""Would this choice use DFlash2, is the Q4_0 pack here, and is the converted pack (Q4_0 selector) not made yet? (Then setup / Load makes it, locally, once.)""" 1445return (choice_of (mode ,model_name = model_name ,family = family ,backend = backend ,archs = archs ,args = args ,vram_mib = vram_mib )== "dflash2" and bool (data_dir ) 1446and _here (Path (data_dir )/ FOLDER / PACK_NAME )and not converted_ok (data_dir )) 1447 1448 1449def needs_pack (mode :Any ,* ,klass :str = "other" ,model_name :str | None = None ,family :str | None = None ,data_dir :str | Path | None = None , 1450backend :str | None = None ,archs :Any = None ,args :list [Any ]| None = None ,vram_mib :float | None = None ,** _ignored :Any )-> bool : 1451"""Would this choice use the DFlash2 drafter if its file were here, and is it not here yet? (Then it is fetched before the start, once.)""" 1452return choice_of (mode ,model_name = model_name ,family = family ,backend = backend ,archs = archs ,args = args ,vram_mib = vram_mib )== "dflash2" and not drafter_ready (data_dir ,model_name ,backend ) 1453 1454 1455def needs_tuned (mode :Any ,* ,klass :str = "other" ,model_name :str | None = None ,family :str | None = None ,data_dir :str | Path | None = None , 1456backend :str | None = None ,archs :Any = None ,args :list [Any ]| None = None ,vram_mib :float | None = None ,** _ignored :Any )-> bool : 1457"""Would this choice use DFlash2 with the tuned drafter (this set has an entry in SET_DEFAULTS) and is that file not here yet? (Setup, Load and `strata drafting fetch` 1458fetch it, once; offline they skip it and the stock pack or the MTP runs.)""" 1459return (choice_of (mode ,model_name = model_name ,family = family ,backend = backend ,archs = archs ,args = args ,vram_mib = vram_mib )== "dflash2" 1460and tuned_applies (backend ,model_name ,archs ,args = args ,vram_mib = vram_mib )and bool (data_dir )and not tuned_ok (data_dir ,tuned_variant (backend ,model_name ))) 1461 1462 1463def needs_mtp (mode :Any ,* ,klass :str = "other" ,model_name :str | None = None ,family :str | None = None ,backend :str | None = None , 1464archs :Any = None ,mtp_here :bool | None = None ,args :list [Any ]| None = None ,vram_mib :float | None = None ,** _ignored :Any )-> bool : 1465"""Would this choice use the MTP layer, and is it not on this computer yet? (A new install fetches only the drafter it will use; this is what a later switch 1466to the MTP fetches, once.)""" 1467return choice_of (mode ,model_name = model_name ,family = family ,backend = backend ,archs = archs ,args = args ,vram_mib = vram_mib )== "mtp" and mtp_here is False 1468 1469 1470#: The engine options of the DFlash2 drafter; none of them goes with the MTP. 1471DRAFT_FLAGS = {"--draft" :True ,"--draft-model" :True ,"--draft-conf" :True ,"--draft-mtp-spec" :True ,"--draft-fallback" :True ,"--draft-cap" :True , 1472"--draft-rule" :True ,"--draft-mtp-min-p" :True } 1473#: The engine options of the MTP layer; none of them goes with DFlash2 (``--mtp-max-t`` is left: DFlash2 reads it too). 1474MTP_ONLY_FLAGS = {"--mtp" :True ,"--mtp-q4" :True ,"--mtp-hnorm" :True ,"--mtp-window" :True ,"--mtp-draft-vocab" :True ,"--spec-min-p" :True ,"--batch-mtp" :False } 1475 1476 1477def _strip (args :list [Any ],table :dict [str ,bool ])-> list [str ]: 1478out :list [str ]= [] 1479items = [str (a )for a in args ] 1480i = 0 1481while i < len (items ): 1482if items [i ]in table : 1483i += 2 if table [items [i ]]and i + 1 < len (items )and not items [i + 1 ].startswith ("--" )else 1 1484continue 1485out .append (items [i ]) 1486i += 1 1487return out 1488 1489 1490def strip_draft_flags (args :list [Any ])-> list [str ]: 1491"""The arguments without the DFlash2 drafter's options (``--draft``, ``--draft-model``, ``--draft-fallback``, ``--draft-conf``... and their values).""" 1492return _strip (args ,DRAFT_FLAGS ) 1493 1494 1495def strip_mtp_flags (args :list [Any ])-> list [str ]: 1496"""The arguments without the MTP layer's options (``--mtp``, ``--mtp-q4``, ``--spec-min-p``, ``--batch-mtp``... and their values).""" 1497return _strip (args ,MTP_ONLY_FLAGS ) 1498 1499 1500def data_dir_of (args :list [Any ])-> Path | None : 1501"""The model data folder an argument list belongs to: `--pack <data>/packs/<tag>`, else `--mtp <data>/mtp/rt`.""" 1502items = [str (a )for a in args ] 1503for flag ,up in (("--pack" ,2 ), ("--mtp" ,2 )): 1504if flag in items and items .index (flag )+ 1 < len (items ): 1505path = Path (items [items .index (flag )+ 1 ]) 1506if flag == "--mtp" and path .name .isdigit (): 1507continue 1508return path .parents [up - 1 ]if len (path .parents )>= up else None 1509return None 1510 1511 1512def _flag_value (args :list [Any ],flag :str )-> str | None : 1513items = [str (a )for a in args or []] 1514return items [items .index (flag )+ 1 ]if flag in items and items .index (flag )+ 1 < len (items )else None 1515 1516 1517def _without_flag (args :list [str ],flag :str )-> list [str ]: 1518out :list [str ]= [] 1519i = 0 1520while i < len (args ): 1521if args [i ]== flag : 1522i += 2 if i + 1 < len (args )and not args [i + 1 ].startswith ("--" )else 1 1523continue 1524out .append (args [i ]) 1525i += 1 1526return out 1527 1528 1529def apply (cfg :dict [str ,Any ],* ,klass :str = "other" ,data_dir :str | Path | None = None ,family :str | None = None , 1530backend :str | None = None ,archs :Any = None ,vram_mib :float | None = None ,split :bool = False ,slots :int = 0 , 1531engine :str | os .PathLike [str ]| None = None )-> Decision : 1532"""Put the config's ``"drafting"`` choice on its engine arguments (in place): ONE drafter's options and none of the other's. DFlash2: no ``--mtp``, no MTP option, 1533``--draft dflash2 --draft-model <pack> --draft-fallback none --mtp-draft-vocab <file> --spec W --draft-conf C`` (W = window_for: 8 on Strix Halo and on cc 12.0 with >= 48 GB, else 6); the person's own ``--spec`` or ``--draft-conf`` 1534in ``user_args`` stays. C is 0.35 where the card holds most experts and higher where fewer slots fit (conf_for_slots): from the person's own ``--expert-cache N``, 1535else from ``vram_mib``, the memory of the one card (None: several cards, a shared-memory chip, unknown: 0.35). MTP: the arguments without any DFlash2 option. 1536``off``: neither (the draft layer's own switch, ``"mtp": false``). ``slots`` says that this start serves several requests at 1537once: with Auto that is the MTP, said in one line (except the one class of slot_drafts_by_default: 2 requests on one large Blackwell card holding every expert, where it is 1538DFlash2 with a drafter per request); with DFlash2 chosen by name it is DFlash2 with a drafter per request (blocked_by ``named``; ``split``, a layer 1539split over several cards, is ignored: DFlash2 runs on it). A config from before this rule that names both drafters starts with the one chosen. 1540`engine` is the engine program that will start (None: not known, the usual flags): an engine that only takes `--mtp DIR` for the vocabulary gets that 1541(still without the MTP layer), and an engine without `--draft-fallback` gets no DFlash2 flag at all (the MTP, said in one line).""" 1542args = [str (a )for a in cfg .get ("args" )or []] 1543if cfg .get ("split_engine_note" )and _flag_value (args ,"--draft" )== "dflash2" :# the all-cards split engine started with DFlash2 as its drafter (split_engine.split_config): its flags are its own, nothing is added or taken out 1544return Decision ("dflash2" ,"dflash2" ) 1545name = cfg .get ("model_name" ) 1546fit = "" 1547if not supported_model (name ,family ): 1548# the name is not one setup writes: what the FILE is decides (a renamed Flash-Next file, a hand-written config, a feed model under its own name); Coder, NVFP4 and Swift stay out by name 1549fit = file_fit (args ,data_dir )if family is None and not _EXCLUDED_NAME .search (str (name or "" ))else "" 1550if fit == "fits" : 1551name = known_name_of_file (args )or FILE_FITS_AS # a file that is exactly a known set gets that set's table entry; any other the general defaults 1552if not supported_model (name ,family ):# another model: its drafting is not this choice's business (Swift, Coder, NVFP4, Qwen3.6...) 1553asked = normalize (cfg .get ("drafting" )) 1554if asked == "off" or cfg .get ("mtp" )is False :# no drafter for this model (its draft layer is off, or a feed model whose entry says drafter: none): say so, start none 1555# "mtp": false: the server's own draft-layer step takes the layer out (and says so); "drafting": "off" alone: taken out here 1556cfg ["args" ]= strip_draft_flags (args )if cfg .get ("mtp" )is False else strip_mtp_flags (strip_draft_flags (args )) 1557return Decision (asked ,"off" ) 1558if asked == "dflash2" : 1559cfg ["args" ]= strip_draft_flags (args ) 1560return Decision (asked ,"mtp" ,NOT_SUPPORTED ) 1561if fit == "family" :# a Qwen3.8-Flash-Next-family file the drafter was not made for (other sizes): the MTP, and the person is told 1562cfg ["args" ]= strip_draft_flags (args ) 1563return Decision (asked ,"mtp" ,NOT_SUPPORTED ) 1564return Decision (asked ,"mtp" ) 1565mtp_here = mtp_ready (args ) 1566vocab = vocab_path (args ,data_dir ) 1567form = engine_form (engine ) 1568if form == FORM_DIR and vocab is not None and vocab .name != VOCAB_NAME : 1569vocab = None # `--mtp DIR` can only name DIR/draft_vocab.bin 1570mode = cfg .get ("drafting" ) 1571if cfg .get ("mtp" )is False and normalize (mode )== "auto" : 1572mode = "off" # "Draft layer (MTP)" turned off by the person, and no drafter chosen since: no drafter 1573slot_drafts = slot_drafts_by_default (mode ,backend = backend ,archs = archs ,vram_mib = vram_mib ,args = args ,slots = slots ,split = split , 1574drafter_here = vocab is not None and form != FORM_NONE and drafter_ready (data_dir ,name ,backend )) 1575decision = decide (mode ,model_name = name ,family = family ,data_dir = data_dir ,backend = backend ,archs = archs , 1576mtp_here = mtp_here ,blocked = blocked_by (strip_draft_flags (args ),split = split ,slots = slots ,named = normalize (mode )== "dflash2" ,backend = backend ,slot_drafts = slot_drafts )or form == FORM_NONE , 1577vocab_here = vocab is not None ,args = strip_mtp_flags (strip_draft_flags (args )),vram_mib = vram_mib , 1578slots_none = slots_draft_nothing (args ,slots ))# request slots with no --batch-mtp draft nothing: say that, not "DFlash2 isn't available in this mode" (MTP slot drafts keep that line) 1579mine = cfg .get ("user_args" )or [] 1580pack = None 1581if decision .drafter == "dflash2" : 1582qualifies = tuned_applies (backend ,name ,archs ,args = strip_mtp_flags (strip_draft_flags (args )),vram_mib = vram_mib ) 1583pack = pack_path (data_dir ,engine ,model_name = name ,backend = backend ,tuned = qualifies ) 1584if Path (pack )!= tuned_path (data_dir ,tuned_variant (backend ,name ))and not pack_ready (data_dir ):# (only the tuned pack is here and this engine cannot read it: no drafter file for it) 1585decision = Decision (decision .asked ,"mtp" ,NOT_DOWNLOADED )if mtp_here is not False else Decision (decision .asked ,"off" ,NONE_HERE ) 1586if decision .drafter == "off" : 1587cfg ["args" ]= strip_mtp_flags (strip_draft_flags (args )) 1588cfg ["mtp" ]= False 1589elif decision .drafter == "mtp" : 1590cfg ["args" ]= strip_draft_flags (args ) 1591if cfg .get ("drafting" )is not None and normalize (cfg .get ("drafting" ))!= "off" and cfg .get ("mtp" )is False : 1592cfg ["mtp" ]= True # an explicit drafter choice overrides an older "mtp": false 1593else : 1594base = strip_mtp_flags (strip_draft_flags (args )) 1595vocab ,vocab_line = auto_vocab (cfg ,args ,vocab ,form ,data_dir )# the person's own choice, else the computer's language, else the default 1596decision .vocab = vocab_line 1597flags = list (engine_flags (pack ,vocab ,form )) 1598kept_conf = _flag_value (mine ,"--draft-conf" ) 1599tuned_conf = tuned_conf_for (backend ,name )if Path (pack )== tuned_path (data_dir ,tuned_variant (backend ,name ))else None # Metal: the conf the tuned pack was measured with; CUDA / HIP: None, the backend's own conf stays 1600held = slots_of (base ,vram_mib ) 1601tuned_here = Path (pack )== tuned_path (data_dir ,tuned_variant (backend ,name )) 1602card_conf = big_blackwell_conf_for (backend ,name ,archs ,vram_mib ,held )if tuned_here else None # large-VRAM Blackwell, IQ3_S, tuned pack: the measured 0.55; Strix keeps 0.35 and only widens the window 1603flags [flags .index ("--draft-conf" )+ 1 ]= kept_conf if kept_conf is not None else f" { tuned_conf if tuned_conf is not None else card_conf if card_conf is not None else conf_for ( backend , held ):g } " 1604flags [flags .index ("--spec" )+ 1 ]= str (window_for (backend ,archs ,vram_mib ,held )) 1605if _flag_value (mine ,"--spec" )is None : 1606base = _without_flag (base ,"--spec" )# the DFlash2 window; the person's own --spec stays 1607else : 1608i = flags .index ("--spec" ) 1609del flags [i :i + 2 ] 1610cfg ["args" ]= base + flags 1611return decision 1612 1613 1614# --------------------------------------------------------------------------------------------------- what the engine said 1615 1616_ON = re .compile (r"DFlash2 drafter on\b|sfnx: DFlash2 on card 0\b" )# (the second line is the all-cards split engine's) 1617 1618 1619def fallback_note (log_text :str )-> str : 1620"""From one engine start's log: ``Drafting: MTP (DFlash2 didn't fit)`` when the engine fell back from DFlash2, else ``""``. The engine 1621names the reason in its own words; two are told apart: no room in graphics memory, and a mode this build does not support.""" 1622text = str (log_text or "" ) 1623if _ON .search (text ): 1624return "" 1625if "--draft dflash2" not in text : 1626return "" 1627low = text .lower () 1628if "it is for one card and the cli run" in low or "needs a native pack" in low or "it needs --mtp" in low : 1629reason = NOT_HERE 1630else : 1631reason = DIDNT_FIT 1632return mtp_line (reason ) 1633 1634 1635#: A load that is not the person's own asks the signed feed for the tuned drafter at most this often when the answer was "nothing" (strata_control/drafting_fetch.py keeps the mark). 1636RETRY_AFTER_S = 12 * 3600 1637MISS_MARK = ".tuned-feed-miss" 1638 1639 1640def recent_miss (data_dir :str | Path )-> bool : 1641"""Did the feed have nothing for the tuned drafter within the last RETRY_AFTER_S seconds (the mark `drafting_fetch` leaves)?""" 1642try : 1643return time .time ()- (Path (data_dir )/ FOLDER / MISS_MARK ).stat ().st_mtime < RETRY_AFTER_S 1644except OSError : 1645return False 1646 1647 1648def fetch_hint (decision :Decision ,* ,model_name :str | None ,backend :str | None ,archs :Any = None ,data_dir :str | Path | None ,args :list [Any ]| None = None , 1649vram_mib :float | None = None )-> str : 1650"""The line after "Drafting: off (no drafter is downloaded yet)": only when the choice is DFlash2 or Auto on a set with a tuned drafter and a load has just 1651found the feed empty (a recent miss mark), so the person knows `strata drafting fetch` asks again now. "" in every other case.""" 1652if decision .drafter != "off" or decision .note != NONE_HERE or normalize (decision .asked )not in ("auto" ,"dflash2" )or not data_dir : 1653return "" 1654if not tuned_applies (backend ,model_name ,archs ,args = args ,vram_mib = vram_mib )or not recent_miss (data_dir ): 1655return "" 1656return FETCH_HINT 1657 1658 1659def summary_line (decision :Decision ,engine_note :str = "" )-> str : 1660"""The line the Terminal and the app show: what drafts.""" 1661if engine_note : 1662return engine_note 1663if decision .note : 1664return line (decision .drafter ,decision .note ) 1665return f"Drafting: { LABELS . get ( decision . drafter , decision . drafter ) if decision . drafter != 'mtp' else 'MTP' } " 1666 1667 1668# --------------------------------------------------------------------------------------------------- what a start did 1669 1670_pending_note = "" 1671 1672 1673def remember_note (note :str )-> None : 1674"""The server calls this when it builds the engine arguments: why the choice was not applied, for the engine that starts next.""" 1675global _pending_note 1676_pending_note = note or "" 1677 1678 1679def take_note ()-> str : 1680global _pending_note 1681note ,_pending_note = _pending_note ,"" 1682return note 1683 1684 1685def engine_info (args :list [Any ],log_text :str = "" ,note :str = "" )-> dict [str ,str ]: 1686"""The facts of one engine start for /metrics and the apps: ``drafting`` (mtp | dflash2 | off) and ``drafting_note`` (plain words, or ""): the one drafter this 1687start loads (``--draft dflash2`` without ``--mtp``, ``--mtp`` without ``--draft``), and why it is not the one asked for. The engine's own log wins over the choice.""" 1688items = [str (a )for a in args ] 1689asked_dflash2 = any (items [i ]== "--draft" and i + 1 < len (items )and items [i + 1 ]== "dflash2" for i in range (len (items ))) 1690fell_back = fallback_note (log_text )if asked_dflash2 else "" 1691drafter = "mtp" if "--mtp" in items else "off" 1692if asked_dflash2 and not fell_back : 1693drafter = "dflash2" 1694text = fell_back or (line (drafter ,note )if note else "" ) 1695return {"drafting" :drafter ,"drafting_note" :text }