Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
qwen35: faster decode kernels with the old kernels' bits (STRATA_Q36_VERIFY=1 compares them on real activations)
Niko1221c9e7f6dd5afb
diff --git a/src/qwen35/q36_engine.cu b/src/qwen35/q36_engine.cuindex 04cbbe623..0c5479525 100644--- a/src/qwen35/q36_engine.cu+++ b/src/qwen35/q36_engine.cu@@ -26,6 +26,7 @@#include "strata/prefill/gemm.hpp"#include "strata/prefill/moe_mmq.hpp"#include "strata/qwen35/engine.hpp"+#include "q36_kernels.cuh"#if defined(STRATA_Q36_CPU_POOL)#include "strata/kernels/cpu/native_expert.hpp"#include "strata/kernels/cpu/pool.hpp"@@ -77,6 +78,7 @@ double ms_since(Clock::time_point t) { return std::chrono::duration<double, std:constexpr int kThreads = 256;constexpr int kChunkCells = 256; // attention split-K chunk+constexpr int kConvTile = 16; // tokens per block of the prompt conv (k_conv_seq tile mode)// ------------------------------------------------------------------------------------------------ small kernels__device__ __forceinline__ float silu(float v) { return v / (1.0f + expf(-v)); }@@ -615,9 +617,31 @@ __global__ void __launch_bounds__(128) k_conv_seq(float* hist, const float* qkv,}const int c = blockIdx.x * 128 + threadIdx.x;float v0 = hist[c * 3], v1 = hist[c * 3 + 1], v2 = hist[c * 3 + 2];+ // TILE mode (a prompt chunk: grid y > 1, no batch tables): the tiles of kConvTile tokens run side by side. A tile's history+ // is the three inputs before its first token (exactly the values the sequential loop carries); tile 0 reads the old history,+ // and, as the only writer, stores the new one: the last three of (old history, inputs). The arithmetic per token is the same.+ int t_first = 0, t_end = T;+ if (hist_tab == nullptr && gridDim.y > 1) {+ t_first = (int) blockIdx.y * kConvTile;+ t_end = min(T, t_first + kConvTile);+ if (t_first == 0 && write) {+ const float o0 = v0, o1 = v1, o2 = v2;+ const float old3[3] = {o0, o1, o2};+ for (int k = 0; k < 3; ++k) {+ const int idx = T - 3 + k;+ hist[c * 3 + k] = idx >= 0 ? qkv[(size_t) idx * C + c] : old3[idx + 3];+ }+ }+ if (t_first > 0) {+ v0 = qkv[(size_t) (t_first - 3) * C + c];+ v1 = qkv[(size_t) (t_first - 2) * C + c];+ v2 = qkv[(size_t) (t_first - 1) * C + c];+ }+ if (t_first >= T) return;+ }const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3];const bool qk = (int) blockIdx.x < qk_heads;- for (int t = 0; t < T; ++t) {+ for (int t = t_first; t < t_end; ++t) {const float x = qkv[(size_t) t * C + c];const float sum = v0 * w0 + v1 * w1 + v2 * w2 + x * w3;v0 = v1;@@ -635,7 +659,7 @@ __global__ void __launch_bounds__(128) k_conv_seq(float* hist, const float* qkv,}h[(size_t) t * C + c] = y;}- if (!write) return; // a verify window: the history is commit()'s to move+ if (!write || gridDim.y > 1) return; // a verify window: the history is commit()'s to move; tiles: tile 0 stored ithist[c * 3] = v0;hist[c * 3 + 1] = v1;hist[c * 3 + 2] = v2;@@ -1498,8 +1522,297 @@ struct Engine {}/// x [T][n] -> its q8_1 image (T contiguous columns: one vector of T * n), for every matrix that reads x.void quant(const float* xin, int n, int T, void* q) { K::native_quantize_q8_1(xin, q, n * T, 1, st); }+ // ---- decode kernels of this engine (q36_kernels.cuh), each the old kernel's bits (STRATA_Q36_VERIFY=1 compares)+ bool fast_k = std::getenv("STRATA_Q36_OLD_KERNELS") == nullptr;+ bool verify_k = std::getenv("STRATA_Q36_VERIFY") != nullptr;+ float* vbuf = nullptr; // verify scratch+ long long v_calls = 0, v_bad = 0;+ std::map<std::string, long long> v_by; // mismatches per check+ void verify_cmp(const char* what, const float* a, const float* b, size_t n, const std::string& tag = "") {+ CK(cudaStreamSynchronize(st));+ std::vector<float> ha(n), hb(n);+ CK(cudaMemcpy(ha.data(), a, n * 4, cudaMemcpyDeviceToHost));+ CK(cudaMemcpy(hb.data(), b, n * 4, cudaMemcpyDeviceToHost));+ ++v_calls;+ if (std::memcmp(ha.data(), hb.data(), n * 4) != 0) {+ ++v_bad;+ size_t i = 0;+ while (i < n && std::memcmp(&ha[i], &hb[i], 4) == 0) ++i;+ if (++v_by[what] <= 3)+ std::fprintf(stderr, "strata-q36 VERIFY MISMATCH %s%s: first at %zu of %zu: new %g old %g (bits %08x %08x)\n", what,+ tag.c_str(), i, n, (double) ha[i], (double) hb[i], *(unsigned*) &ha[i], *(unsigned*) &hb[i]);+ }+ }+ /// A Q8_0 matrix that is not on the packed decode kernel (the shared expert, attention k / v: fewer than 2048+ /// rows) for T <= 8 columns: one warp per row (q36k::k_q8_rows) in place of the 4-warp block of+ /// native_small_mmvq_kernel; the same bits.+ bool q8_small(const Mat& w, const void* q, float* out, int T) {+ if (!fast_k || w.type != 8 || T < 1 || T > 8 || w.n_in % 32 != 0) return false;+ if (K::native_q8_0_packed_eligible(w.n_in, w.n_out) && K::native_q8_0_packed_enabled()) return false;+ const int nb = w.n_in / 32;+ if (nb > 64) return false;+ const void* wp = w.d;+ const half* dpl = nullptr;+ const int NJ = nb <= 32 ? 1 : 2;+#define Q36_Q8(NCV) \+ case NCV: \+ if (NJ == 1) q36k::launch_q8_rows<NCV, 1, false>(wp, dpl, q, out, nb, w.n_out, st); \+ else q36k::launch_q8_rows<NCV, 2, false>(wp, dpl, q, out, nb, w.n_out, st); \+ break;+ switch (T) { Q36_Q8(1) Q36_Q8(2) Q36_Q8(3) Q36_Q8(4) Q36_Q8(5) Q36_Q8(6) Q36_Q8(7) Q36_Q8(8) }+#undef Q36_Q8+ if (verify_k) {+ if (!vbuf) CK(cudaMalloc((void**) &vbuf, (size_t) 8 * 16384 * 4));+ const size_t qb = K::native_q8_1_bytes(w.n_in, 1);+ for (int c0 = 0; c0 < T; c0 += 8) {+ const int nc = std::min(8, T - c0);+ K::native_mmvq(w.type, w.d, (const char*) q + (size_t) c0 * qb, vbuf + (size_t) c0 * w.n_out, w.n_in, w.n_out,+ nc, st);+ }+ verify_cmp("q8_small", out, vbuf, (size_t) T * w.n_out,+ " n_in " + std::to_string(w.n_in) + " n_out " + std::to_string(w.n_out) + " T " + std::to_string(T));+ }+ return true;+ }+ // ---- the q8_1 images produced by the norm kernels themselves (fast_k, T <= kGemmT): xq_ready = the layer's input h is+ // already quantized in xq (k_moe_out_small of the layer before), xq_post = the MoE input h is (k_add_rms_q)+ bool xq_ready = false, xq_post = false;+ void* vq = nullptr;+ void verify_q8(const char* what, const float* hsrc, int T, const std::string& tag) {+ const int N = (int) m->g.n_embd;+ const size_t qb = K::native_q8_1_bytes(N, 1);+ if (!vq) CK(cudaMalloc(&vq, qb * 8));+ K::native_quantize_q8_1(hsrc, vq, N * T, 1, st);+ const long long before = v_bad;+ verify_cmp(what, (const float*) xq, (const float*) vq, qb * (size_t) T / 4, tag);+ if (v_bad != before && std::getenv("STRATA_Q36_VDEBUG") && v_by[what] <= 2) { // a mismatching block, on the host+ std::vector<uint8_t> a(qb * (size_t) T), b(qb * (size_t) T);+ std::vector<float> hv((size_t) N * T);+ CK(cudaMemcpy(a.data(), xq, a.size(), cudaMemcpyDeviceToHost));+ CK(cudaMemcpy(b.data(), vq, b.size(), cudaMemcpyDeviceToHost));+ CK(cudaMemcpy(hv.data(), hsrc, hv.size() * 4, cudaMemcpyDeviceToHost));+ for (size_t o = 0; o < a.size(); o += 36)+ if (std::memcmp(&a[o], &b[o], 36) != 0) {+ const size_t blk = o / 36;+ float v[32], t[32];+ for (int l = 0; l < 32; ++l) v[l] = t[l] = hv[blk * 32 + (size_t) l];+ for (int off = 16; off > 0; off >>= 1) { // the xor butterfly, lane by lane+ float u[32];+ for (int l = 0; l < 32; ++l) u[l] = t[l] + t[l ^ off];+ std::memcpy(t, u, sizeof(u));+ }+ unsigned ds_a, ds_b;+ std::memcpy(&ds_a, &a[o], 4);+ std::memcpy(&ds_b, &b[o], 4);+ std::fprintf(stderr, "VDEBUG block %zu: ds new %08x old %08x, qs bytes %s, cpu butterfly sum %.9g (half %04x)\n",+ blk, ds_a, ds_b, std::memcmp(&a[o + 4], &b[o + 4], 32) == 0 ? "equal" : "DIFFER", (double) t[0],+ (unsigned) __half_as_ushort(__float2half(t[0])));+ break;+ }+ }+ }+ void prep_in(int T) {+ if (xq_ready && T <= kGemmT) {+ xq_ready = false;+ return;+ }+ xq_ready = false;+ prep(h, (int) m->g.n_embd, T, xq);+ }+ void add_rms_post(const Layer& L, int T) {+ const int N = (int) m->g.n_embd;+ xq_post = false;+ if (fast_k && T <= kGemmT) {+ if (verify_k) {+ if (!vx_) {+ CK(cudaMalloc((void**) &vx_, (size_t) 8 * 2048 * 4));+ CK(cudaMalloc((void**) &vh_, (size_t) 8 * 2048 * 4));+ }+ CK(cudaMemcpyAsync(vx_, x, (size_t) T * N * 4, cudaMemcpyDeviceToDevice, st));+ k_add_rms<<<T, kThreads, 0, st>>>(vx_, y, L.post_norm, vh_, N, m->eps);+ }+ q36k::k_add_rms_q<<<T, 256, 0, st>>>(x, y, L.post_norm, h, (q36k::QB*) xq, N, m->eps);+ xq_post = true;+ if (verify_k) {+ verify_cmp("add_rms x", x, vx_, (size_t) T * N, " T " + std::to_string(T));+ verify_cmp("add_rms h", h, vh_, (size_t) T * N, " T " + std::to_string(T));+ verify_q8("add_rms q8", h, T, " T " + std::to_string(T));+ }+ return;+ }+ k_add_rms<<<T, kThreads, 0, st>>>(x, y, L.post_norm, h, N, m->eps);+ }+ /// The shared expert's gate + up + SwiGLU + q8_1 image (into q8) for T <= 4 rows in one launch (q36k::k_sh_gu), else false.+ bool shared_gu(const Layer& L, int T) {+ const int FS = (int) m->g.n_ff_shexp;+ const Mat &a = L.sh_gate, &b = L.sh_up;+ if (!fast_k || T < 1 || T > 4 || a.type != 8 || b.type != 8 || a.n_in != b.n_in || a.n_out != FS || b.n_out != FS ||+ a.n_in % 32 != 0 || a.n_in / 32 > 64 || a.n_in / 32 <= 32 || FS % 32 != 0 ||+ (K::native_q8_0_packed_eligible(a.n_in, a.n_out) && K::native_q8_0_packed_enabled()))+ return false;+ const int nb = a.n_in / 32;+ const dim3 grid((unsigned) (FS / 32));+ const bool pkd = false;+ const uint8_t* wa = a.d;+ const uint8_t* wb = b.d;+ const half* da = nullptr;+ const half* db = nullptr;+#define Q36_SH(NCV) \+ case NCV: \+ if (pkd) \+ q36k::k_sh_gu<NCV, 2, true><<<grid, 1024, 0, st>>>(wa, da, wb, db, (const q36k::QB*) xq, \+ (q36k::QB*) q8, nb, FS); \+ else \+ q36k::k_sh_gu<NCV, 2, false><<<grid, 1024, 0, st>>>(wa, nullptr, wb, nullptr, (const q36k::QB*) xq, \+ (q36k::QB*) q8, nb, FS); \+ break;+ switch (T) { Q36_SH(1) Q36_SH(2) Q36_SH(3) Q36_SH(4) }+#undef Q36_SH+ if (verify_k) {+ if (!vbuf) CK(cudaMalloc((void**) &vbuf, (size_t) 8 * 16384 * 4));+ if (!vq) CK(cudaMalloc(&vq, K::native_q8_1_bytes(m->g.n_embd, 1) * 8));+ float* vg = vbuf;+ float* vu = vbuf + (size_t) 8 * FS;+ mmq_ref(a, xq, vg, T);+ mmq_ref(b, xq, vu, T);+ K::native_swiglu_quantize_q8_1(vg, vu, vq, FS, T, st);+ verify_cmp("shared_gu q8", (const float*) q8, (const float*) vq, K::native_q8_1_bytes(FS, 1) * (size_t) T / 4,+ " T " + std::to_string(T));+ }+ return true;+ }+ /// The old products (native MMVQ), for the checks.+ void mmq_ref(const Mat& w, const void* q, float* out, int T) {+ const size_t qb = K::native_q8_1_bytes(w.n_in, 1);+ for (int c0 = 0; c0 < T; c0 += 8) {+ const int nc = std::min(8, T - c0);+ K::native_mmvq(w.type, w.d, (const char*) q + (size_t) c0 * qb, out + (size_t) c0 * w.n_out, w.n_in, w.n_out, nc, st);+ }+ }+ void group_old(const Layer& L, const int32_t* slot_of, int T, unsigned long long* o_ptr, int32_t* o_start, int32_t* o_ng,+ int32_t* o_dst, int32_t* o_tok) {+ const int Kp = (int) m->top_k, n_ent = T * Kp;+ if (slot_of)+ k_group_hy<<<1, kThreads, 0, st>>>(ids, n_ent, Kp, (int) m->g.n_expert, slot_of, L.blobs, L.stride, o_ptr, o_start,+ o_ng, o_dst, o_tok);+ else+ k_group<<<1, kThreads, 0, st>>>(ids, n_ent, Kp, (int) m->g.n_expert, L.blobs, L.stride, o_ptr, o_start, o_ng, o_dst,+ o_tok);+ }+ /// VERIFY: the old grouping of the current `ids` into scratch, compared with grp_ptr / grp_start / n_groups / ent_dst / ent_tok.+ void group_verify(const Layer& L, const int32_t* slot_of, int T) {+ if (!vgrp) CK(cudaMalloc((void**) &vgrp, 2048));+ unsigned long long* o_ptr = (unsigned long long*) vgrp;+ int32_t* o_start = (int32_t*) (o_ptr + 65);+ int32_t* o_ng = o_start + 66;+ int32_t* o_dst = o_ng + 2;+ int32_t* o_tok = o_dst + 64;+ group_old(L, slot_of, T, o_ptr, o_start, o_ng, o_dst, o_tok);+ CK(cudaStreamSynchronize(st));+ int nn = 0, no = 0;+ CK(cudaMemcpy(&nn, n_groups, 4, cudaMemcpyDeviceToHost));+ CK(cudaMemcpy(&no, o_ng, 4, cudaMemcpyDeviceToHost));+ ++v_calls;+ bool bad = nn != no;+ if (!bad) {+ std::vector<unsigned long long> a((size_t) nn + 1), b((size_t) nn + 1);+ std::vector<int32_t> sa((size_t) nn + 1), sb((size_t) nn + 1), da(64), db(64), ta(64), tb(64);+ CK(cudaMemcpy(a.data(), grp_ptr, (size_t) nn * 8, cudaMemcpyDeviceToHost));+ CK(cudaMemcpy(b.data(), o_ptr, (size_t) nn * 8, cudaMemcpyDeviceToHost));+ CK(cudaMemcpy(sa.data(), grp_start, ((size_t) nn + 1) * 4, cudaMemcpyDeviceToHost));+ CK(cudaMemcpy(sb.data(), o_start, ((size_t) nn + 1) * 4, cudaMemcpyDeviceToHost));+ const int tot = sa[(size_t) nn];+ CK(cudaMemcpy(da.data(), ent_dst, (size_t) tot * 4, cudaMemcpyDeviceToHost));+ CK(cudaMemcpy(db.data(), o_dst, (size_t) tot * 4, cudaMemcpyDeviceToHost));+ CK(cudaMemcpy(ta.data(), ent_tok, (size_t) tot * 4, cudaMemcpyDeviceToHost));+ CK(cudaMemcpy(tb.data(), o_tok, (size_t) tot * 4, cudaMemcpyDeviceToHost));+ bad = std::memcmp(a.data(), b.data(), (size_t) nn * 8) != 0 ||+ std::memcmp(sa.data(), sb.data(), ((size_t) nn + 1) * 4) != 0 ||+ std::memcmp(da.data(), db.data(), (size_t) tot * 4) != 0 ||+ std::memcmp(ta.data(), tb.data(), (size_t) tot * 4) != 0;+ }+ if (bad) {+ ++v_bad;+ if (v_bad <= 20) std::fprintf(stderr, "strata-q36 VERIFY MISMATCH group (T %d, groups %d vs %d)\n", T, nn, no);+ }+ }+ bool grouped_by_route = false; // route_group already filled the group arrays of this layer+ /// The router's top-k and the grouping of the picks in one launch (T <= 8, 256 experts, 8 picks); the logits are in logits_r.+ /// `slot_of`: the hybrid mode's slot table (null: every expert resident). Returns false when the old kernels must run.+ bool route_group(const Layer& L, const int32_t* slot_of, int T) {+ const int Kp = (int) m->top_k;+ grouped_by_route = false;+ if (!fast_k || T > 8 || m->g.n_expert != 256 || Kp != 8) return false;+ if (slot_of)+ q36k::k_route_group<true><<<1, dim3(32, 8), 0, st>>>(logits_r, ids, ewts, T, slot_of, L.blobs, L.stride, grp_ptr,+ grp_start, n_groups, ent_dst, ent_tok);+ else+ q36k::k_route_group<false><<<1, dim3(32, 8), 0, st>>>(logits_r, ids, ewts, T, nullptr, L.blobs, L.stride, grp_ptr,+ grp_start, n_groups, ent_dst, ent_tok);+ grouped_by_route = true;+ if (verify_k) {+ // the old top-k into scratch, the ids / weights compared, then the old grouping of the new ids+ if (!vbuf) CK(cudaMalloc((void**) &vbuf, (size_t) 8 * 16384 * 4));+ int32_t* vid = (int32_t*) (vbuf + 8 * 8192);+ float* vw = vbuf + 8 * 8192 + 64;+ K::native_router_topk(logits_r, vid, vw, 256, Kp, T, st);+ verify_cmp("route ids", (const float*) ids, (const float*) vid, (size_t) T * Kp, " T " + std::to_string(T));+ verify_cmp("route weights", ewts, vw, (size_t) T * Kp, " T " + std::to_string(T));+ group_verify(L, slot_of, T);+ }+ return true;+ }+ /// The routed entries of T rows grouped per expert (k_group; with slot_of the hybrid mode's k_group_hy).+ void group_entries(const Layer& L, const int32_t* slot_of, int T) {+ if (grouped_by_route) { // route_group did it+ grouped_by_route = false;+ return;+ }+ const int Kp = (int) m->top_k, n_ent = T * Kp;+ if (fast_k && n_ent <= 64) {+ if (slot_of)+ q36k::k_group_small<true><<<1, 64, 0, st>>>(ids, n_ent, Kp, slot_of, L.blobs, L.stride, grp_ptr, grp_start,+ n_groups, ent_dst, ent_tok);+ else+ q36k::k_group_small<false><<<1, 64, 0, st>>>(ids, n_ent, Kp, nullptr, L.blobs, L.stride, grp_ptr, grp_start,+ n_groups, ent_dst, ent_tok);+ if (verify_k) group_verify(L, slot_of, T);+ return;+ }+ group_old(L, slot_of, T, grp_ptr, grp_start, n_groups, ent_dst, ent_tok);+ }+ void* vgrp = nullptr;+ float *vx_ = nullptr, *vh_ = nullptr;+ /// The MoE block's end (k_moe_out) for T rows.+ void moe_end(int T, const int32_t* prow, const float* shared, const float* sgate, const float* wn, float* hout) {+ const int N = (int) m->g.n_embd, Kp = (int) m->top_k;+ const bool small = fast_k && T <= 8 && N <= 2048 && N % 256 == 0 && Kp <= 15;+ if (small && verify_k) {+ if (!vx_) {+ CK(cudaMalloc((void**) &vx_, (size_t) 8 * 2048 * 4));+ CK(cudaMalloc((void**) &vh_, (size_t) 8 * 2048 * 4));+ }+ CK(cudaMemcpyAsync(vx_, x, (size_t) T * N * 4, cudaMemcpyDeviceToDevice, st));+ k_moe_out<<<T, kThreads, 0, st>>>(vx_, eparts, prow, ewts, Kp, shared, sgate, 1, wn, vh_, N, m->eps);+ }+ if (small) {+ const bool mkq = wn != nullptr && hout == h; // the next layer's input, quantized here+ q36k::k_moe_out_small<<<T, 1024, 0, st>>>(x, eparts, prow, ewts, Kp, shared, sgate, 1, wn, hout, N, m->eps,+ mkq ? (q36k::QB*) xq : nullptr);+ xq_ready = mkq;+ if (verify_k) {+ if (mkq) verify_q8("moe_out q8", hout, T, " T " + std::to_string(T));+ verify_cmp("moe_out x", x, vx_, (size_t) T * N, " T " + std::to_string(T));+ if (wn) verify_cmp("moe_out h", hout, vh_, (size_t) T * N, " T " + std::to_string(T));+ }+ return;+ }+ xq_ready = false;+ k_moe_out<<<T, kThreads, 0, st>>>(x, eparts, prow, ewts, Kp, shared, sgate, 1, wn, hout, N, m->eps);+ }/// y [T][n_out] = W x from x's q8_1 image, 8 columns per launch.void mmq(const Mat& w, const void* q, float* out, int T) {+ if (q8_small(w, q, out, T)) return;const size_t qb = K::native_q8_1_bytes(w.n_in, 1);for (int c0 = 0; c0 < T; c0 += 8) {const int nc = std::min(8, T - c0);@@ -1523,7 +1836,7 @@ struct Engine {float* hc_b = verify ? v_hc[li] : hc;float* al_b = verify ? v_alpha[li] : alpha;float* be_b = verify ? v_beta[li] : beta;- prep(h, N, T, xq);+ prep_in(T);apply(L.qkv, xq, qkv_b, T);apply(L.zg, xq, z, T);if (T <= kGemmT) {@@ -1546,7 +1859,9 @@ struct Engine {// fused single-token kernels are not used here: fused_gdn_conv_l2's 4-tap sum contracts into FMAs// differently from k_conv_seq's, a 1-ulp difference in h that the Q8_1 activation rounding can turn into a// flipped near-tie later; with them the KL is the same, 1.05x / 0.81x the floor, but MTP would not be exact.)- k_conv_seq<<<C / 128, 128, 0, st>>>(conv[li], qkv_b, L.conv, hc_b, C, 2 * HK, m->eps, T, !verify);+ // a prompt chunk: tiles of kConvTile tokens side by side (tile mode); else one block per head walks the tokens+ const int tiles = (fast_k && T > kGemmT && !verify) ? (T + kConvTile - 1) / kConvTile : 1;+ k_conv_seq<<<dim3(C / 128, tiles), 128, 0, st>>>(conv[li], qkv_b, L.conv, hc_b, C, 2 * HK, m->eps, T, !verify);if (T > kGemmT && !verify) { // a prompt chunk: the column-split delta rule, then the normk_gdn_seq_cols<<<dim3(HV, kGdnColGroups), dim3(128 / kGdnColGroups, 16), 0, st>>>(S[li], hc_b, C, al_b,be_b, gdn_y, HK, HV, T);@@ -1558,7 +1873,7 @@ struct Engine {}mm(L.ssm_out, gdn_y, y, T);} else {- prep(h, N, T, xq);+ prep_in(T);apply(L.wq, xq, qg, T);apply(L.wk, xq, kx, T);apply(L.wv, xq, vx, T);@@ -1630,17 +1945,19 @@ struct Engine {}mm(L.wo, att, y, T);}- k_add_rms<<<T, kThreads, 0, st>>>(x, y, L.post_norm, h, N, m->eps);+ add_rms_post(L, T);// routed experts (one token: the router and the shared expert's gate in one product, the gate its last row)const bool one = T == 1;if (one) f32mm(L.router_ext, h, logits_r, N, (int) g.n_expert + 1, 1);else f32mm(L.router, h, logits_r, N, (int) g.n_expert, T);- K::native_router_topk(logits_r, ids, ewts, (int) g.n_expert, Kp, T, st);- const int64_t n_ent = (int64_t) T * Kp;- const int32_t* prow = nullptr;// the hybrid rows path: a batch of up to hybrid_t rows; when only the MTP block is hybrid, its every batch// (its prompt pass too: no staging buffers then)const bool hy_rows = lhy(li) && (T <= hybrid_t || !main_hybrid);+ const bool mmq_rows = !hy_rows && T > kGemmT && use_mmq;+ if (!(!mmq_rows && route_group(L, hy_rows ? hy[li].slot_of_d : nullptr, T)))+ K::native_router_topk(logits_r, ids, ewts, (int) g.n_expert, Kp, T, st);+ const int64_t n_ent = (int64_t) T * Kp;+ const int32_t* prow = nullptr;if (hy_rows) {moe_hybrid_gpu(L, li, T);} else if (T > kGemmT && use_mmq) {@@ -1675,28 +1992,30 @@ struct Engine {if (lhy(li)) stream_done();prow = rinv;} else {- k_group<<<1, kThreads, 0, st>>>(ids, (int) n_ent, Kp, (int) g.n_expert, L.blobs, L.stride, grp_ptr, grp_start,- n_groups, ent_dst, ent_tok);- quant(h, N, T, xq); // the experts' and the shared expert's input+ group_entries(L, nullptr, T);+ if (!xq_post) quant(h, N, T, xq); // the experts' and the shared expert's inputK::native_expert_grouped(L.L, grp_ptr, grp_start, n_groups, ent_dst, ent_tok,std::min<int64_t>(n_ent, g.n_expert), n_ent, xq, escr, eparts, st);}// the shared expert, scaled by sigmoid(w . h)if (T > kGemmT) k_to_f16<<<grid1((int64_t) N * T), kThreads, 0, st>>>(h, x16, (int64_t) N * T);- apply(L.sh_gate, xq, sg, T);- apply(L.sh_up, xq, su, T);- if (T <= kGemmT) { // SwiGLU and its q8_1 image in one launch- K::native_swiglu_quantize_q8_1(sg, su, q8, FS, T, st);+ if (T <= kGemmT) {+ if (!shared_gu(L, T)) {+ apply(L.sh_gate, xq, sg, T);+ apply(L.sh_up, xq, su, T);+ K::native_swiglu_quantize_q8_1(sg, su, q8, FS, T, st); // SwiGLU and its q8_1 image in one launch+ }mmq(L.sh_down, q8, sy, T);} else {+ apply(L.sh_gate, xq, sg, T);+ apply(L.sh_up, xq, su, T);k_swiglu<<<grid1((int64_t) T * FS), kThreads, 0, st>>>(sg, su, shh, (int64_t) T * FS);mm(L.sh_down, shh, sy, T);}if (!one) f32mm(L.sh_gate_inp, h, sgate, N, 1, T);if (hy_rows) moe_hybrid_cpu(li, T); // the CPU pool's experts (while the GPU runs the rest), merged// the combine, the shared expert's gate, the residual add and the next norm in one launch- k_moe_out<<<T, kThreads, 0, st>>>(x, eparts, prow, ewts, Kp, sy, one ? logits_r + g.n_expert : sgate, 1, wn, hout,- N, m->eps);+ moe_end(T, prow, sy, one ? logits_r + g.n_expert : sgate, wn, hout);}/// The main model over T rows (device `tok`, positions p0 .. p0 + T - 1, also at *pos0): hmain gets every row's@@ -1729,6 +2048,32 @@ struct Engine {k_argmax<<<dim3(1, n), kThreads, 0, st>>>(lg, kArgBlocks, pk, amv, ami, true);}+ /// The draft head: the MTP block's pick over the first `draft_n` rows of the output matrix only (the lowest token ids are+ /// the most frequent ones). A draft only proposes: the verify window decides, so a token outside the subset is a+ /// rejected draft and nothing else - the answer is the plain greedy answer whatever draft_n is. 0 = the whole vocabulary.+ int draft_n = 0;+ void head_draft(const float* hn) {+ const auto& g = m->g;+ const int N = (int) g.n_embd;+ const Mat& hd = m->head;+ if (!fast_k || draft_n <= 0 || draft_n >= g.n_vocab || draft_n % 8 != 0 || hd.type != 8 || hd.n_in != N || N / 32 != 64) {+ head_rows(hn, 1, logits_m, pick_m);+ return;+ }+ quant(hn, N, 1, q8);+ const uint8_t* pk = nullptr;+ for (const auto& p : m->packed)+ if (std::get<0>(p) == hd.d) pk = std::get<1>(p);+ if (pk) {+ const half* dpl = reinterpret_cast<const half*>(pk + (size_t) hd.n_in * hd.n_out);+ q36k::launch_q8_rows<1, 2, true>(pk, dpl, q8, logits_m, 64, draft_n, st);+ } else {+ q36k::launch_q8_rows<1, 2, false>(hd.d, nullptr, q8, logits_m, 64, draft_n, st);+ }+ k_argmax<<<dim3(kArgBlocks, 1), kThreads, 0, st>>>(logits_m, draft_n, pick_m, amv, ami, false);+ k_argmax<<<dim3(1, 1), kThreads, 0, st>>>(logits_m, kArgBlocks, pick_m, amv, ami, true);+ }+/// The MTP block over T rows: row t reads token tok_m[t] at position p0 + t (also at *pos0_m) and the seed hidden/// seeds[t] (the main model's normed hidden of the position before, or the block's own for a chained draft);/// hmtp gets each row's normed output. `draft`: logits of the last row and its pick (`pick_m`).@@ -1743,7 +2088,7 @@ struct Engine {mm(m->eh_proj, mtp_cat, x, T);k_rms<<<T, kThreads, 0, st>>>(x, m->mtp.attn_norm, h, N, m->eps);layer(m->mtp, m->layers.size(), T, p0, pos0_m, graph_mode, false, m->mtp_shnorm, hmtp);- if (draft) head_rows(hmtp + (size_t) (T - 1) * N, 1, logits_m, pick_m);+ if (draft) head_draft(hmtp + (size_t) (T - 1) * N);}/// After a verify window of T rows: the GDN state takes the first n_keep rows (conv history and recurrence run@@ -1827,9 +2172,8 @@ struct Engine {CK(cudaMemcpyAsync(h_ids, ids, (size_t) n_ent * 4, cudaMemcpyDeviceToHost, st));CK(cudaMemcpyAsync(h_h, h, (size_t) T * N * 4, cudaMemcpyDeviceToHost, st));CK(cudaEventRecord(ev_route, st));- k_group_hy<<<1, kThreads, 0, st>>>(ids, (int) n_ent, Kp, (int) g.n_expert, hy[li].slot_of_d, L.blobs, L.stride,- grp_ptr, grp_start, n_groups, ent_dst, ent_tok);- quant(h, N, T, xq); // the experts' and the shared expert's input+ group_entries(L, hy[li].slot_of_d, T);+ if (!xq_post) quant(h, N, T, xq); // the experts' and the shared expert's inputK::native_expert_grouped(L.L, grp_ptr, grp_start, n_groups, ent_dst, ent_tok,std::min<int64_t>(n_ent, g.n_expert), n_ent, xq, escr, eparts, st);}@@ -3321,7 +3665,7 @@ int strata::qwen35::run(int argc, char** argv) {int ctx = 32768, chunk = 0, n_gen = 64, bench_pp = 0, bench_tg = 0, mtp_d = 0, cpu_threads = 0, hybrid_rows = 128;double expert_vram = -1.0;bool warm = true;- int expert_slots = 0, batch = 0;+ int expert_slots = 0, batch = 0, draft_vocab = -1;bool serve_mode = false, graph = true, vision = false, batch_mtp = false;for (int i = 1; i < argc; ++i) {const std::string a = argv[i];@@ -3355,6 +3699,7 @@ int strata::qwen35::run(int argc, char** argv) {else std::fprintf(stderr, "strata-q36: ignoring --mtp %s (this family's MTP is the GGUF's own block: --mtp N ""drafts)\n", v.c_str());}+ else if (a == "--draft-vocab") draft_vocab = std::atoi(next().c_str()); // the MTP drafts pick among the first N token idselse if (a == "--vision") vision = true; // pictures (GENI): the encoder is strata-vision'selse if (a == "--batch" || a == "--slots") batch = std::atoi(next().c_str()); // sessions decoding togetherelse if (a == "--batch-mtp") batch_mtp = true; // ... each verifying an MTP proposal@@ -3384,6 +3729,7 @@ int strata::qwen35::run(int argc, char** argv) {setenv("STRATA_MMQ_KQ", "1", 0); // the K-quant MMQ prompt kernels (every expert of this family is a K-quant)#elseif (std::getenv("STRATA_MMQ_KQ") == nullptr) _putenv_s("STRATA_MMQ_KQ", "1");+ if (std::getenv("STRATA_Q8_PACKED") == nullptr) _putenv_s("STRATA_Q8_PACKED", "1"); // as on Linux (it was missing here)if (std::getenv("CUDA_MODULE_LOADING") == nullptr) _putenv_s("CUDA_MODULE_LOADING", "EAGER");#endifif (mtp_d < 0 || mtp_d > 7) { std::fprintf(stderr, "strata-q36: --mtp takes 0 .. 7 drafts\n"); return 2; }@@ -3425,6 +3771,10 @@ int strata::qwen35::run(int argc, char** argv) {struct Report {Engine& E;~Report() {+ if (E.verify_k) std::fprintf(stderr, "strata-q36 VERIFY: %lld comparisons, %lld mismatches\n", E.v_calls, E.v_bad);+ if (E.verify_k)+ for (const auto& kv : E.v_by)+ std::fprintf(stderr, "strata-q36 VERIFY %s: %lld mismatches\n", kv.first.c_str(), kv.second);if (!E.m->hybrid) return;const long long n = E.hy_cpu + E.hy_gpu;std::fprintf(stderr, "strata-q36: hybrid experts: %lld of %lld batch entries on the GPU (%.1f%%), %lld on the "@@ -3434,6 +3784,8 @@ int strata::qwen35::run(int argc, char** argv) {} report{E};E.reset();E.mtp_d = m.has_mtp ? mtp_d : 0;+ if (draft_vocab < 0 && std::getenv("STRATA_Q36_DRAFT_VOCAB") != nullptr) draft_vocab = std::atoi(std::getenv("STRATA_Q36_DRAFT_VOCAB"));+ E.draft_n = std::max(0, draft_vocab);E.bmtp = (batch_mtp || (std::getenv("STRATA_BATCH_MTP") != nullptr && std::string(std::getenv("STRATA_BATCH_MTP")) != "0")) && E.n_sess > 1 && E.mtp_d > 0;if (batch_mtp && !E.bmtp) std::fprintf(stderr, "strata-q36: --batch-mtp needs --batch N (2 or more) and --mtp N: ignored\n");if (warm) E.warmup();diff --git a/src/qwen35/q36_kernels.cuh b/src/qwen35/q36_kernels.cuhnew file mode 100644index 000000000..84e668484--- /dev/null+++ b/src/qwen35/q36_kernels.cuh@@ -0,0 +1,399 @@+// q36_kernels.cuh - decode kernels of the Qwen3.6 engine (q36_engine.cu), written to give the SAME BITS as the shared+// kernels they replace (native_small_mmvq_kernel, k_moe_out, k_add_rms, k_group, native_quantize_q8_1) with a layout that+// keeps more bytes in flight and fewer launches. Every kernel here is checked bit for bit against the old one on the+// real activations (STRATA_Q36_VERIFY=1, --no-graph).+#pragma once++#include "strata/kernels/dp4a.hpp"+#include "strata/kernels/q8_1_finite.hpp"++#include <cuda_fp16.h>+#include <cuda_runtime.h>++#include <cfloat>+#include <cmath>+#include <cstdint>++namespace q36k {++struct QB { // a q8_1 activation block (what native_quantize_q8_1 writes)+ half2 ds;+ int8_t qs[32];+};+static_assert(sizeof(QB) == 36, "q8_1 block");++__device__ __forceinline__ float wsum(float x) {+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) x += __shfl_xor_sync(0xffffffffu, x, o, 32);+ return x;+}+__device__ __forceinline__ float wmax(float x) {+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) x = fmaxf(x, __shfl_xor_sync(0xffffffffu, x, o, 32));+ return x;+}+__device__ __forceinline__ float sigm(float v) { return 1.0f / (1.0f + expf(-v)); }++// The shared CUDA kernels these ones replace (native_mmvq.cu, native_router.cu) are compiled with --use_fast_math (CMakeLists.txt);+// this file is not, so on CUDA the division and the exponential they use are spelled out as the instructions that flag selects+// (div.approx.ftz, rcp.approx.ftz, ex2.approx.ftz via __expf). HIP builds have no such flag: plain operators.+#if defined(__CUDACC__) && !defined(__HIPCC__)+__device__ __forceinline__ float fdiv_fm(float a, float b) {+ float r;+ asm("div.approx.ftz.f32 %0, %1, %2;" : "=f"(r) : "f"(a), "f"(b));+ return r;+}+__device__ __forceinline__ float frcp_fm(float a) {+ float r;+ asm("rcp.approx.ftz.f32 %0, %1;" : "=f"(r) : "f"(a));+ return r;+}+__device__ __forceinline__ float fexp_fm(float a) { return __expf(a); }+#else+__device__ __forceinline__ float fdiv_fm(float a, float b) { return a / b; }+__device__ __forceinline__ float frcp_fm(float a) { return 1.0f / a; }+__device__ __forceinline__ float fexp_fm(float a) { return expf(a); }+#endif++/// One lane's element `v` of a 32-element q8_1 block (the warp is the block): native_quantize_q8_1_kernel's body.+/// `y` points at the row's blocks, `i` is the element index within the row.+__device__ __forceinline__ void q8_store(QB* __restrict__ y, int i, float v, int lane) {+ const float amax = wmax(fabsf(v));+ const float sum = wsum(v);+ const float d = strata::kernels::q8_1_finite(fdiv_fm(amax, 127.0f));+ int8_t q = 0; // strata::kernels::q8_1_quant with the division of the fast-math TU+ if (amax != 0.0f) {+ const float qf = roundf(fdiv_fm(v, d));+ q = (int8_t) (qf > 127.0f ? 127.0f : qf < -127.0f ? -127.0f : qf);+ }+ y[i >> 5].qs[lane] = q;+ if (lane == 0) y[i >> 5].ds = strata::kernels::q8_1_ds(d, sum);+}++/// A Q8_0 row (GGUF blocks of 34 bytes, or the qs / d planes with PK) against NC activation columns, with the arithmetic of+/// native_small_mmvq_kernel / native_mmvq_multi_kernel's exact layout: the 4 warps of the old block are the 4 partial sums+/// P_w of one lane here (block kbx = 8 w + lane / 4 + 32 j, ints 2 (lane % 4) and +1), added in warp order, then the xor+/// tree. One warp per row, every load of a lane issued before the first dot (NJ = ceil(nb / 32) terms per partial).+/// res[c] = the row's value for column c in every lane.+template <int NC, int NJ, bool PK>+__device__ __forceinline__ void q8_row_dot(const uint8_t* __restrict__ w, const half* __restrict__ dpl, const QB* __restrict__ x,+ int row, int nb, int lane, float (&res)[NC]) {+ const int kqs = 2 * (lane & 3);+ const int kb0 = lane >> 2;+ int v0[4][NJ], v1[4][NJ];+ float d0[4][NJ];+ bool ok[4][NJ];+#pragma unroll+ for (int p = 0; p < 4; ++p)+#pragma unroll+ for (int j = 0; j < NJ; ++j) {+ const int kbx = kb0 + 8 * p + 32 * j;+ ok[p][j] = kbx < nb;+ if (!ok[p][j]) continue;+ const size_t blk = (size_t) row * nb + kbx;+ if (PK) {+ const int* q = reinterpret_cast<const int*>(w + blk * 32) + kqs;+ v0[p][j] = q[0];+ v1[p][j] = q[1];+ d0[p][j] = __half2float(dpl[blk]);+ } else {+ const uint16_t* b = reinterpret_cast<const uint16_t*>(w + blk * 34);+ d0[p][j] = __half2float(__ushort_as_half(b[0]));+ v0[p][j] = (int) b[1 + 2 * kqs] | ((int) b[2 + 2 * kqs] << 16);+ v1[p][j] = (int) b[3 + 2 * kqs] | ((int) b[4 + 2 * kqs] << 16);+ }+ }+ float P[NC][4];+#pragma unroll+ for (int c = 0; c < NC; ++c)+#pragma unroll+ for (int p = 0; p < 4; ++p) {+ float t = 0.f;+#pragma unroll+ for (int j = 0; j < NJ; ++j) {+ if (!ok[p][j]) continue;+ const QB* xb = x + (size_t) c * nb + kb0 + 8 * p + 32 * j;+ const int* u = reinterpret_cast<const int*>(xb->qs);+ int sumi = 0;+ sumi = STRATA_DP4A(v0[p][j], u[kqs], sumi);+ sumi = STRATA_DP4A(v1[p][j], u[kqs + 1], sumi);+ const float d1 = __low2float(xb->ds);+ t += d0[p][j] * d1 * float(sumi);+ }+ P[c][p] = t;+ }+#pragma unroll+ for (int c = 0; c < NC; ++c) {+ float t = P[c][0];+ t += P[c][1];+ t += P[c][2];+ t += P[c][3];+ res[c] = wsum(t);+ }+}++/// y[c][row] = W[row] . x[c], NC columns, 8 rows (warps) per 256-thread block.+template <int NC, int NJ, bool PK>+__global__ void __launch_bounds__(256) k_q8_rows(const uint8_t* __restrict__ w, const half* __restrict__ dpl,+ const QB* __restrict__ x, float* __restrict__ y, int nb, int n_out) {+ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int stride = gridDim.x * (blockDim.x >> 5); // a grid-stride loop over the rows (see launch_q8_rows)+ for (int row = blockIdx.x * (blockDim.x >> 5) + warp; row < n_out; row += stride) {+ float res[NC];+ q8_row_dot<NC, NJ, PK>(w, dpl, x, row, nb, lane, res);+ if (lane == 0)+#pragma unroll+ for (int c = 0; c < NC; ++c) y[(size_t) c * n_out + row] = res[c];+ }+}++template <int NC, int NJ, bool PK>+inline void launch_q8_rows_t(const void* w, const half* dpl, const void* x, float* y, int nb, int n_out, int warps, int max_warps,+ cudaStream_t s) {+ const int rows = n_out < max_warps ? n_out : max_warps;+ k_q8_rows<NC, NJ, PK><<<(unsigned) ((rows + warps - 1) / warps), warps * 32, 0, s>>>(static_cast<const uint8_t*>(w), dpl,+ static_cast<const QB*>(x), y, nb, n_out);+}++template <int NC, int NJ, bool PK>+/// At most 1024 warps in the grid, a grid-stride loop over the rows beyond: a 2048-row product took 21 us on gfx1201 as 2048 warps and+/// 5.2 us as 1024 (a grid above 32768 threads is several times slower there; the same rows, the same sums).+inline void launch_q8_rows(const void* w, const half* dpl, const void* x, float* y, int nb, int n_out, cudaStream_t s) {+ launch_q8_rows_t<NC, NJ, PK>(w, dpl, x, y, nb, n_out, 8, 1024, s);+}++/// The shared expert's gate and up products and SwiGLU + q8_1 in one launch: 32 rows (one q8_1 block of h) per 1024-thread+/// block, warp w computing gate row and up row 32 b + w, then warp 0 applying native_swiglu_quantize_q8_1_kernel's body to+/// the 32 pairs. Column c of the h image is at hq + c * (n_out / 32). n_out % 32 == 0.+template <int NC, int NJ, bool PK>+__global__ void __launch_bounds__(1024) k_sh_gu(const uint8_t* __restrict__ wg, const half* __restrict__ dg, const uint8_t* __restrict__ wu,+ const half* __restrict__ du, const QB* __restrict__ x, QB* __restrict__ hq,+ int nb, int n_out) {+ __shared__ float g[NC][32], u[NC][32];+ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int row = blockIdx.x * 32 + warp;+ float rg[NC], ru[NC];+ q8_row_dot<NC, NJ, PK>(wg, dg, x, row, nb, lane, rg);+ q8_row_dot<NC, NJ, PK>(wu, du, x, row, nb, lane, ru);+ if (lane == 0)+#pragma unroll+ for (int c = 0; c < NC; ++c) {+ g[c][warp] = rg[c];+ u[c][warp] = ru[c];+ }+ __syncthreads();+ if (warp == 0) {+#pragma unroll+ for (int c = 0; c < NC; ++c) {+ const float gi = g[c][lane];+ const float xi = __fmul_rn(__fdividef(gi, __fadd_rn(1.0f, __expf(-gi))), u[c][lane]);+ q8_store(hq + (size_t) c * (n_out >> 5), blockIdx.x * 32 + lane, xi, lane);+ }+ }+}++/// k_add_rms (x += y; h = rms(x) * w, one block of 256 per row) and the q8_1 image of h in the same launch.+__global__ void __launch_bounds__(256) k_add_rms_q(float* x, const float* y, const float* w, float* h, QB* hq, int n, float eps) {+ __shared__ float sh[256];+ float* xr = x + (size_t) blockIdx.x * n;+ const float* yr = y + (size_t) blockIdx.x * n;+ float* hr = h + (size_t) blockIdx.x * n;+ QB* qr = hq + (size_t) blockIdx.x * (n >> 5);+ float s = 0.f;+ for (int i = threadIdx.x; i < n; i += 256) {+ const float v = xr[i] + yr[i];+ xr[i] = v;+ s += v * v;+ }+ sh[threadIdx.x] = s;+ __syncthreads();+ for (int o = 128; o > 0; o >>= 1) {+ if ((int) threadIdx.x < o) sh[threadIdx.x] += sh[threadIdx.x + o];+ __syncthreads();+ }+ const float r = rsqrtf(sh[0] / (float) n + eps);+ for (int i = threadIdx.x; i < n; i += 256) {+ const float hv = __fmul_rn(__fmul_rn(xr[i], r), w[i]); // no FMA with the quantizer's sums: the old h was stored first+ hr[i] = hv;+ q8_store(qr, i, ((volatile float*) hr)[i], threadIdx.x & 31); // the stored value, as the standalone quantizer reads it+ }+}++/// k_moe_out for T <= 8 rows (decode, verify windows) with n <= 2048 and n % 256 == 0: 1024 threads per row instead of 256+/// (the elements' loads in parallel), the squares summed per old thread (element t, t + 256, ... in order) and the+/// 256-wide tree as before: the same bits. x += sum_k w_k part_k (+ gate * shared); h = rms(x) * wn; with hq the q8_1+/// image of h as well (the next layer's input).+__global__ void __launch_bounds__(1024) k_moe_out_small(float* x, const float* parts, const int32_t* prow, const float* wts,+ int K_, const float* shared, const float* sgate, int sg_stride,+ const float* wn, float* h, int n, float eps, QB* hq = nullptr) {+ __shared__ float vv[2048];+ __shared__ float sh[256];+ __shared__ const float* pk[16];+ const int t = blockIdx.x;+ float* xr = x + (size_t) t * n;+ if (threadIdx.x < K_) pk[threadIdx.x] = parts + (size_t) (prow ? prow[t * K_ + threadIdx.x] : t * K_ + threadIdx.x) * n;+ __syncthreads();+ const float* wr = wts + (size_t) t * K_;+ const float gs = sigm(sgate[(size_t) t * sg_stride]);+ for (int i = threadIdx.x; i < n; i += 1024) {+ float acc = wr[0] * pk[0][i];+ for (int k = 1; k < K_; ++k) acc = fmaf(wr[k], pk[k][i], acc);+ acc += gs * shared[(size_t) t * n + i];+ const float v = xr[i] + acc;+ xr[i] = v;+ vv[i] = v;+ }+ if (wn == nullptr) return;+ __syncthreads();+ if (threadIdx.x < 256) {+ float s = 0.f;+ for (int i = threadIdx.x; i < n; i += 256) s += vv[i] * vv[i];+ sh[threadIdx.x] = s;+ }+ __syncthreads();+ for (int s = 128; s > 0; s >>= 1) {+ if ((int) threadIdx.x < s) sh[threadIdx.x] += sh[threadIdx.x + s];+ __syncthreads();+ }+ const float r = rsqrtf(sh[0] / (float) n + eps);+ for (int i = threadIdx.x; i < n; i += 1024) {+ const float hv = __fmul_rn(__fmul_rn(vv[i], r), wn[i]);+ h[(size_t) t * n + i] = hv;+ if (hq) q8_store(hq + (size_t) t * (n >> 5), i, ((volatile float*) h)[(size_t) t * n + i], threadIdx.x & 31);+ }+}++/// k_group / k_group_hy for n_ent <= 64 entries: one block of 64 threads ranks each entry by (expert id, entry) in+/// parallel instead of one thread walking all the experts; the same group / entry arrays. HY: only the entries whose+/// expert has a VRAM slot (slot_of >= 0), the group's blob at blobs + slot * blob.+template <bool HY>+__global__ void k_group_small(const int32_t* ids, int n_ent, int K_, const int32_t* slot_of, const uint8_t* blobs,+ unsigned long long blob, unsigned long long* grp_ptr, int32_t* grp_start, int32_t* n_groups,+ int32_t* ent_dst, int32_t* ent_tok) {+ __shared__ int sid[64];+ const int e = threadIdx.x;+ const int id = e < n_ent ? ids[e] : 0;+ const bool valid = e < n_ent && (!HY || slot_of[id] >= 0);+ int rank = 0;+ if (valid) {+ for (int e2 = 0; e2 < n_ent; ++e2) {+ const int id2 = ids[e2];+ if (HY && slot_of[id2] < 0) continue;+ if (id2 < id || (id2 == id && e2 < e)) ++rank;+ }+ ent_dst[rank] = e;+ ent_tok[rank] = e / K_;+ sid[rank] = id;+ }+ __syncthreads();+ int nv = 0;+ for (int e2 = 0; e2 < n_ent; ++e2) nv += (!HY || slot_of[ids[e2]] >= 0) ? 1 : 0;+ if (valid && (rank == 0 || sid[rank - 1] != sid[rank])) {+ int g = 0;+ for (int q = 1; q < rank; ++q) g += sid[q - 1] != sid[q] ? 1 : 0;+ g += rank > 0 ? 1 : 0;+ grp_ptr[g] = (unsigned long long) (blobs + (size_t) (HY ? slot_of[id] : id) * blob);+ grp_start[g] = rank;+ }+ if (e == 0) {+ int G = nv > 0 ? 1 : 0;+ for (int q = 1; q < nv; ++q) G += sid[q - 1] != sid[q] ? 1 : 0;+ grp_start[G] = nv;+ *n_groups = G;+ }+}++/// route_topk<256, 8> (native_router.cu, copied: the same expressions) for n_tok <= 8 tokens (one warp each) and, in the same+/// launch, k_group_small's grouping of the picks. block (32, 8). HY as k_group_small.+template <bool HY>+__global__ void __launch_bounds__(256) k_route_group(const float* __restrict__ logits, int32_t* __restrict__ ids,+ float* __restrict__ weights, int n_tok, const int32_t* slot_of,+ const uint8_t* blobs, unsigned long long blob,+ unsigned long long* grp_ptr, int32_t* grp_start, int32_t* n_groups,+ int32_t* ent_dst, int32_t* ent_tok) {+ constexpr int NE = 256, K = 8, V = NE / 32;+ __shared__ int sids[64], sid[64];+ const int tk = threadIdx.y;+ const int lane = threadIdx.x;+ if (tk < n_tok) {+ const float* lg = logits + (size_t) tk * NE;+ float values[V];+#pragma unroll+ for (int i = 0; i < V; ++i) values[i] = lg[lane + i * 32];+ float maximum = -INFINITY;+#pragma unroll+ for (int i = 0; i < V; ++i) maximum = max(maximum, values[i]);+ maximum = wmax(maximum);+ float sum = 0.0f;+#pragma unroll+ for (int i = 0; i < V; ++i) {+ values[i] = fexp_fm(values[i] - maximum);+ sum += values[i];+ }+ const float reciprocal = frcp_fm(wsum(sum));+#pragma unroll+ for (int i = 0; i < V; ++i) {+ values[i] *= reciprocal;+ if (__isnanf(values[i])) values[i] = -FLT_MAX;+ }+ float selected = 0.0f, selected_sum = 0.0f;+ for (int rank = 0; rank < K; ++rank) {+ float best = values[0];+ int expert = lane;+#pragma unroll+ for (int i = 1; i < V; ++i) {+ if (values[i] > best) { best = values[i]; expert = lane + i * 32; }+ }+#pragma unroll+ for (int mask = 16; mask; mask >>= 1) {+ const float other = __shfl_xor_sync(0xffffffffu, best, mask, 32);+ const int other_id = __shfl_xor_sync(0xffffffffu, expert, mask, 32);+ if (other > best || (other == best && other_id < expert)) { best = other; expert = other_id; }+ }+ if ((expert & 31) == lane) {+ values[expert / 32] = -INFINITY;+ ids[(size_t) tk * K + rank] = expert;+ sids[tk * K + rank] = expert;+ selected_sum += best;+ }+ if (rank == lane) selected = best;+ }+ selected_sum = max(wsum(selected_sum), 6.103515625e-5f);+ const float inverse_selected_sum = frcp_fm(selected_sum);+ if (lane < K) weights[(size_t) tk * K + lane] = selected * inverse_selected_sum;+ }+ __syncthreads();+ const int n_ent = n_tok * K;+ const int e = tk * 32 + lane; // 0 .. 255: the entries are the first n_ent threads+ const int id = e < n_ent ? sids[e] : 0;+ const bool valid = e < n_ent && (!HY || slot_of[id] >= 0);+ int rank = 0;+ if (valid) {+ for (int e2 = 0; e2 < n_ent; ++e2) {+ const int id2 = sids[e2];+ if (HY && slot_of[id2] < 0) continue;+ if (id2 < id || (id2 == id && e2 < e)) ++rank;+ }+ ent_dst[rank] = e;+ ent_tok[rank] = e / K;+ sid[rank] = id;+ }+ __syncthreads();+ int nv = 0;+ for (int e2 = 0; e2 < n_ent; ++e2) nv += (!HY || slot_of[sids[e2]] >= 0) ? 1 : 0;+ if (valid && (rank == 0 || sid[rank - 1] != sid[rank])) {+ int g = 0;+ for (int q = 1; q < rank; ++q) g += sid[q - 1] != sid[q] ? 1 : 0;+ g += rank > 0 ? 1 : 0;+ grp_ptr[g] = (unsigned long long) (blobs + (size_t) (HY ? slot_of[id] : id) * blob);+ grp_start[g] = rank;+ }+ if (e == 0) {+ int G = nv > 0 ? 1 : 0;+ for (int q = 1; q < nv; ++q) G += sid[q - 1] != sid[q] ? 1 : 0;+ grp_start[G] = nv;+ *n_groups = G;+ }+}++} // namespace q36k