From 6667ac43d49a39db5d0d40a19dae22c54f5f2f8b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 22 Oct 2026 18:13:54 +0200 Subject: [PATCH 1/3] wip: DFlash2 in the serve loop (ring stamps, request history, prompt rows, spec loop), serve test harness --- include/strata/core/dflash2.hpp | 12 ++- include/strata/kernels/dflash2.hpp | 7 +- include/strata/prefill/prefill.hpp | 2 + src/core/dflash2.cpp | 37 ++++++++- src/kernels/cuda/dflash2.cu | 23 ++++-- src/prefill/prefill.cpp | 19 +++++ src/program/generate.cpp | 89 +++++++++++++++++++-- tools/dflash2/mk_serve_scenario.py | 48 +++++++++++ tools/dflash2/serve_test.py | 124 +++++++++++++++++++++++++++++ 9 files changed, 342 insertions(+), 19 deletions(-) create mode 100644 tools/dflash2/mk_serve_scenario.py create mode 100644 tools/dflash2/serve_test.py diff --git a/include/strata/core/dflash2.hpp b/include/strata/core/dflash2.hpp index 205bff3d09..c536b76a6d 100644 --- a/include/strata/core/dflash2.hpp +++ b/include/strata/core/dflash2.hpp @@ -50,7 +50,13 @@ public: bool bind_raw(EmbedFn embed, const void* head_w, int head_type, int64_t head_rows, const std::vector& vocab, std::string& err); /// A new request: the ring is empty again. - void reset() { have_ctx_ = 0; } + void reset() { have_ctx_ = 0; hist_.clear(); ++epoch_; ring_hi_ = 0; } + /// Serve: a request starts with prompt `ids` (n tokens) and the session continues at `resume`. The drafter keeps the token history of the rows its ring + /// was filled for: when that agrees with ids[0, resume) the ring serves the request as it is (a live conversation going on); when it does not (a parked + /// conversation restored, an edited turn) the ring starts over and `*cold` is set (the drafts are poor for the first rounds, never wrong: the verify decides). + bool begin_request(const int32_t* ids, int64_t n, int64_t resume, bool* cold); + /// Serve: rows [pos0, pos0 + n) were committed with these tokens (a prompt chunk, a prompt window, a decode window's accepted rows). + void note_rows(const int32_t* toks, int64_t n, int64_t pos0); /// Context rows without a draft: `n` rows of taps (device, [n][5 * n_embd]) for positions pos0 ... pos0 + n - 1. bool context(const float* taps_dev, int64_t n, int64_t pos0, std::string& err); /// One round: the new context rows (n_new in 1..8: the committed window rows, taps device [n_new][5 * n_embd], positions pos0 ...), @@ -134,6 +140,10 @@ private: cudaGraphExec_t exec_[kRows + 1] = {}; const float* graph_taps_ = nullptr; int64_t have_ctx_ = 0; + std::vector hist_; ///< the token of every position the ring was filled for (serve) + int64_t ring_hi_ = 0; ///< one past the highest position written in this epoch + int32_t epoch_ = 0; ///< stamped into the ring tags: a new epoch makes every older slot invalid + int64_t* tag_ = nullptr; ///< per ring slot: (epoch << 32 | position) of the row it holds, -1 none cudaEvent_t ev_a_ = nullptr, ev_b_ = nullptr; bool timing_ = false; }; diff --git a/include/strata/kernels/dflash2.hpp b/include/strata/kernels/dflash2.hpp index bdcf0cbe4c..3a0c4f1631 100644 --- a/include/strata/kernels/dflash2.hpp +++ b/include/strata/kernels/dflash2.hpp @@ -42,7 +42,7 @@ void df2_copy_rows(const float* in, float* out, const int32_t* pos, int slot_mod /// s + i - j < window (j in [max(0, s - window + 1), s - 1], slot j % ring_slots) and every block key. `s` is read from *anchor_pos /// on the device. Partials in `part` ([kDf2MaxChunks][8][32][130] floats) are combined and the 8 output rows (4096 wide) written planar-quantized to xq / xd. void df2_attention(const float* q, const float* kring, const float* vring, const float* kblk, const float* vblk, const int32_t* anchor_pos, - int ring_slots, int window, float* part, void* xq, float* xd, void* stream); + int ring_slots, int window, float* part, void* xq, float* xd, void* stream, const int64_t* tag = nullptr, const int32_t* epoch = nullptr); /// The Q8 GEMM the drafter's matrices run on. A weight matrix is TILED (see the layout note in dflash2.cu; df2_q8_tile makes it from GGUF Q8_0 blocks): /// the int8 plane at `w` (n_out * n_in bytes) then the fp16 scale plane. Activations are planar (df2_quant_rows and the fused quantizers below): @@ -72,9 +72,10 @@ void df2_conv_rms_quant(const float* x, const float* dyn, int dyn_stride, const /// The block's q (q_heads x 128) and k (k_heads x 128) per row: RMS norm and rope with the table of the block's positions -> qo, ko (row-major). void df2_norm_rope_qk(const float* q, const float* k, const float* gq, const float* gk, const float* table, float* qo, float* ko, int rows, int q_heads, int k_heads, float eps, void* stream); -/// The context update's write: K (norm + rope) and V of `rows` rows into the head-major rings at slot pos[r] % slots. +/// The context update's write: K (norm + rope) and V of `rows` rows into the head-major rings at slot pos[r] % slots. With `tag` (int64 per slot) the slot is +/// stamped (*epoch << 32 | pos) and the attention (same tag / epoch) ignores a slot whose stamp is not the position it expects. void df2_kv_ring(const float* kin, const float* vin, const float* gk, const int32_t* pos, const float* table, float* kring, float* vring, int slots, int rows, - int heads, float eps, void* stream); + int heads, float eps, void* stream, int64_t* tag = nullptr, const int32_t* epoch = nullptr); /// Top-16 per row of logits [rows][n] (value-descending; ties to the lower index). idx_map (optional) maps a column to a token id. /// scratch: rows * kDf2TopBlocks * 16 * 2 words. Outputs val[rows][16] and tok[rows][16]. n <= 4096 * kDf2TopBlocks. diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index 3e2e13c0a3..7d61626027 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -197,6 +197,8 @@ public: /// [rows][layers][n_embd] device, rows, first position, err) runs with the stream synchronized. clear_taps frees the staging. void set_taps(const std::vector& layers, int64_t first_pos, int64_t cap_rows) { tap_layers_ = layers; tap_first_ = first_pos; tap_cap_ = cap_rows; } void clear_taps(); + /// Allocate the staging now (serve: so a request never fails on it): `cap_rows` rows of `layers` x `n_embd` floats. False: the card has no room. + bool reserve_taps(const std::vector& layers, int64_t cap_rows, int64_t n_embd, std::string& err); std::function on_taps; /// Layer split: called by every stage when it has read a chunk, with the position reached, while its own state diff --git a/src/core/dflash2.cpp b/src/core/dflash2.cpp index bf9855c0db..8c0839cd0c 100644 --- a/src/core/dflash2.cpp +++ b/src/core/dflash2.cpp @@ -45,7 +45,7 @@ Dflash2Drafter::~Dflash2Drafter() { for (cudaGraphExec_t& e : exec_) if (e) cudaGraphExecDestroy(e); auto fr = [](void* p) { if (p) cudaFree(p); }; - fr(blob_); fr(d_meta_); fr(xq_); fr(xqp_); fr(xdp_); fr(xqc_); fr(xdc_); fr(rt_ctx_); fr(rt_blk_); + fr(blob_); fr(tag_); fr(d_meta_); fr(xq_); fr(xqp_); fr(xdp_); fr(xqc_); fr(xdc_); fr(rt_ctx_); fr(rt_blk_); for (int l = 0; l < 8; ++l) { fr(kring_[l]); fr(vring_[l]); } fr(fcy_); fr(hctx_); fr(kc_); fr(vc_); fr(h_); fr(xn_); fr(xc_); fr(dyn_); fr(q_); fr(qn_); fr(k_); fr(v_); fr(kblk_); fr(ao_); fr(o_); fr(gate_); fr(up_); fr(mlp_); fr(part_); fr(fn_); fr(logits_); fr(topval_); fr(hsel_); fr(toptok_); fr(topscratch_); @@ -250,6 +250,9 @@ bool Dflash2Drafter::alloc(std::string& err) { out_tok_ = (int32_t*) dd; // the select kernel writes the 7 picks here (host-visible) ... out_prob_ = (float*) dd + 16; // ... and their probabilities at +16 ints cudaMemset(rt_ctx_, 0, B * 128 * 4); + if (cudaMalloc((void**) &tag_, (size_t) kRing * 8) != cudaSuccess) { err = "dflash2: ring tags"; return false; } + vram_ += (uint64_t) kRing * 8; + cudaMemset(tag_, 0xff, (size_t) kRing * 8); // -1: no slot holds a context row yet cudaMemset(xqp_, 0, (size_t) 5 * N_ * 8 + 4096); cudaMemset(xdp_, 0, ((size_t) 5 * N_ / 32 * 8 + 64) * 4); cudaMemset(xqc_, 0, (size_t) 5 * N_ * 8 + 4096); @@ -361,7 +364,7 @@ bool Dflash2Drafter::record_context(const float* taps, int n, cudaStream_t cs, s const std::string kp = p + "self_attn.k_proj.weight", vp = p + "self_attn.v_proj.weight"; gemm({kp.c_str(), vp.c_str()}, {kc_, vc_}, n, cs, xqc_, xdc_); stamp("gemm:kp"); - df2_kv_ring(kc_, vc_, f32(p + "self_attn.k_norm.weight"), d_meta_ + 0, rt_ctx_, kring_[l], vring_[l], kRing, n, NKV_, eps_, cs); + df2_kv_ring(kc_, vc_, f32(p + "self_attn.k_norm.weight"), d_meta_ + 0, rt_ctx_, kring_[l], vring_[l], kRing, n, NKV_, eps_, cs, tag_, d_meta_ + 18); stamp("df2_kv_ring"); if (fork_) cudaEventRecord(ev_ctx_[l], cs); // layer l's keys and values are in the ring } @@ -398,7 +401,7 @@ bool Dflash2Drafter::record_block(cudaStream_t cs, std::string& err) { if (!skip_part("small")) df2_norm_rope_qk(q_, k_, f32(p + "self_attn.q_norm.weight"), f32(p + "self_attn.k_norm.weight"), rt_blk_, qn_, kblk_, B, NH_, NKV_, eps_, cs); stamp("df2_norm_rope_qk"); if (fork_) cudaStreamWaitEvent(cs, ev_ctx_[l], 0); // the context update has written this layer's ring - if (!skip_part("attn")) df2_attention(qn_, kring_[l], vring_[l], kblk_, v_, d_meta_ + 17, kRing, window_, part_, xqp_, xdp_, cs); + if (!skip_part("attn")) df2_attention(qn_, kring_[l], vring_[l], kblk_, v_, d_meta_ + 17, kRing, window_, part_, xqp_, xdp_, cs, tag_, d_meta_ + 18); stamp("df2_attention"); if (!skip_part("qkvo")) gemm({(p + "self_attn.o_proj.weight").c_str()}, {o_}, B, cs, xqp_, xdp_); stamp("gemm:o_proj"); @@ -486,18 +489,44 @@ bool Dflash2Drafter::prepare(const float* taps, std::string& err) { return true; } +bool Dflash2Drafter::begin_request(const int32_t* ids, int64_t n, int64_t resume, bool* cold) { + resume = std::max(0, std::min(resume, n)); + // the longest common prefix of what the ring was last filled for and what this request keeps + int64_t lcp = 0; + const int64_t lim = std::min((int64_t) hist_.size(), resume); + while (lcp < lim && hist_[(size_t) lcp] == ids[lcp]) ++lcp; + // The session says positions [0, resume) are in the state. When the history agrees with all of them the ring serves them as it is. When the history + // holds other tokens below `resume` (a parked conversation restored, an edited turn) those slots belong to another lineage: a new epoch invalidates every + // older stamp (the drafts are poor for the first rounds, never wrong). A history that only ends earlier leaves nothing stale; one that goes on past + // `resume` has its extra rows rewritten before the window reaches them. + const bool stale = ring_hi_ > lcp && lcp < resume; + if (stale) { ++epoch_; ring_hi_ = 0; } + if (cold) *cold = stale; + hist_.assign(ids, ids + resume); + return true; +} + +void Dflash2Drafter::note_rows(const int32_t* toks, int64_t n, int64_t pos0) { + if (pos0 < 0) return; + if ((int64_t) hist_.size() > pos0) hist_.resize((size_t) pos0); + if ((int64_t) hist_.size() < pos0) return; // a gap: the history stops being a prefix, so it stays where it is (the next begin_request starts over) + hist_.insert(hist_.end(), toks, toks + n); +} + bool Dflash2Drafter::context(const float* taps, int64_t n, int64_t pos0, std::string& err) { const OnDevice on_device(device_); const int tap_n = (int) taps_.size() * N_; for (int64_t r0 = 0; r0 < n; r0 += kRows) { const int m = (int) std::min(kRows, n - r0); for (int i = 0; i < m; ++i) h_meta_[i] = (int32_t) (pos0 + r0 + i); + h_meta_[18] = epoch_; std::atomic_thread_fence(std::memory_order_seq_cst); kernels::copy_i32_from_mapped(d_meta_, m_meta_, 32, cs_); if (!record_context(taps + (size_t) r0 * (size_t) tap_n, m, cs_, err)) return false; if (cudaStreamSynchronize(cs_) != cudaSuccess) { err = std::string("dflash2: ") + cudaGetErrorString(cudaGetLastError()); return false; } } have_ctx_ = std::max(have_ctx_, pos0 + n); + ring_hi_ = std::max(ring_hi_, pos0 + n); return true; } @@ -516,6 +545,7 @@ bool Dflash2Drafter::draft(const float* taps, int n_new, int64_t pos0, int32_t a const int64_t s = pos0 + n_new; for (int i = 0; i < 8; ++i) { h_meta_[i] = (int32_t) (pos0 + std::min(i, n_new - 1)); h_meta_[8 + i] = (int32_t) (s + i); } h_meta_[16] = anchor; + h_meta_[18] = epoch_; h_meta_[17] = (int32_t) s; h_meta_[24] = anchor; for (int i = 1; i < 8; ++i) h_meta_[24 + i] = mask_token_; @@ -545,6 +575,7 @@ bool Dflash2Drafter::draft(const float* taps, int n_new, int64_t pos0, int32_t a if (cudaEventElapsedTime(&ms, ev_a_, ev_b_) == cudaSuccess) ms_gpu += ms; } have_ctx_ = std::max(have_ctx_, s); + ring_hi_ = std::max(ring_hi_, pos0 + n_new); ms_draft += ms_since(t0); ++rounds; return true; diff --git a/src/kernels/cuda/dflash2.cu b/src/kernels/cuda/dflash2.cu index 997a3e3536..8d488f31e4 100644 --- a/src/kernels/cuda/dflash2.cu +++ b/src/kernels/cuda/dflash2.cu @@ -100,18 +100,21 @@ constexpr int AS = 132; // smem row stride of the Q / K / V tiles (float4 alig constexpr int PS = 36; // stride of the transposed probabilities P[key][query] __global__ void __launch_bounds__(128) attn_part_kernel(const float* __restrict__ q, const float* __restrict__ kring, const float* __restrict__ vring, const float* __restrict__ kblk, const float* __restrict__ vblk, - const int32_t* __restrict__ anchor_pos, int ring_slots, int window, float* __restrict__ part, int variant) { + const int32_t* __restrict__ anchor_pos, int ring_slots, int window, float* __restrict__ part, int variant, + const int64_t* __restrict__ tag, const int32_t* __restrict__ epoch_ptr) { __shared__ __align__(16) float Qs[32 * AS]; __shared__ __align__(16) float Ks[32 * AS]; // the K tile, then the V tile __shared__ __align__(16) float Ps[32 * PS]; __shared__ float Sc[32 * 33]; __shared__ float m_s[32], l_s[32], corr_s[32]; + __shared__ unsigned char kvalid[32]; // key t of the tile holds the context row it should (ring tags, serve: a ring left by another conversation) const int kvh = blockIdx.x, chunk = blockIdx.y, tid = threadIdx.x; const int s = *anchor_pos; const int lo = s - (window - 1) > 0 ? s - (window - 1) : 0; const int nctx = s - lo; const int nkeys = nctx + kDf2Rows; const int k_begin = chunk * kDf2Chunk; + const int64_t ep = tag != nullptr ? ((int64_t) *epoch_ptr << 32) : 0; float* const pbase = part + (((size_t) chunk * kDf2Kv + kvh) * 32) * 130; if (k_begin >= nkeys) { for (int i = tid; i < 32 * 130; i += 128) pbase[i] = (i % 130 == 0) ? -INFINITY : 0.0f; @@ -156,6 +159,10 @@ __global__ void __launch_bounds__(128) attn_part_kernel(const float* __restrict_ for (int k0 = k_begin; k0 < k_end; k0 += 32) { __syncthreads(); // Ks free (the last tile's V reads done); Qs / m_s written on the first pass put(kreg); + if (tid < 32) { + const int k = k0 + tid; + kvalid[tid] = (tag == nullptr || k >= nctx || k >= nkeys) ? 1 : (tag[(lo + k) % ring_slots] == (ep | (int64_t) (lo + k)) ? 1 : 0); + } fetch(k0, vreg, vring, vblk); // this tile's V, hidden behind the S stage and the softmax __syncthreads(); if (tid < 64) { // S tile: 4 queries x 4 keys per thread @@ -184,7 +191,7 @@ __global__ void __launch_bounds__(128) attn_part_kernel(const float* __restrict_ for (int j = 0; j < 4; ++j) { const int qi = qg * 4 + i, t = kg * 4 + j, k = k0 + t, row = qi >> 2; bool ok = k < nkeys; - if (ok && k < nctx) ok = (lo + k) > (s + row - window); // s + row - j < window + if (ok && k < nctx) ok = (lo + k) > (s + row - window) && kvalid[t]; // s + row - j < window, and the slot holds that row Sc[qi * 33 + t] = ok ? acc[i][j] : -INFINITY; } } @@ -465,7 +472,8 @@ __global__ void norm_rope_qk_kernel(const float* __restrict__ q, const float* __ // the context update's ring write: K norm + rope of (row, head) and the V copy, both into the head-major ring slot pos % slots __global__ void kv_ring_kernel(const float* __restrict__ kin, const float* __restrict__ vin, const float* __restrict__ gk, const int32_t* __restrict__ pos, - const float* __restrict__ table, float* __restrict__ kring, float* __restrict__ vring, int slots, int heads, float eps) { + const float* __restrict__ table, float* __restrict__ kring, float* __restrict__ vring, int slots, int heads, float eps, + int64_t* __restrict__ tag, const int32_t* __restrict__ epoch_ptr) { const int r = blockIdx.x, h = blockIdx.y, d = threadIdx.x; __shared__ float red[4]; __shared__ float y[HD]; @@ -483,6 +491,7 @@ __global__ void kv_ring_kernel(const float* __restrict__ kin, const float* __res const size_t at = ((size_t) h * slots + slot) * HD + d; kring[at] = d < 64 ? v * c - y[d + 64] * sn : v * c + y[d - 64] * sn; vring[at] = vin[((size_t) r * heads + h) * HD + d]; + if (tag != nullptr && h == 0 && d == 0) tag[slot] = ((int64_t) *epoch_ptr << 32) | (int64_t) pos[r]; } // silu(gate) * up then the planar quantization: grid (ceil(I / 32 / 8), rows), 256 threads @@ -686,8 +695,8 @@ void df2_copy_rows(const float* in, float* out, const int32_t* pos, int slot_mod } void df2_attention(const float* q, const float* kring, const float* vring, const float* kblk, const float* vblk, const int32_t* anchor_pos, - int ring_slots, int window, float* part, void* xq, float* xd, void* stream) { - attn_part_kernel<<>>(q, kring, vring, kblk, vblk, anchor_pos, ring_slots, window, part, g_attn_variant); + int ring_slots, int window, float* part, void* xq, float* xd, void* stream, const int64_t* tag, const int32_t* epoch) { + attn_part_kernel<<>>(q, kring, vring, kblk, vblk, anchor_pos, ring_slots, window, part, g_attn_variant, tag, epoch); check("attn_part"); attn_merge_kernel<<>>(part, static_cast(xq), xd); check("attn_merge"); @@ -707,8 +716,8 @@ void df2_norm_rope_qk(const float* q, const float* k, const float* gq, const flo } void df2_kv_ring(const float* kin, const float* vin, const float* gk, const int32_t* pos, const float* table, float* kring, float* vring, int slots, int rows, - int heads, float eps, void* stream) { - kv_ring_kernel<<>>(kin, vin, gk, pos, table, kring, vring, slots, heads, eps); + int heads, float eps, void* stream, int64_t* tag, const int32_t* epoch) { + kv_ring_kernel<<>>(kin, vin, gk, pos, table, kring, vring, slots, heads, eps, tag, epoch); check("kv_ring"); } diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 5182a41cd9..d31b7ecfd2 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1210,6 +1210,25 @@ Prefill::~Prefill() { release(); } +bool Prefill::reserve_taps(const std::vector& layers, int64_t cap_rows, int64_t n_embd, std::string& err) { +#if defined(STRATA_HAVE_DFLASH2) + tap_layers_ = layers; + tap_cap_ = cap_rows; + if (tap_dev_ != nullptr) return true; + if (cudaMalloc((void**) &tap_dev_, (size_t) cap_rows * layers.size() * (size_t) n_embd * 4) != cudaSuccess) { + (void) cudaGetLastError(); + tap_dev_ = nullptr; + err = "the prompt staging of the DFlash2 taps does not fit in VRAM"; + return false; + } + return true; +#else + (void) layers; (void) cap_rows; (void) n_embd; + err = "no DFlash2 in this build"; + return false; +#endif +} + void Prefill::clear_taps() { if (tap_dev_ != nullptr) { cudaFree(tap_dev_); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index f6d1e7e911..d604abb10d 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -6249,6 +6249,8 @@ int main(int argc, char** argv) { #if defined(STRATA_HAVE_DFLASH2) strata::core::Dflash2Drafter df2; // --draft dflash2 (CLI spec loop only) bool use_df2 = false; +#else + constexpr bool use_df2 = false; #endif // the draft layer's geometry (the canonical model's MTP head), `static` because MtpDrafter keeps a reference; the batch // slots' draft-KV copies use this one too @@ -6301,7 +6303,7 @@ int main(int argc, char** argv) { if (o.draft == "dflash2") { const char* why = o.mtp.empty() ? "it needs --mtp (the fallback) and --spec 2 or more" : !native_pack ? "it needs a native pack" - : multi_gpu || o.batch > 0 || o.serve ? "it is for one card and the CLI run (not --serve, --batch or a layer split) in this build" + : multi_gpu || o.batch > 0 || o.pipeline_windows > 0 ? "it is for one card and one request at a time (not --batch, --pipeline-windows or a layer split) in this build" : o.draft_model.empty() ? "it needs --draft-model PACK (tools/dflash2_pack.py)" : nullptr; if (why == nullptr) { if (df2.load(o.draft_model, 0, err)) { @@ -6690,7 +6692,7 @@ int main(int argc, char** argv) { int64_t mtp_b = (!o.mtp.empty() && native_head.loaded()) ? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0; #if defined(STRATA_HAVE_DFLASH2) - if (use_df2 && native_head.loaded()) mtp_b += (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) + (48 << 20); // DFlash2's own draft head and logits + if (use_df2 && native_head.loaded()) mtp_b += (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) + (48 << 20) + (o.serve ? (112 << 20) : 0); // DFlash2's own draft head and logits (serve: and the prompt staging) #endif if (stages.empty()) for (const auto& d : slot_mtp) mtp_b += (int64_t) d->bind_bytes(native_head.row_bytes(), n_vocab); @@ -6937,7 +6939,7 @@ int main(int argc, char** argv) { for (const auto& d : slot_mtp) mtp_bind += (int64_t) d->bind_bytes(native_head.row_bytes(), n_vocab); #if defined(STRATA_HAVE_DFLASH2) - if (use_df2 && native_head.loaded()) mtp_bind += (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) + (48 << 20); // DFlash2's own draft head and logits, bound after this + if (use_df2 && native_head.loaded()) mtp_bind += (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) + (48 << 20) + (o.serve ? (112 << 20) : 0); // DFlash2's own draft head and logits (serve: and the prompt staging), bound after this #endif const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind + pipe_first; const int64_t blob = (int64_t) nibble_max_slot_bytes(); // max_blob (STRATA_EXPERT_NIBBLE: or a larger 4-bit slot) @@ -10218,6 +10220,9 @@ int main(int argc, char** argv) { ver.set_remote_expert_opt(remote_opt.get()); 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()); +#endif if (!ver.init(wt, g, ss, vh, native_head.loaded() || prefill_head_alias_bound ? &native_head : nullptr, batch_max_t(), err) || (use_mtp && !prefill_head_alias_bound && !mtp.bind(last_st && !mtp_first ? last_st->wt : wt, last_st ? &last_st->head : &native_head, @@ -10226,6 +10231,26 @@ int main(int argc, char** argv) { return 1; } if (prefill_head_alias_bound) mtp.set_window_R(ver.final_R_all()); +#if defined(STRATA_HAVE_DFLASH2) + if (use_df2) { // DFlash2 in the serve loop: one card, one request at a time (--batch, a layer split and --pipeline-windows keep the MTP) + std::string why_not; + if (!ver.tapping()) why_not = "the verifier keeps no taps here"; + else if (!df2.bind(wt, &native_head, o.mtp_draft_vocab.empty() ? o.mtp + "/draft_vocab.bin" : o.mtp_draft_vocab, why_not) || + !df2.prepare(ver.tap_dev(), why_not) || + !sp.reserve_taps(df2.tap_layers(), 2048, g.n_embd, why_not)) { + if (why_not.empty()) why_not = "the drafter could not be set up"; + } + if (!why_not.empty()) { + std::fprintf(stderr, "strata serve: --draft dflash2: %s. It needs about 1.2 GiB of VRAM in all (the pack 0.76 GiB, buffers and K/V ring 0.25 GiB, " + "a draft head 0.2 GiB, 0.1 GiB of prompt staging); --vram-reserve-mib 1900 keeps it. The MTP drafts instead.\n", why_not.c_str()); + use_df2 = false; + } else { + sp.on_taps = [&](const float* taps, int64_t rows, int64_t pos0, std::string& e) -> bool { return df2.context(taps, rows, pos0, e); }; + std::fprintf(stderr, "strata serve: DFlash2 drafter on (%s, graphs captured in %.0f ms); windows up to %d tokens; the MTP layer stays as the fallback\n", + o.draft_model.c_str(), df2.ms_capture, o.spec); + } + } +#endif if (pipe) mtp.set_source_R(ver.final_R_all()); // the serial decode's rows (the last stage's even verifier) auto free_slot_mtp_rows = [](float* p) { if (p != nullptr) (void) cudaFree(p); }; std::vector> slot_mtp_rows; @@ -11059,6 +11084,13 @@ int main(int argc, char** argv) { } } if (!e.empty() || (use_mtp && !batched && !mtp.prefill(R_rows, nxt.data(), T, p0, e))) return false; +#if defined(STRATA_HAVE_DFLASH2) + if (use_df2) { + std::vector tk((size_t) T); + for (int64_t t = 0; t < T; ++t) tk[(size_t) t] = (int32_t) cur[(size_t) (p0 + t)]; + df2.note_rows(tk.data(), T, p0); + } +#endif if (use_mtp && std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) std::fprintf(stderr, "strata serve: DRAFT_PREFILL path=%s mode=%d cells=%lld\n", batched ? "batched" : "token", mtp.kv_state().kv_mode, (long long) T); @@ -14769,6 +14801,17 @@ int main(int argc, char** argv) { // first segment raises it if KVA approximates it - and for any state no KVA read produced) if (use_mtp && mtp.cell_floor_enabled()) mtp.set_cell_floor(resume > 0 && reread_to <= 0 ? kva_floors.floor_for(ids.data(), resume) : 0); +#if defined(STRATA_HAVE_DFLASH2) + if (use_df2) { // the drafter's ring goes on from the live conversation, or starts over (a parked or edited one) + std::vector idv(ids.begin(), ids.end()); + bool cold = false; + df2.begin_request(idv.data(), (int64_t) idv.size(), reread_to > 0 ? 0 : resume, &cold); + if (cold) + std::fprintf(stderr, "strata serve: DFlash2: the conversation is not the one the drafter last saw (a parked or edited one): it starts with an " + "empty context and drafts poorly for the first rounds (the answers are the same)\n"); + sp.set_taps(df2.tap_layers(), std::max(0, n - 2047), 2048); + } +#endif const int64_t read_from = reread_to > 0 ? 0 : resume; conversations.limit_reuse(read_from); pp_total = n; @@ -14971,6 +15014,12 @@ int main(int argc, char** argv) { if (logpos != nullptr && !ver.window_logprobs(nxt.data(), T, q, logpos_extra, logpos, e)) return false; if (!ver.commit(T, e) || (use_mtp && !mtp.prefill(ver.final_R_all(), nxt.data(), T, q, e))) return false; +#if defined(STRATA_HAVE_DFLASH2) + if (use_df2) { + if (!df2.context(ver.tap_dev(), T, q, e)) return false; + df2.note_rows(win.data(), T, q); + } +#endif q += T; pp_reached = q; // #471 pp_exact = true; @@ -16768,6 +16817,33 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata pipeline calibration (p_on decile: on/scored):%s\n", cal.c_str()); } } +#if defined(STRATA_HAVE_DFLASH2) + // the next round's drafts from the committed rows' taps (DFlash2), as the CLI loop does + auto draft_df2 = [&](int a_) -> bool { + int32_t dd[strata::core::Dflash2Drafter::kDrafts]; + float pp[strata::core::Dflash2Drafter::kDrafts]; + if (!df2.draft(ver.tap_dev(), a_ + 1, p, outv[(size_t) a_], dd, pp, err)) return false; + for (size_t i = 0; i < drafts.size() && i < (size_t) strata::core::Dflash2Drafter::kDrafts; ++i) { drafts[i] = dd[i]; dprob[i] = pp[i]; } + if (ss.ple.ready() && ss.ple.table != nullptr) { // the PLE rows of the next window's tokens, read ahead (as the MTP's draft does) + int n_pf = 0; + const int cap = std::min(S_mtp, (int) drafts.size() + 1); + for (int t = 1; t < cap && (req_spec_min_p <= 0.0 || dprob[(size_t) t - 1] >= (float) req_spec_min_p); ++t) ++n_pf; + int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]}; + auto pf = [&](int32_t tok) { + uint32_t rows16[strata::kernels::PLE_N_HEADS]; + strata::kernels::ngram_rows(&tok, prev, 1, ss.ple.consts, rows16); + prev[0] = prev[1]; + prev[1] = tok; + ss.ple.table->prefetch_rows(rows16); + }; + pf(outv[(size_t) a_]); + for (int i = 0; i < n_pf; ++i) pf(drafts[(size_t) i]); + } + return true; + }; +#else + auto draft_df2 = [&](int) -> bool { return false; }; +#endif while (!pl_ran && !cancelled && produced_n < max_new) { int T = 1; policy.set_context(p); @@ -17071,6 +17147,9 @@ int main(int argc, char** argv) { } // the window's first a + 1 tokens are in the session now (the last output is not: it is next x) for (int i = 0; i <= a; ++i) consumed.push_back(window[(size_t) i]); +#if defined(STRATA_HAVE_DFLASH2) + if (use_df2) df2.note_rows(window.data(), a + 1, p); +#endif if (!merged) { // (a merged window's rows are prompt tokens, not drafts) draft_offered += T - 1; draft_accepted += a; @@ -17098,8 +17177,8 @@ int main(int argc, char** argv) { generation = {}; // a skipped or failed production must not expose an older q view const GatedDraftLimit draft_limit(mtp, gated_proposal, S_mtp, p + a + 1, o.max_context); const bool drafted = !use_mtp || eos || produced_n >= max_new || - mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) req_spec_min_p, - nullptr, gated_proposal ? &generation : nullptr); + (use_df2 ? draft_df2(a) : mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) req_spec_min_p, + nullptr, gated_proposal ? &generation : nullptr)); { const Clock::time_point tw3 = Clock::now(); auto msd = [](Clock::time_point a0, Clock::time_point b0) { return std::chrono::duration(b0 - a0).count(); }; diff --git a/tools/dflash2/mk_serve_scenario.py b/tools/dflash2/mk_serve_scenario.py new file mode 100644 index 0000000000..dfee2d9905 --- /dev/null +++ b/tools/dflash2/mk_serve_scenario.py @@ -0,0 +1,48 @@ +"""Builds the scenario of tools/dflash2/serve_test.py from the prompt id files of the DFlash2 experiments. + + python mk_serve_scenario.py [max_new=100] + +prompt_dir holds .prompt.ids (comma separated token ids of a chat-templated prompt). Conversations: a (three turns), then b (a different conversation, so a's +live state is replaced), then a's fourth turn (a parked or checkpointed conversation resumes), c (two turns), d (one). +""" +import json +import sys +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(REPO / "tools")) +sys.path.insert(0, str(REPO)) +import strata_tokenizer as ST # noqa: E402 + + +def main(): + pdir, tdir, out = Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[3] + max_new = int(sys.argv[4]) if len(sys.argv) > 4 else 100 + vocab = json.loads((tdir / "vocab.json").read_text(encoding="utf-8")) + toks = [None] * len(vocab) + for t, i in vocab.items(): + toks[i] = t + tok = ST.Tokenizer(toks, (tdir / "merges.txt").read_text(encoding="utf-8").split("\n"), json.loads((tdir / "token_type.json").read_text())) + + def ids(name): + return [int(x) for x in (pdir / (name + ".prompt.ids")).read_text().strip().split(",")] + + def follow(text): + return tok.encode("<|im_end|>\n<|im_start|>user\n" + text + "<|im_end|>\n<|im_start|>assistant\n", parse_special=True) + + reqs = [ + {"name": "a1", "ids": ids("chat_explain")}, + {"name": "a2", "after": "a1", "follow": follow("Now say the same in two short sentences.")}, + {"name": "a3", "after": "a2", "follow": follow("Give one concrete example of it.")}, + {"name": "b1", "ids": ids("code_py")}, + {"name": "a4", "after": "a3", "follow": follow("Thanks. Last question: what is the main limit of this idea?")}, + {"name": "c1", "ids": ids("json_extract")}, + {"name": "c2", "after": "c1", "follow": follow("Now list only the keys.")}, + {"name": "d1", "ids": ids("tool_call")}, + ] + json.dump({"max_new": max_new, "requests": reqs}, open(out, "w")) + print("scenario with", len(reqs), "requests ->", out) + + +if __name__ == "__main__": + main() diff --git a/tools/dflash2/serve_test.py b/tools/dflash2/serve_test.py new file mode 100644 index 0000000000..0c2712b4df --- /dev/null +++ b/tools/dflash2/serve_test.py @@ -0,0 +1,124 @@ +"""Serve-API test of the DFlash2 drafter: runs `strata --serve` on one arm and a scenario of greedy requests, writes the tokens and the engine's DONE figures. + + python serve_test.py --exe ENGINE --arm df2 --scenario scenario.json --out out_df2.json --log arm.log -- + +The wire is the engine's own: stdin `GEN ,,...`, stdout `T ` ... `DONE ...` +(serve/server.py is the Python client). A scenario is {"requests": [{"name", "ids": [...]} | {"name", "after": "", "follow": [...]}, ...], "max_new": N}: +a request with `after` continues that request's conversation (its prompt + its output + `follow`), which is what a chat client sends for the next turn. +Pure standard library: it runs on any box that has the engine. + +compare mode: python serve_test.py --compare nd.json mtp.json df2.json +prints, per request, the first token where the arm differs from the no-draft arm (the engine's windows are not bitwise equal to one-token decode at near-ties, +for the MTP as well; the DFlash2 arm must not be worse than the MTP arm), the drafts accepted / offered, and the figures the park test needs. +""" +import json +import subprocess +import sys +import threading +import time + + +def run(exe, args, scenario, log_path, ready_timeout=900, req_timeout=600): + log = open(log_path, "ab") + proc = subprocess.Popen([exe, "--serve", *args], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log, text=True, bufsize=1) + lines = [] + cv = threading.Condition() + + def pump(): + for ln in proc.stdout: + with cv: + lines.append(ln.rstrip("\n")) + cv.notify_all() + with cv: + lines.append(None) + cv.notify_all() + + threading.Thread(target=pump, daemon=True).start() + pos = 0 + + def next_line(timeout): + nonlocal pos + end = time.time() + timeout + with cv: + while pos >= len(lines): + left = end - time.time() + if left <= 0: + raise TimeoutError("no line from the engine") + cv.wait(left) + ln = lines[pos] + pos += 1 + return ln + + while True: + ln = next_line(ready_timeout) + if ln is None: + raise RuntimeError("the engine ended before READY") + if ln.startswith("READY"): + break + done = {} + results = [] + for req in scenario["requests"]: + if "after" in req: + prev = done[req["after"]] + ids = prev["ids"] + prev["out"] + req.get("follow", []) + else: + ids = list(req["ids"]) + proc.stdin.write("GEN %d %s\n" % (req.get("max_new", scenario.get("max_new", 100)), ",".join(str(int(t)) for t in ids))) + proc.stdin.flush() + out, stats, resume = [], {}, None + while True: + ln = next_line(req_timeout) + if ln is None: + raise RuntimeError("the engine ended during %s" % req["name"]) + if ln.startswith("T "): + out.append(int(ln.split()[1])) + elif ln.startswith("RESUME "): + resume = int(ln.split()[1]) + elif ln.startswith("ERR"): + raise RuntimeError("engine: " + ln) + elif ln.startswith("DONE"): + f = ln.split() + stats = {"produced": int(f[1]), "prompt_tokens": int(f[2]), "prompt_ms": float(f[3]), "decode_ms": float(f[4]), "finish": f[5], + "accepted": int(f[6]), "offered": int(f[7]), "resume": int(f[8])} + break + done[req["name"]] = {"ids": ids, "out": out} + results.append({"name": req["name"], "prompt_len": len(ids), "out": out, "resume": resume, **stats}) + print("%-14s prompt %5d resume %5s tokens %3d drafts %s/%s %.1f tok/s" % ( + req["name"], len(ids), resume, len(out), stats.get("accepted"), stats.get("offered"), + 1000.0 * len(out) / max(1e-9, stats.get("decode_ms", 0.0))), flush=True) + try: + proc.stdin.close() + proc.wait(60) + except Exception: + proc.kill() + return results + + +def compare(nd_path, mtp_path, df2_path): + nd, mtp, df2 = (json.load(open(p)) for p in (nd_path, mtp_path, df2_path)) + worst = 0 + print("%-14s %7s %9s %9s %12s %12s" % ("request", "tokens", "mtp diff@", "df2 diff@", "mtp drafts", "df2 drafts")) + for a, b, c in zip(nd["results"], mtp["results"], df2["results"]): + def first(x, y): + n = min(len(x), len(y)) + return next((i for i in range(n) if x[i] != y[i]), None) + fm, fd = first(a["out"], b["out"]), first(a["out"], c["out"]) + print("%-14s %7d %9s %9s %12s %12s" % (a["name"], len(a["out"]), fm, fd, "%d/%d" % (b["accepted"], b["offered"]), "%d/%d" % (c["accepted"], c["offered"]))) + return worst + + +if __name__ == "__main__": + argv = sys.argv[1:] + if argv and argv[0] == "--compare": + compare(*argv[1:4]) + sys.exit(0) + opts = {} + i = 0 + while i < len(argv) and argv[i] != "--": + opts[argv[i].lstrip("-")] = argv[i + 1] + i += 2 + engine_args = argv[i + 1:] + scenario = json.load(open(opts["scenario"])) + res = run(opts["exe"], engine_args, scenario, opts.get("log", "serve_test.log")) + json.dump({"arm": opts.get("arm"), "results": res}, open(opts["out"], "w")) + print("SERVE_TEST_DONE") From 40da04d49aaf2fe1bd49daa40733d0f6ca8ff41a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 22 Oct 2026 18:23:38 +0200 Subject: [PATCH 2/3] Serve: DFlash2 on (ENGINE_SERVES_DFLASH2 = True); tests cover both states --- strata_control/drafting.py | 10 ++++------ tests/terminal/test_drafting.py | 22 +++++++++++++++------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/strata_control/drafting.py b/strata_control/drafting.py index 0e5bd7672d..a48400aae6 100644 --- a/strata_control/drafting.py +++ b/strata_control/drafting.py @@ -138,12 +138,10 @@ def normalize(value: Any) -> str: return text if text in MODES else DEFAULT_MODE -#: Does the engine in this release run DFlash2 when it serves (the app and `strata launch`)? In f-023-int src/program/generate.cpp, `--draft dflash2` -#: is "for one card and the CLI run (not --serve, --batch or a layer split)": a served model prints "--draft dflash2 is off: ... the MTP drafts -#: instead". So today the choice cannot take effect when serving, and nothing is downloaded or packed for it (1.2 GB for no effect would be a bad -#: surprise); the start says so ("Drafting: MTP (DFlash2 isn't available in this mode yet)"). Flip this when the engine serves it; everything -#: else (flags, download, pack, fallback text) is in place and tested with it on. -ENGINE_SERVES_DFLASH2 = False +#: 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 +#: card and one request at a time (src/program/generate.cpp); --batch, --pipeline-windows and a layer split keep the MTP and the engine says so. A parked or 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. +ENGINE_SERVES_DFLASH2 = True #: Why the MTP runs when something else was asked for: a closed set of short reasons, each one is a sentence in the interface catalog in all eight #: languages (the line is "Drafting: MTP ()"). diff --git a/tests/terminal/test_drafting.py b/tests/terminal/test_drafting.py index f1fdb311e3..80e2cd5214 100644 --- a/tests/terminal/test_drafting.py +++ b/tests/terminal/test_drafting.py @@ -23,7 +23,7 @@ GYRO = "qwen3.8-flash-next-gyro-gyro-s" def serving_dflash2(): - """The engine of this release runs DFlash2 only in its CLI run (drafting.ENGINE_SERVES_DFLASH2): the tests turn the switch on.""" + """The tests turn the switch on explicitly (drafting.ENGINE_SERVES_DFLASH2).""" return mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", True) @@ -115,8 +115,14 @@ class Decisions(unittest.TestCase): self.assertTrue(drafting.supported_model(family="qwen") and drafting.supported_model(family="gyro")) self.assertFalse(drafting.supported_model(family="coder") or drafting.supported_model(family="swift") or drafting.supported_model(family="nvfp4")) + def test_the_engine_of_this_branch_serves_dflash2(self): + self.assertTrue(drafting.ENGINE_SERVES_DFLASH2, "src/program/generate.cpp: --draft dflash2 runs with --serve (one card, one request at a time)") + def test_while_the_engine_cannot_serve_it_the_choice_says_so_and_nothing_is_downloaded(self): - self.assertFalse(drafting.ENGINE_SERVES_DFLASH2, "src/program/generate.cpp: --draft dflash2 is off with --serve in this release") + with mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", False): + self.not_served() + + def not_served(self): d = drafting.decide("dflash2", klass="blackwell", model_name=GYRO, data_dir=self.data) self.assertEqual((d.drafter, d.note), ("mtp", drafting.NOT_SERVED)) self.assertFalse(drafting.needs_pack("dflash2", klass="blackwell", model_name=GYRO, data_dir=self.data)) @@ -188,7 +194,7 @@ class EngineArguments(unittest.TestCase): mock.patch.object(drafting, "pack_ready", return_value=True), mock.patch.object(drafting, "data_dir_of", return_value=Path("/d")): args = engine_args(self.cfg(drafting="dflash2")) self.assertEqual(args[-4:], ["--draft", "dflash2", "--draft-model", str(pack)]) - with mock.patch("serve.server.drafting_card_class", return_value="blackwell"): + with mock.patch("serve.server.drafting_card_class", return_value="blackwell"), mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", False): self.assertEqual(engine_args(self.cfg()), self.ARGS, "no choice: nothing changes") off = engine_args(self.cfg(drafting="off")) self.assertNotIn("--mtp", off) @@ -425,7 +431,8 @@ class TheAppAsksControl(unittest.TestCase): self.assertEqual(self.plan("--mode", "off")["drafter"], "off") def test_dflash2_is_needed_once_the_engine_can_serve_it_and_not_before(self): - before = self.plan("--mode", "dflash2") + with mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", False): + before = self.plan("--mode", "dflash2") self.assertFalse(before["needed"], "while the engine cannot serve it nothing is downloaded") self.assertEqual(before["line"], "Drafting: MTP (DFlash2 isn't available in this mode)") with serving_dflash2(): @@ -461,9 +468,10 @@ class TheDownloadPlanListsIt(unittest.TestCase): from strata_cli.launch.runner import Runner with Home() as home: runner = Runner(S.LaunchSettings(family="qwen", model="Q2_0", context=32768, vision="off", drafting="dflash2"), catalog=catalog(HW_12)) - line = runner.drafting_plan_line() - self.assertEqual(line, "Drafting: MTP (DFlash2 isn't available in this mode)") - self.assertNotIn("dflash2", [p["kind"] for p in runner.download_plan()["parts"]], "nothing to fetch while the engine cannot serve it") + with mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", False): + line = runner.drafting_plan_line() + self.assertEqual(line, "Drafting: MTP (DFlash2 isn't available in this mode)") + self.assertNotIn("dflash2", [p["kind"] for p in runner.download_plan()["parts"]], "nothing to fetch while the engine cannot serve it") with serving_dflash2(): kinds = {p["kind"]: p for p in runner.download_plan()["parts"]} self.assertEqual(kinds["dflash2"]["gb"], 1.2) From eeb21d0e4f02b5b999865b26b5716cb3dbeab4b3 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 31 Oct 2026 21:45:10 +0100 Subject: [PATCH 3/3] serve: --draft-conf honored with --draft dflash2 (the window ends where the product of the selector's probabilities falls below P), as in the CLI loop --- src/program/generate.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index d604abb10d..1c1ce6c0eb 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -16868,6 +16868,13 @@ int main(int argc, char** argv) { T = 1; while (T < S_mtp && dprob[(size_t) T - 1] >= (float) req_spec_min_p) ++T; } +#if defined(STRATA_HAVE_DFLASH2) + if (use_df2 && o.draft_conf > 0.0 && !first_window) { // --draft-conf in serve as in the CLI loop: the chance that every draft so far holds + T = 1; + double chain = 1.0; + while (T < S_mtp && (chain *= (double) dprob[(size_t) T - 1]) >= o.draft_conf) ++T; + } +#endif if (first_window) T = merge_T > 0 ? merge_T : 1; // a repeat of earlier context (prompt lookup) where the MTP's own first guess agrees: the policy takes it // when its expected tokens per ms, from the measured acceptance and window costs, beat the MTP window's