From 73671b432fc7a118a4cca67b258fcc75ecc8aacd Mon Sep 17 00:00:00 2001 From: Sarah Date: Thu, 26 Nov 2026 11:34:13 +0100 Subject: [PATCH 1/3] 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 58c3e0f48..37ef83e21 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 687311cdd..9c1d65a3e 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 89a4a647a..5b3d65773 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 5bb4e771f..1b753b86f 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/3] 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 37ef83e21..6a2ea6280 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 9c1d65a3e..10d780d95 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 5b3d65773..91e1d835f 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 c7e0809f3..99df1277f 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/3] 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 6a2ea6280..3784bc4a3 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 10d780d95..e942cacb0 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 91e1d835f..f1d0be835 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 1b753b86f..f6167ba04 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