From 73671b432fc7a118a4cca67b258fcc75ecc8aacd Mon Sep 17 00:00:00 2001 From: Sarah Date: Thu, 26 Nov 2026 11:34:13 +0100 Subject: [PATCH 1/7] poly: Inkling 2 DFlash2 drafter behind --draft-model (refs #339) A dflash GGUF with selector_hidden.weight (incoai/Inkling-2-Mini-DFlash2 as qwen.py converts it) runs as a DFlash2 drafter: two-tap dynamic grouped convolutions around attention and MLP, a fusion matrix over the four features, and a selector walk over the top 16 candidates of each mask row. It reuses DSpark's layer caches, feature capture, rope, attention and graph recording. DSpark files take the old path unchanged; Metal refuses a DFlash2 file. Compiles for HIP gfx1010. Not run: no card here holds Inkling 2 Mini with a drafter. Co-Authored-By: Claude Sonnet 5.5 --- engine/src/poly/inkling2.cpp | 219 ++++++++++++++++++++++++++- engine/src/poly/inkling2.cu | 178 ++++++++++++++++++++++ engine/src/poly/inkling2.hpp | 22 ++- engine/src/poly/inkling2_kernels.hpp | 21 +++ 4 files changed, 437 insertions(+), 3 deletions(-) diff --git a/engine/src/poly/inkling2.cpp b/engine/src/poly/inkling2.cpp index 58c3e0f48b..37ef83e216 100644 --- a/engine/src/poly/inkling2.cpp +++ b/engine/src/poly/inkling2.cpp @@ -328,7 +328,13 @@ void Inkling2::ds_open() { if (!ok) throw std::runtime_error(opt_.draft_model + ": not a DSpark drafter of this model (" + what + ")"); }; const MetaValue* arch = ds_file_->get("general.architecture"); - need(arch && arch->s == "dflash" && ds_file_->find("markov_w1.weight"), "general.architecture dflash, markov_w1"); + // a DFlash2 file (a candidate selector) or a DSpark file (a Markov head) + ds2_ = ds_file_->find("selector_hidden.weight") != nullptr; + need(arch && arch->s == "dflash" && (ds2_ || ds_file_->find("markov_w1.weight")), + "general.architecture dflash, markov_w1 or selector_hidden"); +#if defined(STRATA_GPU_METAL) + need(!ds2_, "DFlash2 is not on Metal yet"); +#endif const auto key = [&](const char* k) { const MetaValue* v = ds_file_->get(std::string("dflash.") + k); need(v != nullptr, std::string("dflash.") + k); @@ -337,7 +343,7 @@ void Inkling2::ds_open() { ds_block_ = (int) key("block_size")->u; ds_window_ = (int) key("attention.sliding_window")->u; ds_ff_ = (int) key("feed_forward_length")->u; - ds_rank_ = (int) key("dspark.markov_rank")->u; + ds_rank_ = ds2_ ? (int) key("selector_rank")->u : (int) key("dspark.markov_rank")->u; ds_theta_ = (float) key("rope.freq_base")->num(); ds_eps_ = (float) key("attention.layer_norm_rms_epsilon")->num(); ds_cap_ = (float) key("final_logit_softcapping")->num(); @@ -358,12 +364,125 @@ void Inkling2::ds_open() { targets->items.size() == 4 && (int) targets->items[3].u == visits, "a window pattern a layer, three layer runs and the final state as its features"); for (int k = 0; k < 3; ++k) ds_visit_[k] = (int) targets->items[(size_t) k].u; + if (ds2_) { + ds2_taps_ = (int) key("conv_kernel_size")->u; + ds2_group_ = (int) key("conv_group_size")->u; + ds2_topk_ = (int) key("selector_top_k")->u; + const MetaValue* mask = ds_file_->get("tokenizer.ggml.mask_token_id"); + need(mask != nullptr, "tokenizer.ggml.mask_token_id"); + ds2_mask_id_ = (int) mask->u; + need(ds2_taps_ >= 1 && ds2_taps_ <= 4 && ds2_group_ > 0 && n_embd_ % ds2_group_ == 0 && ds2_topk_ == 16 && + ds_rank_ <= 512 && ds2_mask_id_ >= 0 && ds2_mask_id_ < n_vocab_, + "a convolution of 1 to 4 taps over groups that divide the width, 16 candidates, a selector rank of 512 at " + "most, a mask token"); + } ds_.assign((size_t) layers, DsLayer{}); for (int l = 0; l < layers; ++l) ds_[(size_t) l].swa = swa->items[(size_t) l].u != 0; } +// DFlash2's weights and caches to VRAM, once (ds_load()'s counterpart for a file with a candidate selector). The +// layers' attention and MLP are DSpark's (the context keys and values come from the same wk and wv); each also has the +// two convolutions' base and projection, and the file has the fusion matrix over the four features, its norm, and the +// selector (a hidden projection and two BF16 codebooks). The mask token's row is made on the first block. +void Inkling2::ds_load2() { +#if !defined(STRATA_GPU_METAL) + const Shards& f = *ds_file_; + const auto bad = [&](const std::string& name, const TensorInfo* t) { + return std::runtime_error(opt_.draft_model + ": " + name + (t ? " is " + shape_of(*t) : " is missing")); + }; + const auto find = [&](const std::string& name, uint32_t type, uint64_t n_in, uint64_t n_out) { + const TensorInfo* t = f.find(name); + if (!t || t->type != type || t->shape.empty() || t->shape[0] != n_in || t->elements() != n_in * n_out) + throw bad(name, t); + return t; + }; + const auto to_dev = [&](const TensorInfo* t) { + const size_t bytes = f.payload(*t); + void* d = dmalloc(bytes, "the drafter"); + ck(cudaMemcpy(d, f.data(*t), bytes, cudaMemcpyHostToDevice), "the drafter"); + return d; + }; + const auto f32 = [&](const std::string& name, uint64_t n) { return (float*) to_dev(find(name, kTypeF32, n, 1)); }; + const auto mat = [&](const std::string& name, uint64_t n_in, uint64_t n_out) { + const TensorInfo* t = f.find(name); + const uint32_t type = t ? t->type : 0; + find(name, type == kTypeBF16 ? kTypeBF16 : 8u, n_in, n_out); // BF16 or Q8_0 + return Dev{to_dev(t), type, (int) n_in, (int) n_out}; + }; + // a convolution's base [2][taps][n_embd] (the file names it without a suffix), F32 or BF16, to F32 on the card + const auto base = [&](const std::string& name, uint64_t n_in, uint64_t n_out) { + const TensorInfo* t = f.find(name); + if (!t) t = f.find(name + ".weight"); + if (!t || (t->type != kTypeF32 && t->type != kTypeBF16) || t->shape.empty() || t->shape[0] != n_in || + t->elements() != n_in * n_out) + throw bad(name, t); + f.payload(*t); + std::vector v((size_t) t->elements()); + if (t->type == kTypeF32) { + std::memcpy(v.data(), f.data(*t), v.size() * sizeof(float)); + } else { + const uint16_t* w = (const uint16_t*) f.data(*t); + for (size_t i = 0; i < v.size(); ++i) { + const uint32_t bits = uint32_t(w[i]) << 16; + std::memcpy(&v[i], &bits, 4); + } + } + float* d = (float*) dmalloc(v.size() * sizeof(float), "the drafter"); + ck(cudaMemcpy(d, v.data(), v.size() * sizeof(float), cudaMemcpyHostToDevice), "the drafter"); + return (const float*) d; + }; + const uint64_t E = (uint64_t) n_embd_, hq = (uint64_t) n_head_ * head_dim_, kv = (uint64_t) n_kv_ * head_dim_, + ff = (uint64_t) ds_ff_, R = (uint64_t) ds_rank_, V = (uint64_t) n_vocab_, + K = (uint64_t) ds2_taps_, proj = 2 * K * (E / (uint64_t) ds2_group_); + const size_t cell = kv * sizeof(uint16_t); + for (size_t l = 0; l < ds_.size(); ++l) { + DsLayer& L = ds_[l]; + const std::string b = "blk." + std::to_string(l) + "."; + L.wq = mat(b + "attn_q.weight", E, hq); + L.wk = mat(b + "attn_k.weight", E, kv); + L.wv = mat(b + "attn_v.weight", E, kv); + L.wo = mat(b + "attn_output.weight", hq, E); + L.gate = mat(b + "ffn_gate.weight", E, ff); + L.up = mat(b + "ffn_up.weight", E, ff); + L.down = mat(b + "ffn_down.weight", ff, E); + L.attn_norm = f32(b + "attn_norm.weight", E); + L.ffn_norm = f32(b + "ffn_norm.weight", E); + L.q_norm = f32(b + "attn_q_norm.weight", (uint64_t) head_dim_); + L.k_norm = f32(b + "attn_k_norm.weight", (uint64_t) head_dim_); + L.k_ctx_norm = L.k_norm; // the context keys are normed by the block's norm + L.a_proj = mat(b + "attn_conv_proj.weight", E, proj); + L.f_proj = mat(b + "ffn_conv_proj.weight", E, proj); + L.a_base = base(b + "attn_conv_base", E, 2 * K); + L.f_base = base(b + "ffn_conv_base", E, 2 * K); + L.cap = L.swa ? (int64_t) ds_window_ + 64 : (int64_t) opt_.max_context + 64; + L.keys = (uint16_t*) dmalloc((size_t) L.cap * cell, "the drafter's caches"); + L.vals = (uint16_t*) dmalloc((size_t) L.cap * cell, "the drafter's caches"); + if (L.swa) { + L.tags = (long long*) dmalloc((size_t) L.cap * sizeof(long long), "the drafter's caches"); + ck(cudaMemset(L.tags, 0xff, (size_t) L.cap * sizeof(long long)), "the drafter's caches"); + } + } + ds2_fc_ = mat("fc.weight", 4 * E, E); + ds2_enc_norm_ = f32("enc.output_norm.weight", E); + ds_norm_ = f32("output_norm.weight", E); + ds2_sel_h_ = mat("selector_hidden.weight", E, R); + ds2_prev_cb_ = (uint16_t*) to_dev(find("selector_predecessor.weight", kTypeBF16, R, V)); + ds2_succ_cb_ = (uint16_t*) to_dev(find("selector_successor.weight", kTypeBF16, R, V)); + ds_mask_ = (float*) dmalloc(E * 4, "the drafter"); + ds_ring_ = (float*) dmalloc(E * 4, "the drafter"); // (set: ds_load() has run) + ds_pick_ = (Likeliest*) dmalloc((size_t) ds_block_ * sizeof(Likeliest), "the drafter"); + ds_at_ = (long long*) dmalloc((2 * kDsRows + 1) * sizeof(long long), "the drafter"); + h_ds_row_ = (float*) hmalloc(E * 4, "pinned memory"); + h_ds_at_ = (long long*) hmalloc((2 * kDsRows + 1) * sizeof(long long), "pinned memory"); +#endif +} + // The drafter's weights and caches to VRAM, once (before the expert cache takes the rest). void Inkling2::ds_load() { + if (ds2_) { + ds_load2(); + return; + } const Shards& f = *ds_file_; const auto find = [&](const std::string& name, uint32_t type, uint64_t n_in, uint64_t n_out) { const TensorInfo* t = f.find(name); @@ -540,6 +659,10 @@ DsScreen Inkling2::ds_screen() const { // A call's rows' features for the drafter: their final normed state (the other three were copied as the layers ran), // mixed into each drafter layer's keys and values at the rows' positions and the Markov head's context. void Inkling2::ds_commit(int n) { + if (ds2_) { + ds_commit2(n); + return; + } const size_t E = (size_t) n_embd_; output_rows(0, n, ds_tap_ + 3 * (size_t) rows_ * E); const DsPos p{recording_ ? at_ : nullptr, (long long) pos_}; @@ -562,6 +685,77 @@ void Inkling2::ds_commit(int n) { } } +// ds_commit() for DFlash2: the four features of a row side by side through the fusion matrix and its norm, and the +// result through each layer's wk and wv into the caches at the rows' positions (the keys normed and rotated). +void Inkling2::ds_commit2(int n) { +#if !defined(STRATA_GPU_METAL) + const size_t E = (size_t) n_embd_; + output_rows(0, n, ds_tap_ + 3 * (size_t) rows_ * E); + const DsPos p{recording_ ? at_ : nullptr, (long long) pos_}; + ds2_cat(ds_tap_, (size_t) rows_ * E, n_embd_, n, ds2_cat_, st_); + lin(ds2_fc_, ds2_cat_, ds_mix_, n); + rms_norm(ds_mix_, ds2_enc_norm_, ds2_enc_, n_embd_, n, ds_eps_, st_); + for (size_t l = 0; l < ds_.size(); ++l) { + DsLayer& L = ds_[l]; + lin(L.wk, ds2_enc_, ds_k_, n); + lin(L.wv, ds2_enc_, ds_v_, n); + ds_rope(ds_k_, n_kv_, n, L.k_ctx_norm, ds_eps_, ds_theta_, p, L.keys, L.cap, ds_v_, L.vals, st_, L.tags); + } +#endif +} + +// ds_block() for DFlash2: the anchor's normed embedding and nb - 1 mask rows through the layers, each side of the +// attention and of the MLP with its convolution (the dynamic part from the layer's normed input, once for both sides), +// then the target's output matrix on the mask rows, their 16 best candidates and the selector's walk over them. +void Inkling2::ds_block2(int nb) { +#if !defined(STRATA_GPU_METAL) + const size_t E = (size_t) n_embd_, V = (size_t) n_vocab_; + const int nd = nb - 1; + const int dyn_row = 2 * ds2_taps_ * (n_embd_ / ds2_group_); + ck(cudaMemcpyAsync(ds_at_, h_ds_at_, (2 * kDsRows + 1) * sizeof(long long), cudaMemcpyHostToDevice, cs(st_)), + "the drafter"); + ck(cudaMemcpyAsync(ds_y_, h_ds_row_, E * 4, cudaMemcpyHostToDevice, cs(st_)), "the drafter"); + rms_norm(ds_y_, fp(tok_norm_), ds_x_, n_embd_, 1, rms_eps_, st_); + const DsPos p{ds_at_, 0}; + ds2_block_in(ds_x_, ds_mask_, n_embd_, nb, st_); + const float scale = 1.f / std::sqrt((float) head_dim_); + const auto conv = [&](const float* hidden, const float* base, int side, const float* acc, float* out) { + ds2_conv(hidden, ds2_dyn_, dyn_row, base, side, ds2_taps_, ds2_group_, n_embd_, nb, acc, out, st_); + }; + for (DsLayer& L : ds_) { + rms_norm(ds_x_, L.attn_norm, ds_y_, n_embd_, nb, ds_eps_, st_); + lin(L.a_proj, ds_y_, ds2_dyn_, nb); + conv(ds_y_, L.a_base, 0, nullptr, ds2_cv_); + kernels::native_quantize_q8_1(ds2_cv_, ds_yq_, n_embd_ * nb, 1, st_); + lin(L.wq, ds2_cv_, ds_q_, nb, ds_yq_); + lin_pair(L.wk, L.wv, ds2_cv_, ds_k_, ds_v_, nb, ds_yq_); + ds_rope(ds_q_, n_head_, nb, L.q_norm, ds_eps_, ds_theta_, p, nullptr, 0, nullptr, nullptr, st_); + ds_rope(ds_k_, n_kv_, nb, L.k_norm, ds_eps_, ds_theta_, p, L.keys, L.cap, ds_v_, L.vals, st_, L.tags); + // a context key is seen by a row if its distance is under the window: the first row's span is one key shorter + ds_attend(ds_q_, L.keys, L.vals, L.tags, L.cap, p, L.swa ? ds_window_ - 1 : 0, nb, n_head_, n_kv_, scale, + ds_part_, ds_att_, st_); + lin(L.wo, ds_att_, ds_y_, nb); + conv(ds_y_, L.a_base, 1, ds_x_, ds_x_); // x += the attention's output through the second side + rms_norm(ds_x_, L.ffn_norm, ds_y_, n_embd_, nb, ds_eps_, st_); + lin(L.f_proj, ds_y_, ds2_dyn_, nb); + conv(ds_y_, L.f_base, 0, nullptr, ds2_cv_); + kernels::native_quantize_q8_1(ds2_cv_, ds_yq_, n_embd_ * nb, 1, st_); + lin_pair(L.gate, L.up, ds2_cv_, ds_g_, ds_u_, nb, ds_yq_); + ds_swiglu(ds_g_, ds_u_, (size_t) nb * ds_ff_, st_); + lin(L.down, ds_g_, ds_y_, nb); + conv(ds_y_, L.f_base, 1, ds_x_, ds_x_); // x += the MLP's output through the second side + } + rms_norm(ds_x_ + E, ds_norm_, ds_h_, n_embd_, nd, ds_eps_, st_); + lin(output_, ds_h_, ds_base_, nd); + lin(ds2_sel_h_, ds_h_, ds2_gate_, nd); + ds2_topk(ds_base_, V, n_unpadded_, nd, ds2_tki_, ds2_tkv_, st_); + ds2_select(ds2_tki_, ds2_tkv_, ds2_gate_, ds_rank_, ds2_prev_cb_, ds2_succ_cb_, nd, ds_at_ + 2 * kDsRows, ds_cap_, + ds_pick_, st_); + ck(cudaMemcpyAsync(h_block_, ds_pick_, (size_t) nd * sizeof(Likeliest), cudaMemcpyDeviceToHost, cs(st_)), + "the drafter"); +#endif +} + // The drafter's block after `token` (the token at pos(), not yet run): its guesses of the tokens after it, with their // probabilities, into h_block_. A block's launches read its position and anchor on the card (ds_at_), so they are // the same for every block of its length: recorded once, then replayed with one call. Launched one by one, a @@ -575,6 +769,13 @@ void Inkling2::guess_block(int32_t token) { #endif const int nb = (int) std::min({(int64_t) cap, (int64_t) opt_.window, opt_.max_context - pos_}); if (!ds_file_ || nb < 2 || pos_ < 1) return; + if (ds2_ && !ds2_mask_ready_) { // DFlash2's mask row: the mask token's embedding, normed as an input's is + input(ds2_mask_id_, -1, h_ds_row_); + ck(cudaMemcpyAsync(ds_y_, h_ds_row_, (size_t) n_embd_ * 4, cudaMemcpyHostToDevice, cs(st_)), "the drafter"); + rms_norm(ds_y_, fp(tok_norm_), ds_mask_, n_embd_, 1, rms_eps_, st_); + ck(cudaStreamSynchronize(cs(st_)), "the drafter"); + ds2_mask_ready_ = true; + } input(token, pos_, h_ds_row_); for (int t = 0; t < kDsRows; ++t) h_ds_at_[2 * t] = pos_ + t; h_ds_at_[2 * kDsRows] = token; @@ -612,6 +813,10 @@ void Inkling2::guess_block(int32_t token) { // layers, then the Markov head on the mask rows' final rows, a guess at a time from the one before. The weights read // are the drafter's, and the output matrix and the fold, once for the guesses (or their 2-bit copies, ds_screen()). void Inkling2::ds_block(int nb) { + if (ds2_) { + ds_block2(nb); + return; + } const size_t E = (size_t) n_embd_, V = (size_t) n_vocab_, R = (size_t) ds_rank_; const int nd = nb - 1; ck(cudaMemcpyAsync(ds_at_, h_ds_at_, (2 * kDsRows + 1) * sizeof(long long), cudaMemcpyHostToDevice, cs(st_)), @@ -1037,6 +1242,16 @@ void Inkling2::assign_scratch() { ds_gq_ = bytes(B * kernels::native_q8_1_bytes((int) std::max(hq, (size_t) ds_ff_))); ds_approx_ = fbuf(B * (size_t) ds_screen_rows(n_unpadded_)); ds_hscr_ = (float*) bytes(ds_screen_scratch_bytes(n_unpadded_)); + if (ds2_) { // DFlash2's: the four features of a call's rows side by side, the fusion's output, a block's rows + const size_t dyn = (size_t) 2 * ds2_taps_ * (n_embd_ / ds2_group_); + ds2_cat_ = fbuf(4 * n * E); + ds2_enc_ = fbuf(n * E); + ds2_dyn_ = fbuf(B * dyn); + ds2_cv_ = fbuf(B * E); + ds2_gate_ = fbuf(B * R); + ds2_tki_ = (int32_t*) fbuf(B * 16); + ds2_tkv_ = fbuf(B * 16); + } if (!ds_ring_ && scratch_) ds_load(); } if (!side_) { diff --git a/engine/src/poly/inkling2.cu b/engine/src/poly/inkling2.cu index 687311cdd6..9c1d65a3ef 100644 --- a/engine/src/poly/inkling2.cu +++ b/engine/src/poly/inkling2.cu @@ -5379,8 +5379,186 @@ __global__ void __launch_bounds__(512) scr_final_kernel(DsScreen h, const QB* xh } } +// ---- the DFlash2 drafter's kernels (Inkling2::ds_block2(), ds_commit2()) ---- +// +// DFlash2 (incoai/Inkling-2-Mini-DFlash2) is a block drafter like DSpark's, with two-tap dynamic grouped convolutions +// around its attention and its MLP, one fusion layer over the four features, and a candidate selector in place of the +// Markov head. Its forward follows the model's GGUF graph (strata-llama src/models/dflash.cpp) and the selector the +// trained one (SGLang's DFlash2 patch: selector_softcap_mode after_correction). The kernels are this engine's own. + +constexpr int kD2TopK = 16; // candidates a position +constexpr int kD2MaxRank = 512; // the selector's rank at most + +// fused[t][k * n + i] = tap k's row t: the four features of a row side by side, as the fusion layer reads them +__global__ void ds2_cat_kernel(const float* __restrict__ tap, size_t stride, int n, float* __restrict__ out) { + const int t = blockIdx.x, k = blockIdx.y; + for (int i = threadIdx.x; i < n; i += blockDim.x) + out[((size_t) t * 4 + k) * n + i] = tap[(size_t) k * stride + (size_t) t * n + i]; +} + +// rows 1 .. rows - 1 of x = mask (the block's mask token, normed as the target norms an embedding) +__global__ void ds2_block_in_kernel(float* __restrict__ x, const float* __restrict__ mask, int n, int rows) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + for (int t = 1; t < rows; ++t) x[(size_t) t * n + i] = mask[i]; +} + +// One side of the dynamic grouped convolution: out[t][c] = acc[t][c] + sum over taps j <= t of (base[side][j][c] + +// dyn[t][side][j][c / group]) * hidden[t - j][c]. A tap never reads before the block's first row. dyn's row is +// [side][tap][group]; acc and out may be the same. +__global__ void ds2_conv_kernel(const float* __restrict__ hidden, const float* __restrict__ dyn, int dyn_row, + const float* __restrict__ base, int side, int taps, int group, int n, + const float* acc, float* out) { + const int t = blockIdx.y; + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= n) return; + const int g = c / group, groups = n / group; + float sum = acc ? acc[(size_t) t * n + c] : 0.0f; + for (int j = 0; j < taps && j <= t; ++j) { + const float w = base[((size_t) side * taps + j) * n + c] + + dyn[(size_t) t * dyn_row + (side * taps + j) * groups + g]; + sum = fmaf(w, hidden[(size_t) (t - j) * n + c], sum); + } + out[(size_t) t * n + c] = sum; +} + +// Row r (blockIdx.x): the 16 largest of its first n_valid logits, in descending order (a tie: the lower id first). +// Each thread keeps the 16 largest of its strided share; then 16 rounds take the block's best head. +__global__ void __launch_bounds__(256) ds2_topk_kernel(const float* __restrict__ logits, size_t stride, int n_valid, + int32_t* __restrict__ idx, float* __restrict__ val) { + __shared__ float sv[256][kD2TopK + 1]; + __shared__ int si[256][kD2TopK + 1]; + __shared__ float wv[8]; + __shared__ int wi[8], wt[8]; + const float* row = logits + (size_t) blockIdx.x * stride; + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + float lv[kD2TopK]; + int li[kD2TopK]; +#pragma unroll + for (int j = 0; j < kD2TopK; ++j) lv[j] = -INFINITY, li[j] = 0x7fffffff; + for (int i = tid; i < n_valid; i += 256) { + float v = row[i]; + int id = i; + if (!(v > lv[kD2TopK - 1])) continue; // ids rise along the stride, so an equal value is never earlier +#pragma unroll + for (int j = 0; j < kD2TopK; ++j) { + if (v > lv[j]) { + const float tv = lv[j]; + const int ti = li[j]; + lv[j] = v, li[j] = id; + v = tv, id = ti; + } + } + } +#pragma unroll + for (int j = 0; j < kD2TopK; ++j) sv[tid][j] = lv[j], si[tid][j] = li[j]; + int head = 0; // this thread's next unconsumed entry + for (int r = 0; r < kD2TopK; ++r) { + float v = head < kD2TopK ? sv[tid][head] : -INFINITY; + int id = head < kD2TopK ? si[tid][head] : 0x7fffffff; + int who = tid; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) { + const float ov = __shfl_xor_sync(0xffffffff, v, o, 32); + const int oi = __shfl_xor_sync(0xffffffff, id, o, 32); + const int ow = __shfl_xor_sync(0xffffffff, who, o, 32); + if (ov > v || (ov == v && oi < id)) v = ov, id = oi, who = ow; + } + if (lane == 0) wv[warp] = v, wi[warp] = id, wt[warp] = who; + __syncthreads(); + float bv = wv[0]; + int bi = wi[0], bw = wt[0]; + for (int w = 1; w < 8; ++w) + if (wv[w] > bv || (wv[w] == bv && wi[w] < bi)) bv = wv[w], bi = wi[w], bw = wt[w]; + if (tid == 0) { + idx[(size_t) blockIdx.x * kD2TopK + r] = bi; + val[(size_t) blockIdx.x * kD2TopK + r] = bv; + } + if (tid == bw) ++head; + __syncthreads(); // wv, wi, wt are free again + } +} + +__device__ __forceinline__ float d2_bf16(uint16_t v) { return __uint_as_float(uint32_t(v) << 16); } + +// The selector's walk, one block of 512 threads (a warp a candidate): draft s, from the 16 candidates of mask row s + 1 +// (idx, val: their ids and logits) and the row's gate (gate[s], rank values), scores candidate k as +// cap * tanh((val + sum_r prev_cb[prev][r] gate[r] succ_cb[cand][r]) / cap) +// where prev is the token picked before it (the anchor for the first); the pick is the largest (the lower id of a tie) +// and its probability the softmax of the 16 scores. The scores are over the candidates only. +__global__ void __launch_bounds__(512) ds2_select_kernel(const int32_t* __restrict__ idx, const float* __restrict__ val, + const float* __restrict__ gate, int rank, + const uint16_t* __restrict__ prev_cb, + const uint16_t* __restrict__ succ_cb, int steps, + const long long* __restrict__ anchor, float cap, + Likeliest* __restrict__ out) { + __shared__ float pred[kD2MaxRank]; + __shared__ float score[kD2TopK]; + __shared__ int prev; + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + if (tid == 0) prev = (int) *anchor; + __syncthreads(); + for (int s = 0; s < steps; ++s) { + for (int r = tid; r < rank; r += 512) + pred[r] = d2_bf16(prev_cb[(size_t) prev * rank + r]) * gate[(size_t) s * rank + r]; + __syncthreads(); + const int cand = idx[s * kD2TopK + warp]; + float dot = 0.0f; + for (int r = lane; r < rank; r += 32) dot = fmaf(pred[r], d2_bf16(succ_cb[(size_t) cand * rank + r]), dot); + dot = warp_sum(dot); + if (lane == 0) { + const float x = val[s * kD2TopK + warp] + dot; + score[warp] = cap > 0.0f ? cap * tanhf(x / cap) : x; + } + __syncthreads(); + if (tid == 0) { + int best = 0; + for (int k = 1; k < kD2TopK; ++k) + if (score[k] > score[best] || + (score[k] == score[best] && idx[s * kD2TopK + k] < idx[s * kD2TopK + best])) + best = k; + float z = 0.0f; + for (int k = 0; k < kD2TopK; ++k) z += __expf(score[k] - score[best]); + out[s].token = idx[s * kD2TopK + best]; + out[s].prob = 1.0f / z; + prev = out[s].token; + } + __syncthreads(); + } +} + } // namespace +void ds2_cat(const float* tap, size_t stride, int n, int rows, float* out, void* stream) { + if (rows <= 0) return; + ds2_cat_kernel<<>>(tap, stride, n, out); + launched("ds2_cat"); +} + +void ds2_block_in(float* x, const float* mask, int n, int rows, void* stream) { + ds2_block_in_kernel<<>>(x, mask, n, rows); + launched("ds2_block_in"); +} + +void ds2_conv(const float* hidden, const float* dyn, int dyn_row, const float* base, int side, int taps, int group, + int n, int rows, const float* acc, float* out, void* stream) { + ds2_conv_kernel<<>>(hidden, dyn, dyn_row, base, side, taps, + group, n, acc, out); + launched("ds2_conv"); +} + +void ds2_topk(const float* logits, size_t stride, int n_valid, int rows, int32_t* idx, float* val, void* stream) { + ds2_topk_kernel<<>>(logits, stride, n_valid, idx, val); + launched("ds2_topk"); +} + +void ds2_select(const int32_t* idx, const float* val, const float* gate, int rank, const uint16_t* prev_cb, + const uint16_t* succ_cb, int steps, const long long* anchor, float cap, Likeliest* out, void* stream) { + if (rank > kD2MaxRank) throw std::logic_error("ds2_select: the selector's rank is more than it holds"); + ds2_select_kernel<<<1, 512, 0, cs(stream)>>>(idx, val, gate, rank, prev_cb, succ_cb, steps, anchor, cap, out); + launched("ds2_select"); +} + void ds_mix(const DsMix& m, int n, int rows, float eps, void* stream) { if (rows <= 0) return; ds_mix_kernel<<>>(m, n, rows, eps); diff --git a/engine/src/poly/inkling2.hpp b/engine/src/poly/inkling2.hpp index 89a4a647a6..5b3d657736 100644 --- a/engine/src/poly/inkling2.hpp +++ b/engine/src/poly/inkling2.hpp @@ -172,6 +172,9 @@ class Inkling2 final : public Engine { void ds_commit(int n); void ds_fold(); void ds_block(int nb); + void ds_load2(); + void ds_commit2(int n); + void ds_block2(int nb); DsScreen ds_screen() const; template void window_runs(int64_t pos, F&& f) const; @@ -221,8 +224,25 @@ class Inkling2 final : public Engine { uint16_t *keys = nullptr, *vals = nullptr; ///< fp16, n_kv * head_dim a cell, position p at cell p % cap long long* tags = nullptr; ///< a window layer's: the position each cell holds (-1: none) int64_t cap = 0; + // DFlash2's (ds2_): the two-tap dynamic convolutions around the attention and the MLP: a [2][taps][n_embd] + // base and the projection of the layer's normed input to the [2][taps][groups] dynamic part + Dev a_proj, f_proj; + const float *a_base = nullptr, *f_base = nullptr; }; - static constexpr int kDsRing = 16; ///< positions whose Markov-head context ds_ring_ keeps + // DFlash2 (--draft-model of an incoai/Inkling-2-Mini-DFlash2 GGUF: a `dflash` file with a candidate selector instead + // of the Markov head): the same layers and caches and the same four features, fused by one matrix, with + // convolutions around each layer's work and a selector that walks the top 16 candidates of each mask row. + // Set by ds_open() from the file's tensors; DSpark files never touch the ds2_ members. + bool ds2_ = false; + int ds2_taps_ = 0, ds2_group_ = 0, ds2_topk_ = 0, ds2_mask_id_ = -1; + bool ds2_mask_ready_ = false; + Dev ds2_fc_, ds2_sel_h_; + const float* ds2_enc_norm_ = nullptr; + uint16_t *ds2_prev_cb_ = nullptr, *ds2_succ_cb_ = nullptr; ///< the selector's BF16 codebooks [vocabulary][rank] + float *ds2_cat_ = nullptr, *ds2_enc_ = nullptr, *ds2_dyn_ = nullptr, *ds2_cv_ = nullptr, *ds2_gate_ = nullptr, + *ds2_tkv_ = nullptr; + int32_t* ds2_tki_ = nullptr; + static constexpr int kDsRing = 16; ///< positions whose Markov-head context ds_ring_ keeps static constexpr int kDsRows = 8; ///< a block's rows at most std::unique_ptr ds_file_; std::vector ds_; diff --git a/engine/src/poly/inkling2_kernels.hpp b/engine/src/poly/inkling2_kernels.hpp index 5bb4e771f1..1b753b86fc 100644 --- a/engine/src/poly/inkling2_kernels.hpp +++ b/engine/src/poly/inkling2_kernels.hpp @@ -406,6 +406,27 @@ void ds_markov_fused(const float* state_in, const uint16_t* w1, const int32_t* p const float* ctx_h, const float* ctx_f, const float* bias, float* state_out, float* latent, void* lat_q8, int rank, void* stream); #endif +#if !defined(STRATA_GPU_METAL) +// ---- the DFlash2 drafter (a --draft-model file with a candidate selector; Inkling2::ds_block2()) ---- +/// out[t] = the four features of row t side by side (tap k at tap + k * stride, n values a row): 4 * n values a row. +void ds2_cat(const float* tap, size_t stride, int n, int rows, float* out, void* stream); +/// Rows 1 .. rows - 1 of x (n values a row) = mask. +void ds2_block_in(float* x, const float* mask, int n, int rows, void* stream); +/// One side (0 before the layer's work, 1 after) of the two-tap dynamic grouped convolution over a block's `rows` rows: +/// out[t] = acc[t] (none: 0) + sum over taps j <= t of (base[side][j] + dyn[t][side][j][channel / group]) * hidden[t - j]. +/// base: [2][taps][n] floats; dyn: a row of dyn_row = 2 * taps * n / group floats a row. acc and out may be one. +void ds2_conv(const float* hidden, const float* dyn, int dyn_row, const float* base, int side, int taps, int group, + int n, int rows, const float* acc, float* out, void* stream); +/// The 16 largest of the first n_valid logits of each of `rows` rows (stride apart), descending, into idx and val +/// (16 a row). +void ds2_topk(const float* logits, size_t stride, int n_valid, int rows, int32_t* idx, float* val, void* stream); +/// The selector's walk over `steps` (at most 7) mask rows: draft s is the best of row s's 16 candidates by cap tanh((logit +/// + prev_cb[previous token] . gate[s] . succ_cb[candidate]) / cap), the previous token of the first the anchor +/// (*anchor); BF16 codebooks [vocabulary][rank], gate steps x rank floats. The pick and its softmax probability over +/// the 16 into out. +void ds2_select(const int32_t* idx, const float* val, const float* gate, int rank, const uint16_t* prev_cb, + const uint16_t* succ_cb, int steps, const long long* anchor, float cap, Likeliest* out, void* stream); +#endif /// A draft's pick from its scores cap tanh((base + fy + fb) / cap) over the first n_keep tokens: the lowest id of the /// largest and its softmax probability into out, the id into prev too. scratch: ds_pick_floats() floats. void ds_pick(const float* base, const float* fy, const float* fb, int n_keep, float cap, float* scratch, Likeliest* out, From 015a56c4c5e06a41ce410133691b4744de3a7b36 Mon Sep 17 00:00:00 2001 From: Sarah Date: Thu, 26 Nov 2026 12:14:46 +0100 Subject: [PATCH 2/7] poly: DFlash2 drafter loads and drafts with Inkling 2 Mini (refs #339) The drafter has its own attention: 32 query heads over 8 KV heads, while Inkling 2 Mini's target has 24. The engine checked the drafter's head count against the target's and refused the file, and it took the query width from the target too. Now the drafter's heads are read from its file (ds_heads_) for its weights, RoPE, attention and buffers. The attention kernel takes 32 query rows a KV head (4 heads of 8 block rows), up from 24. A DFlash2 file has no dflash.sample_from_anchor (a DSpark key), so absent means drafting from the mask rows. The converter: a DFlash2 file keeps target_layer_ids as they are. Its last id is the final state (48 of 48 layers), so the +1 the other DFlash drafters take would put it past the last layer. A target whose architecture the converter does not know (Inkling 2 Mini's loop model) gives the drafter its size and mask token only: the engine takes the tokenizer from the target's file. Measured on RTX 4060 (8 GB, sm_89), CUDA 13.4, Inkling-2-Mini-UD-Q4_K_XL, 8-token prompt, 64 new tokens, --window 4: the DFlash2 file loads, and with the drafter forced on (a test-only change, reverted) 7 of 13 guesses were accepted. Without forcing it, the drafter does not guess on this card: blocks are asked only when every routed expert is in VRAM (3072 experts; 758 fit here), so the output equals the no-drafter run at the same window. Not measured: the drafted output against the no-drafter output over longer runs (batched numerics differ at the window size), DSpark files (none here), and the Metal backend. Co-Authored-By: Claude Haiku 5.5 --- engine/src/poly/inkling2.cpp | 35 ++++++++++--------- engine/src/poly/inkling2.cu | 4 +-- engine/src/poly/inkling2.hpp | 1 + .../converter/conversion/qwen.py | 19 +++++++--- 4 files changed, 37 insertions(+), 22 deletions(-) diff --git a/engine/src/poly/inkling2.cpp b/engine/src/poly/inkling2.cpp index 37ef83e216..6a2ea62809 100644 --- a/engine/src/poly/inkling2.cpp +++ b/engine/src/poly/inkling2.cpp @@ -351,14 +351,17 @@ void Inkling2::ds_open() { const MetaValue* swa = key("attention.sliding_window_pattern"); const MetaValue* targets = key("target_layers"); const int visits = n_layer_ + (n_pass_ - 1) * (core_end_ - core_start_); - need((int) key("embedding_length")->u == n_embd_ && (int) key("attention.head_count")->u == n_head_ && + ds_heads_ = (int) key("attention.head_count")->u; // the drafter's own attention, not the target's + need((int) key("embedding_length")->u == n_embd_ && ds_heads_ > 0 && ds_heads_ % n_kv_ == 0 && (int) key("attention.head_count_kv")->u == n_kv_ && (int) key("attention.key_length")->u == head_dim_ && head_dim_ == 128 && (int) key("vocab_size")->u == n_vocab_, - "the target's width, heads and vocabulary"); + "the target's width and vocabulary, the drafter's heads a multiple of the kv heads"); need(ds_block_ >= 2 && ds_block_ <= kDsRows && ds_rank_ % 32 == 0 && ds_rank_ <= 1024 && ds_ff_ > 0 && - ds_window_ > 0 && n_head_ % n_kv_ == 0 && n_head_ / n_kv_ * ds_block_ <= 24, - "a block of 2 to 8, a Markov rank of a multiple of 32, 24 query rows a key head at most"); - need(!key("sample_from_anchor")->u && !key("attention.causal")->u, "drafts from the mask rows, a block's rows " + ds_window_ > 0 && ds_heads_ / n_kv_ * ds_block_ <= 32, + "a block of 2 to 8, a Markov rank of a multiple of 32, 32 query rows a key head at most"); + // a DFlash2 file has no sample_from_anchor (it is DSpark's key): absent means drafting from the mask rows + const MetaValue* sfa = ds_file_->get("dflash.sample_from_anchor"); + need((!sfa || !sfa->u) && !key("attention.causal")->u, "drafts from the mask rows, a block's rows " "seeing each other"); need(swa->type == MetaType::ARRAY && (int) swa->items.size() == layers && targets->type == MetaType::ARRAY && targets->items.size() == 4 && (int) targets->items[3].u == visits, @@ -431,7 +434,7 @@ void Inkling2::ds_load2() { ck(cudaMemcpy(d, v.data(), v.size() * sizeof(float), cudaMemcpyHostToDevice), "the drafter"); return (const float*) d; }; - const uint64_t E = (uint64_t) n_embd_, hq = (uint64_t) n_head_ * head_dim_, kv = (uint64_t) n_kv_ * head_dim_, + const uint64_t E = (uint64_t) n_embd_, hq = (uint64_t) ds_heads_ * head_dim_, kv = (uint64_t) n_kv_ * head_dim_, ff = (uint64_t) ds_ff_, R = (uint64_t) ds_rank_, V = (uint64_t) n_vocab_, K = (uint64_t) ds2_taps_, proj = 2 * K * (E / (uint64_t) ds2_group_); const size_t cell = kv * sizeof(uint16_t); @@ -503,7 +506,7 @@ void Inkling2::ds_load() { find(name, type == kTypeBF16 ? kTypeBF16 : 8u, n_in, n_out); // BF16 or Q8_0 return Dev{to_dev(t), type, (int) n_in, (int) n_out}; }; - const uint64_t E = (uint64_t) n_embd_, hq = (uint64_t) n_head_ * head_dim_, kv = (uint64_t) n_kv_ * head_dim_, + const uint64_t E = (uint64_t) n_embd_, hq = (uint64_t) ds_heads_ * head_dim_, kv = (uint64_t) n_kv_ * head_dim_, ff = (uint64_t) ds_ff_, R = (uint64_t) ds_rank_, V = (uint64_t) n_vocab_; const size_t cell = kv * sizeof(uint16_t); for (size_t l = 0; l < ds_.size(); ++l) { @@ -729,10 +732,10 @@ void Inkling2::ds_block2(int nb) { kernels::native_quantize_q8_1(ds2_cv_, ds_yq_, n_embd_ * nb, 1, st_); lin(L.wq, ds2_cv_, ds_q_, nb, ds_yq_); lin_pair(L.wk, L.wv, ds2_cv_, ds_k_, ds_v_, nb, ds_yq_); - ds_rope(ds_q_, n_head_, nb, L.q_norm, ds_eps_, ds_theta_, p, nullptr, 0, nullptr, nullptr, st_); + ds_rope(ds_q_, ds_heads_, nb, L.q_norm, ds_eps_, ds_theta_, p, nullptr, 0, nullptr, nullptr, st_); ds_rope(ds_k_, n_kv_, nb, L.k_norm, ds_eps_, ds_theta_, p, L.keys, L.cap, ds_v_, L.vals, st_, L.tags); // a context key is seen by a row if its distance is under the window: the first row's span is one key shorter - ds_attend(ds_q_, L.keys, L.vals, L.tags, L.cap, p, L.swa ? ds_window_ - 1 : 0, nb, n_head_, n_kv_, scale, + ds_attend(ds_q_, L.keys, L.vals, L.tags, L.cap, p, L.swa ? ds_window_ - 1 : 0, nb, ds_heads_, n_kv_, scale, ds_part_, ds_att_, st_); lin(L.wo, ds_att_, ds_y_, nb); conv(ds_y_, L.a_base, 1, ds_x_, ds_x_); // x += the attention's output through the second side @@ -859,10 +862,10 @@ void Inkling2::ds_block(int nb) { } { gpu::metal::ParallelScope par(static_cast(st_)); - ds_rope(ds_q_, n_head_, nb, L.q_norm, ds_eps_, ds_theta_, p, nullptr, 0, nullptr, nullptr, st_); + ds_rope(ds_q_, ds_heads_, nb, L.q_norm, ds_eps_, ds_theta_, p, nullptr, 0, nullptr, nullptr, st_); ds_rope(ds_k_, n_kv_, nb, L.k_norm, ds_eps_, ds_theta_, p, L.keys, L.cap, ds_v_, L.vals, st_, L.tags); } - ds_attend_q8(ds_q_, L.keys, L.vals, L.tags, L.cap, p, L.swa ? ds_window_ : 0, nb, n_head_, n_kv_, scale, + ds_attend_q8(ds_q_, L.keys, L.vals, L.tags, L.cap, p, L.swa ? ds_window_ : 0, nb, ds_heads_, n_kv_, scale, ds_part_, ds_att_, st_, ds_gq_); lin(L.wo, ds_att_, ds_y_, nb, ds_gq_); ink_add_norm_q8_rows(ds_x_, ds_y_, L.ffn_norm, ds_y_, ds_yq_, n_embd_, nb, ds_eps_, st_); @@ -923,9 +926,9 @@ void Inkling2::ds_block(int nb) { lin(L.wq, ds_h_, ds_q_, nb, ds_yq_); lin_pair(L.wk, L.wv, ds_h_, ds_k_, ds_v_, nb, ds_yq_); } - ds_rope_qkv(ds_q_, ds_k_, ds_v_, n_head_, n_kv_, nb, L.q_norm, L.k_norm, ds_eps_, ds_theta_, p, L.keys, + ds_rope_qkv(ds_q_, ds_k_, ds_v_, ds_heads_, n_kv_, nb, L.q_norm, L.k_norm, ds_eps_, ds_theta_, p, L.keys, L.vals, L.cap, L.tags, st_); - ds_attend(ds_q_, L.keys, L.vals, L.tags, L.cap, p, L.swa ? ds_window_ : 0, nb, n_head_, n_kv_, scale, + ds_attend(ds_q_, L.keys, L.vals, L.tags, L.cap, p, L.swa ? ds_window_ : 0, nb, ds_heads_, n_kv_, scale, ds_part_, ds_att_, st_, ds_gq_); lin(L.wo, ds_att_, ds_y_, nb, ds_gq_); kernels::native_add_rms_norm_q8_1(ds_x_, ds_y_, L.ffn_norm, ds_h_, ds_yq_, n_embd_, nb, ds_eps_, @@ -954,9 +957,9 @@ void Inkling2::ds_block(int nb) { lin(L.wq, ds_y_, ds_q_, nb, ds_yq_); lin_pair(L.wk, L.wv, ds_y_, ds_k_, ds_v_, nb, ds_yq_); // a window layer's context is the window before the block, a full one's every position; and the block - ds_rope(ds_q_, n_head_, nb, L.q_norm, ds_eps_, ds_theta_, p, nullptr, 0, nullptr, nullptr, st_); + ds_rope(ds_q_, ds_heads_, nb, L.q_norm, ds_eps_, ds_theta_, p, nullptr, 0, nullptr, nullptr, st_); ds_rope(ds_k_, n_kv_, nb, L.k_norm, ds_eps_, ds_theta_, p, L.keys, L.cap, ds_v_, L.vals, st_, L.tags); - ds_attend(ds_q_, L.keys, L.vals, L.tags, L.cap, p, L.swa ? ds_window_ : 0, nb, n_head_, n_kv_, scale, + ds_attend(ds_q_, L.keys, L.vals, L.tags, L.cap, p, L.swa ? ds_window_ : 0, nb, ds_heads_, n_kv_, scale, ds_part_, ds_att_, st_); lin(L.wo, ds_att_, ds_y_, nb); axpy(ds_y_, 1.f, ds_x_, nb * n_embd_, true, st_); @@ -1211,7 +1214,7 @@ void Inkling2::assign_scratch() { kvw_ = fbuf(kvw_halves_); // 2 * kvw_halves_ halves } if (ds_file_) { // the drafter's: a call's features and mixes, and a block's rows - const size_t E = (size_t) n_embd_, hq = (size_t) n_head_ * head_dim_, kv = (size_t) n_kv_ * head_dim_, + const size_t E = (size_t) n_embd_, hq = (size_t) ds_heads_ * head_dim_, kv = (size_t) n_kv_ * head_dim_, B = (size_t) ds_block_, V = (size_t) n_vocab_, R = (size_t) ds_rank_; ds_tap_ = ds_home_ = fbuf(kDsTaps * n * E); ds_mix_ = fbuf(3 * n * E); diff --git a/engine/src/poly/inkling2.cu b/engine/src/poly/inkling2.cu index 9c1d65a3ef..10d780d95f 100644 --- a/engine/src/poly/inkling2.cu +++ b/engine/src/poly/inkling2.cu @@ -4576,7 +4576,7 @@ __global__ void ds_rope_qkv_kernel(float* q, float* k, const float* v, int heads // The block's attention, the keys split among blocks so that a long context is read at once: block (g, s) takes kv // head g's query rows (block row t's head g * grp + k as row t * grp + k, one warp per query row) over split s of // [lo, hi) with online softmax, zero shared memory and zero per-tile barriers; ds_join_kernel joins the splits. -constexpr int kDsRows = 24; // a kv head's query rows at most: 8 block rows of 3 heads +constexpr int kDsRows = 32; // a kv head's query rows at most: 8 block rows of 4 heads (32 heads, 8 kv heads) constexpr int kDsTile = 32; // split alignment in keys constexpr int kDsSplits = 64; // splits at most constexpr int kDsPart = kDsHead + 2; // a row's part: its values' weighted sum, its max, its sum @@ -4590,7 +4590,7 @@ __device__ __forceinline__ void ds_span(const DsPos& p, int nb, int window, long constexpr int kDsSmTile = 8; -__global__ void __launch_bounds__(768) ds_part_kernel(const float* q, const __half* keys, const __half* vals, +__global__ void __launch_bounds__(1024) ds_part_kernel(const float* q, const __half* keys, const __half* vals, const long long* tags, long long cap, DsPos p, int nb, int window, int heads, int kv_heads, float scale, float* part) { const int g = int(blockIdx.x), s = int(blockIdx.y), lane = int(threadIdx.x), r = int(threadIdx.y); diff --git a/engine/src/poly/inkling2.hpp b/engine/src/poly/inkling2.hpp index 5b3d657736..91e1d835fd 100644 --- a/engine/src/poly/inkling2.hpp +++ b/engine/src/poly/inkling2.hpp @@ -247,6 +247,7 @@ class Inkling2 final : public Engine { std::unique_ptr ds_file_; std::vector ds_; int ds_block_ = 0, ds_window_ = 0, ds_ff_ = 0, ds_rank_ = 0, ds_visit_[3] = {}; + int ds_heads_ = 0; ///< the drafter's query heads (its own: 32 for Inkling 2 Mini DFlash2, the target's 24 differ) float ds_theta_ = 0, ds_eps_ = 0, ds_cap_ = 0; float *ds_alpha_ = nullptr, *ds_mask_ = nullptr, *ds_norm_ = nullptr, *ds_mnorm_ = nullptr, *ds_jb_ = nullptr, *ds_ob_ = nullptr, *ds_wt_ = nullptr, *ds_fold_b_ = nullptr, *ds_ring_ = nullptr, *h_ds_row_ = nullptr; diff --git a/engine/third_party/strata-gguf-py/converter/conversion/qwen.py b/engine/third_party/strata-gguf-py/converter/conversion/qwen.py index c7e0809f38..99df1277f4 100644 --- a/engine/third_party/strata-gguf-py/converter/conversion/qwen.py +++ b/engine/third_party/strata-gguf-py/converter/conversion/qwen.py @@ -667,9 +667,17 @@ def set_vocab(self): with open(self.target_model_dir / "config.json", "r", encoding="utf-8") as f: target_hparams = json.load(f) target_arch = target_hparams["architectures"][0] - target_cls = get_model_class(target_arch) - - if target_cls is not type(self): + try: + target_cls = get_model_class(target_arch) + except NotImplementedError: + # The target's architecture has no tokenizer handler here (Inkling 2 Mini's loop model). The engine takes + # its tokenizer from the target's file, so this drafter writes no vocabulary: only its size and mask token. + logger.warning(f"DFlash: no tokenizer handler for {target_arch}; the drafter writes no vocabulary") + target_cls = None + + if target_cls is None: + self.gguf_writer.add_vocab_size(int(self.hparams["vocab_size"])) + elif target_cls is not type(self): if target_arch == "NemotronHForCausalLM": setattr(self, "is_moe", "num_experts_per_tok" in target_hparams) target_cls.set_vocab(self) # ty: ignore[unresolved-attribute] @@ -713,7 +721,10 @@ def set_gguf_parameters(self): target_layer_ids = dflash_config.get("target_layer_ids", []) if target_layer_ids: - extract_layer_ids = [i + 1 for i in target_layer_ids] + # DFlash2 (incoai) names hidden_states indices, the last one the final state (48 of 48 layers): no shift. + # The other DFlash drafters keep the +1 their converter always wrote. + is_dflash2 = (self.hparams.get("architectures") or [""])[0] == "DFlash2DraftModel" + extract_layer_ids = list(target_layer_ids) if is_dflash2 else [i + 1 for i in target_layer_ids] self.gguf_writer.add_target_layers(extract_layer_ids) use_sliding_window = self.hparams.get("use_sliding_window", False) or dflash_config.get("use_swa", False) From ecdfa5b211bb216f8e18db7fc5692920c8d1fc36 Mon Sep 17 00:00:00 2001 From: Sarah Date: Thu, 26 Nov 2026 12:32:10 +0100 Subject: [PATCH 3/7] poly: DFlash2 top-16 selector in two kernels, a split and a merge (refs #339) ds2_topk() took the 16 best of the whole vocabulary in one block a mask row, so with 8 rows only 8 blocks ran. Now each row's vocabulary is cut into 32 ranges, one block each (ds2_topk_part_kernel), and a merge kernel takes the 16 best of the 512 partial candidates (ds2_topk_merge_kernel). Same ordering as before: value descending, a tie the lower id first. Measured on RTX 4060 (8 GB, sm_89), CUDA 13.4, Inkling-2-Mini-UD-Q4_K_XL, the 8-token prompt, 64 tokens, --window 4, drafter forced on (a test-only change, reverted): the output is byte-identical to the build before this commit; kernel time per round went from 193 us (ds2_topk) to 46 us (34 us split + 12 us merge); drafter kernels summed to 5.9 ms against 12.2 ms over the traced run. Acceptance counts differ between runs (25 of 67 and 25 of 65 guesses) because the guess policy reads wall-clock timings. DSpark files take no part in this: ds2_topk runs only on a DFlash2 file. Co-Authored-By: Claude Haiku 5.5 --- engine/src/poly/inkling2.cpp | 4 +- engine/src/poly/inkling2.cu | 76 +++++++++++++++++++++++----- engine/src/poly/inkling2.hpp | 2 + engine/src/poly/inkling2_kernels.hpp | 4 +- 4 files changed, 72 insertions(+), 14 deletions(-) diff --git a/engine/src/poly/inkling2.cpp b/engine/src/poly/inkling2.cpp index 6a2ea62809..3784bc4a37 100644 --- a/engine/src/poly/inkling2.cpp +++ b/engine/src/poly/inkling2.cpp @@ -751,7 +751,7 @@ void Inkling2::ds_block2(int nb) { rms_norm(ds_x_ + E, ds_norm_, ds_h_, n_embd_, nd, ds_eps_, st_); lin(output_, ds_h_, ds_base_, nd); lin(ds2_sel_h_, ds_h_, ds2_gate_, nd); - ds2_topk(ds_base_, V, n_unpadded_, nd, ds2_tki_, ds2_tkv_, st_); + ds2_topk(ds_base_, V, n_unpadded_, nd, ds2_tki_, ds2_tkv_, ds2_ptki_, ds2_ptkv_, st_); ds2_select(ds2_tki_, ds2_tkv_, ds2_gate_, ds_rank_, ds2_prev_cb_, ds2_succ_cb_, nd, ds_at_ + 2 * kDsRows, ds_cap_, ds_pick_, st_); ck(cudaMemcpyAsync(h_block_, ds_pick_, (size_t) nd * sizeof(Likeliest), cudaMemcpyDeviceToHost, cs(st_)), @@ -1254,6 +1254,8 @@ void Inkling2::assign_scratch() { ds2_gate_ = fbuf(B * R); ds2_tki_ = (int32_t*) fbuf(B * 16); ds2_tkv_ = fbuf(B * 16); + ds2_ptki_ = (int32_t*) fbuf(B * kDs2TopKSplits * 16); + ds2_ptkv_ = fbuf(B * kDs2TopKSplits * 16); } if (!ds_ring_ && scratch_) ds_load(); } diff --git a/engine/src/poly/inkling2.cu b/engine/src/poly/inkling2.cu index 10d780d95f..e942cacb0a 100644 --- a/engine/src/poly/inkling2.cu +++ b/engine/src/poly/inkling2.cu @@ -5422,21 +5422,19 @@ __global__ void ds2_conv_kernel(const float* __restrict__ hidden, const float* _ out[(size_t) t * n + c] = sum; } -// Row r (blockIdx.x): the 16 largest of its first n_valid logits, in descending order (a tie: the lower id first). -// Each thread keeps the 16 largest of its strided share; then 16 rounds take the block's best head. -__global__ void __launch_bounds__(256) ds2_topk_kernel(const float* __restrict__ logits, size_t stride, int n_valid, - int32_t* __restrict__ idx, float* __restrict__ val) { +// The 16 largest of logits[lo, hi) (the ids are positions), in descending order (a tie: the lower id first), by one +// block of 256 threads: each keeps the 16 largest of its strided share, then 16 rounds take the block's best head. +__device__ __forceinline__ void d2_top16_range(const float* row, int lo, int hi, int32_t* out_i, float* out_v) { __shared__ float sv[256][kD2TopK + 1]; __shared__ int si[256][kD2TopK + 1]; __shared__ float wv[8]; __shared__ int wi[8], wt[8]; - const float* row = logits + (size_t) blockIdx.x * stride; const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; float lv[kD2TopK]; int li[kD2TopK]; #pragma unroll for (int j = 0; j < kD2TopK; ++j) lv[j] = -INFINITY, li[j] = 0x7fffffff; - for (int i = tid; i < n_valid; i += 256) { + for (int i = lo + tid; i < hi; i += 256) { float v = row[i]; int id = i; if (!(v > lv[kD2TopK - 1])) continue; // ids rise along the stride, so an equal value is never earlier @@ -5470,15 +5468,66 @@ __global__ void __launch_bounds__(256) ds2_topk_kernel(const float* __restrict__ int bi = wi[0], bw = wt[0]; for (int w = 1; w < 8; ++w) if (wv[w] > bv || (wv[w] == bv && wi[w] < bi)) bv = wv[w], bi = wi[w], bw = wt[w]; - if (tid == 0) { - idx[(size_t) blockIdx.x * kD2TopK + r] = bi; - val[(size_t) blockIdx.x * kD2TopK + r] = bv; - } + if (tid == 0) out_i[r] = bi, out_v[r] = bv; if (tid == bw) ++head; __syncthreads(); // wv, wi, wt are free again } } +// Split s of row r (blockIdx.x, blockIdx.y): the 16 largest of its share of the first n_valid logits, into its slot of +// the partials (kDs2TopKSplits slots a row). The shares are contiguous ranges, so a tie still has the lower id first. +__global__ void __launch_bounds__(256) ds2_topk_part_kernel(const float* __restrict__ logits, size_t stride, + int n_valid, int32_t* __restrict__ pidx, + float* __restrict__ pval) { + const int r = blockIdx.x, s = blockIdx.y; + const int chunk = (n_valid + kDs2TopKSplits - 1) / kDs2TopKSplits; + const int lo = min(s * chunk, n_valid), hi = min(lo + chunk, n_valid); + const size_t slot = ((size_t) r * kDs2TopKSplits + s) * kD2TopK; + d2_top16_range(logits + (size_t) r * stride, lo, hi, pidx + slot, pval + slot); +} + +// Row r (blockIdx.x): the 16 largest of its kDs2TopKSplits * 16 partial candidates, in descending order (a tie: the +// lower id first). Each round, every thread offers its best unused candidate (two per thread), the block takes the best. +__global__ void __launch_bounds__(256) ds2_topk_merge_kernel(const int32_t* __restrict__ pidx, + const float* __restrict__ pval, + int32_t* __restrict__ idx, float* __restrict__ val) { + constexpr int N = kDs2TopKSplits * kD2TopK; + __shared__ float cv[N]; + __shared__ int ci[N]; + __shared__ bool used[N]; + __shared__ float wv[8]; + __shared__ int wi[8], wk[8]; + const int r = blockIdx.x, tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + for (int k = tid; k < N; k += 256) cv[k] = pval[(size_t) r * N + k], ci[k] = pidx[(size_t) r * N + k], used[k] = false; + __syncthreads(); + for (int round = 0; round < kD2TopK; ++round) { + float bv = -INFINITY; + int bi = 0x7fffffff, bk = -1; + for (int k = tid; k < N; k += 256) { + if (used[k]) continue; + if (bk < 0 || cv[k] > bv || (cv[k] == bv && ci[k] < bi)) bv = cv[k], bi = ci[k], bk = k; + } + for (int o = 16; o > 0; o >>= 1) { + const float ov = __shfl_xor_sync(0xffffffff, bv, o, 32); + const int oi = __shfl_xor_sync(0xffffffff, bi, o, 32); + const int ok = __shfl_xor_sync(0xffffffff, bk, o, 32); + if (ok >= 0 && (bk < 0 || ov > bv || (ov == bv && oi < bi))) bv = ov, bi = oi, bk = ok; + } + if (lane == 0) wv[warp] = bv, wi[warp] = bi, wk[warp] = bk; + __syncthreads(); + if (tid == 0) { + float xv = wv[0]; + int xi = wi[0], xk = wk[0]; + for (int w = 1; w < 8; ++w) + if (wk[w] >= 0 && (xk < 0 || wv[w] > xv || (wv[w] == xv && wi[w] < xi))) xv = wv[w], xi = wi[w], xk = wk[w]; + idx[(size_t) r * kD2TopK + round] = xi; + val[(size_t) r * kD2TopK + round] = xv; + used[xk] = true; + } + __syncthreads(); + } +} + __device__ __forceinline__ float d2_bf16(uint16_t v) { return __uint_as_float(uint32_t(v) << 16); } // The selector's walk, one block of 512 threads (a warp a candidate): draft s, from the 16 candidates of mask row s + 1 @@ -5547,9 +5596,12 @@ void ds2_conv(const float* hidden, const float* dyn, int dyn_row, const float* b launched("ds2_conv"); } -void ds2_topk(const float* logits, size_t stride, int n_valid, int rows, int32_t* idx, float* val, void* stream) { - ds2_topk_kernel<<>>(logits, stride, n_valid, idx, val); +void ds2_topk(const float* logits, size_t stride, int n_valid, int rows, int32_t* idx, float* val, int32_t* pidx, + float* pval, void* stream) { + ds2_topk_part_kernel<<>>(logits, stride, n_valid, pidx, pval); launched("ds2_topk"); + ds2_topk_merge_kernel<<>>(pidx, pval, idx, val); + launched("ds2_topk_merge"); } void ds2_select(const int32_t* idx, const float* val, const float* gate, int rank, const uint16_t* prev_cb, diff --git a/engine/src/poly/inkling2.hpp b/engine/src/poly/inkling2.hpp index 91e1d835fd..f1d0be8354 100644 --- a/engine/src/poly/inkling2.hpp +++ b/engine/src/poly/inkling2.hpp @@ -242,6 +242,8 @@ class Inkling2 final : public Engine { float *ds2_cat_ = nullptr, *ds2_enc_ = nullptr, *ds2_dyn_ = nullptr, *ds2_cv_ = nullptr, *ds2_gate_ = nullptr, *ds2_tkv_ = nullptr; int32_t* ds2_tki_ = nullptr; + int32_t* ds2_ptki_ = nullptr; ///< ds2_topk()'s per-split candidates + float* ds2_ptkv_ = nullptr; static constexpr int kDsRing = 16; ///< positions whose Markov-head context ds_ring_ keeps static constexpr int kDsRows = 8; ///< a block's rows at most std::unique_ptr ds_file_; diff --git a/engine/src/poly/inkling2_kernels.hpp b/engine/src/poly/inkling2_kernels.hpp index 1b753b86fc..f6167ba04b 100644 --- a/engine/src/poly/inkling2_kernels.hpp +++ b/engine/src/poly/inkling2_kernels.hpp @@ -419,7 +419,9 @@ void ds2_conv(const float* hidden, const float* dyn, int dyn_row, const float* b int n, int rows, const float* acc, float* out, void* stream); /// The 16 largest of the first n_valid logits of each of `rows` rows (stride apart), descending, into idx and val /// (16 a row). -void ds2_topk(const float* logits, size_t stride, int n_valid, int rows, int32_t* idx, float* val, void* stream); +constexpr int kDs2TopKSplits = 32; // splits of the vocabulary per row in ds2_topk() +void ds2_topk(const float* logits, size_t stride, int n_valid, int rows, int32_t* idx, float* val, int32_t* pidx, + float* pval, void* stream); /// The selector's walk over `steps` (at most 7) mask rows: draft s is the best of row s's 16 candidates by cap tanh((logit /// + prev_cb[previous token] . gate[s] . succ_cb[candidate]) / cap), the previous token of the first the anchor /// (*anchor); BF16 codebooks [vocabulary][rank], gate steps x rank floats. The pick and its softmax probability over From fb856dd1f3daf887e480b2742ece2e9993942a29 Mon Sep 17 00:00:00 2001 From: Sarah Date: Fri, 27 Nov 2026 09:29:29 +0100 Subject: [PATCH 4/7] convert: DFlash2 selector codebooks stay BF16 under a q8_0 output type (refs #339) The engine reads selector_predecessor and selector_successor as BF16. The generic q8_0 path would quantize them. Co-Authored-By: Claude Haiku 5.5 --- .../third_party/strata-gguf-py/converter/conversion/qwen.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/engine/third_party/strata-gguf-py/converter/conversion/qwen.py b/engine/third_party/strata-gguf-py/converter/conversion/qwen.py index 99df1277f4..4b1c63076d 100644 --- a/engine/third_party/strata-gguf-py/converter/conversion/qwen.py +++ b/engine/third_party/strata-gguf-py/converter/conversion/qwen.py @@ -690,6 +690,12 @@ def set_vocab(self): if mask_token_id is not None: self.gguf_writer.add_mask_token_id(mask_token_id) + def tensor_force_quant(self, name, new_name, bid, n_dims): + # The DFlash2 selector's codebooks stay BF16 whatever the output type: the engine reads them as BF16. + if "selector_predecessor" in new_name or "selector_successor" in new_name: + return gguf.GGMLQuantizationType.BF16 + return super().tensor_force_quant(name, new_name, bid, n_dims) + def set_gguf_parameters(self): super().set_gguf_parameters() From dc5468a08e20ddd59659f7c900e36d179508cb6c Mon Sep 17 00:00:00 2001 From: Sarah Date: Fri, 27 Nov 2026 10:02:06 +0100 Subject: [PATCH 5/7] poly: DFlash2 head scored from 2-bit copies, the best rows exactly; Q4_0 and other matrix types load (refs #339) The DFlash2 drafter's head was one product of the target's whole output matrix (Q8_0, 469 MiB on Inkling 2 Mini), the largest part of its round. Now, where the output matrix is Q8_0 and the card holds every expert (STRATA_DS2_SCREEN=0 turns it off, =1 turns it on where the card does not), DSpark's 2-bit copies of the matrix score every token once for all the block's rows (ds_head_base()), the per-split best 16 of those scores are merged to the best 96 rows, which are scored exactly (Q8_0 row . q8_1 row, as the head's product does), and the exact 16 largest go to the selector as before (ds2_screen_topk()). The copy is about 144 MB of VRAM. The DFlash2 loader takes any matrix type the products take (Q8_0, Q4_0 ...), as the DSpark loader does since the last merge; before it took BF16 or Q8_0 only. Measured on an RTX 4060 (8 GB, sm_89), CUDA 13.4, Inkling-2-Mini-UD-Q4_K_XL, --window 4, the drafter forced into drafting (a test-only change, reverted: this card holds 790 of 3,072 experts), drafter GPU time a round from nsys: BF16 file 14.8 ms; Q8_0 file 3.8 ms; Q8_0 file with the screened head 2.5 ms (head 1.96 ms -> 0.67 ms). Against the exact head on two real prompts, 256 tokens (about 360 rows checked): the exact top 16's first entry found every time, 96 to 98% of its 16 entries found, the exact scores equal to 1e-5. Accepted guesses did not drop (code 119 of 214 against 116 of 238, prose 73 of 197 against 42 of 118). The drafter's extra GPU time over a 300-token prompt is about 3 ms with the Q8_0 file (the BF16 file's 320 ms was its slow products). Not checked: tokens a second against DSpark on a card that holds every expert; output equality with the undrafted run (two identical undrafted runs on this card already differ after 22 to 67 tokens, with and without --expert-swaps 0); HIP and SYCL builds; DSpark files. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018j62UGHq9crCFFy7fHrCcW --- docs/models/inkling.md | 14 ++++ engine/src/poly/inkling2.cpp | 29 ++++++- engine/src/poly/inkling2.cu | 120 +++++++++++++++++++++++++++ engine/src/poly/inkling2.hpp | 1 + engine/src/poly/inkling2_kernels.hpp | 4 + 5 files changed, 164 insertions(+), 4 deletions(-) diff --git a/docs/models/inkling.md b/docs/models/inkling.md index e8ff6a4cb6..2276a9ab06 100644 --- a/docs/models/inkling.md +++ b/docs/models/inkling.md @@ -310,6 +310,20 @@ are opt-in on an NVIDIA card (up to 16 slots), not with the draft file, not with On a Mac the engine takes one request at a time for this model, and the installer writes `"parallel": 1` there. Its license is Apache 2.0. +**DFlash2 drafter (`--draft-model` with `incoai/Inkling-2-Mini-DFlash2`).** `strata-poly` also takes the DFlash2 drafter as +the draft file: a GGUF with `selector_hidden.weight` runs as DFlash2, a DSpark file (`markov_w1.weight`) as before. Setup +does not download it yet. Convert it on your PC with `engine/third_party/strata-gguf-py/converter/convert_hf_to_gguf.py` +on the drafter's folder, `--target-model-dir` set to the Inkling 2 Mini folder (its `config.json` is enough) and +`--outtype q8_0`: the two selector codebooks stay BF16, the other matrices are Q8_0 (0.6 GB; `--outtype bf16` is 1.0 GB +and its products are several times slower). Like DSpark it guesses only where the card holds all of the model's experts. +Its head is scored from 2-bit copies of the output matrix (about 150 MB more VRAM) when that matrix is Q8_0 and the card +holds every expert, the best 96 rows then exactly; `STRATA_DS2_SCREEN=0` turns that off and `=1` turns it on for a card +that does not hold every expert. Measured on an RTX 4060 (8 GB, sm_89, CUDA 13.4), UD-Q4_K_XL, `--window 4`, the +drafter's GPU time a round is 14.8 ms with the BF16 file, 3.8 ms with Q8_0 and 2.5 ms with Q8_0 and the screened head +(the experts were forced into drafting there: this card holds 790 of 3,072). Its top 16 from the screen has the exact +top 16's first entry every time and 96 to 98% of the others (about 360 rows of two prompts). Not measured: tokens a +second against DSpark on a card that holds all the experts. + ## Install ```sh diff --git a/engine/src/poly/inkling2.cpp b/engine/src/poly/inkling2.cpp index e30e9ed66d..251a813865 100644 --- a/engine/src/poly/inkling2.cpp +++ b/engine/src/poly/inkling2.cpp @@ -427,7 +427,8 @@ void Inkling2::ds_load2() { const auto mat = [&](const std::string& name, uint64_t n_in, uint64_t n_out) { const TensorInfo* t = f.find(name); const uint32_t type = t ? t->type : 0; - find(name, type == kTypeBF16 ? kTypeBF16 : 8u, n_in, n_out); // BF16 or Q8_0 + // BF16, or a type the card's products take (lin(): Q8_0 as published, or a smaller quantization of it) + find(name, type == kTypeBF16 || kernels::native_mmvq_supported((int) type) ? type : 8u, n_in, n_out); return Dev{to_dev(t), type, (int) n_in, (int) n_out}; }; // a convolution's base [2][taps][n_embd] (the file names it without a suffix), F32 or BF16, to F32 on the card @@ -495,6 +496,18 @@ void Inkling2::ds_load2() { ds_at_ = (long long*) dmalloc((2 * kDsRows + 1) * sizeof(long long), "the drafter"); h_ds_row_ = (float*) hmalloc(E * 4, "pinned memory"); h_ds_at_ = (long long*) hmalloc((2 * kDsRows + 1) * sizeof(long long), "pinned memory"); + { // The screened head: 2-bit copies of the output matrix (Q8_0 [vocabulary][2304]) score every token once for all + // the block's rows, the best rows are then scored exactly (ds2_screen_topk()). On, as DSpark's, where the + // card holds every expert; STRATA_DS2_SCREEN=0 turns it off, =1 on where it does not. + const char* env = std::getenv("STRATA_DS2_SCREEN"); + const bool want = env ? env[0] != '0' : every_expert_fits(); + ds2_screen_ = want && output_.type == 8u && n_embd_ == 2304; + if (ds2_screen_) { + ds_head_sc_ = dmalloc(ds_screen_bytes(n_embd_, n_unpadded_), "the drafter"); + ds_screen_pack(output_.p, n_embd_, n_unpadded_, ds_head_sc_, st_, output_.type); + ck(cudaStreamSynchronize(cs(st_)), "the drafter's screen"); + } + } #endif } @@ -769,9 +782,17 @@ void Inkling2::ds_block2(int nb) { conv(ds_y_, L.f_base, 1, ds_x_, ds_x_); // x += the MLP's output through the second side } rms_norm(ds_x_ + E, ds_norm_, ds_h_, n_embd_, nd, ds_eps_, st_); - lin(output_, ds_h_, ds_base_, nd); - lin(ds2_sel_h_, ds_h_, ds2_gate_, nd); - ds2_topk(ds_base_, V, n_unpadded_, nd, ds2_tki_, ds2_tkv_, ds2_ptki_, ds2_ptkv_, st_); + if (ds2_screen_) { // the copies score every token, the best rows are scored exactly + kernels::native_quantize_q8_1(ds_h_, ds_hq_, n_embd_ * nd, 1, st_); + ds_head_base(ds_screen(), ds_hq_, nd, ds_approx_, st_); + lin(ds2_sel_h_, ds_h_, ds2_gate_, nd); + ds2_screen_topk(ds_approx_, ds_screen_rows(n_unpadded_), n_unpadded_, nd, ds_hq_, output_.p, ds2_tki_, ds2_tkv_, + ds2_ptki_, ds2_ptkv_, st_); + } else { + lin(output_, ds_h_, ds_base_, nd); + lin(ds2_sel_h_, ds_h_, ds2_gate_, nd); + ds2_topk(ds_base_, V, n_unpadded_, nd, ds2_tki_, ds2_tkv_, ds2_ptki_, ds2_ptkv_, st_); + } ds2_select(ds2_tki_, ds2_tkv_, ds2_gate_, ds_rank_, ds2_prev_cb_, ds2_succ_cb_, nd, ds_at_ + 2 * kDsRows, ds_cap_, ds_pick_, st_); ck(cudaMemcpyAsync(h_block_, ds_pick_, (size_t) nd * sizeof(Likeliest), cudaMemcpyDeviceToHost, cs(st_)), diff --git a/engine/src/poly/inkling2.cu b/engine/src/poly/inkling2.cu index c5b3177ec4..88596d220e 100644 --- a/engine/src/poly/inkling2.cu +++ b/engine/src/poly/inkling2.cu @@ -5627,6 +5627,115 @@ __global__ void __launch_bounds__(256) ds2_topk_merge_kernel(const int32_t* __re } } +// The screened head's top 16 (DFlash2): from the head copy's approximate scores, whose per-split 16 best are in the +// partials (copy rows and scores), the kD2Cand best approximate rows are scored exactly (Q8_0 row . q8_1 row, as the +// head's product does) and the exact 16 largest are the row's candidates, in descending order (a tie: the lower id +// first), as ds2_topk_merge_kernel writes them. A row past the vocabulary (the copy is padded to whole tiles) is +// never a candidate. Block r (blockIdx.x), 256 threads. +constexpr int kD2Cand = 96; // rows scored exactly +constexpr int kD2HeadBlocks = 72; // Q8_0 blocks of a 2,304-value row +__global__ void __launch_bounds__(256) ds2_screen_final_kernel(const int32_t* __restrict__ pidx, + const float* __restrict__ pval, + const QB* __restrict__ hq, + const uint8_t* __restrict__ head, int64_t tiles, + int n_tok, int32_t* __restrict__ idx, + float* __restrict__ val) { + constexpr int N = kDs2TopKSplits * kD2TopK; + __shared__ float cv[N]; + __shared__ int ct[N]; // the candidate's token, -1 for none + __shared__ bool used[N]; + __shared__ __align__(16) QB xq[kD2HeadBlocks]; + __shared__ int cand[kD2Cand]; + __shared__ float ev[kD2Cand]; + __shared__ bool taken[kD2Cand]; + __shared__ float wv[8]; + __shared__ int wk[8]; + const int r = blockIdx.x, tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + for (int k = tid; k < N; k += 256) { + const int row = pidx[(size_t) r * N + k]; + const float v = pval[(size_t) r * N + k]; + const int64_t tok = row == 0x7fffffff ? -1 : scr_token(row, tiles); + const bool ok = tok >= 0 && tok < n_tok; + cv[k] = ok ? v : -INFINITY; + ct[k] = ok ? (int) tok : -1; + used[k] = false; + } + for (int i = tid; i < kD2HeadBlocks * (int) sizeof(QB) / 4; i += 256) + reinterpret_cast(xq)[i] = reinterpret_cast(hq + (size_t) r * kD2HeadBlocks)[i]; + __syncthreads(); + // the kD2Cand best approximate rows + for (int round = 0; round < kD2Cand; ++round) { + float bv = -INFINITY; + int bk = -1; + for (int k = tid; k < N; k += 256) + if (!used[k] && ct[k] >= 0 && (bk < 0 || cv[k] > bv)) bv = cv[k], bk = k; + for (int o = 16; o > 0; o >>= 1) { + const float ov = __shfl_xor_sync(0xffffffff, bv, o, 32); + const int ok = __shfl_xor_sync(0xffffffff, bk, o, 32); + if (ok >= 0 && (bk < 0 || ov > bv || (ov == bv && ok < bk))) bv = ov, bk = ok; + } + if (lane == 0) wv[warp] = bv, wk[warp] = bk; + __syncthreads(); + if (tid == 0) { + float xv = wv[0]; + int xk = wk[0]; + for (int w = 1; w < 8; ++w) + if (wk[w] >= 0 && (xk < 0 || wv[w] > xv || (wv[w] == xv && wk[w] < xk))) xv = wv[w], xk = wk[w]; + cand[round] = xk >= 0 ? ct[xk] : -1; + if (xk >= 0) used[xk] = true; + taken[round] = false; + } + __syncthreads(); + } + // exact scores: a warp a candidate, its lanes the row's Q8_0 blocks (34 bytes: a half scale, 32 codes) + for (int c = warp; c < kD2Cand; c += 8) { + const int tok = cand[c]; + float acc = 0.0f; + if (tok >= 0) { + const uint8_t* row = head + (size_t) tok * kD2HeadBlocks * 34; + for (int b = lane; b < kD2HeadBlocks; b += 32) { + const uint8_t* blk = row + (size_t) b * 34; + const float dw = __half2float(*reinterpret_cast(blk)); + const uint16_t* wq = reinterpret_cast(blk + 2); + const int* xi = reinterpret_cast(xq[b].qs); + int sum = 0; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int w4 = (int) ((uint32_t) wq[2 * i] | ((uint32_t) wq[2 * i + 1] << 16)); + sum = __dp4a(w4, xi[i], sum); + } + acc += dw * __low2float(xq[b].ds) * (float) sum; + } + } + for (int o = 16; o > 0; o >>= 1) acc += __shfl_xor_sync(0xffffffff, acc, o, 32); + if (lane == 0) ev[c] = tok >= 0 ? acc : -INFINITY; + } + __syncthreads(); + // the 16 largest exact scores, a tie to the lower token id + if (warp == 0) { + for (int round = 0; round < kD2TopK; ++round) { + float bv = -INFINITY; + int bt = 0x7fffffff, bc = -1; + for (int c = lane; c < kD2Cand; c += 32) { + if (taken[c] || cand[c] < 0) continue; + if (bc < 0 || ev[c] > bv || (ev[c] == bv && cand[c] < bt)) bv = ev[c], bt = cand[c], bc = c; + } + for (int o = 16; o > 0; o >>= 1) { + const float ov = __shfl_xor_sync(0xffffffff, bv, o, 32); + const int ot = __shfl_xor_sync(0xffffffff, bt, o, 32); + const int oc = __shfl_xor_sync(0xffffffff, bc, o, 32); + if (oc >= 0 && (bc < 0 || ov > bv || (ov == bv && ot < bt))) bv = ov, bt = ot, bc = oc; + } + if (lane == 0) { + idx[(size_t) r * kD2TopK + round] = bc >= 0 ? bt : 0x7fffffff; + val[(size_t) r * kD2TopK + round] = bv; + if (bc >= 0) taken[bc] = true; + } + __syncwarp(); + } + } +} + __device__ __forceinline__ float d2_bf16(uint16_t v) { return __uint_as_float(uint32_t(v) << 16); } // The selector's walk, one block of 512 threads (a warp a candidate): draft s, from the 16 candidates of mask row s + 1 @@ -5703,6 +5812,17 @@ void ds2_topk(const float* logits, size_t stride, int n_valid, int rows, int32_t launched("ds2_topk_merge"); } +void ds2_screen_topk(const float* approx, int64_t n_pad, int64_t n_tok, int rows, const void* hq, const void* head, + int32_t* idx, float* val, int32_t* pidx, float* pval, void* stream) { + if (rows < 1 || rows > kDsDraftsMax) throw std::logic_error("ds2_screen_topk: 1 to 7 rows"); + ds2_topk_part_kernel<<>>(approx, (size_t) n_pad, (int) n_pad, pidx, + pval); + launched("ds2_screen_part"); + ds2_screen_final_kernel<<>>(pidx, pval, (const QB*) hq, (const uint8_t*) head, + scr_tiles(n_tok), (int) n_tok, idx, val); + launched("ds2_screen_final"); +} + void ds2_select(const int32_t* idx, const float* val, const float* gate, int rank, const uint16_t* prev_cb, const uint16_t* succ_cb, int steps, const long long* anchor, float cap, Likeliest* out, void* stream) { if (rank > kD2MaxRank) throw std::logic_error("ds2_select: the selector's rank is more than it holds"); diff --git a/engine/src/poly/inkling2.hpp b/engine/src/poly/inkling2.hpp index d00c4ab71d..928078b8b9 100644 --- a/engine/src/poly/inkling2.hpp +++ b/engine/src/poly/inkling2.hpp @@ -272,6 +272,7 @@ class Inkling2 final : public Engine { std::unique_ptr ds_file_; std::vector ds_; int ds_block_ = 0, ds_window_ = 0, ds_ff_ = 0, ds_rank_ = 0, ds_visit_[3] = {}; + bool ds2_screen_ = false; ///< the DFlash2 head scored from the 2-bit copies, the best rows exactly (ds2_screen_topk()) int ds_heads_ = 0; ///< the drafter's query heads (its own: 32 for Inkling 2 Mini DFlash2, the target's 24 differ) float ds_theta_ = 0, ds_eps_ = 0, ds_cap_ = 0; float *ds_alpha_ = nullptr, *ds_mask_ = nullptr, *ds_norm_ = nullptr, *ds_mnorm_ = nullptr, *ds_jb_ = nullptr, diff --git a/engine/src/poly/inkling2_kernels.hpp b/engine/src/poly/inkling2_kernels.hpp index 32d55a4488..f317eeeb03 100644 --- a/engine/src/poly/inkling2_kernels.hpp +++ b/engine/src/poly/inkling2_kernels.hpp @@ -431,6 +431,10 @@ void ds2_conv(const float* hidden, const float* dyn, int dyn_row, const float* b constexpr int kDs2TopKSplits = 32; // splits of the vocabulary per row in ds2_topk() void ds2_topk(const float* logits, size_t stride, int n_valid, int rows, int32_t* idx, float* val, int32_t* pidx, float* pval, void* stream); +/// ds2_topk() from the head copy's approximate scores (ds_head_base()'s: rows of n_pad copy-row scores) instead of the +/// exact logits: the best approximate rows are scored exactly from the Q8_0 head ([n_tok][2304]) and the q8_1 rows hq. +void ds2_screen_topk(const float* approx, int64_t n_pad, int64_t n_tok, int rows, const void* hq, const void* head, + int32_t* idx, float* val, int32_t* pidx, float* pval, void* stream); /// The selector's walk over `steps` (at most 7) mask rows: draft s is the best of row s's 16 candidates by cap tanh((logit /// + prev_cb[previous token] . gate[s] . succ_cb[candidate]) / cap), the previous token of the first the anchor /// (*anchor); BF16 codebooks [vocabulary][rank], gate steps x rank floats. The pick and its softmax probability over From 1a5ec9193132a0281fff1c2b2023c65c1140fefa Mon Sep 17 00:00:00 2001 From: Sarah Date: Fri, 27 Nov 2026 11:31:52 +0100 Subject: [PATCH 6/7] poly: DFlash2 reads its taps with the buffer's row stride, not the prompt layout's (refs #339) The target writes the drafter's feature taps with a stride of buf_rows_ rows (copy_rows(), ds_tap_ + k buf_rows_ E), and the DSpark commit reads them so. ds_commit2() read and wrote them with rows_. Where the engine keeps two scratch layouts (a card that does not hold every expert: one for a prompt batch, buf_rows_ = rows_, and one for a few tokens, buf_rows_ = 15), every call of a few tokens (decode, a window) then read taps 1 to 3 from offsets of 1,024 rows in a buffer of 15, and its final-state row was written 28 MB past the buffer: wrong features for the drafter, and a write outside its buffer, on every step of an answer whether or not the drafter guessed. A card that holds every expert has one layout (buf_rows_ = rows_), where the two strides are the same: nothing changes there. Measured on an RTX 4060 (8 GB, sm_89), CUDA 13.4, Inkling-2-Mini-UD-Q4_K_XL, DFlash2 Q8_0 file, --window 4 --lookup 0 (so every guess is the drafter's; the no-drafter run with lookup makes 10 of 30 and 2 of 9), 256 tokens, the drafter forced into drafting by a test-only change (reverted: this card holds 790 of 3,072 experts): code prompt: 113 of 220 guesses right, 40.4 tok/s -> 155 of 178 and 155 of 190 (two runs), 51.8 and 50.9 tok/s prose prompt: 40 of 121, 32.6 tok/s -> 115 of 165 and 118 of 209, 38.5 and 38.4 tok/s Not checked: a card that holds every expert (unchanged by construction, not run), HIP, SYCL, and Metal builds. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018j62UGHq9crCFFy7fHrCcW --- engine/src/poly/inkling2.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/engine/src/poly/inkling2.cpp b/engine/src/poly/inkling2.cpp index 251a813865..f54f573393 100644 --- a/engine/src/poly/inkling2.cpp +++ b/engine/src/poly/inkling2.cpp @@ -726,9 +726,9 @@ void Inkling2::ds_commit(int n) { void Inkling2::ds_commit2(int n) { #if !defined(STRATA_GPU_METAL) const size_t E = (size_t) n_embd_; - output_rows(0, n, ds_tap_ + 3 * (size_t) rows_ * E); + output_rows(0, n, ds_tap_ + 3 * (size_t) buf_rows_ * E); const DsPos p{recording_ ? at_ : nullptr, (long long) pos_}; - ds2_cat(ds_tap_, (size_t) rows_ * E, n_embd_, n, ds2_cat_, st_); + ds2_cat(ds_tap_, (size_t) buf_rows_ * E, n_embd_, n, ds2_cat_, st_); lin(ds2_fc_, ds2_cat_, ds_mix_, n); rms_norm(ds_mix_, ds2_enc_norm_, ds2_enc_, n_embd_, n, ds_eps_, st_); for (size_t l = 0; l < ds_.size(); ++l) { From a61959b08f038e204ddc0126cbc64148c2ca5e7f Mon Sep 17 00:00:00 2001 From: Sarah Date: Fri, 27 Nov 2026 11:49:08 +0100 Subject: [PATCH 7/7] poly: DFlash2 review fixes: a ring that a big prompt batch overran, an unguarded candidate, unchecked taps and softcap mode (refs #339) From a read of the DFlash2 code against SGLang's patch, the llama.cpp port's converter and the TensorRT Edge-LLM drafter: - ds_commit(), ds_commit2(): a layer's key/value ring holds L.cap positions (the window and 64), and ds_rope() writes every row to cell pos % cap. A call of more rows than that (a prompt batch over 2,112 tokens, --prompt-batch 4096) put two rows in one cell in one launch, so a key could land beside another row's value and tag. Now only the last L.cap rows are written. (ds_commit() is DSpark's, which has the same loop.) Read from the code, not shown to fail here: 7,000 tokens of Python source read in 4,096 batches write the same guesses as in 1,024 batches (63 of 73 both ways, two runs), so nothing regressed. - ds2_select(): a candidate id out of range (the 0x7fffffff the top-16 writes where fewer than 16 rows are valid, which only a NaN row does) indexed the codebook out of range. Now it scores -inf, and a step with no candidate returns its previous token with probability 0. - ds_open(): the three run-input taps must be increasing and below the final state's visit; a tap no visit matched left its rows as they were. The selector's softcap mode is checked: only after_correction is run (SGLang's default for a file that names none is before_correction). The converter now refuses any other mode and writes dflash.selector_softcap_after_correction; a file written without it (every file so far) is read as after_correction. The error says DSpark or DFlash2. Measured on an RTX 4060 (8 GB, sm_89), CUDA 13.4, UD-Q4_K_XL, the DFlash2 Q8_0 file, --window 4 --lookup 0, drafter forced on by a test-only change (reverted): code prompt 157 of 188 guesses right (before: 155 of 178 and 190), prose 124 of 210 (115 of 165, 118 of 209); a file without the new key loads and drafts (161 of 186). Not checked: a card that holds every expert, HIP, SYCL, Metal. Not changed, seen in the review: the attention's key span is the first row's, so rows after it see up to 7 of the oldest keys that SGLang's rule (qpos - p < window) hides, once the context passes the 2,048-token window; and the selector's probability is a softmax over 16 candidates, not the vocabulary, so --spec-min-p means something else than for DSpark. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018j62UGHq9crCFFy7fHrCcW --- engine/src/poly/inkling2.cpp | 29 +++++++++++++++---- engine/src/poly/inkling2.cu | 28 +++++++++++------- engine/src/poly/inkling2_kernels.hpp | 3 +- .../converter/conversion/qwen.py | 8 +++++ 4 files changed, 52 insertions(+), 16 deletions(-) diff --git a/engine/src/poly/inkling2.cpp b/engine/src/poly/inkling2.cpp index f54f573393..03551c91cb 100644 --- a/engine/src/poly/inkling2.cpp +++ b/engine/src/poly/inkling2.cpp @@ -343,7 +343,7 @@ void Inkling2::load_geometry() { void Inkling2::ds_open() { ds_file_ = std::make_unique(opt_.draft_model); const auto need = [&](bool ok, const std::string& what) { - if (!ok) throw std::runtime_error(opt_.draft_model + ": not a DSpark drafter of this model (" + what + ")"); + if (!ok) throw std::runtime_error(opt_.draft_model + ": not a DSpark or DFlash2 drafter of this model (" + what + ")"); }; const MetaValue* arch = ds_file_->get("general.architecture"); // a DFlash2 file (a candidate selector) or a DSpark file (a Markov head) @@ -385,7 +385,14 @@ void Inkling2::ds_open() { targets->items.size() == 4 && (int) targets->items[3].u == visits, "a window pattern a layer, three layer runs and the final state as its features"); for (int k = 0; k < 3; ++k) ds_visit_[k] = (int) targets->items[(size_t) k].u; - if (ds2_) { + // the three run inputs are visits of the loop, in order, before the final state (a tap that no visit matches would + // leave its rows as they were) + need(ds_visit_[0] >= 0 && ds_visit_[0] < ds_visit_[1] && ds_visit_[1] < ds_visit_[2] && ds_visit_[2] < visits, + "three increasing layer runs before the final state"); if (ds2_) { + // The trained selector softcaps its scores after adding the correction (selector_softcap_mode after_correction); + // the engine has no other mode. A file written before this key existed is the same mode. + const MetaValue* after = ds_file_->get("dflash.selector_softcap_after_correction"); + need(!after || after->u != 0, "selector_softcap_mode after_correction"); ds2_taps_ = (int) key("conv_kernel_size")->u; ds2_group_ = (int) key("conv_group_size")->u; ds2_topk_ = (int) key("selector_top_k")->u; @@ -717,7 +724,14 @@ void Inkling2::ds_commit(int n) { DsLayer& L = ds_[l]; lin(L.k_ctx, ds_mix_ + l * (size_t) n * E, ds_k_, n); lin(L.v_ctx, ds_mix_ + l * (size_t) n * E, ds_v_, n); - ds_rope(ds_k_, n_kv_, n, L.k_ctx_norm, ds_eps_, ds_theta_, p, L.keys, L.cap, ds_v_, L.vals, st_, L.tags); + // A layer's ring holds L.cap positions: of a call's rows the last L.cap are written, for a row's cell is also a + // later row's when the call has more rows than that (a prompt batch over the window), and the two would race. + const int skip = !p.at && (int64_t) n > L.cap ? (int) ((int64_t) n - L.cap) : 0; + DsPos ps = p; + ps.pos0 += skip; + const size_t kv = (size_t) n_kv_ * head_dim_; + ds_rope(ds_k_ + (size_t) skip * kv, n_kv_, n - skip, L.k_ctx_norm, ds_eps_, ds_theta_, ps, L.keys, L.cap, + ds_v_ + (size_t) skip * kv, L.vals, st_, L.tags); } } @@ -735,7 +749,12 @@ void Inkling2::ds_commit2(int n) { DsLayer& L = ds_[l]; lin(L.wk, ds2_enc_, ds_k_, n); lin(L.wv, ds2_enc_, ds_v_, n); - ds_rope(ds_k_, n_kv_, n, L.k_ctx_norm, ds_eps_, ds_theta_, p, L.keys, L.cap, ds_v_, L.vals, st_, L.tags); + const int skip = !p.at && (int64_t) n > L.cap ? (int) ((int64_t) n - L.cap) : 0; // as in ds_commit() + DsPos ps = p; + ps.pos0 += skip; + const size_t kv = (size_t) n_kv_ * head_dim_; + ds_rope(ds_k_ + (size_t) skip * kv, n_kv_, n - skip, L.k_ctx_norm, ds_eps_, ds_theta_, ps, L.keys, L.cap, + ds_v_ + (size_t) skip * kv, L.vals, st_, L.tags); } #endif } @@ -794,7 +813,7 @@ void Inkling2::ds_block2(int nb) { ds2_topk(ds_base_, V, n_unpadded_, nd, ds2_tki_, ds2_tkv_, ds2_ptki_, ds2_ptkv_, st_); } ds2_select(ds2_tki_, ds2_tkv_, ds2_gate_, ds_rank_, ds2_prev_cb_, ds2_succ_cb_, nd, ds_at_ + 2 * kDsRows, ds_cap_, - ds_pick_, st_); + (int) n_unpadded_, ds_pick_, st_); ck(cudaMemcpyAsync(h_block_, ds_pick_, (size_t) nd * sizeof(Likeliest), cudaMemcpyDeviceToHost, cs(st_)), "the drafter"); #endif diff --git a/engine/src/poly/inkling2.cu b/engine/src/poly/inkling2.cu index 88596d220e..7ace92e066 100644 --- a/engine/src/poly/inkling2.cu +++ b/engine/src/poly/inkling2.cu @@ -5747,7 +5747,7 @@ __global__ void __launch_bounds__(512) ds2_select_kernel(const int32_t* __restri const float* __restrict__ gate, int rank, const uint16_t* __restrict__ prev_cb, const uint16_t* __restrict__ succ_cb, int steps, - const long long* __restrict__ anchor, float cap, + const long long* __restrict__ anchor, float cap, int n_tok, Likeliest* __restrict__ out) { __shared__ float pred[kD2MaxRank]; __shared__ float score[kD2TopK]; @@ -5760,12 +5760,14 @@ __global__ void __launch_bounds__(512) ds2_select_kernel(const int32_t* __restri pred[r] = d2_bf16(prev_cb[(size_t) prev * rank + r]) * gate[(size_t) s * rank + r]; __syncthreads(); const int cand = idx[s * kD2TopK + warp]; + const bool real = cand >= 0 && cand < n_tok; // (never a candidate's id otherwise, but a NaN row has none) float dot = 0.0f; - for (int r = lane; r < rank; r += 32) dot = fmaf(pred[r], d2_bf16(succ_cb[(size_t) cand * rank + r]), dot); + if (real) + for (int r = lane; r < rank; r += 32) dot = fmaf(pred[r], d2_bf16(succ_cb[(size_t) cand * rank + r]), dot); dot = warp_sum(dot); if (lane == 0) { const float x = val[s * kD2TopK + warp] + dot; - score[warp] = cap > 0.0f ? cap * tanhf(x / cap) : x; + score[warp] = !real ? -INFINITY : cap > 0.0f ? cap * tanhf(x / cap) : x; } __syncthreads(); if (tid == 0) { @@ -5774,11 +5776,16 @@ __global__ void __launch_bounds__(512) ds2_select_kernel(const int32_t* __restri if (score[k] > score[best] || (score[k] == score[best] && idx[s * kD2TopK + k] < idx[s * kD2TopK + best])) best = k; - float z = 0.0f; - for (int k = 0; k < kD2TopK; ++k) z += __expf(score[k] - score[best]); - out[s].token = idx[s * kD2TopK + best]; - out[s].prob = 1.0f / z; - prev = out[s].token; + if (!(score[best] > -INFINITY)) { // no candidate: a token that cannot be taken, with no confidence + out[s].token = prev; + out[s].prob = 0.0f; + } else { + float z = 0.0f; + for (int k = 0; k < kD2TopK; ++k) z += __expf(score[k] - score[best]); + out[s].token = idx[s * kD2TopK + best]; + out[s].prob = 1.0f / z; + prev = out[s].token; + } } __syncthreads(); } @@ -5824,9 +5831,10 @@ void ds2_screen_topk(const float* approx, int64_t n_pad, int64_t n_tok, int rows } void ds2_select(const int32_t* idx, const float* val, const float* gate, int rank, const uint16_t* prev_cb, - const uint16_t* succ_cb, int steps, const long long* anchor, float cap, Likeliest* out, void* stream) { + const uint16_t* succ_cb, int steps, const long long* anchor, float cap, int n_tok, Likeliest* out, + void* stream) { if (rank > kD2MaxRank) throw std::logic_error("ds2_select: the selector's rank is more than it holds"); - ds2_select_kernel<<<1, 512, 0, cs(stream)>>>(idx, val, gate, rank, prev_cb, succ_cb, steps, anchor, cap, out); + ds2_select_kernel<<<1, 512, 0, cs(stream)>>>(idx, val, gate, rank, prev_cb, succ_cb, steps, anchor, cap, n_tok, out); launched("ds2_select"); } diff --git a/engine/src/poly/inkling2_kernels.hpp b/engine/src/poly/inkling2_kernels.hpp index f317eeeb03..69da710da2 100644 --- a/engine/src/poly/inkling2_kernels.hpp +++ b/engine/src/poly/inkling2_kernels.hpp @@ -440,7 +440,8 @@ void ds2_screen_topk(const float* approx, int64_t n_pad, int64_t n_tok, int rows /// (*anchor); BF16 codebooks [vocabulary][rank], gate steps x rank floats. The pick and its softmax probability over /// the 16 into out. void ds2_select(const int32_t* idx, const float* val, const float* gate, int rank, const uint16_t* prev_cb, - const uint16_t* succ_cb, int steps, const long long* anchor, float cap, Likeliest* out, void* stream); + const uint16_t* succ_cb, int steps, const long long* anchor, float cap, int n_tok, Likeliest* out, + void* stream); #endif /// A draft's pick from its scores cap tanh((base + fy + fb) / cap) over the first n_keep tokens: the lowest id of the /// largest and its softmax probability into out, the id into prev too. scratch: ds_pick_floats() floats. diff --git a/engine/third_party/strata-gguf-py/converter/conversion/qwen.py b/engine/third_party/strata-gguf-py/converter/conversion/qwen.py index 4b1c63076d..ba053ff255 100644 --- a/engine/third_party/strata-gguf-py/converter/conversion/qwen.py +++ b/engine/third_party/strata-gguf-py/converter/conversion/qwen.py @@ -725,6 +725,14 @@ def set_gguf_parameters(self): if embedding_scale is not None: self.gguf_writer.add_embedding_scale(float(embedding_scale)) + if (self.hparams.get("architectures") or [""])[0] == "DFlash2DraftModel": + # The trained selector softcaps its scores after adding the correction; a drafter without the field is the + # other mode (SGLang's default, before_correction), which the engine does not run: refuse it here. + mode = dflash_config.get("selector_softcap_mode", "before_correction") + if mode != "after_correction": + raise ValueError(f"DFlash2 selector_softcap_mode {mode!r} is not supported (after_correction only)") + self.gguf_writer.add_bool(f"{self.gguf_writer.arch}.selector_softcap_after_correction", True) + target_layer_ids = dflash_config.get("target_layer_ids", []) if target_layer_ids: # DFlash2 (incoai) names hidden_states indices, the last one the final state (48 of 48 layers): no shift.