From bd90b8c5262b70b4933fdfbf024b408eaa9e6f80 Mon Sep 17 00:00:00 2001 From: Saatvik Viniak Date: Fri, 4 Dec 2026 00:36:28 -0600 Subject: [PATCH] drafting: a run config's own DFlash2 pack and tap; --draft-tap block-input A run config may now name its own DFlash2 drafter instead of the pinned incoai/Flash-Next packs: "draft_model": "", or "dflash2": {"pack": ..., "family": ..., "tap": "block-input"}. - supported_model() takes a config-named pack and lifts the model-family gate for that config only; pack_ready()/drafter_ready() check that exact file (a whole DF2P v1 pack: magic, version, an index whose tensors lie inside the file, and its own size + SHA-256 kept in a .ok marker); nothing is fetched, tuned, converted or replaced for it. Decision.pack reaches decide()/apply() and an explicit --draft-model in user_args is the same assertion. A config without the keys keeps the pinned flow byte-identical. - "tap": "block-input" (or "draft_tap") adds the engine's new --draft-tap block-input. The pinned packs read each target layer's completed output (mean of the hc streams); the RadixArk/Qwen4-DFlash2 checkpoint and SGLang's DFLASH taps read the NEXT layer's input, after the hyper-connection mix and per-stream norm, before attention (vLLM captures it at layer+1). - engine: core/tap_plan.hpp maps a pack's target ids to the tapped layer for both styles (count, per-stage share of a layer split, slot0), with a CPU-only test. Verifier::set_taps(layers, block_input) captures the block input from the window's mixed buffer in pre() and keeps the completed-output tap unchanged in post(); generate.cpp parses --draft-tap output|block-input, refuses block-input on Metal (its window writes output taps), and ends a start whose pack cannot be served in block-input style rather than let the drafter read a short tap row. Default unchanged. Tests: terminal/tests/terminal/test_drafting_custom_pack.py (new), test_drafting_pin.py now uses a whole DF2P pack, engine tap_plan_test. Engine built with -DCMAKE_CUDA_ARCHITECTURES=70 -DSTRATA_GEOMETRY=q4_lite (sm_70, CUDA 12.6). --- docs/QWEN4_35B.md | 43 ++- engine/cmake/backends/cpu.cmake | 5 + engine/include/strata/core/tap_plan.hpp | 73 ++++ engine/include/strata/core/verify.hpp | 14 +- engine/src/core/verify.cpp | 30 +- engine/src/program/generate.cpp | 38 ++- engine/tests/core/tap_plan_test.cpp | 78 +++++ terminal/strata_cli/drafting_cmd.py | 1 + terminal/strata_cli/launch/runner.py | 3 +- terminal/strata_control/doctor.py | 3 +- terminal/strata_control/drafting.py | 321 +++++++++++++----- terminal/tests/terminal/strata_fixtures.py | 13 + .../terminal/test_drafting_custom_pack.py | 196 +++++++++++ terminal/tests/terminal/test_drafting_pin.py | 3 +- 14 files changed, 717 insertions(+), 104 deletions(-) create mode 100644 engine/include/strata/core/tap_plan.hpp create mode 100644 engine/tests/core/tap_plan_test.cpp create mode 100644 terminal/tests/terminal/test_drafting_custom_pack.py diff --git a/docs/QWEN4_35B.md b/docs/QWEN4_35B.md index b57cef5d4c..368008fd7e 100644 --- a/docs/QWEN4_35B.md +++ b/docs/QWEN4_35B.md @@ -254,10 +254,8 @@ refused on a layer split ("the pipelined groups run no slot drafts") and measure **DFlash2.** The RadixArk/Qwen4-35B-A3B-Dflash2 checkpoint (395M, 5 GQA layers, taps [19,23,27,31,35], width 8) packs with the existing `tools/dflash2_pack.py`: 81 tensors, 539.4 MB, taps carried in the pack and read by -`df2.tap_layers()`. It cannot be compared at 8 streams in this build: the server's drafting policy only knows the -pinned Flash-Next pack (a custom `--draft-model` is stripped), and a layer split with `--batch` pipelines its -groups, which run no slot drafts - the same restriction that disables `--batch-mtp`. The 397 tok/s above is raw -decode, no slot drafting. DFlash2 stays a single-request option until the slot path supports it. +`df2.tap_layers()`. Section 13 has the server keys, the corrected block-input tap and the engine geometry port +that still blocks it; the numbers above are raw decode, no slot drafting. ## 12. 16 x 128K profile (more users, same aggregate KV) @@ -291,3 +289,40 @@ timings. The even mix is the best writer experience: eight readers prefilling serially while eight slots decode costs the writers nothing (35+ tok/s each, above the all-decode 30.6-33.4), and every reader still reads at 5.2-6.1K tok/s. Fewer writers buy much faster per-stream decode (4+12: 78-80 tok/s). This is the profile to optimize for. + +## 13. DFlash2 through the server: a config-chosen pack, the Qwen4 tap, and what still blocks it + +Since this section was first written the server takes a run config's own drafter (strata_control/drafting.py): +`"drafting": "dflash2"` with either `"draft_model": ""` or +`"dflash2": {"pack": "", "family": "qwen4", "tap": "block-input"}`. Naming the pack lifts the +Qwen3.8-Flash-Next family gate for that config only; `pack_ready()` checks the exact file (a whole DF2P v1 pack: +magic, version, an index whose tensors lie inside the file, and its own size + SHA-256 kept in a `.ok` marker +beside it - there is no repository pin to compare a locally made pack with), and nothing is fetched or converted +for it. The pinned Flash-Next flow is byte-identical when none of the keys is present. `"tap": "block-input"` +adds the engine's `--draft-tap block-input`. + +**The tap is the one thing that had to change in the engine.** A pinned pack reads each target layer's completed +output, averaged over the hyper-connection streams (`df2_tap_gr`). The Qwen4/RadixArk checkpoint (and SGLang's +DFLASH taps) was trained on the *next* layer's input instead: after the hyper-connection mix and per-stream +GemmaRMSNorm, immediately before attention, shape [tokens, 2048] - vLLM captures it at `layer + 1` +(`aux_hidden_state_layers`, qwen4_dflash2_taps.diff). The CUDA/HIP verifier now has `--draft-tap output|block-input` +(core/tap_plan.hpp): the default keeps the measured Flash-Next tap exactly, and block-input takes that tensor from +the verifier's `mixed` buffer of layer `target + 1` and shifts the layer split's per-stage share and slot0 with it. +The Metal engine refuses the flag (its window writes output taps only). + +**What still blocks the Qwen4 drafter in Strata's engine (not fixed here):** `Dflash2Drafter::load` refuses the +pack's geometry outright - `NH_ != 32 || NKV_ != 8 || HD_ != 128 || rank_ != 256 || N_ != 2560` - and that is not a +conservative check: the attention kernel is written for 8 K/V heads x 4 query heads (32 queries) and the ring log's +activation row is 2560 bytes. The Qwen4 pack is 16 heads / 2 K/V heads / hidden 2048. Running it needs a second +kernel instantiation (64 queries per K/V head, a 2048-byte log row), a port, not a flag. So a Qwen4 config now +reaches the engine with the right flags and fails there with the engine's own message until that port lands. + +**The vLLM Qwen4 notes that do not apply to Strata:** the draft K/V is already a fixed ring (`kRing` 2064 slots per +layer, ~84 MB total, independent of the context; the "1520 MiB of draft head and buffers" in the old log is the +248320-row draft head, not K/V), so there is no full-sequence allocation to cap; the ring is the drafter's own and +has no attention-page divisibility constraint; and the selector reads exactly the rows it computed (`ndraft_`), so +there are no unfilled gathers to clamp. The one measured opportunity left is QSA index sharing: Strata builds the +top-k per verify row, where vLLM's `index_share_for_mtp_iteration` reuses the anchor's blocks for the draft rows +(a speed/accuracy trade-off to measure, not a correctness fix). Per-slot DFlash2 drafts on a layer split still +need serial windows (`--batch-groups 1`), where a draft-carrying window holds 8 rows: at 16 slots every row is a +slot's token, so nothing is left to draft with - the reason `--batch-mtp` reads the same there. diff --git a/engine/cmake/backends/cpu.cmake b/engine/cmake/backends/cpu.cmake index 602b796a8d..b45016182d 100644 --- a/engine/cmake/backends/cpu.cmake +++ b/engine/cmake/backends/cpu.cmake @@ -236,6 +236,11 @@ if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS) add_executable(bdone_drafts_test src/program/bdone_drafts_test.cpp) target_include_directories(bdone_drafts_test PRIVATE include) add_test(NAME bdone_drafts_test COMMAND bdone_drafts_test) + # which layer's tensor a DFlash2 tap row is taken from: --draft-tap output (the pinned packs) or block-input (the Qwen4 checkpoint), and a + # layer split's per-stage share and slot0 (header-only, CPU) + add_executable(tap_plan_test tests/core/tap_plan_test.cpp) + target_include_directories(tap_plan_test PRIVATE include) + add_test(NAME tap_plan_test COMMAND tap_plan_test) endif() if(STRATA_CPU_X86) diff --git a/engine/include/strata/core/tap_plan.hpp b/engine/include/strata/core/tap_plan.hpp new file mode 100644 index 0000000000..02fd5c3bc1 --- /dev/null +++ b/engine/include/strata/core/tap_plan.hpp @@ -0,0 +1,73 @@ +// include/strata/core/tap_plan.hpp - which layer's tensor a DFlash2 tap row is taken from (header-only, no GPU). +// +// A drafter pack names the target layers whose hidden state it reads (`cfg taps`, tools/dflash2_pack.py: dc["target_layer_ids"]). +// There are two styles of tap (generate.cpp --draft-tap): +// +// output the layer's completed output - the residual after its FFN write, averaged over the hyper-connection streams +// (kernels::df2_tap_gr). This is what every pinned pack was measured with (incoai/Qwen3.8-Flash-Next-DFlash2) and stays +// the default: a start with no --draft-tap reads exactly the bytes it read before. +// block-input the input of the NEXT layer - after that layer's hyper-connection mix and per-stream GemmaRMSNorm, immediately +// before attention (the tensor Qwen4's attention consumes; vLLM's aux_hidden_state_layers hook captures it at layer+1, +// shape [tokens, n_embd]). The RadixArk Qwen4-35B-A3B-DFlash2 checkpoint and SGLang's DFLASH taps are trained on it. +// Taken from the verifier's `mixed` buffer of the tapped layer. +// +// One place maps a pack's target ids to the layer a stage of a layer split taps, so the capture, the gathered row (slot0) and the +// count the drafter allocated can never disagree. The vLLM ring/KV and selector notes do not apply here: Strata's drafter keeps its +// own fixed K/V ring (kRing slots) and its selector reads only the rows it computed. +#pragma once + +#include +#include + +namespace strata::core::tap_plan { + +enum class Style { Output, BlockInput }; + +/// `--draft-tap`'s value. "" is not a style: the caller keeps its default. `block` is accepted as the short word for block-input. +inline bool parse_style(const char* text, Style* out) { + if (text == nullptr || out == nullptr) return false; + const std::string s(text); + if (s.empty() || s == "output") { *out = Style::Output; return true; } + if (s == "block-input" || s == "block_input" || s == "block") { *out = Style::BlockInput; return true; } + return false; +} + +inline const char* style_name(Style s) { return s == Style::BlockInput ? "block-input" : "output"; } + +/// The tensor a target layer id names: the completed output of `requested`, or the block input of the layer after it. +inline int layer_of(int requested, Style s) { return s == Style::BlockInput ? requested + 1 : requested; } + +/// Is this target id one the model can serve? Both styles stop one short of the last layer: an output tap there is the model head's +/// own input (nothing follows to read it), and a block-input tap at layer n_layers - 1 needs layer n_layers, which does not exist. +inline bool requested_ok(int requested, int n_layers) { return requested >= 0 && requested < n_layers - 1; } + +/// How many taps the whole chain keeps: the drafter's tap count (its landing buffer is [rows][this][n_embd]). +inline int total(const std::vector& requested, int n_layers) { + int n = 0; + for (int r : requested) if (requested_ok(r, n_layers)) ++n; + return n; +} + +/// The tap layers a stage [lb, le) keeps, in the pack's order (its buffer's slot order). +inline std::vector stage_layers(const std::vector& requested, Style s, int lb, int le, int n_layers) { + std::vector out; + for (int r : requested) { + if (!requested_ok(r, n_layers)) continue; + const int l = layer_of(r, s); + if (l < lb || l >= le) continue; + out.push_back(l); + } + return out; +} + +/// The slot in the pack's order where this stage's first kept tap goes in the gathered row ([rows][total][n_embd]). +inline int slot0(const std::vector& requested, Style s, int lb, int n_layers) { + int n = 0; + for (int r : requested) { + if (!requested_ok(r, n_layers)) continue; + if (layer_of(r, s) < lb) ++n; + } + return n; +} + +} // namespace strata::core::tap_plan diff --git a/engine/include/strata/core/verify.hpp b/engine/include/strata/core/verify.hpp index b8aa2fb015..aecdb99ef8 100644 --- a/engine/include/strata/core/verify.hpp +++ b/engine/include/strata/core/verify.hpp @@ -405,12 +405,15 @@ public: /// Token t's residual after the last layer, (hc, n_embd) on the device, valid until the next `run`. const float* final_R(int t) const; const float* final_R_all() const { return next_ ? next_->final_R_all() : R_; } - /// DFlash2 (before init): keep the completed outputs of these layers (zero-based; the mean of the hc streams) for every row of - /// each window in a device buffer, tap_dev() = [max_t][n_taps][n_embd] floats, valid until the next window. Single-stage - /// verifiers only; STRATA_TAP_FILE (research dump) turns the same buffer on without this call. - void set_taps(const std::vector& layers) { tap_req_ = layers; } + /// DFlash2 (before init): keep the tensor of these target layers for every row of each window in a device buffer, + /// tap_dev() = [max_t][n_taps][n_embd] floats, valid until the next window. `block_input`: each id names the block input of the layer + /// after it (after the hyper-connection mix and per-stream norm, before attention: the RadixArk/Qwen4 tap) instead of the layer's own + /// completed output (the default, the mean of the hc streams: the incoai/Flash-Next tap). Single-stage verifiers only; + /// STRATA_TAP_FILE (research dump) turns the same buffer on without this call. See core/tap_plan.hpp for the mapping. + void set_taps(const std::vector& layers, bool block_input = false) { tap_req_ = layers; tap_block_ = block_input; } const float* tap_dev() const { return tap_dev_; } bool tapping() const { return tap_on_; } + bool tap_block_input() const { return tap_block_; } /// Batch windows tap too (default off: the graphs of --batch windows carry no tap kernels): the slot drafters of DFlash2 read rows of tap_dev(). Before init. void set_batch_taps(bool on) { tap_batch_ = on; } /// Layer split (DFlash2): every stage of this chain keeps the requested layers inside its own range (set_taps on each stage before init). @@ -719,8 +722,9 @@ private: // (pos, token, taps) records to the file. bool tap_on_ = false; bool tap_batch_ = false; ///< set_batch_taps + bool tap_block_ = false; ///< set_taps(..., block_input): the next layer's input (core/tap_plan.hpp), not the layer output std::vector tap_req_; ///< set_taps - std::vector tap_layers_; ///< the tapped layer ids (zero-based, completed outputs) + std::vector tap_layers_; ///< the tapped layer ids (zero-based; completed outputs, or block inputs of that layer) std::vector tap_slot_; ///< layer -> slot in tap_layers_, or -1 float* tap_dev_ = nullptr; ///< [max_t][n_taps][n_embd] float* tap_scratch_ = nullptr; ///< one row's streams, [hc][n_embd] diff --git a/engine/src/core/verify.cpp b/engine/src/core/verify.cpp index a87f284ee9..df6528af5e 100644 --- a/engine/src/core/verify.cpp +++ b/engine/src/core/verify.cpp @@ -17,6 +17,7 @@ #include "strata/core/window_evict.hpp" #include "strata/core/expert_nibble.hpp" #include "strata/core/pin_budget.hpp" +#include "strata/core/tap_plan.hpp" #if defined(STRATA_VERIFY_HGL) #include "strata/core/host_graph_launch.hpp" #endif @@ -860,10 +861,8 @@ void Verifier::set_peer(PeerExperts* peer, int parity) { } int Verifier::tap_total() const { - int n = 0; if (g_ == nullptr) return 0; - for (int l : tap_req_) if (l >= 0 && l < g_->n_layers - 1) ++n; - return n; + return strata::core::tap_plan::total(tap_req_, (int) g_->n_layers); } bool Verifier::tapping_chain() const { @@ -889,8 +888,8 @@ bool Verifier::gather_taps_host(float* dst, int row0, int rows, std::string& err err = "verify: the tap gather stream could not be created"; return false; } - int slot0 = 0; - for (int l : tap_req_) if (l >= 0 && l < g_->n_layers - 1 && l < v->lb_) ++slot0; + int slot0 = strata::core::tap_plan::slot0(tap_req_, tap_block_ ? strata::core::tap_plan::Style::BlockInput : strata::core::tap_plan::Style::Output, + (int) v->lb_, (int) g_->n_layers); const int64_t nv = (int64_t) v->tap_layers_.size(); for (int r = 0; r < rows; ++r) { const cudaError_t ce = cudaMemcpyAsync(dst + ((size_t) r * (size_t) nt_all + (size_t) slot0) * (size_t) N, @@ -917,9 +916,9 @@ bool Verifier::gather_taps(float* landing, int landing_device, int row0, int row err = "verify: the tap gather stream could not be created"; return false; } - // this stage's first tap among all of them: the requested layers below its first layer - int slot0 = 0; - for (int l : tap_req_) if (l >= 0 && l < g_->n_layers - 1 && l < v->lb_) ++slot0; + // this stage's first tap among all of them: the requested layers below its first layer (core/tap_plan.hpp maps both styles) + int slot0 = strata::core::tap_plan::slot0(tap_req_, tap_block_ ? strata::core::tap_plan::Style::BlockInput : strata::core::tap_plan::Style::Output, + (int) v->lb_, (int) g_->n_layers); const int64_t nv = (int64_t) v->tap_layers_.size(); for (int r = 0; r < rows; ++r) { const float* src = v->tap_dev_ + (size_t) (row0 + r) * (size_t) (nv * N); @@ -1116,8 +1115,9 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& } if (tap_path != nullptr || !tap_req_.empty()) { tap_layers_.clear(); + const auto style = tap_block_ ? strata::core::tap_plan::Style::BlockInput : strata::core::tap_plan::Style::Output; if (tap_path == nullptr) { - for (int l : tap_req_) if (l >= lb_ && l < le_ && l < g.n_layers - 1) tap_layers_.push_back(l); + tap_layers_ = strata::core::tap_plan::stage_layers(tap_req_, style, (int) lb_, (int) le_, (int) g.n_layers); } else { const char* tl = std::getenv("STRATA_TAP_LAYERS"); std::string list = tl != nullptr && tl[0] != '\0' ? tl : "5,15,25,35,45"; @@ -1841,6 +1841,16 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { (int) (l * kProfPer + (half == 0 ? 27 : 30))); }; const bool q8_attn = gr_read_group(0, pending, inj2_, inj_); // true: xq_ holds mixed's q8_1 (STRATA_QFUSE) + // --draft-tap block-input: the tensor this layer's attention reads, after the hyper-connection mix and per-stream norm (gr_read + // above, into mixed_) and before any attention kernel - the Qwen4/RadixArk tap. The default style taps the layer's completed output + // in post() instead (df2_tap_gr); each style writes the layer's own tap slot only, so neither can overwrite the other. +#if defined(STRATA_HAVE_DFLASH2) + if (tap_on_ && tap_block_ && (!batch_rec_ || tap_batch_) && l >= 0 && l < (int64_t) tap_slot_.size() && tap_slot_[(size_t) l] >= 0) { + const int64_t nt = (int64_t) tap_layers_.size(); + strata::kernels::df2_tap_rows(mixed_ + (size_t) tb * N, tap_dev_ + ((size_t) tb * nt + (size_t) tap_slot_[(size_t) l]) * N, + nt * N, N, 1, n, cs); + } +#endif { // measurement only: STRATA_DUMMY_NODES=k adds k empty kernel nodes per layer (what one node costs in a window) static const int dummy = [] { const char* e = std::getenv("STRATA_DUMMY_NODES"); return e != nullptr ? std::atoi(e) : 0; }(); for (int d = 0; d < dummy; ++d) gpu_noop(cs); @@ -2989,7 +2999,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { if (remote_opt_) remote_opt_->combine(bo_ + tb * N, y_dummy_ + tb * N, tb, n, device_plan_ ? skip_ + grp : nullptr, ring, cs); stamp(l, 24, grp); - if (tap_on_ && (!batch_rec_ || tap_batch_) && l < (int64_t) tap_slot_.size() && tap_slot_[(size_t) l] >= 0) { + if (tap_on_ && !tap_block_ && (!batch_rec_ || tap_batch_) && l < (int64_t) tap_slot_.size() && tap_slot_[(size_t) l] >= 0) { // the layer's completed output: R with this FFN half's write applied (the next layer's read would fold it), the mean of // the hc streams, all rows of the group in one launch const int64_t nt = (int64_t) tap_layers_.size(); diff --git a/engine/src/program/generate.cpp b/engine/src/program/generate.cpp index cb4752323c..b7621a5b7e 100644 --- a/engine/src/program/generate.cpp +++ b/engine/src/program/generate.cpp @@ -1,4 +1,5 @@ #include "strata/core/logit_bias.hpp" +#include "strata/core/tap_plan.hpp" // src/program/generate.cpp - P2.S6: `strata generate`. // // THE DRIVER, and the first program in this project that answers a question. Everything below it is a @@ -1188,6 +1189,10 @@ struct Options { /// --draft dflash2 --draft-model PACK (opt-in, CUDA / HIP): the DFlash2 block drafter for Qwen3.8-Flash-Next (tools/dflash2_pack.py) drafts instead /// of the MTP layer, which is not loaded (--draft-fallback mtp loads it too, as the fallback). Needs --mtp DIR (its draft_vocab.bin), --spec, --draft-model and a native pack; DFlash2 that cannot start is an error unless the fallback is mtp. std::string draft, draft_model; + /// --draft-tap output|block-input (with --draft dflash2; CUDA / HIP): which tensor of each target layer the pack reads (core/tap_plan.hpp). + /// output (the default) is the layer's completed output, the mean of the hc streams - every pinned pack (incoai/Flash-Next). block-input is the + /// NEXT layer's input, after its hyper-connection mix and per-stream norm and before attention - the RadixArk/Qwen4-DFlash2 and SGLang taps. + bool draft_tap_block = false; /// --draft-fallback mtp|none (with --draft dflash2): none = the MTP layer is NOT loaded, DFlash2 is the only drafter (the draft vocabulary still comes /// from /draft_vocab.bin). A DFlash2 that cannot start then ends the start with an error: nothing drafts instead. A per-run choice, not a per-round one. /// Unset: `--draft dflash2` means none (the owner's order: the DFlash2 and the MTP layer are never loaded together unless asked); `--draft auto` needs both. @@ -1364,6 +1369,9 @@ void usage() { " --mtp-draft-vocab FILE opt-in: the draft head's token subset (default /draft_vocab.bin)\n" " --draft mtp|dflash2 the draft source (default mtp); dflash2 needs --draft-model PACK (tools/dflash2_pack.py)\n" " and loads no MTP layer (--draft-fallback mtp keeps it as the fallback) (opt-in, Flash-Next, CUDA / HIP)\n" + " --draft-tap output|block-input which tensor of each target layer PACK reads (default output: the layer's completed output, the\n" + " mean of the hc streams, every pinned pack; block-input: the next layer's input after its hyper-connection mix\n" + " and per-stream norm, before attention - the RadixArk/Qwen4-DFlash2 tap) (CUDA / HIP)\n" " --draft-fallback mtp|none with --draft dflash2 (default none): none = the MTP layer is not loaded at all, DFlash2 is the only drafter and a DFlash2 that cannot start is an error;\n" " mtp = load both, the MTP drafts if DFlash2 cannot start (--draft auto always loads both)\n" " (the MTP layer's ~0.9 GiB of VRAM goes to the expert cache; --mtp DIR is still needed for DIR/draft_vocab.bin)\n" @@ -4274,6 +4282,21 @@ int main(int argc, char** argv) { else if (a == "--draft-mtp-spec") { o.draft_mtp_spec = std::max(2, std::atoi(next("--draft-mtp-spec"))); o.draft_mtp_spec_set = true; } else if (a == "--draft-mtp-min-p") o.draft_mtp_min_p = std::clamp(std::atof(next("--draft-mtp-min-p")), 0.0, 1.0); else if (a == "--draft-model") o.draft_model = next("--draft-model"); + else if (a == "--draft-tap") { + const std::string v = next("--draft-tap"); +#if defined(STRATA_GPU_METAL) + if (v != "output") { // the Metal window writes each layer's completed output itself (metal/src/engine/window.cpp); nothing there takes the block input + std::fprintf(stderr, "strata generate: --draft-tap block-input is not implemented on the Metal engine (its taps are the layer's completed output)\n"); + return 2; + } +#else + if (v == "block-input" || v == "block_input" || v == "block") o.draft_tap_block = true; + else if (v != "output") { + std::fprintf(stderr, "strata generate: --draft-tap takes output or block-input\n"); + return 2; + } +#endif + } else if (a == "--draft-fallback") { o.draft_fallback = next("--draft-fallback"); if (o.draft_fallback != "mtp" && o.draft_fallback != "none") { @@ -8399,6 +8422,15 @@ int main(int argc, char** argv) { if (why == nullptr) { if (df2.load(o.draft_model, multi_gpu && last_st != nullptr && !df2_first ? last_st->dev : 0, err)) { use_df2 = true; + // --draft-tap block-input reads the NEXT layer's input, so every pack tap needs a layer after it; the drafter allocated a landing row + // for each tap and the verifier must keep exactly those (core/tap_plan.hpp). A pack whose last target layer is the model's last-but-one + // cannot be served this way: said once, and the start ends rather than the drafter silently reading a stale tap row. + if (o.draft_tap_block && strata::core::tap_plan::total(df2.tap_layers(), (int) g.n_layers) != (int) df2.tap_layers().size()) { + std::fprintf(stderr, "strata generate: --draft-tap block-input: %s names a target layer of the model's last two (%zu taps, %d layers); " + "the layer after it is not there, so the drafter's tap rows would be short\n", + o.draft_model.c_str(), df2.tap_layers().size(), (int) g.n_layers); + return 1; + } // Per card class, from the measured A/Bs (notes-dflash2-p1.md, RESULTS-CONF.md 11-08; the numbers are in core/draft_cap.hpp): Strix Halo 8, Blackwell cc 12.0 with // at least 48 GB 8, other Blackwell 6; a 12 GB NVIDIA card is slower with DFlash2 than with the MTP at every cap but code, which only the user can know. // Recommend, never force: the window is capped for the card unless --draft-cap says otherwise, and a small NVIDIA card gets one plain line. @@ -13503,7 +13535,7 @@ int main(int argc, char** argv) { st == 0 ? nullptr : hand[(size_t) st - 1], st + 1 < n_stages ? hand[(size_t) st] : nullptr); if (hrows > strata::kernels::kVerifyNarrowT) stage_ver(st).set_handoff_rows(hrows); #if defined(STRATA_HAVE_DFLASH2) - if (use_df2 && st > 0) stage_ver(st).set_taps(df2.tap_layers()); // (stage 0 gets its taps below, as on one card) + if (use_df2 && st > 0) stage_ver(st).set_taps(df2.tap_layers(), o.draft_tap_block); // (stage 0 gets its taps below, as on one card) if (batch_df2 && st > 0) stage_ver(st).set_batch_taps(true); #endif if (overlap) @@ -13618,7 +13650,7 @@ int main(int argc, char** argv) { if (pcie_balance() && n_stages == 1) ver.set_pcie_balance(&drive.d.pcie_model); if (batch_mtp) ver.set_batch_graph_limit(64); // --batch-mtp only: slot rotation makes many layouts (LRU); 0.1.39 keeps all #if defined(STRATA_HAVE_DFLASH2) - if (use_df2) ver.set_taps(df2.tap_layers()); + if (use_df2) ver.set_taps(df2.tap_layers(), o.draft_tap_block); if (batch_df2) ver.set_batch_taps(true); #endif peer_autonomous_guard(peer, host_res, g.n_layers, g.n_expert); @@ -24635,7 +24667,7 @@ int main(int argc, char** argv) { vh.n_slots = xcache.slots(); if (pcie_balance()) ver.set_pcie_balance(&drive.d.pcie_model); #if defined(STRATA_HAVE_DFLASH2) - if (use_df2) ver.set_taps(df2.tap_layers()); + if (use_df2) ver.set_taps(df2.tap_layers(), o.draft_tap_block); #endif peer_autonomous_guard(peer, host_res, g.n_layers, g.n_expert); if (peer.valid()) ver.set_peer(&peer, 0); diff --git a/engine/tests/core/tap_plan_test.cpp b/engine/tests/core/tap_plan_test.cpp new file mode 100644 index 0000000000..732f6eddd8 --- /dev/null +++ b/engine/tests/core/tap_plan_test.cpp @@ -0,0 +1,78 @@ +// tests/core/tap_plan_test.cpp - the DFlash2 tap styles (header-only, CPU). +// +// 1. a pack's target ids map to the completed output (default) or to the block input of the next layer; +// 2. both styles stop one short of the last layer, so the count the drafter allocated is the count the chain keeps; +// 3. a layer split's stage keeps the taps inside its own range, and its slot0 is the number of taps below it - for both styles, +// including a tap at a stage boundary (the next layer lives on the next stage); +// 4. --draft-tap parses output / block-input / block and refuses anything else. +#include "strata/core/tap_plan.hpp" + +#include +#include + +namespace tp = strata::core::tap_plan; + +namespace { +int g_fail = 0; +void check(bool ok, const char* what) { + std::printf(" %-84s %s\n", what, ok ? "ok" : "FAIL"); + if (!ok) ++g_fail; +} +std::vector ids(std::initializer_list v) { return std::vector(v); } +} // namespace + +int main() { + std::printf("tap_plan_test\n"); + const std::vector qwen4 = ids({19, 23, 27, 31, 35}); + const std::vector flash = ids({5, 15, 25, 35, 45}); + tp::Style out = tp::Style::BlockInput, in = tp::Style::BlockInput; + + check(tp::parse_style("output", &out) && out == tp::Style::Output, "--draft-tap output"); + check(tp::parse_style("block-input", &in) && in == tp::Style::BlockInput, "--draft-tap block-input"); + check(tp::parse_style("block", &in) && in == tp::Style::BlockInput, "--draft-tap block (the short word)"); + check(tp::parse_style("", &in) && in == tp::Style::Output, "--draft-tap '' (the default)"); + check(!tp::parse_style("pooled", &in) && !tp::parse_style("streams_mean", &in), "--draft-tap refuses a word it does not know"); + + // 1-2: the mapping and the count + check(tp::layer_of(19, tp::Style::Output) == 19 && tp::layer_of(19, tp::Style::BlockInput) == 20, "output keeps the id; block-input reads the next layer"); + check(tp::total(qwen4, 40) == 5, "40-layer model: all five Qwen4 taps are served"); + check(tp::total(ids({5, 15, 25, 35, 47}), 48) == 4, "a target id at the last layer is not served (47 of 48)"); + check(tp::total(ids({0, 46}), 48) == 2, "0 and n_layers - 2 are the edges: both are served on a 48-layer model"); + check(tp::total(ids({47}), 48) == 0 && tp::total(ids({46}), 48) == 1, "46 of 48 is served; 47 is not"); + + // 3: one card keeps them all, in the pack's order + { + const auto all = tp::stage_layers(qwen4, tp::Style::Output, 0, 40, 40); + check(all == qwen4, "one card: output taps at 19,23,27,31,35"); + const auto blk = tp::stage_layers(qwen4, tp::Style::BlockInput, 0, 40, 40); + check(blk == ids({20, 24, 28, 32, 36}), "one card: block-input taps at 20,24,28,32,36"); + check(tp::slot0(qwen4, tp::Style::BlockInput, 0, 40) == 0, "one card: slot0 is 0"); + } + { + // a 3-GPU split 12,28,40: stage 0 [0,12), stage 1 [12,28), stage 2 [28,40) + check(tp::stage_layers(qwen4, tp::Style::Output, 0, 12, 40).empty(), "split: stage 0 keeps no Qwen4 output tap (none below 12)"); + check(tp::stage_layers(qwen4, tp::Style::Output, 12, 28, 40) == ids({19, 23, 27}), "split: stage 1 keeps 19,23,27"); + check(tp::stage_layers(qwen4, tp::Style::Output, 28, 40, 40) == ids({31, 35}), "split: stage 2 keeps 31,35"); + check(tp::slot0(qwen4, tp::Style::Output, 12, 40) == 0 && tp::slot0(qwen4, tp::Style::Output, 28, 40) == 3, "split: output slot0 0 then 3"); + check(tp::stage_layers(qwen4, tp::Style::BlockInput, 0, 12, 40).empty(), "split: stage 0 keeps no block-input tap either"); + check(tp::stage_layers(qwen4, tp::Style::BlockInput, 12, 28, 40) == ids({20, 24}), "split: block-input stage 1 keeps 20,24 (28 is stage 2's)"); + check(tp::stage_layers(qwen4, tp::Style::BlockInput, 28, 40, 40) == ids({28, 32, 36}), "split: block-input stage 2 keeps 28,32,36"); + check(tp::slot0(qwen4, tp::Style::BlockInput, 28, 40) == 2, "split: block-input slot0 counts the taps below stage 2"); + } + { + // a tap exactly at a boundary: target 11 is layer 11's output (stage 0) but layer 12's block input (stage 1) + check(tp::stage_layers(ids({11}), tp::Style::Output, 0, 12, 40) == ids({11}), "boundary: output 11 is stage 0's"); + check(tp::stage_layers(ids({11}), tp::Style::BlockInput, 0, 12, 40).empty(), "boundary: block-input 11 is not stage 0's"); + check(tp::stage_layers(ids({11}), tp::Style::BlockInput, 12, 28, 40) == ids({12}), "boundary: block-input 11 is stage 1's layer 12"); + check(tp::slot0(ids({11}), tp::Style::BlockInput, 12, 40) == 0 && tp::slot0(ids({11}), tp::Style::Output, 12, 40) == 1, + "boundary: slot0 follows the style"); + } + { + // the pinned Flash-Next pack on one card and on a split + check(tp::stage_layers(flash, tp::Style::Output, 0, 48, 48) == flash, "Flash-Next: output taps 5,15,25,35,45 unchanged"); + const auto s1 = tp::stage_layers(flash, tp::Style::Output, 12, 28, 48); + check(s1 == ids({15, 25}) && tp::slot0(flash, tp::Style::Output, 12, 48) == 1, "Flash-Next split: stage 1 keeps 15,25 at slot0 1"); + } + if (g_fail != 0) std::printf("tap_plan_test: %d FAILED\n", g_fail); + return g_fail == 0 ? 0 : 1; +} diff --git a/terminal/strata_cli/drafting_cmd.py b/terminal/strata_cli/drafting_cmd.py index 986fb8068c..a8a5bf9f5a 100644 --- a/terminal/strata_cli/drafting_cmd.py +++ b/terminal/strata_cli/drafting_cmd.py @@ -130,6 +130,7 @@ def _inputs(a) -> dict: slot_drafts = drafting.slot_drafts_by_default(mode, backend=backend, archs=archs, vram_mib=sig.get("vram_mib"), args=sig.get("args"), slots=parallel) # the drafter is fetched before the start return {"mode": mode, "klass": drafting.card_class(archs), "model_name": model_name, "family": a.family, "data_dir": data, "backend": backend, "archs": archs, "mtp_here": drafting.mtp_ready(args) if cfg else None, + "pack": drafting.custom_pack(cfg), "tap": drafting.custom_tap(cfg), # the config's own DFlash2 drafter (dflash2.pack / draft_model) and its tap style "blocked": drafting.blocked_by(args, slots=parallel, named=drafting.normalize(mode) == "dflash2", backend=backend, slot_drafts=slot_drafts), "slots_none": drafting.slots_draft_nothing(drafting.merged_args(cfg), parallel), # (False when the request count is not in the config: today's line) "mtp_dropped": drafting.batch_mtp_dropped(drafting.merged_args(cfg), parallel, diff --git a/terminal/strata_cli/launch/runner.py b/terminal/strata_cli/launch/runner.py index c5326a4cbb..d742487c62 100644 --- a/terminal/strata_cli/launch/runner.py +++ b/terminal/strata_cli/launch/runner.py @@ -2328,6 +2328,7 @@ class Runner: return {"mode": mode, "klass": drafting.card_class(archs), "model_name": name, "family": self.s.family, "data_dir": drafting.data_dir_of(args) or (Path(self.s.data_dir) if self.s.data_dir else None), "backend": backend, "archs": archs, "mtp_here": drafting.mtp_ready(args) if cfg else None, + "pack": drafting.custom_pack(cfg), "tap": drafting.custom_tap(cfg), # the config's own DFlash2 drafter (dflash2.pack / draft_model) and its tap style "blocked": drafting.blocked_by(args, split=split, slots=int(self.s.parallel or 0), named=drafting.normalize(mode) == "dflash2", backend=backend, slot_drafts=slot_drafts), "slots_none": drafting.slots_draft_nothing(drafting.merged_args(cfg), int(self.s.parallel or 0)), "mtp_dropped": drafting.batch_mtp_dropped(drafting.merged_args(cfg), int(self.s.parallel or 0), len(self.s.gpus) if split else 1)} @@ -2344,7 +2345,7 @@ class Runner: cfg = read_config(config) want = self.drafting_inputs(cfg) sig = self.drafting_signals(cfg, want) - if not drafting.wants_one_request(**want, **sig) or not drafting.drafter_ready(want["data_dir"], want["model_name"], want["backend"]): + if not drafting.wants_one_request(**want, **sig) or not drafting.drafter_ready(want["data_dir"], want["model_name"], want["backend"], pack=want.get("pack")): return False # (no drafter file after all, e.g. no internet: the MTP runs and the slots stay) except Exception: # noqa: BLE001 - a note is never a reason to stop a launch return False diff --git a/terminal/strata_control/doctor.py b/terminal/strata_control/doctor.py index 1176c84143..a447e7b3e4 100644 --- a/terminal/strata_control/doctor.py +++ b/terminal/strata_control/doctor.py @@ -172,7 +172,8 @@ def _drafter_is_dflash2(cfg: dict) -> bool: try: from strata_control import drafting backend, archs = drafting.hardware_for(cfg.get("backend")) # #5109: the config's card family on a mixed NVIDIA + AMD computer - return cfg.get("mtp") is not False and drafting.choice_of(cfg.get("drafting"), model_name=cfg.get("model_name"), backend=backend, archs=archs) == "dflash2" + return cfg.get("mtp") is not False and drafting.choice_of(cfg.get("drafting"), model_name=cfg.get("model_name"), backend=backend, archs=archs, + pack=drafting.custom_pack(cfg)) == "dflash2" except Exception: # noqa: BLE001 - unknown means the MTP, which stays required return False diff --git a/terminal/strata_control/drafting.py b/terminal/strata_control/drafting.py index 010b1af0ec..d465717ba4 100644 --- a/terminal/strata_control/drafting.py +++ b/terminal/strata_control/drafting.py @@ -18,6 +18,14 @@ strata_control/draft_layer.py), so a setup run that rewrites the engine argument Recommend, never force: a choice that cannot be applied (DFlash2 with several requests at once, no drafter file yet) does not stop the start. 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 engine never switches drafter mid-run. + +A run config may also name its own DFlash2 pack instead of the pinned incoai/Flash-Next ones: ``"draft_model": ""`` beside ``"drafting"``, or a +``"dflash2": {"pack": "", "family": "", "tap": "block-input"}`` block (custom_pack / custom_family / custom_tap). Naming the pack is the person's +assertion that this drafter is the one for this model, so the model-family gate (supported_model) does not apply to that config and the pack's own bytes are +what is checked (custom_pack_ok: there is no pin to compare a file made on this computer with). ``tap`` names which tensor of each target layer the pack +reads: ``output`` (the default, the pinned packs' completed layer output) or ``block-input`` (the next layer's input after its hyper-connection mix and +norm, just before attention: the RadixArk/Qwen4-DFlash2 checkpoint and SGLang's DFLASH taps), passed on as the engine's ``--draft-tap``. The pinned +Flash-Next flow is unchanged: a config without those keys reads, packs, fetches and starts exactly as before. """ from __future__ import annotations @@ -508,9 +516,14 @@ NAMED_ONLY_FAMILIES = ("coder",) _NAMED_ONLY_NAME = re.compile(r"^qwen3\.8-flash-next-coder-[a-z0-9._-]+$", re.IGNORECASE) -def supported_model(model_name: str | None = None, family: str | None = None, *, named: bool = False) -> bool: +def supported_model(model_name: str | None = None, family: str | None = None, *, named: bool = False, + pack: str | Path | None = None) -> bool: """DFlash2 is for Qwen3.8-Flash-Next only: by family when it is known (the Terminal), else by the run config's model name. ``named``: DFlash2 is the - person's own choice, which also takes the Coder (NAMED_ONLY_FAMILIES, #5240).""" + person's own choice, which also takes the Coder (NAMED_ONLY_FAMILIES, #5240). ``pack``: the run config names its own drafter file (custom_pack), which is + the person's assertion that this is the drafter for this model: the family gate does not apply (the pack's own ``cfg`` lines carry the geometry the engine + reads, so what can run it is the engine's answer, not a name).""" + if pack: + return True if family is not None: return family.lower() in SUPPORTED_FAMILIES or (named and family.lower() in NAMED_ONLY_FAMILIES) return bool(model_name and (_SUPPORTED_NAME.match(str(model_name)) or (named and _NAMED_ONLY_NAME.match(str(model_name))))) @@ -623,45 +636,49 @@ def known_name_of_file(args: list[Any]) -> str | None: return None -def pack_target(data_dir: str | Path | None = None) -> dict[str, Any]: - """What the drafter pack on this computer says it was made for (``hidden``, ``vocab``, ``taps`` from its ``cfg`` lines), else PACK_TARGET.""" +def pack_target(data_dir: str | Path | None = None, pack: str | Path | None = None) -> dict[str, Any]: + """What the drafter pack says it was made for (``hidden``, ``vocab``, ``taps`` from its ``cfg`` lines), else PACK_TARGET. ``pack``: the file a run + config names itself (custom_pack), read first: the geometry a custom drafter was made for is the one file_fit and the vocabulary check compare with.""" want = dict(PACK_TARGET) + candidates: list[Path] = [Path(pack)] if pack else [] if data_dir: base = Path(data_dir) / FOLDER - for name in (TUNED_NAME, TUNED_BF16_NAME, CONVERTED_NAME, PACK_NAME): - try: - with open(base / name, "rb") as f: - head = f.read(_PACK_HEAD) - except OSError: - continue - if len(head) < 12 or head[:4] != b"DF2P": - continue - (n,) = struct.unpack_from("= 3 and parts[0] == "cfg": - try: - if parts[1] in ("hidden", "vocab"): - want[parts[1]] = int(parts[2]) - elif parts[1] == "taps": - want["taps"] = tuple(int(x) for x in parts[2].split(",")) - except ValueError: - pass - break + candidates += [base / name for name in (TUNED_NAME, TUNED_BF16_NAME, CONVERTED_NAME, PACK_NAME)] + for candidate in candidates: + try: + with open(candidate, "rb") as f: + head = f.read(_PACK_HEAD) + except OSError: + continue + if len(head) < 12 or head[:4] != b"DF2P": + continue + (n,) = struct.unpack_from("= 3 and parts[0] == "cfg": + try: + if parts[1] in ("hidden", "vocab"): + want[parts[1]] = int(parts[2]) + elif parts[1] == "taps": + want["taps"] = tuple(int(x) for x in parts[2].split(",")) + except ValueError: + pass + break return want -def file_fit(args: list[Any], data_dir: str | Path | None = None) -> str: +def file_fit(args: list[Any], data_dir: str | Path | None = None, pack: str | Path | None = None) -> str: """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 vocabulary, more layers than the last tap), ``family`` (the same architecture, other sizes: a different model of that family), ``other`` (another architecture) or - ``unknown`` (no file in the arguments, not a GGUF, or not readable).""" + ``unknown`` (no file in the arguments, not a GGUF, or not readable). ``pack``: the file a run config names itself, whose ``cfg`` lines are what the file is + compared with (pack_target).""" path = _flag_value(args, "--native") facts = gguf_facts(path) if path else None if not facts: return "unknown" if facts["arch"] != TARGET_ARCH: return "other" - want = pack_target(data_dir) + want = pack_target(data_dir, pack) if facts["hidden"] == want["hidden"] and (facts["layers"] or 0) > max(want["taps"]) and facts["vocab"] in (None, want["vocab"]): return "fits" return "family" @@ -829,13 +846,125 @@ def pack_path(data_dir: str | Path, engine: str | os.PathLike[str] | None = None return target_path(data_dir) -def pack_ready(data_dir: str | Path | None) -> bool: +def pack_ready(data_dir: str | Path | None, pack: str | Path | None = None) -> bool: + """Is a drafter file for this start on the computer? The stock selection for the model's data folder, or ``pack``: the exact file a run config names + (custom_pack), whose own size, index and SHA-256 are checked (custom_pack_ok), never the pinned pack's bytes.""" + if pack is not None: + return custom_pack_ok(pack) try: return bool(data_dir) and _here(pack_path(data_dir)) except OSError: return False +#: A run config may name its own DFlash2 pack: ``"draft_model": ""`` beside ``"drafting"``, or the block +#: ``"dflash2": {"pack": "", "family": ""}``. The pinned incoai/Flash-Next packs are the default; a named pack is a file +#: tools/dflash2_pack.py made from another checkpoint (or one copied in), and the config that names it is the person's word that it is the +#: drafter for this model. ``family`` is a word for the record (``qwen4``, ``qwen3``...): the geometry the engine reads is in the pack's +#: own ``cfg`` lines, so a family here gates nothing. +def custom_pack(cfg: dict[str, Any] | None) -> Path | None: + """The DFlash2 pack this run config names itself, or None: ``"draft_model": ""``, or ``"dflash2": {"pack": ""}`` (the block wins when + both are written; ``"dflash2": ""`` is taken as its short form). ``~`` is expanded; a relative path is relative to the folder the server is + started in, as every other path in a run config is. None for anything else (no key, an empty value, a block without ``pack``).""" + if not isinstance(cfg, dict): + return None + block = cfg.get("dflash2") + raw: Any = None + if isinstance(block, dict): + raw = block.get("pack") + elif isinstance(block, str): + raw = block + if not raw: + raw = cfg.get("draft_model") + text = str(raw or "").strip() + if not text: + return None + try: + return Path(text).expanduser() + except (OSError, ValueError): + return None + + +def custom_family(cfg: dict[str, Any] | None) -> str | None: + """The family word a config gives beside its own pack (``"dflash2": {"family": "qwen4"}``), or None. For the record and the log only: naming the + pack is what bypasses the model-family gate (supported_model), and what the engine can read is decided by the pack's own ``cfg`` lines.""" + block = cfg.get("dflash2") if isinstance(cfg, dict) else None + text = str((block or {}).get("family") or "").strip() if isinstance(block, dict) else "" + return text or None + + +#: Which tensor of each target layer a drafter pack reads (the engine's --draft-tap; the pack's ``cfg taps`` are the target layer ids either way): +#: output the layer's completed output (the mean over the hyper-connection streams): the incoai/Flash-Next pack, every pinned set, the default +#: block-input the input of the NEXT layer, after its hyper-connection mix and per-stream norm, just before attention: the RadixArk/Qwen4-DFlash2 +#: checkpoint and SGLang's DFLASH taps (vLLM captures it at layer+1, shape [tokens, hidden]) +TAP_STYLES = ("output", "block-input") + + +def custom_tap(cfg: dict[str, Any] | None) -> str | None: + """The tap style a config gives for its own pack (``"dflash2": {"tap": "block-input"}``, or ``"draft_tap"`` beside ``"draft_model"``), or None for the + default (output). A word this module does not know is None too: the default tap runs, so a typo cannot end a start (the engine's ``--draft-tap`` + refuses a word it does not know when the flag is written by hand in ``user_args``).""" + if not isinstance(cfg, dict): + return None + block = cfg.get("dflash2") + raw = block.get("tap") if isinstance(block, dict) else None + if not raw: + raw = cfg.get("draft_tap") + text = str(raw or "").strip().lower() + return text if text in TAP_STYLES else None + + +_PACK_MAGIC = b"DF2P" # tools/dflash2_pack.py: "DF2P", u32 version 1, u32 index length, the index, then the tensors +_PACK_INDEX_MAX = 4 << 20 # an index of 81 tensors is ~9 KB; anything past a few MiB is not this format + + +def custom_pack_ok(path: str | Path | None) -> bool: + """Is this the complete DF2P v1 pack a run config names: the magic, the version, an index whose every tensor lies inside the file, and (once) the + file's SHA-256 recorded in a marker beside it, so a start after that reads one tiny file instead of the pack (converted_ok's rule, for a file nobody + pinned). The size and the hash are the person's own: there is no repository pin to compare them with, so what is checked is that the file is whole and + that it has not changed under the same name since it was last looked at. Nothing is written when the marker cannot be; a missing, short, cut or + unreadable file is simply "no". Never raises.""" + if not path: + return False + try: + p = Path(path) + stat = p.stat() + if not p.is_file() or stat.st_size <= (1 << 20): + return False + with p.open("rb") as f: + head = f.read(12) + if len(head) != 12 or head[:4] != _PACK_MAGIC: + return False + version, index_len = struct.unpack_from(" _PACK_INDEX_MAX or 12 + index_len > stat.st_size: + return False + index = f.read(index_len) + if len(index) != index_len: + return False + end = 0 + for line in index.decode("utf-8", "replace").splitlines(): + parts = line.split() + if len(parts) >= 7 and parts[0] == "t": # t + end = max(end, int(parts[5]) + int(parts[6])) + if end <= 0 or 12 + index_len + end > stat.st_size: + return False + marker = p.with_name(p.name + ".ok") + try: + known = json.loads(marker.read_text(encoding="utf-8")) + if known.get("size") == stat.st_size and known.get("mtime_ns") == stat.st_mtime_ns and known.get("sha256"): + return True + except (OSError, ValueError): + pass + digest = sha256_of(p) + try: + marker.write_text(json.dumps({"size": stat.st_size, "mtime_ns": stat.st_mtime_ns, "sha256": digest}), encoding="utf-8") + except OSError: + pass + return True + except (OSError, ValueError, struct.error): + return False + + #: AMD chips that share the system memory (serve/server.py HIP_IGPU_ARCHS: the same list): no card memory to read. IGPU_ARCHS = ("gfx1035", "gfx1036", "gfx1037", "gfx1103", "gfx1150", "gfx1151", "gfx1152", "gfx90c") @@ -868,9 +997,13 @@ def card_vram_mib(cfg: dict[str, Any], backend: str | None, archs: Any = None) - return None -def drafter_ready(data_dir: str | Path | None, model_name: str | None = None, backend: str | None = None) -> bool: - """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.""" +def drafter_ready(data_dir: str | Path | None, model_name: str | None = None, backend: str | None = None, + pack: str | Path | None = None) -> bool: + """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; with + ``pack`` the exact file a run config names itself (custom_pack_ok), and nothing else.""" try: + if pack is not None: + return custom_pack_ok(pack) return pack_ready(data_dir) or (bool(data_dir) and uses_tuned(backend, model_name) and tuned_ok(data_dir, tuned_variant(backend, model_name))) except OSError: return False @@ -1025,13 +1158,17 @@ def _read_form(path: Path) -> str | None: return None -def engine_flags(pack: str | Path, vocab: str | Path | None = None, form: str | None = None) -> tuple[str, ...]: +def engine_flags(pack: str | Path, vocab: str | Path | None = None, form: str | None = None, + tap: str | None = None) -> tuple[str, ...]: """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 - `--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.""" + `--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. + `tap`: which tensor of each target layer the pack reads (TAP_STYLES); None or ``output`` is the pinned packs' tap and adds no flag, ``block-input`` + adds ``--draft-tap block-input`` (a config-named pack whose checkpoint was trained on the layer input).""" where: tuple[str, ...] = () if vocab: where = ("--mtp", str(Path(vocab).parent)) if form == FORM_DIR else ("--mtp-draft-vocab", str(vocab)) - return ("--draft", "dflash2", "--draft-model", str(pack), "--draft-fallback", "none", *where, "--spec", str(SPEC_WINDOW), "--draft-conf", f"{DRAFT_CONF:g}") + extra: tuple[str, ...] = ("--draft-tap", tap) if tap in TAP_STYLES and tap != "output" else () + return ("--draft", "dflash2", "--draft-model", str(pack), "--draft-fallback", "none", *where, "--spec", str(SPEC_WINDOW), "--draft-conf", f"{DRAFT_CONF:g}", *extra) def blackwell_w8(backend: str | None, archs: Any = None, vram_mib: float | None = None, slots: int | float | None = None) -> bool: @@ -1432,10 +1569,11 @@ def vocab_ids_fit(path: Path, n_vocab: int | None = None) -> bool: def auto_vocab(cfg: dict, args: list[str], current: Path | None, form: str | None, data_dir: str | Path | None = None, - signals: dict[str, list[str]] | None = None) -> tuple[Path | None, str]: + signals: dict[str, list[str]] | None = None, pack: str | Path | None = None) -> tuple[Path | None, str]: """(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 ``--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 - (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.""" + (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. + ``pack``: the file a run config names itself, whose own vocabulary the shipped subset must fit (pack_target).""" name = lambda p: Path(p).name if p else "none" # noqa: E731 saved = cfg.get("draft_vocab") if saved or _flag_value(args, "--mtp-draft-vocab") or _flag_value(cfg.get("user_args") or [], "--mtp-draft-vocab"): @@ -1449,7 +1587,7 @@ def auto_vocab(cfg: dict, args: list[str], current: Path | None, form: str | Non choice, language = "cjk", "" if choice != "cjk": picked = shipped_vocab(choice) - if picked.is_file() and vocab_ids_fit(picked, pack_target(data_dir)["vocab"]): + if picked.is_file() and vocab_ids_fit(picked, pack_target(data_dir, pack)["vocab"]): return picked, f"draft vocabulary: {picked.name} (by this computer's language: {language})" return current, f"draft vocabulary: {name(current)} (the default)" @@ -1527,10 +1665,11 @@ def vocab_path(args: list[Any], data_dir: str | Path | None = None) -> Path | No return shipped if shipped.is_file() else None -def can_run_dflash2(model_name: str | None, family: str | None, backend: str | None, archs: Any = None, *, named: bool = False) -> bool: - """Is this model one the drafter was made for (``named``: or one it runs on when chosen by name, the Coder), and does this computer's engine have the DFlash2 code? - (The disk and the mode of the start are not looked at.)""" - return bool(supported_model(model_name, family, named=named) and ENGINE_SERVES_DFLASH2 and backend is not None and hardware_support(backend, archs).can_run) +def can_run_dflash2(model_name: str | None, family: str | None, backend: str | None, archs: Any = None, *, named: bool = False, + pack: str | Path | None = None) -> bool: + """Is this model one the drafter was made for (``named``: or one it runs on when chosen by name, the Coder; ``pack``: or one a run config names its own + drafter file for), and does this computer's engine have the DFlash2 code? (The disk and the mode of the start are not looked at.)""" + return bool(supported_model(model_name, family, named=named, pack=pack) and ENGINE_SERVES_DFLASH2 and backend is not None and hardware_support(backend, archs).can_run) def canonical_pack(args: list[Any] | None = None) -> bool: @@ -1570,11 +1709,12 @@ def intel_plain(backend: str | None, model_name: str | None) -> bool: def choice_of(mode: Any, *, model_name: str | None = None, family: str | None = None, backend: str | None = None, archs: Any = None, - args: list[Any] | None = None, vram_mib: float | None = None, canonical: bool | None = None) -> str: + args: list[Any] | None = None, vram_mib: float | None = None, canonical: bool | None = None, + pack: str | Path | None = None) -> str: """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 the 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 where it cannot run is MTP. Auto is also the MTP on a canonical pack (#7090; ``canonical`` says so for a pack that is not built yet, None reads ``--pack`` in ``args``): - the engine's DFlash2 needs a native pack.""" + the engine's DFlash2 needs a native pack. ``pack``: the drafter file this run config names itself (custom_pack): the model-family gate does not apply.""" asked = normalize(mode) if asked == "off": return "off" @@ -1592,52 +1732,56 @@ def choice_of(mode: Any, *, model_name: str | None = None, family: str | None = klass = class_entry(backend, model_name, archs, args=args, vram_mib=vram_mib) if asked == "auto" and klass is not None and klass.drafter == "mtp": return "mtp" # this set on this class of card (CLASS_DEFAULTS) - return "dflash2" if can_run_dflash2(model_name, family, backend, archs, named=asked == "dflash2") else "mtp" + return "dflash2" if can_run_dflash2(model_name, family, backend, archs, named=asked == "dflash2", pack=pack) else "mtp" def decide(mode: Any, *, klass: str = "other", model_name: str | None = None, family: str | None = None, data_dir: str | Path | None = None, backend: str | None = None, archs: Any = None, mtp_here: bool | None = None, blocked: bool = False, vocab_here: bool = True, args: list[Any] | None = None, vram_mib: float | None = None, slots_none: bool = False, pack: str | Path | None = None, - mtp_dropped: bool = False) -> Decision: + mtp_dropped: bool = False, tap: str | None = None) -> Decision: """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 DFlash2 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, else 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 split 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 - does not depend on the kind of card) and stays only so the callers keep working. ``pack`` pins the person's own runtime file instead of the automatic selection.""" + does not depend on the kind of card) and stays only so the callers keep working. ``pack`` pins the person's own runtime file instead of the automatic selection + (a run config's own DFlash2 pack, custom_pack): its exact file is what must be there, and its presence also lifts the model-family gate. ``tap``: which tensor of + each target layer that pack reads (TAP_STYLES; ``block-input`` adds ``--draft-tap block-input``).""" asked = normalize(mode) if asked == "off": return Decision(asked, "off") if asked == "auto" and intel_plain(backend, model_name): return Decision(asked, "off") # no drafter, no note: it is what Auto means here - want = choice_of(asked, model_name=model_name, family=family, backend=backend, archs=archs, args=args, vram_mib=vram_mib) + want = choice_of(asked, model_name=model_name, family=family, backend=backend, archs=archs, args=args, vram_mib=vram_mib, pack=pack) have_mtp = mtp_here is not False # 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 # start never goes without a drafter while one is on disk; not where Auto keeps the MTP because DFlash2 stalls there (AUTO_MTP, gfx1201) # (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 # itself is the person's own choice and is not looked at here) - runnable = can_run_dflash2(model_name, family, backend, archs, named=asked == "dflash2") and not (asked != "dflash2" and auto_mtp_only(backend, archs)) + runnable = can_run_dflash2(model_name, family, backend, archs, named=asked == "dflash2", pack=pack) and not (asked != "dflash2" and auto_mtp_only(backend, archs)) if asked != "dflash2" and str(backend or "").strip().lower() != "metal" and canonical_pack(args): runnable = False # #7090: not a stand-in on a canonical pack either (the engine refuses it: "it needs a native pack"); the start goes without a drafter, and the safety net fetches the MTP + def ready() -> bool: + return pack_ready(None, pack) if pack is not None else drafter_ready(data_dir, model_name, backend) + if want == "dflash2": - ready = _here(Path(pack)) if pack is not None else drafter_ready(data_dir, model_name, backend) - reason = NOT_HERE if (blocked or not vocab_here) else NOT_DOWNLOADED if not ready else "" + reason = NOT_HERE if (blocked or not vocab_here) else NOT_DOWNLOADED if not ready() else "" if reason == NOT_HERE and (slots_none or mtp_dropped): reason = NONE_IN_SLOTS if not reason: - return Decision(asked, "dflash2", flags=engine_flags(pack if pack is not None else pack_path(data_dir))) + return Decision(asked, "dflash2", flags=engine_flags(pack if pack is not None else pack_path(data_dir), tap=tap)) return Decision(asked, "mtp", reason) if have_mtp else Decision(asked, "off", NONE_HERE) # the MTP: asked for, or all there is where DFlash2 cannot run if have_mtp: why = "" if asked == "dflash2": # named, and it cannot run on this model or this computer - why = NOT_SUPPORTED if not supported_model(model_name, family, named=True) else NOT_SERVED if not ENGINE_SERVES_DFLASH2 else NOT_THIS_CARD + why = NOT_SUPPORTED if not supported_model(model_name, family, named=True, pack=pack) else NOT_SERVED if not ENGINE_SERVES_DFLASH2 else NOT_THIS_CARD elif mtp_dropped: # --batch-mtp on a layer split whose slots are pipelined: the engine drops it, the slots draft nothing (batch_mtp_dropped) why = NONE_IN_SLOTS return Decision(asked, "mtp", why) # the layer is not on this computer: DFlash2 instead when it can run and its pack is here (said), else none (said) - if runnable and not blocked and vocab_here and (_here(Path(pack)) if pack is not None else drafter_ready(data_dir, model_name, backend)): - return Decision(asked, "dflash2", NO_MTP, engine_flags(pack if pack is not None else pack_path(data_dir))) + if runnable and not blocked and vocab_here and ready(): + return Decision(asked, "dflash2", NO_MTP, engine_flags(pack if pack is not None else pack_path(data_dir), tap=tap)) return Decision(asked, "off", NONE_HERE) @@ -1648,30 +1792,41 @@ MTP_OFFLINE_NOTE = "There is no internet connection, so the draft layer can't be def wants_one_request(mode: Any, *, klass: str = "other", model_name: str | None = None, family: str | None = None, backend: str | None = None, - archs: Any = None, args: list[Any] | None = None, vram_mib: float | None = None, **_ignored: Any) -> bool: - """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 - engine'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 - they 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.""" - return choice_of(mode, model_name=model_name, family=family, backend=backend, archs=archs, args=args, vram_mib=vram_mib) == "dflash2" + archs: Any = None, args: list[Any] | None = None, vram_mib: float | None = None, pack: str | Path | None = None, + **_ignored: Any) -> bool: + """The choice means DFlash2 on this model and computer (named, or Auto where the engine has it; ``pack``: or the run config names its own drafter file): the model + then starts with one request at a time, because the engine'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 they 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.""" + return choice_of(mode, model_name=model_name, family=family, backend=backend, archs=archs, args=args, vram_mib=vram_mib, pack=pack) == "dflash2" def needs_conversion(mode: Any, *, klass: str = "other", model_name: str | None = None, family: str | None = None, data_dir: str | Path | None = None, - backend: str | None = None, archs: Any = None, args: list[Any] | None = None, vram_mib: float | None = None, **_ignored: Any) -> bool: - """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.)""" - return (choice_of(mode, model_name=model_name, family=family, backend=backend, archs=archs, args=args, vram_mib=vram_mib) == "dflash2" and bool(data_dir) - and _here(Path(data_dir) / FOLDER / PACK_NAME) and not converted_ok(data_dir)) + backend: str | None = None, archs: Any = None, args: list[Any] | None = None, vram_mib: float | None = None, + pack: str | Path | None = None, **_ignored: Any) -> bool: + """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.) + False for a run config that names its own pack: the conversion is the pinned pack's, and a custom file is used as it is.""" + return (pack is None and choice_of(mode, model_name=model_name, family=family, backend=backend, archs=archs, args=args, vram_mib=vram_mib) == "dflash2" + and bool(data_dir) and _here(Path(data_dir) / FOLDER / PACK_NAME) and not converted_ok(data_dir)) def needs_pack(mode: Any, *, klass: str = "other", model_name: str | None = None, family: str | None = None, data_dir: str | Path | None = None, - backend: str | None = None, archs: Any = None, args: list[Any] | None = None, vram_mib: float | None = None, **_ignored: Any) -> bool: - """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.)""" + backend: str | None = None, archs: Any = None, args: list[Any] | None = None, vram_mib: float | None = None, + pack: str | Path | None = None, **_ignored: Any) -> bool: + """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.) Never for a run config + that names its own pack: the person supplies that file, nothing is fetched for it (a missing one is said by the start's own line, not downloaded over).""" + if pack is not None: + return False return 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) def needs_tuned(mode: Any, *, klass: str = "other", model_name: str | None = None, family: str | None = None, data_dir: str | Path | None = None, - backend: str | None = None, archs: Any = None, args: list[Any] | None = None, vram_mib: float | None = None, **_ignored: Any) -> bool: + backend: str | None = None, archs: Any = None, args: list[Any] | None = None, vram_mib: float | None = None, + pack: str | Path | None = None, **_ignored: Any) -> bool: """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` - fetch it, once; offline they skip it and the stock pack or the MTP runs.)""" + fetch it, once; offline they skip it and the stock pack or the MTP runs.) Never for a run config that names its own pack: the tuned files are the pinned sets'.""" + if pack is not None: + return False return (choice_of(mode, model_name=model_name, family=family, backend=backend, archs=archs, args=args, vram_mib=vram_mib) == "dflash2" and 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))) @@ -1685,7 +1840,7 @@ def needs_mtp(mode: Any, *, klass: str = "other", model_name: str | None = None, #: The engine options of the DFlash2 drafter; none of them goes with the MTP. DRAFT_FLAGS = {"--draft": True, "--draft-model": True, "--draft-conf": True, "--draft-mtp-spec": True, "--draft-fallback": True, "--draft-cap": True, - "--draft-rule": True, "--draft-mtp-min-p": True} + "--draft-rule": True, "--draft-mtp-min-p": True, "--draft-tap": True} #: The engine options of the MTP layer; none of them goes with DFlash2 (``--mtp-max-t`` is left: DFlash2 reads it too). MTP_ONLY_FLAGS = {"--mtp": True, "--mtp-q4": True, "--mtp-hnorm": True, "--mtp-window": True, "--mtp-draft-vocab": True, "--spec-min-p": True, "--batch-mtp": False} @@ -1753,19 +1908,28 @@ def apply(cfg: dict[str, Any], *, klass: str = "other", data_dir: str | Path | N once: 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 DFlash2 with a drafter per request); with DFlash2 chosen by name it is DFlash2 with a drafter per request (blocked_by ``named``; ``split``, a layer split over several cards, is ignored: DFlash2 runs on it). A config from before this rule that names both drafters starts with the one chosen. + A config that names its own DFlash2 pack (``"draft_model"`` / ``"dflash2": {"pack": ...}``, custom_pack) uses that exact file, whatever the model is + called or which family it is: the family gate does not apply, the pinned pack, the tuned fallbacks and the conversion are not consulted, and its file is + checked by custom_pack_ok (whole, unchanged) instead of against the pinned bytes. ``"dflash2": {"tap": "block-input"}`` (or ``"draft_tap"``) adds + ``--draft-tap block-input``: the pack reads the next layer's input after its hyper-connection mix and norm (a Qwen4-style checkpoint), not the layer + output the pinned packs read. Nothing else about the start changes: the window, the confidence and the vocabulary keep their usual rules (a ``--spec`` / + ``--draft-conf`` / ``--mtp-draft-vocab`` in ``user_args`` stays the person's own). `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 (still without the MTP layer), and an engine without `--draft-fallback` gets no DFlash2 flag at all (the MTP, said in one line).""" args = [str(a) for a in cfg.get("args") or []] if 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 return Decision("dflash2", "dflash2") + mine = cfg.get("user_args") or [] + pinned_pack = _flag_value(mine, "--draft-model") # the person's own drafter file, in either place: the config's keys or --draft-model in user_args name = cfg.get("model_name") + named_pack = custom_pack(cfg) or (Path(pinned_pack) if pinned_pack else None) # a named pack is the person's assertion: the family gate does not apply fit = "" - if not supported_model(name, family): + if not supported_model(name, family, pack=named_pack): # 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 - fit = file_fit(args, data_dir) if family is None and not _EXCLUDED_NAME.search(str(name or "")) else "" + fit = file_fit(args, data_dir, pack=named_pack) if family is None and not _EXCLUDED_NAME.search(str(name or "")) else "" if fit == "fits": name = 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 - if not supported_model(name, family, named=normalize(cfg.get("drafting")) == "dflash2"): # another model: its drafting is not this choice's business (Swift, NVFP4, Qwen3.6, the Coder under Auto...) + if not supported_model(name, family, named=normalize(cfg.get("drafting")) == "dflash2", pack=named_pack): # another model: its drafting is not this choice's business (Swift, NVFP4, Qwen3.6, the Coder under Auto...) asked = normalize(cfg.get("drafting")) if 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 # "mtp": false: the server's own draft-layer step takes the layer out (and says so); "drafting": "off" alone: taken out here @@ -1786,27 +1950,26 @@ def apply(cfg: dict[str, Any], *, klass: str = "other", data_dir: str | Path | N mode = cfg.get("drafting") if cfg.get("mtp") is False and normalize(mode) == "auto": mode = "off" # "Draft layer (MTP)" turned off by the person, and no drafter chosen since: no drafter - mine = cfg.get("user_args") or [] - pinned_pack = _flag_value(mine, "--draft-model") + tap = custom_tap(cfg) or (_flag_value(mine, "--draft-tap") or None) # which tensor of each target layer the pack reads (block-input for a Qwen4-style checkpoint) slot_drafts = slot_drafts_by_default(mode, backend=backend, archs=archs, vram_mib=vram_mib, args=args, slots=slots, split=split, - drafter_here=vocab is not None and form != FORM_NONE and (_here(Path(pinned_pack)) if pinned_pack is not None else drafter_ready(data_dir, name, backend))) + drafter_here=vocab is not None and form != FORM_NONE and (pack_ready(None, named_pack) if named_pack is not None else drafter_ready(data_dir, name, backend))) decision = decide(mode, model_name=name, family=family, data_dir=data_dir, backend=backend, archs=archs, mtp_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, vocab_here=vocab is not None, args=strip_mtp_flags(strip_draft_flags(args)), vram_mib=vram_mib, - slots_none=slots_draft_nothing(args, slots), pack=pinned_pack, # request slots with no --batch-mtp draft nothing: say that, not "DFlash2 isn't available in this mode" (MTP slot drafts keep that line) + slots_none=slots_draft_nothing(args, slots), pack=named_pack, tap=tap, # request slots with no --batch-mtp draft nothing: say that, not "DFlash2 isn't available in this mode" (MTP slot drafts keep that line) mtp_dropped=batch_mtp_dropped(args, slots, stages)) # --batch-mtp on a layer split with pipelined groups: the engine drops it, same line pack = None fallback_tuned = False # the tuned pack stands in for a missing stock pack (#5810): the stock pack's conf, not the tuned pack's measured one if decision.drafter == "dflash2": qualifies = tuned_applies(backend, name, archs, args=strip_mtp_flags(strip_draft_flags(args)), vram_mib=vram_mib) - pack = pinned_pack if pinned_pack is not None else pack_path(data_dir, engine, model_name=name, backend=backend, tuned=qualifies) - if pinned_pack is None and not qualifies and Path(pack) != tuned_path(data_dir, tuned_variant(backend, name)) and not pack_ready(data_dir): + pack = named_pack if named_pack is not None else pack_path(data_dir, engine, model_name=name, backend=backend, tuned=qualifies) + if named_pack is None and not qualifies and Path(pack) != tuned_path(data_dir, tuned_variant(backend, name)) and not pack_ready(data_dir): # #5810: the stock pack is the one for this start and it is not here, but the set's tuned pack is (setup fetched it for a start that held more # experts): the other DFlash2 pack of the set, before the MTP or no drafter (owner: the drafter stays on) other = pack_path(data_dir, engine, model_name=name, backend=backend, tuned=True) if Path(other) == tuned_path(data_dir, tuned_variant(backend, name)): pack, fallback_tuned = other, True - if pinned_pack is None and 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) + if named_pack is None and 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) decision = Decision(decision.asked, "mtp", NOT_DOWNLOADED) if mtp_here is not False else Decision(decision.asked, "off", NONE_HERE) if decision.drafter == "off": cfg["args"] = strip_mtp_flags(strip_draft_flags(args)) @@ -1817,9 +1980,9 @@ def apply(cfg: dict[str, Any], *, klass: str = "other", data_dir: str | Path | N cfg["mtp"] = True # an explicit drafter choice overrides an older "mtp": false else: base = strip_mtp_flags(strip_draft_flags(args)) - vocab, vocab_line = auto_vocab(cfg, args, vocab, form, data_dir) # the person's own choice, else the computer's language, else the default + vocab, vocab_line = auto_vocab(cfg, args, vocab, form, data_dir, pack=named_pack) # the person's own choice, else the computer's language, else the default decision.vocab = vocab_line - flags = list(engine_flags(pack, vocab, form)) + flags = list(engine_flags(pack, vocab, form, tap=tap)) kept_conf = _flag_value(mine, "--draft-conf") tuned_conf = tuned_conf_for(backend, name) if Path(pack) == tuned_path(data_dir, tuned_variant(backend, name)) and not fallback_tuned else None # Metal: the conf the tuned pack was measured with; CUDA / HIP: None, the backend's own conf stays held = slots_of(base, vram_mib) diff --git a/terminal/tests/terminal/strata_fixtures.py b/terminal/tests/terminal/strata_fixtures.py index 8f6531c309..6220b28061 100644 --- a/terminal/tests/terminal/strata_fixtures.py +++ b/terminal/tests/terminal/strata_fixtures.py @@ -45,3 +45,16 @@ def inkling_strata(k16: bool = False, pad: int = 0) -> bytes: def hy4_strata(k16: bool = False, pad: int = 0) -> bytes: return synthetic_strata({"format": "strata-v1.1", "arch": "hy4flash", "config": {"model_type": "hy_v4"}}, k16, pad=pad) + + +def df2p_pack(hidden: int = 2048, vocab: int = 248320, taps=(19, 23, 27, 31, 35), tensor_bytes: int = 2 << 20, magic: bytes = b"DF2P", + version: int = 1, truncate: int = 0) -> bytes: + """A whole DFlash2 runtime pack as tools/dflash2_pack.py writes one: "DF2P", u32 version 1, u32 index length (padded so the data starts on a 4096 + multiple), the index ("cfg " lines and one "t " tensor), then the tensor's bytes. `truncate` + cuts that many bytes off the end (a pack that is shorter than its index says); `magic` / `version` make files the loader must refuse.""" + lines = [f"cfg hidden {hidden}", f"cfg vocab {vocab}", "cfg taps " + ",".join(str(t) for t in taps), + "t w q8_0 1 %d 0 %d" % (tensor_bytes, tensor_bytes), "end"] + index = ("\n".join(lines) + "\n").encode() + index += b" " * ((-(len(index) + 12)) % 4096) + body = magic + struct.pack(""`` or ``"dflash2": {"pack": "", "family": "qwen4", "tap": "block-input"}`` beside ``"drafting"``: the pack is the person's own +file, the model-family gate does not apply (supported_model), the exact file is what is checked (pack_ready / custom_pack_ok: whole, unchanged), nothing is +fetched for it, and ``tap`` passes the engine's ``--draft-tap block-input`` (the next layer's input after its hyper-connection mix and norm: the Qwen4 tap) +only when the config says so. A config without those keys keeps the pinned Flash-Next flow byte for byte. +""" + +from __future__ import annotations + +import json +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from strata_control import drafting, user_args +from tests.terminal.strata_fixtures import df2p_pack + +Q4 = "qwen4-35b-a3b" +V31 = "qwen3.8-flash-next-unsloth-ud-iq4_xs-v31" +BYTES = df2p_pack() + + +class Base(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.data = self.root / "data" + for sub in ("dflash2", "mtp/rt", "packs/tag"): + (self.data / sub).mkdir(parents=True) + (self.data / "dflash2" / drafting.VOCAB_NAME).write_bytes(b"v" * 100) + (self.data / "mtp" / "rt" / "experts.bin").write_bytes(b"e" * 100) + (self.data / "mtp" / "rt" / drafting.VOCAB_NAME).write_bytes(b"v" * 100) + self.exe = self.root / "strata" + self.exe.write_bytes(b"--mtp-draft-vocab FILE (or --mtp DIR ... --draft-fallback ... selector codebooks: Q4_0 rows") + self.args = ["--native", "m.gguf", "--pack", str(self.data / "packs" / "tag"), "--mtp", str(self.data / "mtp" / "rt"), + "--spec", "2", "--max-context", "65536"] + patcher = mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", True) + patcher.start() + self.addCleanup(patcher.stop) + + def pack(self, name="qwen4-35b.df2p", body=None): + path = self.root / name + path.write_bytes(BYTES if body is None else body) + return path + + def cfg(self, name=Q4, **extra): + return {"model_name": name, "args": list(self.args), **extra} + + def apply(self, cfg, backend="cuda", archs=("sm_70",), **kw): + return drafting.apply(cfg, data_dir=self.data, backend=backend, archs=list(archs), engine=self.exe, **kw) + + @staticmethod + def flag(args, name): + return args[args.index(name) + 1] if name in args and args.index(name) + 1 < len(args) else None + + +class TheConfigsOwnPack(Base): + def test_the_family_gate_is_lifted_only_by_a_named_pack(self): + self.assertFalse(drafting.supported_model(Q4)) + self.assertFalse(drafting.supported_model(None, "qwen4")) + self.assertFalse(drafting.supported_model(Q4, "", named=True)) + path = self.pack() + self.assertTrue(drafting.supported_model(Q4, pack=path)) + self.assertTrue(drafting.supported_model(None, "qwen4", pack=path)) + self.assertTrue(drafting.supported_model("qwen3.8-flash-next-swift-iq3_s", pack=path), "the pack is the person's own word, even under an excluded name") + + def test_the_config_keys_are_read_in_both_forms(self): + self.assertIsNone(drafting.custom_pack({})) + self.assertIsNone(drafting.custom_pack(None)) + self.assertEqual(drafting.custom_pack({"draft_model": "/a.pack"}), Path("/a.pack")) + self.assertEqual(drafting.custom_pack({"dflash2": {"pack": "/b.pack", "family": "qwen4"}}), Path("/b.pack")) + self.assertEqual(drafting.custom_pack({"dflash2": "/c.pack"}), Path("/c.pack"), "the block's short form") + self.assertEqual(drafting.custom_pack({"dflash2": {"pack": "/b.pack"}, "draft_model": "/a.pack"}), Path("/b.pack"), "the block wins") + self.assertIsNone(drafting.custom_pack({"dflash2": {"family": "qwen4"}})) + self.assertEqual(drafting.custom_family({"dflash2": {"pack": "/b.pack", "family": "qwen4"}}), "qwen4") + self.assertIsNone(drafting.custom_family({"draft_model": "/a.pack"})) + self.assertEqual(drafting.custom_tap({"dflash2": {"tap": "block-input"}}), "block-input") + self.assertEqual(drafting.custom_tap({"draft_tap": "BLOCK-INPUT"}), "block-input") + self.assertIsNone(drafting.custom_tap({"dflash2": {"tap": "pooled"}}), "an unknown word is not passed to the engine") + self.assertIsNone(drafting.custom_tap({})) + + def test_pack_ready_takes_that_exact_file(self): + path = self.pack() + self.assertTrue(drafting.pack_ready(None, path)) + self.assertTrue(drafting.drafter_ready(None, Q4, "cuda", pack=path)) + self.assertFalse(drafting.pack_ready(self.data), "the pinned pack is not here in this test") + self.assertFalse(drafting.pack_ready(None, self.root / "missing.pack")) + self.assertFalse(drafting.pack_ready(None, self.pack("cut.pack", df2p_pack(truncate=4096))), "a file shorter than its index says") + self.assertFalse(drafting.pack_ready(None, self.pack("nomagic.pack", df2p_pack(magic=b"DF2Q")))) + self.assertFalse(drafting.pack_ready(None, self.pack("v2.pack", df2p_pack(version=2)))) + self.assertFalse(drafting.pack_ready(None, self.root / "tiny.pack"), "a file of 1 MiB or less") + + def test_the_packs_own_vocabulary_is_what_the_shipped_subset_is_checked_against(self): + path = self.pack() + self.assertEqual(drafting.pack_target(self.data, path)["hidden"], 2048) + self.assertEqual(drafting.pack_target(self.data, path)["taps"], (19, 23, 27, 31, 35)) + self.assertEqual(drafting.pack_target(self.data)["hidden"], drafting.PACK_TARGET["hidden"], "no pack of the pinned names: the Flash-Next geometry") + + def test_an_unknown_model_starts_dflash2_with_the_configs_pack(self): + path = self.pack() + cfg = self.cfg(drafting="dflash2", draft_model=str(path)) + decision = self.apply(cfg) + self.assertEqual((decision.drafter, decision.note), ("dflash2", "")) + self.assertEqual(self.flag(cfg["args"], "--draft-model"), str(path)) + self.assertEqual(self.flag(cfg["args"], "--draft-fallback"), "none") + self.assertNotIn("--mtp", cfg["args"]) + self.assertNotIn("--draft-tap", cfg["args"], "the default tap (the pinned packs' layer output) adds no flag") + + def test_auto_also_takes_the_configs_pack(self): + path = self.pack() + cfg = self.cfg(draft_model=str(path)) # no "drafting": Auto + decision = self.apply(cfg) + self.assertEqual(decision.drafter, "dflash2") + self.assertEqual(self.flag(cfg["args"], "--draft-model"), str(path)) + + def test_a_missing_pack_starts_the_mtp_with_the_reason(self): + cfg = self.cfg(drafting="dflash2", dflash2={"pack": str(self.root / "not-copied.pack"), "family": "qwen4"}) + decision = self.apply(cfg) + self.assertEqual((decision.drafter, decision.note), ("mtp", drafting.NOT_DOWNLOADED)) + self.assertNotIn("--draft-model", cfg["args"]) + + def test_nothing_is_fetched_or_converted_for_a_named_pack(self): + path = self.pack() + for missing in (path, self.root / "not-copied.pack"): + self.assertFalse(drafting.needs_pack("dflash2", model_name=Q4, data_dir=self.data, backend="cuda", archs=["sm_70"], pack=missing)) + self.assertFalse(drafting.needs_tuned("dflash2", model_name=Q4, data_dir=self.data, backend="cuda", archs=["sm_70"], pack=missing)) + self.assertFalse(drafting.needs_conversion("dflash2", model_name=Q4, data_dir=self.data, backend="cuda", archs=["sm_70"], pack=missing)) + + def test_the_block_input_tap_is_a_flag_when_the_config_names_it(self): + path = self.pack() + for extra in ({"dflash2": {"pack": str(path), "family": "qwen4", "tap": "block-input"}}, + {"draft_model": str(path), "draft_tap": "block-input"}): + with self.subTest(extra=sorted(extra)): + cfg = self.cfg(drafting="dflash2", **extra) + decision = self.apply(cfg) + self.assertEqual(decision.drafter, "dflash2") + self.assertEqual(self.flag(cfg["args"], "--draft-tap"), "block-input") + self.assertIn("--draft-tap", decision.flags) + cfg = self.cfg(drafting="dflash2", dflash2={"pack": str(path), "tap": "output"}) + self.apply(cfg) + self.assertNotIn("--draft-tap", cfg["args"], "an explicit output tap is the pinned default: no flag") + + def test_a_user_args_tap_is_kept(self): + path = self.pack() + cfg = self.cfg(drafting="dflash2", draft_model=str(path), user_args=["--draft-tap", "block-input"]) + user_args.apply(cfg) + self.apply(cfg) + self.assertEqual(self.flag(cfg["args"], "--draft-tap"), "block-input") + + def test_the_tap_flag_goes_with_the_dflash2_flags_only(self): + path = self.pack() + cfg = self.cfg(drafting="mtp", dflash2={"pack": str(path), "tap": "block-input"}) + self.apply(cfg) + self.assertNotIn("--draft-tap", cfg["args"], "no DFlash2 option with the MTP") + self.assertIn("--mtp", cfg["args"]) + + def test_user_args_draft_model_is_the_same_assertion(self): + path = self.pack("own.pack") + cfg = self.cfg(drafting="dflash2") + cfg["user_args"] = ["--draft-model", str(path)] + user_args.apply(cfg) + decision = self.apply(cfg) + self.assertEqual(decision.drafter, "dflash2") + self.assertEqual(self.flag(cfg["args"], "--draft-model"), str(path)) + + +class ThePinnedFlowIsUnchanged(Base): + def put_stock(self): + (self.data / "dflash2" / drafting.PACK_NAME).write_bytes(b"s" * (2 << 20)) + + def test_a_config_without_the_keys_gets_the_pinned_flags_byte_for_byte(self): + self.put_stock() + cfg = self.cfg(V31, drafting="dflash2") + decision = self.apply(cfg, archs=("sm_70",)) + self.assertEqual(decision.drafter, "dflash2") + pack = (self.data / "dflash2" / drafting.PACK_NAME) + self.assertEqual(cfg["args"], + ["--native", "m.gguf", "--pack", str(self.data / "packs" / "tag"), "--max-context", "65536", + "--draft", "dflash2", "--draft-model", str(pack), "--draft-fallback", "none", + "--mtp-draft-vocab", str(self.data / "mtp" / "rt" / drafting.VOCAB_NAME), + "--spec", "6", "--draft-conf", "0.35"]) + self.assertNotIn("--draft-tap", cfg["args"]) + + def test_no_config_key_changes_the_pinned_gate(self): + for name in ("qwen3.8-flash-next-iq3_s", V31): + self.assertTrue(drafting.supported_model(name)) + self.assertFalse(drafting.supported_model(Q4)) + self.assertEqual(drafting.choice_of("auto", model_name=Q4, backend="cuda", archs=["sm_70"]), "mtp") + self.assertEqual(drafting.choice_of("auto", model_name=Q4, backend="cuda", archs=["sm_70"], pack=self.pack()), "dflash2") + + +if __name__ == "__main__": + unittest.main() diff --git a/terminal/tests/terminal/test_drafting_pin.py b/terminal/tests/terminal/test_drafting_pin.py index ffddd2bed3..8cd5f12ad4 100644 --- a/terminal/tests/terminal/test_drafting_pin.py +++ b/terminal/tests/terminal/test_drafting_pin.py @@ -1,5 +1,6 @@ """A user-pinned drafter must reach the engine instead of the automatic pack.""" from strata_control import drafting, user_args +from tests.terminal.strata_fixtures import df2p_pack from tests.terminal.test_drafting_tuned import Base, V31, flag @@ -12,7 +13,7 @@ class PinnedDrafter(Base): def pinned(self): path = self.root / "measured-drafter.pack" - path.write_bytes(b"p" * (2 << 20)) + path.write_bytes(df2p_pack()) # a whole DF2P v1 pack (the server checks the file it hands the engine: custom_pack_ok) return path def apply_cuda(self, cfg):