From fb51ae6fbd6f1940bbd26a1c3e18231be72b42d4 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 10:50:29 +0200 Subject: [PATCH 1/8] iq_kernels: the V2K gate/up kernels take Qwen3.6-35B-A3B's expert geometry (n_embd 2048, n_ff 512, Q4_K/Q5_K gate+up, Q5_K down) For that geometry only: the s27 gate/up kernel and the fused SwiGLU/q8_1, then the old down kernel (the new down kernel is slower at n_ff 512). Flash-Next's shapes (2560/640) take the same paths as before; the path is still STRATA_EXPERT_V2K (default on gfx12). --- src/kernels/cuda/iq_kernels.cu | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 947952a0..47e0e76e 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -3682,12 +3682,24 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long return false; #endif }(); - if (v2k && (L.gu_type == 12 || L.gu_type == 13) && (L.d_type == 7 || L.d_type == 8) && L.n_embd == 2560 && - L.n_ff == 640) { + // Qwen3.6-35B-A3B (n_embd 2048, n_ff 512, Q4_K / Q5_K gate+up, Q5_K down): the same kernels, the geometry only sizes the grid + const bool q36geo = L.n_embd == 2048 && L.n_ff == 512 && L.d_type == 13; + if (v2k && (L.gu_type == 12 || L.gu_type == 13) && + (((L.d_type == 7 || L.d_type == 8) && L.n_embd == 2560 && L.n_ff == 640) || q36geo)) { static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }(); const long long nh = (long long) cap_entries * L.n_ff; #define STRATA_V2K(G, D) s27_launch_ts(ts, L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, nh) - if (L.gu_type == 12 && L.d_type == 7) STRATA_V2K(12, 7); + if (q36geo) { + // the gate/up of the V2K path (4 rows per warp, the chunk's activations in LDS) + SwiGLU/q8_1, and the old down kernel: + // for n_ff 512 the new down kernel measured slower (15.1 vs 13.4 us per layer on gfx1201, R9700) + const dim3 ggu((unsigned) (2 * L.n_ff / (GU_ROWS * 4)), (unsigned) cap_groups); + if (L.gu_type == 12) s27_gu_kernel<12, true, 4, false><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); + else s27_gu_kernel<13, true, 4, false><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); + s26_swiglu_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, hq, nh); + const dim3 gd((unsigned) ((L.n_embd + 7) / 8), (unsigned) cap_groups); + launch_down<13>(gd, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + } + else if (L.gu_type == 12 && L.d_type == 7) STRATA_V2K(12, 7); else if (L.gu_type == 12) STRATA_V2K(12, 8); else if (L.d_type == 7) STRATA_V2K(13, 7); else STRATA_V2K(13, 8); From c9e7f6dd5afb011a1631b2ad710558468a967e9d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 10:52:17 +0200 Subject: [PATCH 2/8] qwen35: faster decode kernels with the old kernels' bits (STRATA_Q36_VERIFY=1 compares them on real activations) q36_kernels.cuh: one warp per row for the shared expert's and attention k/v Q8_0 products (grid capped at 1024 warps: 2048 rows as 2048 warps took 21 us, 5 us as 1024), shared gate+up+SwiGLU+q8_1 in one launch, k_moe_out with 1024 threads and the next layer's q8_1 image, k_add_rms with the q8_1 image, router top-k and expert grouping in one launch. CUDA: the division / exp the --use_fast_math TUs they mirror use are spelled out. Engine: prompt GDN conv in tiles of 16 tokens side by side (same arithmetic per token), --draft-vocab N (the MTP draft head over the first N rows only, a draft proposes and the verify window decides: output unchanged), the packed Q8_0 default on Windows too (it was Linux only), STRATA_Q36_OLD_KERNELS=1 switches all of it off. R9700, UD-Q4_K_XL: decode 82.5 -> 120.6 tok/s (greedy 10 prompts identical), --mtp 2 160 -> 174. --- src/qwen35/q36_engine.cu | 398 +++++++++++++++++++++++++++++++++--- src/qwen35/q36_kernels.cuh | 399 +++++++++++++++++++++++++++++++++++++ 2 files changed, 774 insertions(+), 23 deletions(-) create mode 100644 src/qwen35/q36_kernels.cuh diff --git a/src/qwen35/q36_engine.cu b/src/qwen35/q36_engine.cu index 04cbbe62..0c547952 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 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 it hist[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 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 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(wp, dpl, q, out, nb, w.n_out, st); \ + else q36k::launch_q8_rows(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 a(qb * (size_t) T), b(qb * (size_t) T); + std::vector 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<<>>(vx_, y, L.post_norm, vh_, N, m->eps); + } + q36k::k_add_rms_q<<>>(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<<>>(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<<>>(wa, da, wb, db, (const q36k::QB*) xq, \ + (q36k::QB*) q8, nb, FS); \ + else \ + q36k::k_sh_gu<<>>(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 a((size_t) nn + 1), b((size_t) nn + 1); + std::vector 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<<<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<<<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<<<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<<<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<<>>(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<<>>(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<<>>(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<<>>(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<<>>(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 norm k_gdn_seq_cols<<>>(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<<>>(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 input K::native_expert_grouped(L.L, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, std::min(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<<>>(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<<>>(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<<>>(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<<>>(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(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<<>>(logits_m, draft_n, pick_m, amv, ami, false); + k_argmax<<>>(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<<>>(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 input K::native_expert_grouped(L.L, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, std::min(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 ids else if (a == "--vision") vision = true; // pictures (GENI): the encoder is strata-vision's else if (a == "--batch" || a == "--slots") batch = std::atoi(next().c_str()); // sessions decoding together else 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) #else if (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"); #endif if (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.cuh new file mode 100644 index 00000000..84e66848 --- /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 +#include + +#include +#include +#include + +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 +__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(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(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(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 +__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(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 +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<<<(unsigned) ((rows + warps - 1) / warps), warps * 32, 0, s>>>(static_cast(w), dpl, + static_cast(x), y, nb, n_out); +} + +template +/// 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(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 +__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(wg, dg, x, row, nb, lane, rg); + q8_row_dot(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 +__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 +__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 From 6f4697f6622c9861d56faee545422e538b17674c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 11:05:46 +0200 Subject: [PATCH 3/8] qwen35: the prompt's gated delta rule loads the next token's inputs while it computes this one k_gdn_seq_cols started every token with a chain of global loads; they are issued one token ahead now. Same arithmetic: the 3000-token prompt's logits and the next 8 greedy steps are bit-identical to the previous engine at chunk 512 and 2048 (R9700: prompt 931 -> 902 ms at chunk 512 together with the tiled conv, 616 -> 591 ms at 2048). --- src/qwen35/q36_engine.cu | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/qwen35/q36_engine.cu b/src/qwen35/q36_engine.cu index 0c547952..40db7daa 100644 --- a/src/qwen35/q36_engine.cu +++ b/src/qwen35/q36_engine.cu @@ -756,11 +756,22 @@ __global__ void __launch_bounds__(512) k_gdn_seq_cols(float* state, const float* const size_t row_stride = (size_t) h_v * S; #pragma unroll for (int r = 0; r < RPG; ++r) sv[r] = base[r * row_stride]; - for (int t = 0; t < T; ++t) { + // the next token's inputs are loaded while this one is computed (the loads were the head of every iteration) + float nsk = 0.0f, nsq = 0.0f, nvv = 0.0f, ngate = 0.0f, nbeta = 0.0f; + auto load = [&](int t) { const float* ht = h + (size_t) t * C; - if (tid < S) { sk[tid] = ht[h_k * S + qh * S + tid]; sq[tid] = ht[qh * S + tid]; } + if (tid < S) { nsk = ht[h_k * S + qh * S + tid]; nsq = ht[qh * S + tid]; } + nvv = ht[2 * h_k * S + head * S + col]; + ngate = gate[(size_t) t * h_v + head]; + nbeta = beta[(size_t) t * h_v + head]; + }; + if (T > 0) load(0); + for (int t = 0; t < T; ++t) { + if (tid < S) { sk[tid] = nsk; sq[tid] = nsq; } + const float vcur = nvv, gcur = ngate, bcur = nbeta; + if (t + 1 < T) load(t + 1); __syncthreads(); - const float g = __expf(gate[(size_t) t * h_v + head]); + const float g = __expf(gcur); float kv = 0.0f; #pragma unroll for (int r = 0; r < RPG; ++r) kv = fmaf(sv[r], sk[rg * RPG + r], kv); @@ -769,7 +780,7 @@ __global__ void __launch_bounds__(512) k_gdn_seq_cols(float* state, const float* float kv_col = 0.0f; #pragma unroll for (int i = 0; i < RG; ++i) kv_col += red_kv[i][cl]; - const float delta = (ht[2 * h_k * S + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head]; + const float delta = (vcur - g * kv_col) * bcur; float o = 0.0f; #pragma unroll for (int r = 0; r < RPG; ++r) { From 93f0f48f103dc4e2e7d20f4a47cccbc34ffcff41 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 11:24:15 +0200 Subject: [PATCH 4/8] qwen35: the prompt chunk defaults to the largest that fits (4096 .. 1024); the router and the shared gate in one product for decode batches; conv tile fix for batch rows Prompt chunk (owner decision): with every expert in VRAM the auto rule picks 4096, 2048 or 1024 (the chunk's buffers cost ~0.5 MiB per token, the sessions' caches 45 KB per cell and session; 1024 at most with --batch N so the other slots' windows are not held for a whole chunk), else 512. The hybrid mode keeps 2048 and falls back to 1024 / 512 on a card with little room. STRATA_Q36_CHUNK=512 or --prefill 512 gives the old size. R9700 pp4096: 512 3390, 1024 4495, 2048 5353, 4096 5750 tok/s. Not bit-identical to 512 (other GEMM tiles): see docs/QWEN36.md for the KL. Decode batches of up to 8 rows take the router and the shared expert's gate in one product (rows of 257), as a single token already did. k_conv_seq's tile mode switched off the history write for batch rows too (grid y is the group count there): fixed. --- src/qwen35/q36_engine.cu | 54 ++++++++++++++++++++++++++++---------- src/qwen35/q36_kernels.cuh | 4 +-- 2 files changed, 42 insertions(+), 16 deletions(-) diff --git a/src/qwen35/q36_engine.cu b/src/qwen35/q36_engine.cu index 40db7daa..9fcc0d0a 100644 --- a/src/qwen35/q36_engine.cu +++ b/src/qwen35/q36_engine.cu @@ -621,7 +621,8 @@ __global__ void __launch_bounds__(128) k_conv_seq(float* hist, const float* qkv, // 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) { + const bool tiled = hist_tab == nullptr && gridDim.y > 1; + if (tiled) { t_first = (int) blockIdx.y * kConvTile; t_end = min(T, t_first + kConvTile); if (t_first == 0 && write) { @@ -659,7 +660,7 @@ __global__ void __launch_bounds__(128) k_conv_seq(float* hist, const float* qkv, } h[(size_t) t * C + c] = y; } - if (!write || gridDim.y > 1) return; // a verify window: the history is commit()'s to move; tiles: tile 0 stored it + if (!write || tiled) return; // a verify window: the history is commit()'s to move; tiles: tile 0 stored it hist[c * 3] = v0; hist[c * 3 + 1] = v1; hist[c * 3 + 2] = v2; @@ -1750,15 +1751,15 @@ struct Engine { 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) { + bool route_group(const Layer& L, const int32_t* slot_of, int T, int ld) { 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<<<1, dim3(32, 8), 0, st>>>(logits_r, ids, ewts, T, slot_of, L.blobs, L.stride, grp_ptr, + q36k::k_route_group<<<1, dim3(32, 8), 0, st>>>(logits_r, ids, ewts, T, ld, slot_of, L.blobs, L.stride, grp_ptr, grp_start, n_groups, ent_dst, ent_tok); else - q36k::k_route_group<<<1, dim3(32, 8), 0, st>>>(logits_r, ids, ewts, T, nullptr, L.blobs, L.stride, grp_ptr, + q36k::k_route_group<<<1, dim3(32, 8), 0, st>>>(logits_r, ids, ewts, T, ld, nullptr, L.blobs, L.stride, grp_ptr, grp_start, n_groups, ent_dst, ent_tok); grouped_by_route = true; if (verify_k) { @@ -1795,7 +1796,7 @@ struct Engine { 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) { + void moe_end(int T, const int32_t* prow, const float* shared, const float* sgate, const float* wn, float* hout, int sgs = 1) { 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) { @@ -1804,11 +1805,11 @@ struct Engine { CK(cudaMalloc((void**) &vh_, (size_t) 8 * 2048 * 4)); } CK(cudaMemcpyAsync(vx_, x, (size_t) T * N * 4, cudaMemcpyDeviceToDevice, st)); - k_moe_out<<>>(vx_, eparts, prow, ewts, Kp, shared, sgate, 1, wn, vh_, N, m->eps); + k_moe_out<<>>(vx_, eparts, prow, ewts, Kp, shared, sgate, sgs, 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<<>>(x, eparts, prow, ewts, Kp, shared, sgate, 1, wn, hout, N, m->eps, + q36k::k_moe_out_small<<>>(x, eparts, prow, ewts, Kp, shared, sgate, sgs, wn, hout, N, m->eps, mkq ? (q36k::QB*) xq : nullptr); xq_ready = mkq; if (verify_k) { @@ -1819,7 +1820,7 @@ struct Engine { return; } xq_ready = false; - k_moe_out<<>>(x, eparts, prow, ewts, Kp, shared, sgate, 1, wn, hout, N, m->eps); + k_moe_out<<>>(x, eparts, prow, ewts, Kp, shared, sgate, sgs, 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) { @@ -1959,13 +1960,16 @@ struct Engine { 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); + // a decode batch of up to 8 rows takes the router and the shared expert's gate in one product too (rows of 257) when the fused + // router follows; the prompt chunks and the checks keep the separate products + const bool ext = one || (fast_k && std::getenv("STRATA_Q36_NO_EXT") == nullptr && !verify_k && T <= kGemmT && g.n_expert == 256 && Kp == 8); + if (ext) f32mm(L.router_ext, h, logits_r, N, (int) g.n_expert + 1, T); else f32mm(L.router, h, logits_r, N, (int) g.n_expert, T); // 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))) + if (!(!mmq_rows && route_group(L, hy_rows ? hy[li].slot_of_d : nullptr, T, ext ? (int) g.n_expert + 1 : (int) g.n_expert))) 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; @@ -2023,10 +2027,10 @@ struct Engine { k_swiglu<<>>(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 (!ext) 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 - moe_end(T, prow, sy, one ? logits_r + g.n_expert : sgate, wn, hout); + moe_end(T, prow, sy, ext ? logits_r + g.n_expert : sgate, wn, hout, ext ? (int) g.n_expert + 1 : 1); } /// The main model over T rows (device `tok`, positions p0 .. p0 + T - 1, also at *pos0): hmain gets every row's @@ -3756,7 +3760,7 @@ int strata::qwen35::run(int argc, char** argv) { Engine E; E.use_graph = graph; if (chunk == 0) { - // auto: 512 with every expert in VRAM; 2048 when they will not all fit (a prompt chunk streams every layer's + // auto: the largest chunk (4096 .. 1024) that fits beside every expert in VRAM; 2048 when they will not all fit (a prompt chunk streams every layer's // experts over PCIe once, so a bigger chunk pays that once for more tokens) size_t fr = 0, tot = 0, experts = 0; CK(cudaMemGetInfo(&fr, &tot)); @@ -3770,6 +3774,28 @@ int strata::qwen35::run(int argc, char** argv) { const bool fits = expert_slots <= 0 && (expert_vram < 0 ? want <= (double) fr : (double) experts <= expert_vram * (double) (1ull << 30)); chunk = fits ? 512 : 2048; + const double GiB = (double) (1ull << 30); + if (fits && expert_vram < 0) { + // a bigger prompt chunk feeds the MMQ expert kernels more rows per expert (R9700, UD-Q4_K_XL, pp4096: 512 3390, 1024 + // 4495, 2048 5353, 4096 5750 tok/s): the largest that fits beside the experts. Its buffers grow by about 0.5 MiB per + // token (measured 0.47: 1.66 GiB more at 4096 than at 512), the sessions' K / V caches by 45 KB per cell and session. + // With several slots a long prompt would hold the other slots' windows for a whole chunk: 1024 at most there. + const double kv_cell = 45056.0; + const int ns = std::max(1, batch); + const double sess_extra = std::max(0.0, (double) ns * (double) ctx * kv_cell - 8192.0 * kv_cell); + const int cap = ns > 1 ? 1024 : 4096; + for (int c : {4096, 2048, 1024}) + if (c <= cap && want + (double) (c - 512) * 0.5 * 1048576.0 + sess_extra <= (double) fr) { + chunk = c; + break; + } + } else if (!fits) { + // the hybrid mode: 2048 (a chunk streams every layer's experts over PCIe once); a small card, where the chunk's buffers + // would take the slots' room, falls back to less + const double fr_gib = (double) fr / GiB; + chunk = fr_gib >= 7.5 ? 2048 : fr_gib >= 5.5 ? 1024 : 512; + } + if (const char* cv = std::getenv("STRATA_Q36_CHUNK")) chunk = std::max(256, std::min(4096, std::atoi(cv))); // force a chunk (512: the old default) if (std::getenv("STRATA_Q36_PLACE_DEBUG")) std::fprintf(stderr, "strata-q36: chunk rule: free %.2f GiB (with %.2f packed), main experts %.2f GiB\n", fr / 1073741824.0, packed / 1073741824.0, experts / 1073741824.0); diff --git a/src/qwen35/q36_kernels.cuh b/src/qwen35/q36_kernels.cuh index 84e66848..21617b0b 100644 --- a/src/qwen35/q36_kernels.cuh +++ b/src/qwen35/q36_kernels.cuh @@ -307,7 +307,7 @@ __global__ void k_group_small(const int32_t* ids, int n_ent, int K_, const int32 /// launch, k_group_small's grouping of the picks. block (32, 8). HY as k_group_small. template __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, + float* __restrict__ weights, int n_tok, int ld, 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) { @@ -316,7 +316,7 @@ __global__ void __launch_bounds__(256) k_route_group(const float* __restrict__ l const int tk = threadIdx.y; const int lane = threadIdx.x; if (tk < n_tok) { - const float* lg = logits + (size_t) tk * NE; + const float* lg = logits + (size_t) tk * ld; float values[V]; #pragma unroll for (int i = 0; i < V; ++i) values[i] = lg[lane + i * 32]; From b0f675be76133bcdb78cd942c22297a740ba5f02 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 11:40:05 +0200 Subject: [PATCH 5/8] qwen35: the chunk rule counts what the chunk really costs (measured on the R9700) A bigger chunk is only taken when the experts, the 0.77 GiB reserve and the chunk's buffers (0.5 MiB per token) still fit without giving the packed decode copies back: 131072 cells -> 512, 100000 -> 2048, 32768 with --batch 4 -> 1024, --batch 8 -> 512 (hybrid as before). --- src/qwen35/q36_engine.cu | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/qwen35/q36_engine.cu b/src/qwen35/q36_engine.cu index 9fcc0d0a..de95aedb 100644 --- a/src/qwen35/q36_engine.cu +++ b/src/qwen35/q36_engine.cu @@ -3765,6 +3765,7 @@ int strata::qwen35::run(int argc, char** argv) { size_t fr = 0, tot = 0, experts = 0; CK(cudaMemGetInfo(&fr, &tot)); for (const Layer& L : m.layers) experts += L.stride * (size_t) m.g.n_expert; + const size_t fr_raw = fr; // before the packed Q8_0 copies count as given back // (the MTP block's experts can go to the CPU, the packed Q8_0 copies can be given back: see place_experts) size_t packed = 0; for (const auto& pk : m.packed) packed += std::get<2>(pk); @@ -3778,14 +3779,16 @@ int strata::qwen35::run(int argc, char** argv) { if (fits && expert_vram < 0) { // a bigger prompt chunk feeds the MMQ expert kernels more rows per expert (R9700, UD-Q4_K_XL, pp4096: 512 3390, 1024 // 4495, 2048 5353, 4096 5750 tok/s): the largest that fits beside the experts. Its buffers grow by about 0.5 MiB per - // token (measured 0.47: 1.66 GiB more at 4096 than at 512), the sessions' K / V caches by 45 KB per cell and session. + // token (measured 0.47: 1.66 GiB more at 4096 than at 512), the sessions' K / V caches by 50 KB per cell and session. // With several slots a long prompt would hold the other slots' windows for a whole chunk: 1024 at most there. - const double kv_cell = 45056.0; + // (measured on a 32 GB R9700 at 8192 cells, 512 chunk: 1.77 GiB of buffers + K / V; the free room after init must still hold + // every expert and the 0.77 GiB reserve, or place_experts gives the packed decode copies back - slower decode - or goes hybrid) const int ns = std::max(1, batch); - const double sess_extra = std::max(0.0, (double) ns * (double) ctx * kv_cell - 8192.0 * kv_cell); + const double kv_one = 45056.0, kv_shared = 5120.0; // per cell: a session's K / V, and the fp16 copies the prompt attention keeps + const double sess_extra = std::max(0.0, (double) ctx * (kv_one * ns + kv_shared) - 8192.0 * (kv_one + kv_shared)); const int cap = ns > 1 ? 1024 : 4096; for (int c : {4096, 2048, 1024}) - if (c <= cap && want + (double) (c - 512) * 0.5 * 1048576.0 + sess_extra <= (double) fr) { + if (c <= cap && (double) experts + 2.75 * GiB + (double) (c - 512) * 0.5 * 1048576.0 + sess_extra <= (double) fr_raw) { // (no give-back of the packed decode copies for a bigger chunk) chunk = c; break; } @@ -3797,8 +3800,8 @@ int strata::qwen35::run(int argc, char** argv) { } if (const char* cv = std::getenv("STRATA_Q36_CHUNK")) chunk = std::max(256, std::min(4096, std::atoi(cv))); // force a chunk (512: the old default) if (std::getenv("STRATA_Q36_PLACE_DEBUG")) - std::fprintf(stderr, "strata-q36: chunk rule: free %.2f GiB (with %.2f packed), main experts %.2f GiB\n", - fr / 1073741824.0, packed / 1073741824.0, experts / 1073741824.0); + std::fprintf(stderr, "strata-q36: chunk rule: free %.2f GiB (raw %.2f, with %.2f packed), main experts %.2f GiB, chunk %d\n", + fr / 1073741824.0, fr_raw / 1073741824.0, packed / 1073741824.0, experts / 1073741824.0, chunk); } E.init(m, ctx, chunk, batch, vision); if (!place_experts(m, E, expert_vram, cpu_threads, hybrid_rows, expert_slots, err)) { From 6612542e175df4e205fbaa8a925d479d92ba10a2 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 11:43:29 +0200 Subject: [PATCH 6/8] tools/qwen35: q36_lgcmp.py (two logits dumps: KL, top-1) and the multilingual draft-head prompts --- tools/qwen35/q36_lgcmp.py | 13 +++++++++ tools/qwen35/q36_multilingual_prompts.py | 35 ++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 tools/qwen35/q36_lgcmp.py create mode 100644 tools/qwen35/q36_multilingual_prompts.py diff --git a/tools/qwen35/q36_lgcmp.py b/tools/qwen35/q36_lgcmp.py new file mode 100644 index 00000000..fbf62b53 --- /dev/null +++ b/tools/qwen35/q36_lgcmp.py @@ -0,0 +1,13 @@ +"""q36_lgcmp.py A.bin B.bin : two --dump-full-logits files (float32 [steps][248320]) compared: max |dlogit|, mean / max KL(A||B), top-1 agreement. +Used for the prompt-chunk and the kernel checks of docs/QWEN36.md.""" +import sys, numpy as np +V = 248320 +a = np.fromfile(sys.argv[1], dtype=np.float32).reshape(-1, V) +b = np.fromfile(sys.argv[2], dtype=np.float32).reshape(-1, V) +n = min(len(a), len(b)) +def lsm(x): + m = x.max(axis=1, keepdims=True) + return x - m - np.log(np.exp(x - m).sum(axis=1, keepdims=True)) +pa, pb = lsm(a[:n].astype(np.float64)), lsm(b[:n].astype(np.float64)) +kl = (np.exp(pa) * (pa - pb)).sum(axis=1) +print("steps %d max|dlogit| %.4f mean KL(a||b) %.3e max KL %.3e top1 same %d/%d" % (n, np.abs(a[:n]-b[:n]).max(), kl.mean(), kl.max(), (a[:n].argmax(1)==b[:n].argmax(1)).sum(), n)) diff --git a/tools/qwen35/q36_multilingual_prompts.py b/tools/qwen35/q36_multilingual_prompts.py new file mode 100644 index 00000000..4147d10a --- /dev/null +++ b/tools/qwen35/q36_multilingual_prompts.py @@ -0,0 +1,35 @@ +"""q36_multilingual_prompts.py TOKENIZER.json OUT.ids : multilingual / code chat prompts (ChatML, thinking off) as id lists, and the share of token ids +above a few draft-vocab limits in the model's own tokens (the texts below).""" +import sys, json +from tokenizers import Tokenizer + +tok = Tokenizer.from_file(sys.argv[1]) +P = [ + ("en", "Explain how a hash table handles collisions, in about 150 words."), + ("ru", "Объясни простыми словами, как работает рекурсия в программировании, и приведи пример на Python."), + ("zh", "请用中文简单解释一下什么是机器学习,以及它和传统编程的区别。"), + ("es", "Escribe un párrafo sobre la importancia de dormir bien y cómo afecta al rendimiento diario."), + ("de", "Erkläre mir den Unterschied zwischen einem Prozess und einem Thread in einem Betriebssystem."), + ("ja", "日本の四季について、それぞれの季節の特徴を簡単に説明してください。"), + ("ar", "اشرح لي باختصار كيف تعمل الطاقة الشمسية وما هي فوائدها للبيئة."), + ("hi", "भारत की राजधानी के बारे में कुछ वाक्य लिखिए और वहाँ के प्रसिद्ध स्थानों के नाम बताइए।"), + ("ko", "인공지능이 일상생활에 어떤 영향을 미치는지 간단하게 설명해 주세요."), + ("fr", "Rédige un court e-mail pour demander un rendez-vous avec un professeur au sujet d'un mémoire."), + ("code", "Write a Python function that merges two sorted lists into one sorted list, with a short docstring and two tests."), + ("math", "Solve step by step: a train travels 180 km in 2.5 hours. What is its average speed in m/s?"), +] +out = [] +ids_all = [] +for name, text in P: + s = "<|im_start|>user\n" + text + "<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + ids = tok.encode(s).ids + out.append((name, ids)) + ids_all.append(ids) +with open(sys.argv[2], "w") as f: + for name, ids in out: + f.write(",".join(map(str, ids)) + "\n") +with open(sys.argv[2] + ".names", "w") as f: + f.write("\n".join(n for n, _ in out) + "\n") +for name, ids in out: + over = {lim: sum(1 for i in ids if i >= lim) / len(ids) for lim in (32768, 65536, 98304, 131072, 151643)} + print("%-5s %3d tokens; share of ids >= %s" % (name, len(ids), " ".join("%d:%.0f%%" % (k, 100 * v) for k, v in over.items()))) From 55bae973fbac9d1baba3e7eaaa7e134854cc5390 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 21:38:07 +0200 Subject: [PATCH 7/8] qwen35: the prompt delta rule takes two barriers per token instead of three The output sum of token t is done after token t + 1's first barrier (sk / sq double-buffered), off the recurrence's chain. Same arithmetic: the 3000-token prompt's logits and 8 greedy steps are bit-identical to the base engine at chunk 512 and 2048 (R9700: 913 -> 885 ms, 607 -> 573 ms). --- src/qwen35/q36_engine.cu | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/src/qwen35/q36_engine.cu b/src/qwen35/q36_engine.cu index de95aedb..92bbd9b0 100644 --- a/src/qwen35/q36_engine.cu +++ b/src/qwen35/q36_engine.cu @@ -746,7 +746,9 @@ constexpr int kGdnColGroups = 4; __global__ void __launch_bounds__(512) k_gdn_seq_cols(float* state, const float* h, int C, const float* gate, const float* beta, float* o_raw, int h_k, int h_v, int T) { constexpr int S = 128, NC = S / kGdnColGroups, RG = 16, RPG = S / RG; - __shared__ float sk[S], sq[S]; + // two barriers per token (was three): sk / sq are double-buffered, and the output sum of token t is done after token t + 1's first + // barrier, off the chain of the recurrence (red_o is read between that barrier and the next one, written after it) + __shared__ float sk[2][S], sq[2][S]; __shared__ float red_kv[RG][NC]; __shared__ float red_o[RG][NC]; const int head = blockIdx.x, cl = threadIdx.x, rg = threadIdx.y, tid = rg * NC + cl; @@ -768,14 +770,21 @@ __global__ void __launch_bounds__(512) k_gdn_seq_cols(float* state, const float* }; if (T > 0) load(0); for (int t = 0; t < T; ++t) { - if (tid < S) { sk[tid] = nsk; sq[tid] = nsq; } + const int par = t & 1; + if (tid < S) { sk[par][tid] = nsk; sq[par][tid] = nsq; } const float vcur = nvv, gcur = ngate, bcur = nbeta; if (t + 1 < T) load(t + 1); __syncthreads(); + if (t > 0 && rg == 0) { // token t - 1's output + float oc = 0.0f; +#pragma unroll + for (int i = 0; i < RG; ++i) oc += red_o[i][cl]; + o_raw[(size_t) (t - 1) * h_v * S + head * S + col] = oc * rsqrtf((float) S); + } const float g = __expf(gcur); float kv = 0.0f; #pragma unroll - for (int r = 0; r < RPG; ++r) kv = fmaf(sv[r], sk[rg * RPG + r], kv); + for (int r = 0; r < RPG; ++r) kv = fmaf(sv[r], sk[par][rg * RPG + r], kv); red_kv[rg][cl] = kv; __syncthreads(); float kv_col = 0.0f; @@ -785,17 +794,17 @@ __global__ void __launch_bounds__(512) k_gdn_seq_cols(float* state, const float* float o = 0.0f; #pragma unroll for (int r = 0; r < RPG; ++r) { - sv[r] = fmaf(g, sv[r], sk[rg * RPG + r] * delta); - o = fmaf(sv[r], sq[rg * RPG + r], o); + sv[r] = fmaf(g, sv[r], sk[par][rg * RPG + r] * delta); + o = fmaf(sv[r], sq[par][rg * RPG + r], o); } red_o[rg][cl] = o; - __syncthreads(); - if (rg == 0) { - float oc = 0.0f; + } + __syncthreads(); + if (T > 0 && rg == 0) { // the last token's output + float oc = 0.0f; #pragma unroll - for (int i = 0; i < RG; ++i) oc += red_o[i][cl]; - o_raw[(size_t) t * h_v * S + head * S + col] = oc * rsqrtf((float) S); - } + for (int i = 0; i < RG; ++i) oc += red_o[i][cl]; + o_raw[(size_t) (T - 1) * h_v * S + head * S + col] = oc * rsqrtf((float) S); } #pragma unroll for (int r = 0; r < RPG; ++r) base[r * row_stride] = sv[r]; From bb90c106b687cd5ac9eb565bc4977c1e087b1ebe Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 22:04:58 +0200 Subject: [PATCH 8/8] docs/QWEN36.md: speed section (kernels, measured R9700 / RTX 3060 numbers, the prompt chunk default and its KL, what was dropped) --- docs/QWEN36.md | 56 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/docs/QWEN36.md b/docs/QWEN36.md index ae1d408a..34a86c23 100644 --- a/docs/QWEN36.md +++ b/docs/QWEN36.md @@ -1,4 +1,4 @@ -# Qwen3.6-35B-A3B: pictures and several requests at once +# Qwen3.6-35B-A3B: pictures, several requests at once and speed Strata runs [Qwen3.6-35B-A3B](https://huggingface.co/Qwen/Qwen3.6-35B-A3B) (35B mixture of experts, 3B active, 256 experts, top-8) from [Unsloth's GGUFs with the MTP layer](https://huggingface.co/unsloth/Qwen3.6-35B-A3B-MTP-GGUF) (UD-Q4_K_XL, UD-Q6_K_XL, Q8_0) on its own @@ -114,6 +114,60 @@ In the hybrid mode the text of a request can differ a little between running alo GPU or on the CPU change with the routing of all the requests, and the two compute with different rounding. With the slot tables fixed (`STRATA_Q36_FIXED_SLOTS=1`, a test setting) every slot equals its solo run there too, with and without `--batch-mtp`. +## Speed (0.1.45) + +Decode and prompt kernels of this engine path were rewritten for speed; **every change on the decode path gives the old kernels' bits** +(`STRATA_Q36_VERIFY=1 strata ... --no-graph` runs the old kernel beside each new one on the real activations and compares them bit for bit: +0 mismatches in 18,360 / 8,187 / 6,399 comparisons on the R9700 and the RTX 3060; `STRATA_Q36_OLD_KERNELS=1` switches them all off). The +10 parity prompts (greedy 128) give the base engine's tokens, plain and with `--mtp 2`. Where the prompt's chunk size changes, the numbers +change a little: see "Prompt chunk". + +**What was slow** (rocprofv3, R9700, UD-Q4_K_XL, plain decode, 11.25 ms of kernel time per token): the big Q8_0 products (attention, GDN +projections, head: 1.9 GB per token) run at 530 GB/s, the memory bound. The rest did not: the shared expert's and the attention k/v products +(140 per token) at 18 us, the Q4_K gate/up kernel at 250 GB/s, `k_moe_out` (one block) 17 us, `k_group` (one thread walking 256 experts) 9 us. +Now: those products one warp per row (a launch of 2048 warps took 21 us on gfx1201 where 1024 warps took 5 us, so the grid is capped), shared +gate+up+SwiGLU+q8_1 in one launch, the MoE end with 1024 threads and the next layer's q8_1 image, add+norm+q8_1 in one launch, router top-k and +grouping in one launch, the router and the shared gate in one product, Q4_K gate/up on the V2K kernels (`STRATA_EXPERT_V2K`, gfx12 default). +The prompt's GDN conv runs in tiles of 16 tokens side by side and the delta rule loads one token ahead with two barriers per token (both exact). + +R9700 32 GB (p620, HIP gfx1201), UD-Q4_K_XL, base = the engine before this work, 5 interleaved pairs, 3 repetitions each, medians; llama.cpp +972b5fc HIP on the same file (`-fa 1`, best of `-ub` 512 / 2048): + +| | base | 0.1.45 | ratio | pairs faster | llama.cpp | +| --- | ---: | ---: | ---: | ---: | ---: | +| decode tg128 | 83.2 tok/s | 117.8 | 1.42 | 5/5 | 81.9-82.1 | +| prompt pp4096 | 3,453 | 6,220 (chunk 4096) | 1.80 | 5/5 | 3,794 (-ub 2048) / 3,042 (-ub 512) | +| `--mtp 2`, 10 prompts greedy 128 | 167.7 | 183.7 | 1.10 | 3/3 | 129 (draft-mtp, n-max 2, earlier run) | +| 1 / 2 / 4 / 8 requests at once (`--batch 8 --mtp 0`) | 85.2 / 182.4 / 271.9 / 361.1 | 122.4 / 205.1 / 303.3 / 386.9 | 1.44 / 1.12 / 1.12 / 1.07 | 5/5 | | + +UD-Q6_K_XL on the same card (every main layer's experts in VRAM, so the prompt chunk stays 512): decode 80.4 -> 106.9 tok/s (1.33), pp4096 +2,160 -> 2,200 (llama.cpp 3,486 at -ub 2048, 2,738 at -ub 512; decode 81.1), `--mtp 2` 154.7 -> 167.3. `--chunk 2048` there moves the experts +to the hybrid placement (205 of 256 per layer in VRAM): prompt 3,500 tok/s, decode 94 - an option, not the default. + +RTX 3060 12 GB (P2003, CUDA sm_86, 20 threads), UD-Q4_K_XL in the hybrid mode (37 of 256 experts per layer in VRAM): the GPU part of a +token is the dense Q8_0 at the card's bandwidth (6 ms of the 17) and the rest waits for the CPU pool (9 ms of experts), so only the small +kernels' share is gained: decode tg128 58.5 -> 59.7 tok/s (+2%), pp2048 1,958 -> 2,022 (+3.3%), 10/10 identical, plain and `--mtp 2` +(84.3 -> 84.7). llama.cpp 972b5fc CUDA (`-ncmoe 26 -t 8 -ub 2048`): pp2048 1,328, tg128 48-52. + +**Prompt chunk (the default changed).** The MoE prompt kernels read every expert once per chunk, so a bigger chunk feeds them more rows per +expert: R9700 pp4096 at chunk 512 / 1024 / 2048 / 4096 = 3,453 / 4,786 / 5,766 / 6,223 tok/s. With every expert in VRAM the engine now takes the +largest of 4096 / 2048 / 1024 that fits beside the experts, the 0.77 GiB reserve and the sessions' caches without giving the packed decode +copies back (8K-64K context: 4096, 100K: 2048, 131K: 512; `--batch 2..4`: 1024 at most so the other slots are not held for a whole chunk, +`--batch 8`: 512). The hybrid mode keeps 2048 (a bigger chunk takes expert slots: RTX 3060 chunk 4096 reads prompts 5% faster and decodes 13% +slower) and goes down to 1024 / 512 on a card with 7.5 / 5.5 GiB free. **`--prefill 512` (or `STRATA_Q36_CHUNK=512`) gives the old size, and +then the text is the base engine's, bit for bit.** The chunk size changes the GEMM tiles the BLAS picks and with them the last bits of the +prompt state: KL against the 512 chunk on six real 1.5-3.2K-token documents (48 teacher-forced rows each): chunk 1024 4.0e-3, 2048 4.2e-3, +4096 3.6e-3 (per prompt 2.3e-3 .. 5.9e-3), top-1 agreement 44-48 of 48 rows - the size of the llama.cpp CPU-vs-HIP difference on the same +file (4.2e-3), not a quality loss. Greedy 64 tokens after those six documents: the default chunk gives the base engine's text for 2 of 6, +`--prefill 512` for 6 of 6. A prompt shorter than the chunk (every chat turn after the first) is one chunk either way: unchanged. +The new default's goldens are `phaseA-tests/q36speed/golden/` (six documents, greedy 64): later changes are checked against them. + +**Tried and dropped.** The MTP drafts' head over a subset of the vocabulary (`--draft-vocab N`, kept as an opt-in; the answer never +changes): the first 16K-131K rows gain 5-8% on English and code but lose 10-15% on Chinese / Russian / Arabic / Hindi (70% of a Chinese +prompt's token ids are above 65,536), and a candidate list built from the tokens seen so far loses on both. The shared expert on a second +stream (captured into the decode graph) decodes at 36 tok/s instead of 117 with this ROCm. Chunked (WY) GDN and the PCIe-assisted hybrid decode +were not attempted. + ## Not done / limits - Eight slots at most (the window holds 8 rows); `--batch-mtp` shares those rows between slots and proposals.