From de81ac91f47f2dcd93cededa81049c6d452a0f5f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 12 Oct 2026 21:11:03 +0200 Subject: [PATCH] Qwen3.6 T1: SiLU-gated GDN step and a 256/8 router in the native kernels; q36ref runs on them - fused_gdn_step_norm_silu: the fused GDN step with the SiLU output gate (Qwen3.6), a compile-time template flag; fused_gdn_step_norm (Flash-Next, sigmoid) is the same kernel instantiated as before. - native_router_topk(n_expert, k): 512/10 goes to the existing pinned top-10 kernels unchanged; 256/8 is a templated copy of the same topk-moe contract. - strata-q36ref --kernels strata (default): native MMVQ (q8_1) for every quantized matmul, dense and per routed expert (Q4_K/Q5_K/Q6_K/Q8_0), the fused GDN conv+L2 and SiLU step, the native router; --kernels plain keeps the reference kernels. - kl.py: answer-only statistics beside all steps, llama.cpp's logits cached between runs. --- CMakeLists.txt | 2 +- include/strata/kernels/fused_gdn.hpp | 6 ++ include/strata/kernels/native_router.hpp | 4 + src/kernels/cuda/fused_gdn.cu | 30 ++++-- src/kernels/cuda/native_router.cu | 73 ++++++++++++++ src/qwen35/q36ref.cu | 117 ++++++++++++++++++----- tools/qwen35/kl.py | 46 ++++++--- 7 files changed, 232 insertions(+), 46 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e0a3f170..1e9806e4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -613,7 +613,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) # against llama.cpp by tools/qwen35/; the engine itself does not run the family yet add_executable(strata-q36ref src/qwen35/q36ref.cu) target_include_directories(strata-q36ref PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) - target_link_libraries(strata-q36ref PRIVATE strata_warnings ${_strata_gpu_runtime_target}) + target_link_libraries(strata-q36ref PRIVATE strata_kernels strata_warnings ${_strata_gpu_runtime_target}) if(STRATA_ENABLE_HIP) enable_testing() diff --git a/include/strata/kernels/fused_gdn.hpp b/include/strata/kernels/fused_gdn.hpp index 0cf7c66c..d1f39cbd 100644 --- a/include/strata/kernels/fused_gdn.hpp +++ b/include/strata/kernels/fused_gdn.hpp @@ -32,4 +32,10 @@ void fused_gdn_step_norm(float* state, const float* q, const float* k, const flo const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, void* stream); +/// The same step with the SiLU output gate, y = rmsnorm(o) * gamma * silu(z): Qwen3.6-35B-A3B's (qwen35moe) GDN +/// (CUDA / HIP; the SYCL port has no qwen35moe path). +void fused_gdn_step_norm_silu(float* state, const float* q, const float* k, const float* v, const float* gate, + const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, + int h_v, void* stream); + } // namespace strata::kernels diff --git a/include/strata/kernels/native_router.hpp b/include/strata/kernels/native_router.hpp index 96abaed0..a940e1b3 100644 --- a/include/strata/kernels/native_router.hpp +++ b/include/strata/kernels/native_router.hpp @@ -16,6 +16,10 @@ bool native_router_enabled(); void native_router_top10(const float* logits, int32_t* ids, float* weights, void* stream); /// n_tok rows at once (logits [n,512], ids/weights [n,10]); each row exactly as the single call. void native_router_top10_multi(const float* logits, int32_t* ids, float* weights, int n_tok, void* stream); +/// The same contract for a model family's (experts, top-k): 512 / 10 (Flash-Next: the two calls above, unchanged) and +/// 256 / 8 (Qwen3.6-35B-A3B). logits [n_tok, n_expert], ids / weights [n_tok, k]. CUDA / HIP. +bool native_router_topk_supported(int n_expert, int k); +void native_router_topk(const float* logits, int32_t* ids, float* weights, int n_expert, int k, int n_tok, void* stream); /// STRATA_ROUTE_RESIDENT: swap non-resident tail-rank experts for resident ones within `margin` logits (see the .cu). /// `stats` is nullptr or 4 device uint64 counters: tail entries seen, swaps, non-resident before, non-resident after. void native_route_resident(const float* logits, int32_t* ids, float* weights, const int32_t* res_layer, int n_tok, float margin, diff --git a/src/kernels/cuda/fused_gdn.cu b/src/kernels/cuda/fused_gdn.cu index 5d39cd2d..f2056cc4 100644 --- a/src/kernels/cuda/fused_gdn.cu +++ b/src/kernels/cuda/fused_gdn.cu @@ -13,6 +13,9 @@ constexpr int S = 128; // state size (rows = cols = 128) constexpr int RG = 4; // row groups constexpr int RPG = S / RG; // 32 rows per thread +// SILU: the output gate is SiLU(z) (Qwen3.6, qwen35moe) instead of sigmoid(z) (Flash-Next); a compile-time flag, so +// the sigmoid instantiation is the kernel it was. +template __global__ void __launch_bounds__(S * RG) gdn_step_norm_kernel(float* __restrict__ state, const float* __restrict__ q, const float* __restrict__ k, const float* __restrict__ v, const float* __restrict__ gate, @@ -66,7 +69,8 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_kernel(float* __restrict const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; const float scale = rsqrtf(ss / (float) S + eps); const float zz = z[head * S + col]; - y[head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + if constexpr (SILU) y[head * S + col] = oc * scale * gamma[col] * (zz / (1.0f + __expf(-zz))); + else y[head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); } } @@ -147,20 +151,34 @@ void fused_gdn_ab(const float* x, const uint16_t* w_alpha, const uint16_t* w_bet if (e != cudaSuccess) { std::fprintf(stderr, "fused_gdn_ab: %s\n", cudaGetErrorString(e)); std::exit(1); } } -void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate, - const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, - void* stream) { +namespace { +template +void step_norm(float* state, const float* q, const float* k, const float* v, const float* gate, const float* beta, + const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, void* stream) { if (!state || !q || !k || !v || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v <= 0 || h_v % h_k) { std::fprintf(stderr, "fused_gdn_step_norm: invalid arguments\n"); std::exit(1); } - gdn_step_norm_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>(state, q, k, v, gate, beta, z, - gamma, eps, y, h_k, h_v); + gdn_step_norm_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>(state, q, k, v, gate, beta, + z, gamma, eps, y, h_k, h_v); const cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { std::fprintf(stderr, "fused_gdn_step_norm: %s\n", cudaGetErrorString(e)); std::exit(1); } } +} // namespace + +void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate, + const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, + void* stream) { + step_norm(state, q, k, v, gate, beta, z, gamma, eps, y, h_k, h_v, stream); +} + +void fused_gdn_step_norm_silu(float* state, const float* q, const float* k, const float* v, const float* gate, + const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, + int h_v, void* stream) { + step_norm(state, q, k, v, gate, beta, z, gamma, eps, y, h_k, h_v, stream); +} } // namespace strata::kernels diff --git a/src/kernels/cuda/native_router.cu b/src/kernels/cuda/native_router.cu index 526b29c7..6611bceb 100644 --- a/src/kernels/cuda/native_router.cu +++ b/src/kernels/cuda/native_router.cu @@ -148,6 +148,63 @@ __global__ void route_multi(const float* __restrict__ logits, int32_t* __restric const float inverse_selected_sum = 1.0f / selected_sum; if (lane < 10) weights[lane] = selected * inverse_selected_sum; } +// The same contract for other (experts, top-k) shapes - Qwen3.6-35B-A3B's 256 / 8 - one warp per token, n_tok tokens +// (8 per block). The 512 / 10 path keeps its own kernels above (the Flash-Next bits), this template is only used +// for the other shapes. +template +__launch_bounds__(256, 1) +__global__ void route_topk(const float* __restrict__ logits, int32_t* __restrict__ ids, float* __restrict__ weights, + int n_tok) { + static_assert(NE % 32 == 0 && K <= 32, "experts in whole warps, at most 32 picks"); + constexpr int V = NE / 32; + const int tk = (int) blockIdx.x * 8 + (int) threadIdx.y; + if (tk >= n_tok) return; + logits += (size_t) tk * NE; ids += (size_t) tk * K; weights += (size_t) tk * K; + const int lane = threadIdx.x; + float values[V]; +#pragma unroll + for (int i = 0; i < V; ++i) values[i] = logits[lane + i * 32]; + float maximum = -INFINITY; +#pragma unroll + for (int i = 0; i < V; ++i) maximum = max(maximum, values[i]); + maximum = warp_max(maximum); + float sum = 0.0f; +#pragma unroll + for (int i = 0; i < V; ++i) { + values[i] = expf(values[i] - maximum); + sum += values[i]; + } + const float reciprocal = 1.0f / warp_sum(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[rank] = expert; + selected_sum += best; + } + if (rank == lane) selected = best; + } + selected_sum = max(warp_sum(selected_sum), 6.103515625e-5f); + const float inverse_selected_sum = 1.0f / selected_sum; + if (lane < K) weights[lane] = selected * inverse_selected_sum; +} bool valid(const void* p, size_t bytes) { const auto address = reinterpret_cast(p); return p && address % 4 == 0 && bytes <= UINTPTR_MAX - address; @@ -176,6 +233,22 @@ void native_router_top10_multi(const float* logits, int32_t* ids, float* weights const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); } +bool native_router_topk_supported(int n_expert, int k) { return (n_expert == 512 && k == 10) || (n_expert == 256 && k == 8); } +void native_router_topk(const float* logits, int32_t* ids, float* weights, int n_expert, int k, int n_tok, void* stream) { + if (n_expert == 512 && k == 10) { // Flash-Next: the pinned kernels above, unchanged + if (n_tok == 1) native_router_top10(logits, ids, weights, stream); + else native_router_top10_multi(logits, ids, weights, n_tok, stream); + return; + } + if (!stream || n_tok < 1 || !native_router_topk_supported(n_expert, k) || + !valid(logits, (size_t) n_tok * n_expert * 4) || !valid(ids, (size_t) n_tok * k * 4) || + !valid(weights, (size_t) n_tok * k * 4)) + throw std::invalid_argument("native_router_topk: a stream, a supported (experts, k) and aligned buffers"); + route_topk<256, 8><<<(unsigned) ((n_tok + 7) / 8), dim3(32, 8), 0, static_cast(stream)>>>( + logits, ids, weights, n_tok); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); +} // STRATA_ROUTE_RESIDENT (EXPERIMENTAL, opt-in, changes the output): residency-biased routing for 512 x 10. // After the top-10: for the ranks lo..hi a non-resident expert is replaced by the best resident expert not already diff --git a/src/qwen35/q36ref.cu b/src/qwen35/q36ref.cu index 3cfbf95b..8ef9b4b2 100644 --- a/src/qwen35/q36ref.cu +++ b/src/qwen35/q36ref.cu @@ -1,8 +1,10 @@ // src/qwen35/q36ref.cu - NEW-MODELS-PLAN.md phase T1: the reference path for Qwen3.6-35B-A3B (GGUF architecture // qwen35moe), exactness first. One GPU, the whole model resident in VRAM (UD-Q4_K_XL: 21.3 GiB on a 32 GB card), -// one token at a time (the prompt too), fp32 activations, every weight read in its GGUF form by plain kernels. -// No expert cache, no MTP, no graphs: this is the thing the optimised path is checked against, and itself checked -// against llama.cpp (per-layer hidden states and greedy tokens, tools/qwen35/). +// one token at a time (the prompt too), fp32 activations, every weight read in its GGUF form. Two kernel sets: +// --kernels plain, this file's own plain kernels (the reference), and --kernels strata (default), Strata's native +// MMVQ for the quantized matmuls (dense and routed experts) and its fused GDN step with the SiLU-gated norm - the +// engine's kernels on the new family's shapes. No expert cache, no MTP, no graphs: checked against llama.cpp +// (per-layer hidden states, greedy tokens, teacher-forced KL: tools/qwen35/). // // The forward pass, as llama.cpp's src/models/qwen35moe.cpp builds it: // x = token_embd[tok] @@ -21,13 +23,17 @@ // logits = W_output (rms(x) * output_norm) // // Usage: strata-q36ref --model Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf --tokens 248045,846,198,... [--n 64] [--ctx 4096] -// [--dump-layers FILE] [--dump-logits FILE] [--act q8|f32] [--force IDS] [--dump-full-logits F] +// [--dump-layers FILE] [--dump-logits FILE] [--act q8|f32] [--kernels strata|plain] +// [--force IDS] [--dump-full-logits F] // prints the greedy ids ("gen: id id ..."); --dump-layers writes every processed position's 40 layer outputs (f32, // [pos][layer][2048]); --dump-logits writes each greedy step's top-2 (id, logit) pairs for the near-tie report; // --force feeds the given continuation instead of the greedy ids and --dump-full-logits writes every step's // logits (f32, [step][vocab]) for the teacher-forced KL check (tools/qwen35/kl.py). #include "strata/artifact/gguf_reader.hpp" #include "strata/core/family_layout.hpp" +#include "strata/kernels/fused_gdn.hpp" +#include "strata/kernels/native_mmvq.hpp" +#include "strata/kernels/native_router.hpp" #include @@ -232,6 +238,14 @@ __global__ void k_gdn(const float* conv, const float* alpha, const float* dt_bia out[h * D + i] = o; } +/// The fused path's gate and beta, in place: alpha -> softplus(alpha + dt) * ssm_a (exp'd by the step), beta -> sigmoid. +__global__ void k_gdn_gb(float* alpha, const float* dt_bias, const float* ssm_a, float* beta, int HV) { + const int h = threadIdx.x; + if (h >= HV) return; + alpha[h] = softplus(alpha[h] + dt_bias[h]) * ssm_a[h]; + beta[h] = sigm(beta[h]); +} + /// o = rms(o) * w * silu(z), per V head (grid = HV, block = D). __global__ void k_gated_norm(float* o, const float* w, const float* z, int D, float eps) { __shared__ float sh[kThreads]; @@ -373,9 +387,34 @@ bool g_act_q8 = true; float* g_act_buf = nullptr; constexpr size_t kActBuf = 1 << 16; +// --kernels strata (the default): the quantized matmuls run on Strata's native MMVQ (llama.cpp's pinned MMVQ: q8_1 +// activations, one launch per routed expert) and the GDN step on Strata's fused kernels (conv + SiLU + L2, then the +// step with the SiLU-gated norm); --kernels plain keeps every op on this file's own kernels (the reference). The +// Strata kernels run on a blocking stream, so they and the null-stream work here stay in order. +bool g_strata = true; +cudaStream_t g_st = nullptr; +void* g_q8 = nullptr; +std::vector g_ids_host; // the routed experts of the current layer (the native expert path launches per id) + void gemv(const Tensor& w, const float* x, float* y, const int* ids = nullptr, int n_sel = 1, size_t x_stride = 0) { const size_t eb = w.shape.size() == 3 ? w.row_bytes * (size_t) w.shape[1] : 0; const bool quant = w.type == T_Q8_0 || w.type == T_Q4_K || w.type == T_Q5_K || w.type == T_Q6_K; + if (quant && g_strata) { + const int n_in = (int) w.shape[0], n_out = (int) w.shape[1], cols = x_stride ? n_sel : 1; + if (x_stride && x_stride != (size_t) n_in) { + std::fprintf(stderr, "q36ref: the native path wants contiguous input columns\n"); + std::exit(1); + } + strata::kernels::native_quantize_q8_1(x, g_q8, n_in, cols, g_st); + const size_t qb = strata::kernels::native_q8_1_bytes(n_in, 1); + for (int sel = 0; sel < n_sel; ++sel) { + const uint8_t* we = w.d + (ids ? (size_t) g_ids_host[(size_t) sel] * eb : 0); + strata::kernels::native_mmvq(w.type, we, (const char*) g_q8 + (x_stride ? (size_t) sel * qb : 0), + y + (size_t) sel * n_out, n_in, n_out, 1, g_st); + } + CK(cudaGetLastError()); + return; + } if (quant && g_act_q8) { const int n = (int) w.shape[0], sel = x_stride ? n_sel : 1; if ((size_t) n * sel > kActBuf) { @@ -531,6 +570,8 @@ void init_state(const Model& m, State& s) { s.logits = dalloc(g.n_vocab); CK(cudaMalloc(&s.ids, K * sizeof(int))); g_act_buf = dalloc(kActBuf); + CK(cudaStreamCreate(&g_st)); // blocking: ordered with this file's null-stream launches and copies + CK(cudaMalloc(&g_q8, strata::kernels::native_q8_1_bytes((int) kActBuf, 1))); for (int64_t l = 0; l < g.n_layers; ++l) { if (strata::core::is_qsa_layer(g, l)) { s.conv_state.push_back(nullptr); @@ -579,11 +620,22 @@ void forward(const Model& m, State& s, int tok, float* layers) { gemv(m.W(L(l, "attn_gate.weight")), s.h, s.z); gemv(m.W(L(l, "ssm_beta.weight")), s.h, s.beta); gemv(m.W(L(l, "ssm_alpha.weight")), s.h, s.alpha); - k_conv<<<(C + B - 1) / B, B>>>(s.qkv, s.conv_state[l], m.F(L(l, "ssm_conv1d.weight")), s.conv_out, C, - (int) g.ssm_d_conv); - k_gdn<<>>(s.conv_out, s.alpha, m.F(L(l, "ssm_dt.bias")), - m.F(L(l, "ssm_a")), s.beta, s.S[l], s.gdn_out, HK, HV, D, m.eps); - k_gated_norm<<>>(s.gdn_out, m.F(L(l, "ssm_norm.weight")), s.z, D, m.eps); + if (g_strata && D == 128 && g.ssm_d_conv == 4) { + // Strata's fused GDN (its own state layouts: conv history [channel][3], S [row][head][col]) + strata::kernels::fused_gdn_conv_l2(s.conv_state[l], s.qkv, m.F(L(l, "ssm_conv1d.weight")), s.conv_out, + C, 2 * HK, m.eps, g_st); + k_gdn_gb<<<1, 64, 0, g_st>>>(s.alpha, m.F(L(l, "ssm_dt.bias")), m.F(L(l, "ssm_a")), s.beta, HV); + strata::kernels::fused_gdn_step_norm_silu(s.S[l], s.conv_out, s.conv_out + HK * D, + s.conv_out + 2 * HK * D, s.alpha, s.beta, s.z, + m.F(L(l, "ssm_norm.weight")), m.eps, s.gdn_out, HK, HV, g_st); + } else { + k_conv<<<(C + B - 1) / B, B>>>(s.qkv, s.conv_state[l], m.F(L(l, "ssm_conv1d.weight")), s.conv_out, C, + (int) g.ssm_d_conv); + k_gdn<<>>(s.conv_out, s.alpha, m.F(L(l, "ssm_dt.bias")), + m.F(L(l, "ssm_a")), s.beta, s.S[l], s.gdn_out, HK, HV, D, + m.eps); + k_gated_norm<<>>(s.gdn_out, m.F(L(l, "ssm_norm.weight")), s.z, D, m.eps); + } gemv(m.W(L(l, "ssm_out.weight")), s.gdn_out, s.y); } else { const int H = (int) g.n_head, HKV = (int) g.n_head_kv, D = (int) g.head_dim; @@ -602,21 +654,30 @@ void forward(const Model& m, State& s, int tok, float* layers) { k_rms<<<1, kThreads>>>(s.x, m.F(L(l, "post_attention_norm.weight")), s.h, N, m.eps); // router: softmax over every expert, top-k, renormalised (host side: exact and simple) gemv(m.W(L(l, "ffn_gate_inp.weight")), s.h, s.router); - std::vector r((size_t) g.n_expert); - CK(cudaMemcpy(r.data(), s.router, r.size() * 4, cudaMemcpyDeviceToHost)); - const float mx = *std::max_element(r.begin(), r.end()); - double sum = 0; - for (float& v : r) sum += (v = std::exp(v - mx)); - for (float& v : r) v = (float) (v / sum); - std::vector idx((size_t) g.n_expert); - for (int i = 0; i < (int) idx.size(); ++i) idx[i] = i; - std::partial_sort(idx.begin(), idx.begin() + K, idx.end(), [&](int a, int b) { return r[a] > r[b] || (r[a] == r[b] && a < b); }); - std::vector w(K); - float ws = 0; - for (int i = 0; i < K; ++i) ws += (w[i] = r[idx[i]]); - for (float& v : w) v /= ws; - CK(cudaMemcpy(s.ids, idx.data(), K * sizeof(int), cudaMemcpyHostToDevice)); - CK(cudaMemcpy(s.wts, w.data(), K * 4, cudaMemcpyHostToDevice)); + if (g_strata && strata::kernels::native_router_topk_supported((int) g.n_expert, K)) { + // Strata's router (llama.cpp's topk-moe contract) for 256 / 8; the ids come back for the per-expert launches + strata::kernels::native_router_topk(s.router, s.ids, s.wts, (int) g.n_expert, K, 1, g_st); + g_ids_host.resize((size_t) K); + CK(cudaMemcpy(g_ids_host.data(), s.ids, K * sizeof(int), cudaMemcpyDeviceToHost)); + } else { + std::vector r((size_t) g.n_expert); + CK(cudaMemcpy(r.data(), s.router, r.size() * 4, cudaMemcpyDeviceToHost)); + const float mx = *std::max_element(r.begin(), r.end()); + double sum = 0; + for (float& v : r) sum += (v = std::exp(v - mx)); + for (float& v : r) v = (float) (v / sum); + std::vector idx((size_t) g.n_expert); + for (int i = 0; i < (int) idx.size(); ++i) idx[i] = i; + std::partial_sort(idx.begin(), idx.begin() + K, idx.end(), + [&](int a, int b) { return r[a] > r[b] || (r[a] == r[b] && a < b); }); + std::vector w(K); + float ws = 0; + for (int i = 0; i < K; ++i) ws += (w[i] = r[idx[i]]); + for (float& v : w) v /= ws; + g_ids_host.assign(idx.begin(), idx.begin() + K); + CK(cudaMemcpy(s.ids, idx.data(), K * sizeof(int), cudaMemcpyHostToDevice)); + CK(cudaMemcpy(s.wts, w.data(), K * 4, cudaMemcpyHostToDevice)); + } gemv(m.W(L(l, "ffn_gate_exps.weight")), s.h, s.eg, s.ids, K, 0); gemv(m.W(L(l, "ffn_up_exps.weight")), s.h, s.eu, s.ids, K, 0); k_swiglu<<<(K * FF + B - 1) / B, B>>>(s.eg, s.eu, s.eh, K * FF); @@ -684,6 +745,11 @@ int main(int argc, char** argv) { else if (a == "--dump-layers") dump_layers = next(); else if (a == "--dump-logits") dump_logits = next(); else if (a == "--force") force = next(); + else if (a == "--kernels") { + const std::string v = next(); + if (v != "strata" && v != "plain") { std::fprintf(stderr, "q36ref: --kernels strata or plain\n"); return 2; } + g_strata = v == "strata"; + } else if (a == "--dump-full-logits") dump_full = next(); else if (a == "--act") { const std::string v = next(); @@ -692,7 +758,8 @@ int main(int argc, char** argv) { } else { std::fprintf(stderr, "usage: strata-q36ref --model GGUF --tokens ID,ID,... | --tokens-file F [--n 64] [--ctx 4096] " - "[--dump-layers FILE] [--dump-logits FILE] [--act q8|f32] [--force ID,ID,...] [--dump-full-logits FILE]\n"); + "[--dump-layers FILE] [--dump-logits FILE] [--act q8|f32] [--kernels strata|plain] " + "[--force ID,ID,...] [--dump-full-logits FILE]\n"); return 2; } } diff --git a/tools/qwen35/kl.py b/tools/qwen35/kl.py index f0279204..2ec18d57 100644 --- a/tools/qwen35/kl.py +++ b/tools/qwen35/kl.py @@ -16,6 +16,7 @@ from pathlib import Path import numpy as np V = 248320 +EOS = 248046 # <|im_end|> def ids(path: Path, key: str) -> list[int]: @@ -47,6 +48,7 @@ def main() -> int: ap.add_argument("--out", required=True) ap.add_argument("--lock", default="") ap.add_argument("--cpu-lock", default="") + ap.add_argument("--cache", default="", help="where llama.cpp's logits are kept between runs (default --out)") ap.add_argument("--ref-args", default="", help="extra strata-q36ref arguments (e.g. '--act f32')") a = ap.parse_args() out, par = Path(a.out), Path(a.parity) @@ -54,33 +56,49 @@ def main() -> int: tags = sorted(p.name.split(".")[0] for p in par.glob("p*.llama.log")) kl = {"cpu": [], "strata": []} top1 = {"cpu": [], "strata": []} + kl_ans = {"cpu": [], "strata": []} + top1_ans = {"cpu": [], "strata": []} for tag in tags: prompt, gen = ids(par / f"{tag}.llama.log", "prompt"), ids(par / f"{tag}.llama.log", "gen") force = ",".join(map(str, gen)) toks = ",".join(map(str, prompt)) - f = {k: out / f"{tag}.{k}.full" for k in ("gpu", "cpu", "strata")} - run([a.dump, "--model", a.model, "--tokens", toks, "--force", force, "--ngl", "99", "--dump-full-logits", - str(f["gpu"])], a.lock, out / f"{tag}.gpu.log") - run([a.dump, "--model", a.model, "--tokens", toks, "--force", force, "--ngl", "0", "--dump-full-logits", - str(f["cpu"])], a.cpu_lock, out / f"{tag}.cpu.log") + cache = Path(a.cache) if a.cache else out + f = {k: (out if k == "strata" else cache) / f"{tag}.{k}.full" for k in ("gpu", "cpu", "strata")} + # llama.cpp's two runs depend only on the model and the sequence: kept in --out and reused (64 MB each) + if not f["gpu"].exists(): + run([a.dump, "--model", a.model, "--tokens", toks, "--force", force, "--ngl", "99", "--dump-full-logits", + str(f["gpu"])], a.lock, cache / f"{tag}.gpu.log") + if not f["cpu"].exists(): + run([a.dump, "--model", a.model, "--tokens", toks, "--force", force, "--ngl", "0", "--dump-full-logits", + str(f["cpu"])], a.cpu_lock, cache / f"{tag}.cpu.log") run([a.ref, "--model", a.model, "--tokens", toks, "--force", force, "--dump-full-logits", str(f["strata"]), *shlex.split(a.ref_args)], a.lock, out / f"{tag}.strata.log") P = log_softmax(np.fromfile(f["gpu"], dtype=np.float32).reshape(-1, V)) - line = f"{tag}: {len(P)} steps" + # the answer: the steps up to and including the first <|im_end|> of the forced sequence (past it the context is + # one no chat reaches, and its distributions are the noisiest); "all" keeps every step + ans = gen.index(EOS) + 1 if EOS in gen else len(P) + line = f"{tag}: {len(P)} steps ({ans} answer)" + per = {} for k in ("cpu", "strata"): Q = log_softmax(np.fromfile(f[k], dtype=np.float32).reshape(-1, V)) n = min(len(P), len(Q)) d = (np.exp(P[:n]) * (P[:n] - Q[:n])).sum(axis=1) + t1 = P[:n].argmax(axis=1) == Q[:n].argmax(axis=1) kl[k].extend(d.tolist()) - top1[k].extend((P[:n].argmax(axis=1) == Q[:n].argmax(axis=1)).tolist()) - line += f"; {k}: KL {d.mean():.5f} top-1 {np.mean(P[:n].argmax(axis=1) == Q[:n].argmax(axis=1)):.3f}" - for p in f.values(): - p.unlink(missing_ok=True) # 250 MB each: the numbers are what is kept + top1[k].extend(t1.tolist()) + kl_ans[k].extend(d[:ans].tolist()) + top1_ans[k].extend(t1[:ans].tolist()) + per[k] = d + line += f"; {k}: KL {d.mean():.5f} (answer {d[:ans].mean():.5f}) top-1 {t1.mean():.3f}" + np.savez(out / f"{tag}.kl.npz", answer=ans, **per) + f["strata"].unlink(missing_ok=True) print(line, flush=True) - for k in ("cpu", "strata"): - print(f"{k:6s} vs llama.cpp HIP: mean KL {np.mean(kl[k]):.5f} (p99 {np.percentile(kl[k], 99):.4f}), top-1 " - f"{np.mean(top1[k]):.4f} over {len(kl[k])} steps") - print(f"ratio strata / floor: {np.mean(kl['strata']) / max(np.mean(kl['cpu']), 1e-12):.2f}") + for name, K, T in (("all steps", kl, top1), ("answers only", kl_ans, top1_ans)): + print(f"-- {name}") + for k in ("cpu", "strata"): + print(f"{k:6s} vs llama.cpp HIP: mean KL {np.mean(K[k]):.5f} (median {np.median(K[k]):.6f}, p99 " + f"{np.percentile(K[k], 99):.4f}), top-1 {np.mean(T[k]):.4f} over {len(K[k])} steps") + print(f"ratio strata / floor: {np.mean(K['strata']) / max(np.mean(K['cpu']), 1e-12):.2f}") return 0