q4lite: routed experts through the KEXP kernels (codes 1..8 per expert, fused / grouped paths)

moe_routed now calls strata::q4lite::gpu (q4_moe.cu): the fused single-token kernel for N = 1, the grouped-by-expert kernels from N = 16 tokens,
the per-pair kernels otherwise. q4_moe.cu / q4_moe_cpu.cpp added to the CMake targets.
This commit is contained in:
Niko1221 committed 2026-12-04 07:19:53 +01:00
commit 6420ce855c
16 files changed
+1760 -11

No files matched your search

@@ -0,0 +1,12 @@
// include/strata/kernels/gdn_pairing.hpp - which q/k head serves value head `head` in a GatedDeltaNet layer.
//
// Default (tiled, llama.cpp / the Flash-Next GGUFs, whose converter reorders the value heads): `head % h_k`.
// -DSTRATA_GDN_PAIR_GROUPED (Qwen4: the HF checkpoint order, `repeat_interleave`): `head / (h_v / h_k)`.
// Without the define every kernel keeps the expression it always had (`head % h_k`), so the default device code is unchanged.
#pragma once
#if defined(STRATA_GDN_PAIR_GROUPED)
#define STRATA_GDN_QH(head, h_k, h_v) ((head) / ((h_v) / (h_k)))
#else
#define STRATA_GDN_QH(head, h_k, h_v) ((head) % (h_k))
#endif
+2 -1
View File
@@ -1,5 +1,6 @@
// src/kernels/cuda/fused_gdn.cu - see include/strata/kernels/fused_gdn.hpp.
#include "strata/kernels/fused_gdn.hpp"
#include "strata/kernels/gdn_pairing.hpp"
#include "strata/core/geometry.hpp"
#include <cuda_runtime.h>
@@ -33,7 +34,7 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_kernel(float* __restrict
const int col = threadIdx.x; // 0..127
const int rg = threadIdx.y; // 0..3
const int tid = rg * S + col;
const int qh = head % h_k;
const int qh = STRATA_GDN_QH(head, h_k, h_v);
if (tid < S) { sk[tid] = k[qh * S + tid]; sq[tid] = q[qh * S + tid]; }
float s[RPG];
float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;
+2 -1
View File
@@ -3,6 +3,7 @@
// See include/strata/kernels/gdn.hpp for the state layout (S, h_v, S) and for why the recurrence needs no
// barrier at all: every line of it touches only one (j, h) column, so one thread owns a column end to end.
#include "strata/kernels/gdn.hpp"
#include "strata/kernels/gdn_pairing.hpp"
#include <cuda_runtime.h>
@@ -56,7 +57,7 @@ __global__ void gdn_step_kernel(float* __restrict__ state, const float* __restri
// stage this block's q/k rows and its per-head scalars
for (int hi = 0; hi < nh; ++hi) {
const int h = h0 + hi;
const int src = h % h_k; // MODULO head pairing
const int src = STRATA_GDN_QH(h, h_k, h_v); // MODULO head pairing
for (int i = threadIdx.x; i < S; i += JTHREADS) {
ks[hi][i] = k[src * S + i];
qs[hi][i] = q[src * S + i];
+2 -1
View File
@@ -24,6 +24,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "strata/kernels/native_gdn.hpp"
#include "strata/kernels/gdn_pairing.hpp"
#include "strata/core/geometry.hpp"
#include <cuda_runtime.h>
#include <atomic>
@@ -52,7 +53,7 @@ step(float* __restrict__ state, const float* __restrict__ q, const float* __rest
const int head = blockIdx.x;
const int lane = threadIdx.x;
const int col = blockIdx.z * blockDim.y + threadIdx.y;
const int q_head = head % h_k;
const int q_head = STRATA_GDN_QH(head, h_k, h_v);
float s_shard[4], k_reg[4], q_reg[4];
#pragma unroll
for (int r = 0; r < 4; ++r) {
+5 -4
View File
@@ -3,6 +3,7 @@
// The per-token arithmetic of every kernel here is transcribed from its single-token original (fused_gdn.cu,
// elementwise.cu) with the same operation order, so a verify window reproduces plain decode bit for bit.
#include "strata/kernels/verify_kernels.hpp"
#include "strata/kernels/gdn_pairing.hpp"
#include "strata/core/bw_dense_defaults.hpp"
#include "strata/core/geometry.hpp"
#include "strata/core/emulate.hpp"
@@ -269,7 +270,7 @@ __device__ __forceinline__ void gdn_step_commit_body(float* __restrict__ state,
const int col = blockIdx.y * 32 + col_local;
const int rg = threadIdx.y;
const int tid = rg * 32 + col_local; // 0 .. 127
const int qh = head % h_k;
const int qh = STRATA_GDN_QH(head, h_k, h_v);
const int qk = S * h_k;
float s[RPG];
float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;
@@ -344,7 +345,7 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __re
const int head = blockIdx.x;
const int col = threadIdx.x;
const int rg = threadIdx.y;
const int qh = head % h_k;
const int qh = STRATA_GDN_QH(head, h_k, h_v);
const int qk = S * h_k; // q at [0, qk), k at [qk, 2qk), v at [2qk, ...)
const int value_dim = S * h_v;
const int n = ALL_OUT ? T : (n_keep ? *n_keep : T);
@@ -441,7 +442,7 @@ __global__ void __launch_bounds__(GS_COLS * RG) gdn_step_split_kernel(float* __r
const int col = c0 + lc;
const int rg = threadIdx.y;
const int tid = rg * GS_COLS + lc;
const int qh = head % h_k;
const int qh = STRATA_GDN_QH(head, h_k, h_v);
const int qk = S * h_k;
const int value_dim = S * h_v;
const int n = n_keep ? *n_keep : T;
@@ -502,7 +503,7 @@ __global__ void __launch_bounds__(GS_COLS * RG) gdn_state_replay_kernel(float* _
const int col = c0 + lc;
const int rg = threadIdx.y;
const int tid = rg * GS_COLS + lc;
const int qh = head % h_k;
const int qh = STRATA_GDN_QH(head, h_k, h_v);
const int qk = S * h_k;
const int n = n_keep ? *n_keep : T;
float gv[MAXT], bv[MAXT], vv[MAXT];
+4 -3
View File
@@ -10,6 +10,7 @@
// registers - the chunk-serial scan of the reference's fwd kernel). The per-chunk 64x64 matrices A and P are
// computed once per (chunk, head) by the kkt kernel and read by the four column slices.
#include "strata/prefill/gdn_chunk.hpp"
#include "strata/kernels/gdn_pairing.hpp"
#include <cuda_runtime.h>
#if !defined(__HIPCC__)
@@ -81,7 +82,7 @@ __global__ void __launch_bounds__(128) gdn_chunk_kkt_kernel(float* __restrict__
extern __shared__ float sh[];
float* ks = sh;
float* qs = sh + CH * SP;
const int hh = blockIdx.y, ch = blockIdx.x, qh = hh % HK;
const int hh = blockIdx.y, ch = blockIdx.x, qh = STRATA_GDN_QH(hh, HK, HV);
const int64_t base = (size_t) ch * CH;
const float* kh = h + base * C + (size_t) HK * S + (size_t) qh * S;
const float* qh_ = h + base * C + (size_t) qh * S;
@@ -128,7 +129,7 @@ __global__ void __launch_bounds__(128) gdn_chunk_fwd_kernel(float* __restrict__
const float* __restrict__ gcum,
const float* __restrict__ A,
const float* __restrict__ P, int nchunks) {
const int hh = blockIdx.y, sl = blockIdx.x, j0 = sl * NS, qh = hh % HK;
const int hh = blockIdx.y, sl = blockIdx.x, j0 = sl * NS, qh = STRATA_GDN_QH(hh, HK, HV);
const int w = threadIdx.x >> 5, c = threadIdx.x & 31, col = j0 + c;
// red is double-buffered by token parity: the w==0 lane reads token t's partials while the other warps
// may already be staging token t+1's into the other slot (one barrier per token, no reader/writer race)
@@ -245,7 +246,7 @@ __global__ void __launch_bounds__(128) gdn_chunk_wmma_kernel(float* __restrict__
float* dlt = (float*) (Ps + CH * CH); // [CH][NS]
__half* dlt16 = (__half*) (dlt + CH * NS); // [CH][NS]
const int hh = blockIdx.y, sl = blockIdx.x, j0 = sl * NS, qh = hh % HK;
const int hh = blockIdx.y, sl = blockIdx.x, j0 = sl * NS, qh = STRATA_GDN_QH(hh, HK, HV);
const int w = threadIdx.x >> 5, c = threadIdx.x & 31, col = j0 + c;
// the state slice in through smem (load_matrix_sync of an accumulator tile is a shared-memory op on
// sm_70): Ug first as the f32 staging, then W's f32 image in the fragments and its f16 image in W16
+6 -1
View File
@@ -79,7 +79,12 @@ add_library(q4lite_gpu STATIC
# Qwen4
q4_model.cu q4_glue.cu q4_moe.cu q4_engine.cu)
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/q4_mixers_fn.cu")
target_sources(q4lite_gpu PRIVATE q4_mixers_fn.cu)
# the token mixers: Flash-Next kernels at the q4_lite geometry + q4_gdn / q4_attn (q4_mixer_sources.cmake)
include(${CMAKE_CURRENT_SOURCE_DIR}/q4_mixer_sources.cmake)
target_sources(q4lite_gpu PRIVATE q4_mixers_fn.cu ${Q4_MIXER_KERNELS})
target_compile_definitions(q4lite_gpu PUBLIC ${Q4_MIXER_DEFS})
set_source_files_properties(${Q4_MIXER_FASTMATH} PROPERTIES COMPILE_OPTIONS "--use_fast_math")
target_include_directories(q4lite_gpu PRIVATE ${engine_root}/third_party/ggml)
else()
target_sources(q4lite_gpu PRIVATE q4_mixers_stub.cpp)
endif()
@@ -0,0 +1,21 @@
# Standalone test build of the Qwen4 token mixers (q4_gdn / q4_attn on the Flash-Next kernels at the q4_lite geometry). Not part of the main CMake.
# cmake -S engine/src/q4lite/attn_tests -B build -DCMAKE_CUDA_ARCHITECTURES=86 && cmake --build build -j
cmake_minimum_required(VERSION 3.18)
project(q4_attn_tests LANGUAGES CXX CUDA)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CUDA_STANDARD 17)
get_filename_component(engine_root "${CMAKE_CURRENT_LIST_DIR}/../../.." ABSOLUTE)
set(STRATA_GEOMETRY "q4_lite" CACHE STRING "" FORCE)
include(${engine_root}/cmake/strata_geometry.cmake)
include(${engine_root}/src/q4lite/q4_mixer_sources.cmake)
add_library(q4k STATIC ${Q4_MIXER_KERNELS})
target_include_directories(q4k PUBLIC ${engine_root}/include ${engine_root}/third_party/ggml)
target_compile_definitions(q4k PUBLIC ${Q4_MIXER_DEFS})
target_compile_options(q4k PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--expt-relaxed-constexpr>)
set_source_files_properties(${Q4_MIXER_FASTMATH} PROPERTIES COMPILE_OPTIONS "--use_fast_math")
add_executable(q4_attn_test ${engine_root}/tests/q4lite/q4_attn_test.cu)
target_link_libraries(q4_attn_test PRIVATE q4k)
+318
View File
@@ -0,0 +1,318 @@
// src/q4lite/q4_attn.cu - see q4_attn.hpp. The heavy kernels (norm + rope, indexer pooling / scores / top-k, attention) are Flash-Next's, compiled at the q4_lite
// geometry; this file wires them to the HF semantics of Qwen4 (gammas 1 + w, selection width 512 groups + tail, projection layouts) and adds the small
// glue kernels (index_qk split, batched fp16 KV append, rope position fill). Plain CUDA, no tensor-core or PTX code of its own.
#include "q4_attn.hpp"
#include "strata/core/geometry.hpp"
#include "strata/kernels/f16_bits.hpp"
#include "strata/kernels/mrope.hpp"
#include "strata/kernels/native_qsa.hpp"
#include "strata/kernels/native_qsa_indexer.hpp"
#include "strata/kernels/native_rope.hpp"
#include "strata/kernels/qsa.hpp"
#include "strata/kernels/qsa_decode_attn.hpp"
#include "strata/kernels/qsa_prompt_attn.hpp"
#include "strata/kernels/qsa_select.hpp"
#include "strata/kernels/rope.hpp"
#include "strata/kernels/rope_scaling.hpp"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <vector>
namespace strata::q4lite {
namespace K = strata::kernels;
namespace {
constexpr float kEps = 1e-6f;
constexpr int kTail = 3; // ixb - 1
inline size_t al16(size_t x) { return (x + 15) & ~size_t(15); }
float* g_cos = nullptr;
float* g_sin = nullptr;
bool shape_ok(const AttnShape& s, std::string& err) {
const auto& g = strata::core::kCompiledGeometry;
if (s.nh != g.n_head || s.nkv != g.n_head_kv || s.hd != g.head_dim || s.n_rot != g.n_rot || s.ixh != g.idx_q_heads || s.ixd != g.idx_key_dim ||
s.ixb != g.idx_block || s.ix_budget != g.idx_top_k) {
err = "attn: the shape differs from the compiled geometry (core/geometry.hpp)";
return false;
}
return true;
}
bool launch_ok(std::string& err, const char* what) {
const cudaError_t e = cudaGetLastError();
if (e == cudaSuccess) return true;
err = std::string(what) + ": " + cudaGetErrorString(e);
return false;
}
K::QsaShapes qshapes(const AttnShape& s) {
K::QsaShapes q = K::qsa_real_shapes(); // page_size 4
q.n_head = s.nh; q.n_head_kv = s.nkv; q.head_dim = s.hd; q.n_rot = s.n_rot;
q.idx_n_head = s.ixh; q.idx_dim = s.ixd; q.idx_block = s.ixb; q.idx_top_k = s.ix_budget;
return q;
}
// positions of the rows of a [N][per] row-major block: pos0 + row / per
__global__ void fill_pos_kernel(int32_t* pos, int rows, int per, int pos0) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < rows) pos[i] = pos0 + i / per;
}
// index_qk_proj [N][(ixh+1)*ixd] -> qi [N][ixh*ixd] and raw [N][ixd]
__global__ void split_idx_kernel(const float* __restrict__ idx, float* __restrict__ qi, float* __restrict__ raw, int N, int qw, int kw) {
const size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x;
const size_t total = (size_t) N * (qw + kw);
if (i >= total) return;
const size_t t = i / (qw + kw);
const int c = (int) (i % (qw + kw));
const float v = idx[i];
if (c < qw) qi[t * qw + c] = v; else raw[t * kw + (c - qw)] = v;
}
// fp16 KV append of N cells at pos0..: pool layout [page][kv_head][4][hd], identity page table
__global__ void kv_append_batch_kernel(uint16_t* __restrict__ kp, uint16_t* __restrict__ vp, const float* __restrict__ k, const float* __restrict__ v, int N,
int pos0, int nkv, int hd) {
const size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x;
const size_t total = (size_t) N * nkv * hd;
if (i >= total) return;
const size_t t = i / ((size_t) nkv * hd);
const int r = (int) (i % ((size_t) nkv * hd));
const int h = r / hd, d = r % hd;
const size_t cell = (size_t) pos0 + t;
const size_t row = ((cell / 4) * nkv + h) * 4 + (cell % 4);
kp[row * hd + d] = K::f16_from_f32(k[i]);
vp[row * hd + d] = K::f16_from_f32(v[i]);
}
__global__ void gamma_kernel(const float* __restrict__ w, float* __restrict__ out, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) out[i] = 1.0f + w[i];
}
__global__ void fill_ones_kernel(int32_t* p, int n, int v) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) p[i] = v;
}
// step records {pos, n_kv, n_bid, width} of N queries, written on the device (no host copy: nothing synchronises the stream).
// HF width: 512 complete groups + the unfinished group's tokens (NOT the GGUF engine's min(n_kv, budget + r - 1) cells).
__global__ void steps_kernel(int32_t* steps, int N, int pos0, int budget, int ixb) {
const int t = blockIdx.x * blockDim.x + threadIdx.x;
if (t >= N) return;
const int n_kv = pos0 + t + 1;
int32_t* r = steps + (size_t) t * K::kStepCount;
r[K::kStepPos] = pos0 + t;
r[K::kStepNKv] = n_kv;
r[K::kStepNBid] = n_kv / ixb;
r[K::kStepWidth] = min(n_kv, budget + n_kv % ixb);
}
void upload_steps(const AttnShape& s, AttnScratch& sc, int N, int pos0, cudaStream_t st) {
steps_kernel<<<(N + 127) / 128, 128, 0, st>>>(sc.steps, N, pos0, s.ix_budget, s.ixb);
}
K::QsaAttnPools pools_of(const AttnState& st) {
K::QsaAttnPools p;
p.k_pool = st.k_pool;
p.v_pool = st.v_pool;
p.page_table = st.page_table;
return p;
}
// the indexer append of N raw keys at p0 (steps already uploaded for these positions when !native)
void indexer_append(const AttnShape& s, const AttnWeights& w, const AttnState& st, AttnScratch& sc, const float* raw, int N, int p0, const AttnOptions& opt,
cudaStream_t stream) {
const K::QsaShapes q = qshapes(s);
const K::QsaIndexerBuffers ib{st.ix_tail, st.ix_dead, st.ix_pooled, st.ix_block_pos};
if (opt.ix_native) {
K::native_qsa_indexer_append_batch(raw, N, p0, 0, w.ixk_g, kEps, ib, q, st.max_ctx, K::rope_scaling(), stream);
} else {
upload_steps(s, sc, N, p0, stream);
for (int t = 0; t < N; ++t)
K::indexer_key_append(raw + (size_t) t * s.ixd, sc.steps + (size_t) t * K::kStepCount + K::kStepPos, 0, w.ixk_g, kEps, ib, q, g_cos, g_sin, stream);
}
}
} // namespace
size_t attn_state_bytes(const AttnShape& s, int max_ctx) {
const size_t pages = (size_t) max_ctx / 4;
return 2 * al16(pages * s.nkv * 4 * s.hd * 2) + al16(pages * 4) + al16((size_t) kTail * s.ixd * 4) + al16((size_t) s.ixd * 4) + al16((pages + 1) * s.ixd * 4) + 16;
}
bool attn_state_assign(const AttnShape& s, int max_ctx, void* base, AttnState& o) {
if (!base || max_ctx % 4 != 0 || max_ctx < 8) return false;
const size_t pages = (size_t) max_ctx / 4;
uint8_t* p = (uint8_t*) base;
o.max_ctx = max_ctx;
o.k_pool = (uint16_t*) p; p += al16(pages * s.nkv * 4 * s.hd * 2);
o.v_pool = (uint16_t*) p; p += al16(pages * s.nkv * 4 * s.hd * 2);
o.page_table = (int32_t*) p; p += al16(pages * 4);
o.ix_tail = (float*) p; p += al16((size_t) kTail * s.ixd * 4);
o.ix_dead = (float*) p; p += al16((size_t) s.ixd * 4);
o.ix_pooled = (float*) p; p += al16((pages + 1) * s.ixd * 4);
o.ix_block_pos = (int32_t*) p;
std::vector<int32_t> tab(pages);
for (size_t i = 0; i < pages; ++i) tab[i] = (int32_t) i;
return cudaMemcpy(o.page_table, tab.data(), pages * 4, cudaMemcpyHostToDevice) == cudaSuccess;
}
void attn_state_reset(const AttnShape& s, const AttnState& st, cudaStream_t stream) {
const size_t pages = (size_t) st.max_ctx / 4;
cudaMemsetAsync(st.ix_tail, 0, (size_t) kTail * s.ixd * 4, stream);
cudaMemsetAsync(st.ix_dead, 0, (size_t) s.ixd * 4, stream);
cudaMemsetAsync(st.ix_pooled, 0, (pages + 1) * s.ixd * 4, stream);
cudaMemsetAsync(st.ix_block_pos, 0, 4, stream);
// the KV pools need no clearing: cells are read only after they are written
}
size_t attn_scratch_bytes(const AttnShape& s, int max_n, int max_ctx) {
const K::QsaShapes q = qshapes(s);
const int cap = (int) K::qsa_selection_width(K::kTopkMaxCells, q);
const int max_blocks = max_ctx / 4 + 2;
const size_t attn_scr = (size_t) 32 * K::qsa_decode_attn_scratch_floats(cap, q) * 4;
return 2 * al16((size_t) max_n * s.q_width() * 4) + al16((size_t) max_n * s.kv_width() * 4) + al16((size_t) max_n * s.ixh * s.ixd * 4) +
al16((size_t) max_n * s.ixd * 4) + al16((size_t) max_n * s.nh * 4) + al16((size_t) max_n * K::kStepCount * 4) + al16((size_t) 256 * max_blocks * 4) +
al16((size_t) max_n * cap * 4) + al16(attn_scr) + 64;
}
bool attn_scratch_assign(const AttnShape& s, int max_n, int max_ctx, void* base, AttnScratch& o) {
if (!base) return false;
const K::QsaShapes q = qshapes(s);
o.max_n = max_n;
o.cap = (int) K::qsa_selection_width(K::kTopkMaxCells, q);
o.max_blocks = max_ctx / 4 + 2;
o.sel_batch = 256;
o.attn_batch = 32;
uint8_t* p = (uint8_t*) base;
o.q = (float*) p; p += al16((size_t) max_n * s.q_width() * 4);
o.attn = (float*) p; p += al16((size_t) max_n * s.q_width() * 4);
o.k = (float*) p; p += al16((size_t) max_n * s.kv_width() * 4);
o.qi = (float*) p; p += al16((size_t) max_n * s.ixh * s.ixd * 4);
o.raw = (float*) p; p += al16((size_t) max_n * s.ixd * 4);
o.pos = (int32_t*) p; p += al16((size_t) max_n * s.nh * 4);
o.steps = (int32_t*) p; p += al16((size_t) max_n * K::kStepCount * 4);
o.sel_scores = (float*) p; p += al16((size_t) 256 * o.max_blocks * 4);
o.sel_ids = (int32_t*) p; p += al16((size_t) max_n * o.cap * 4);
o.attn_scratch = (float*) p;
return true;
}
void attn_gamma_1pw(const float* w, float* out, int n, cudaStream_t st) { gamma_kernel<<<(n + 127) / 128, 128, 0, st>>>(w, out, n); }
bool attn_global_init(const AttnShape& s, int max_pos, std::string& err) {
if (!shape_ok(s, err)) return false;
#if defined(_WIN32)
_putenv_s("STRATA_ROPE_TABLE", "1");
#else
setenv("STRATA_ROPE_TABLE", "1", 1);
#endif
if (g_cos) attn_global_release();
const int pairs = s.n_rot / 2;
std::vector<float> hc((size_t) max_pos * pairs), hs((size_t) max_pos * pairs);
K::build_rope_table(s.n_rot, K::rope_scaling(), max_pos, hc.data(), hs.data());
if (cudaMalloc((void**) &g_cos, hc.size() * 4) != cudaSuccess || cudaMalloc((void**) &g_sin, hs.size() * 4) != cudaSuccess) {
err = "attn_global_init: cudaMalloc failed";
return false;
}
cudaMemcpy(g_cos, hc.data(), hc.size() * 4, cudaMemcpyHostToDevice);
cudaMemcpy(g_sin, hs.data(), hs.size() * 4, cudaMemcpyHostToDevice);
K::rope_table_set(g_cos, g_sin, max_pos, K::rope_scaling());
return true;
}
void attn_global_release() {
if (g_cos) K::rope_table_release(g_cos);
cudaFree(g_cos);
cudaFree(g_sin);
g_cos = g_sin = nullptr;
}
size_t attn_verify_bytes(const AttnShape& s) { return al16((size_t) kTail * s.ixd * 4) + al16((size_t) kAttnVerifyMax * s.ixd * 4); }
bool attn_verify_assign(const AttnShape& s, void* base, AttnVerifyBuf& o) {
if (!base) return false;
o.tail_save = (float*) base;
o.raw = (float*) ((uint8_t*) base + al16((size_t) kTail * s.ixd * 4));
o.n = 0;
return true;
}
bool attn_run(const AttnShape& s, const AttnWeights& w, const AttnState& st, AttnScratch& sc, const float* q_proj, const float* k_proj, const float* v_proj,
const float* idx_qk, int N, int pos0, float* out, cudaStream_t stream, std::string& err, const AttnOptions& opt, AttnVerifyBuf* vb) {
if (!shape_ok(s, err)) return false;
if (N < 1 || N > sc.max_n) { err = "attn_run: N out of range of the scratch"; return false; }
if (pos0 < 0 || pos0 + N > st.max_ctx) { err = "attn_run: context exceeds max_ctx"; return false; }
if (vb && N > kAttnVerifyMax) { err = "attn_run: a verify window holds at most 16 tokens"; return false; }
const K::QsaShapes q = qshapes(s);
const int qw = s.ixh * s.ixd;
try {
// 1. q / k norm + rope (q rows are the per-head [query | gate] rows of q_proj: stride 2*hd, the gate half is skipped), index split
fill_pos_kernel<<<(N * s.nh + 255) / 256, 256, 0, stream>>>(sc.pos, N * s.nh, s.nh, pos0);
K::native_qsa_rms_norm_rope(q_proj, 2 * s.hd, w.q_g, sc.q, N * s.nh, s.hd, s.n_rot, kEps, K::rope_scaling(), sc.pos, stream);
fill_pos_kernel<<<(N * s.nkv + 255) / 256, 256, 0, stream>>>(sc.pos, N * s.nkv, s.nkv, pos0);
K::native_qsa_rms_norm_rope(k_proj, s.hd, w.k_g, sc.k, N * s.nkv, s.hd, s.n_rot, kEps, K::rope_scaling(), sc.pos, stream);
split_idx_kernel<<<(unsigned) (((size_t) N * (qw + s.ixd) + 255) / 256), 256, 0, stream>>>(idx_qk, sc.qi, sc.raw, N, qw, s.ixd);
fill_pos_kernel<<<(N * s.ixh + 255) / 256, 256, 0, stream>>>(sc.pos, N * s.ixh, s.ixh, pos0);
K::native_qsa_rms_norm_rope(sc.qi, s.ixd, w.ixq_g, sc.qi, N * s.ixh, s.ixd, s.n_rot, kEps, K::rope_scaling(), sc.pos, stream);
// 2. KV append
kv_append_batch_kernel<<<(unsigned) (((size_t) N * s.kv_width() + 255) / 256), 256, 0, stream>>>(st.k_pool, st.v_pool, sc.k, v_proj, N, pos0, s.nkv, s.hd);
// 3. indexer append (a window keeps what it needs to be undone)
if (vb) {
cudaMemcpyAsync(vb->tail_save, st.ix_tail, (size_t) kTail * s.ixd * 4, cudaMemcpyDeviceToDevice, stream);
cudaMemcpyAsync(vb->raw, sc.raw, (size_t) N * s.ixd * 4, cudaMemcpyDeviceToDevice, stream);
vb->n = N;
vb->pos0 = pos0;
}
indexer_append(s, w, st, sc, sc.raw, N, pos0, opt, stream);
// 4. selection: scores + top-k per query (HF widths in the step records)
upload_steps(s, sc, N, pos0, stream);
std::vector<int32_t> nbid(N);
for (int t = 0; t < N; ++t) nbid[t] = (pos0 + t + 1) / s.ixb;
for (int t0 = 0; t0 < N; t0 += sc.sel_batch) {
const int nb = std::min(sc.sel_batch, N - t0);
const int32_t* steps0 = sc.steps + (size_t) t0 * K::kStepCount;
const int64_t active = (int64_t) nbid[t0 + nb - 1] + 1;
const float* qi0 = sc.qi + (size_t) t0 * qw;
if (!(opt.score_tc && K::qsa_block_scores_tc(st.ix_pooled, st.ix_dead, qi0, steps0, nb, sc.max_blocks, q, sc.sel_scores, stream, active)))
K::qsa_block_scores(st.ix_pooled, st.ix_dead, qi0, steps0, nb, sc.max_blocks, q, sc.sel_scores, stream, active);
K::qsa_block_topk(sc.sel_scores, steps0, nb, sc.max_blocks, sc.cap, q, sc.sel_ids + (size_t) t0 * sc.cap, stream, active);
}
// 5. attention over the selected tokens
const K::QsaAttnPools pools = pools_of(st);
bool done = false;
if (opt.prompt_tc && N >= 8)
done = K::qsa_prompt_attn_batch(sc.q, pools, sc.sel_ids, sc.steps, sc.cap, q, sc.attn, N, stream);
if (!done) {
for (int t0 = 0; t0 < N; t0 += sc.attn_batch) {
const int nb = std::min(sc.attn_batch, N - t0);
K::qsa_decode_attn_batch(sc.q + (size_t) t0 * s.q_width(), pools, sc.sel_ids + (size_t) t0 * sc.cap, sc.steps + (size_t) t0 * K::kStepCount, sc.cap,
q, sc.attn_scratch, sc.attn + (size_t) t0 * s.q_width(), nb, stream);
}
}
// 6. sigmoid output gate (second half of each q_proj head row)
K::native_qsa_gate_apply(sc.attn, q_proj, out, N * s.nh, s.hd, stream);
} catch (const std::exception& e) {
err = std::string("attn_run: ") + e.what();
return false;
}
return launch_ok(err, "attn_run");
}
bool attn_rollback(const AttnShape& s, const AttnWeights& w, const AttnState& st, AttnScratch& sc, AttnVerifyBuf& vb, int n_keep, cudaStream_t stream, std::string& err,
const AttnOptions& opt) {
if (n_keep < 0 || n_keep > vb.n) { err = "attn_rollback: n_keep out of range"; return false; }
try {
cudaMemcpyAsync(st.ix_tail, vb.tail_save, (size_t) kTail * s.ixd * 4, cudaMemcpyDeviceToDevice, stream);
if (n_keep > 0) indexer_append(s, w, st, sc, vb.raw, n_keep, vb.pos0, opt, stream);
} catch (const std::exception& e) {
err = std::string("attn_rollback: ") + e.what();
return false;
}
vb.n = 0;
return launch_ok(err, "attn_rollback");
}
} // namespace strata::q4lite
+107
View File
@@ -0,0 +1,107 @@
// src/q4lite/q4_attn.hpp - the QSA full-attention token mixer of Qwen4-35B-A3B (attention with the sparse indexer) on the Flash-Next kernels at the q4_lite geometry.
//
// Inputs are the OUTPUTS OF THE PROJECTIONS (float32 device, token-major):
// q_proj [N, nh*2*hd] per head [query (hd) | gate (hd)]
// k_proj [N, nkv*hd], v_proj [N, nkv*hd]
// idx_qk [N, (ixh+1)*ixd] index_qk_proj: [ixh query heads (ixd each) | one key (ixd)]
// Output: out [N, nh*hd] = attention(selected tokens) * sigmoid(gate), i.e. what o_proj consumes.
//
// What is done here: q/k RMSNorm (gamma = 1 + w, prepared by the caller or attn_gamma_1pw), partial RoPE (first n_rot dims, rotate_half pairs, theta 1e7, text:
// all mrope streams equal the position), KV append (fp16, paged, page_size 4, identity page table), the indexer (raw keys -> mean of 4 -> RMSNorm -> RoPE at the
// group's first position -> compressed-key cache incl. the unfinished tail), group scores sum_h relu(q.k), top 512 complete groups per query (+ the unfinished tail's
// tokens), attention over exactly those tokens (softmax, GQA h / (nh / nkv)), sigmoid gate.
// Selection follows the HF reference (select_compression_indices): 512 groups (2048 tokens) + the t = n_kv % 4 tail tokens, never 2051 cells (that is the GGUF engine's
// rule): the step record is written with width = min(n_kv, 2048 + t). For n_kv <= 2048 + t every token is selected (plain causal attention).
//
// Positions: token i of a call sits at absolute position pos0 + i; the caches hold positions [0, pos0) from earlier calls (pos0 = the engine's position).
#pragma once
#include <cuda_runtime.h>
#include <cstddef>
#include <cstdint>
#include <string>
namespace strata::q4lite {
struct AttnShape {
int nh = 16, nkv = 2, hd = 256, n_rot = 64;
int ixh = 4, ixd = 128, ixb = 4, ix_budget = 2048;
int q_width() const { return nh * hd; }
int kv_width() const { return nkv * hd; }
int ix_width() const { return (ixh + 1) * ixd; }
};
inline constexpr int kAttnVerifyMax = 16;
// caches of one attention layer for max_ctx positions (max_ctx a multiple of 4)
struct AttnState {
uint16_t* k_pool = nullptr; // fp16 [page][kv_head][4][hd]
uint16_t* v_pool = nullptr;
int32_t* page_table = nullptr; // identity, max_ctx / 4 entries
float* ix_tail = nullptr; // [3][ixd] raw tail keys
float* ix_dead = nullptr; // [ixd]
float* ix_pooled = nullptr; // [max_ctx / 4 + 1][ixd]
int32_t* ix_block_pos = nullptr; // [1]
int max_ctx = 0;
};
size_t attn_state_bytes(const AttnShape& s, int max_ctx); // all of the above (16 B aligned parts)
bool attn_state_assign(const AttnShape& s, int max_ctx, void* base, AttnState& out); // carve; also fills the page table (needs a stream sync by the caller)
void attn_state_reset(const AttnShape& s, const AttnState& st, cudaStream_t stream);
// per-call scratch for up to max_n tokens
struct AttnScratch {
float* q = nullptr; // [max_n][nh*hd] normed + roped queries
float* k = nullptr; // [max_n][nkv*hd]
float* qi = nullptr; // [max_n][ixh*ixd]
float* raw = nullptr; // [max_n][ixd]
int32_t* pos = nullptr; // [max_n * nh] rope positions per row
int32_t* steps = nullptr; // [max_n][4]
float* sel_scores = nullptr; // [sel_batch][max_blocks]
int32_t* sel_ids = nullptr; // [max_n][cap]
float* attn = nullptr; // [max_n][nh*hd]
float* attn_scratch = nullptr; // attn_batch x per-query split-K partials
int max_n = 0, max_blocks = 0, cap = 0, sel_batch = 256, attn_batch = 32;
};
size_t attn_scratch_bytes(const AttnShape& s, int max_n, int max_ctx);
bool attn_scratch_assign(const AttnShape& s, int max_n, int max_ctx, void* base, AttnScratch& out);
struct AttnWeights { // device fp32
const float* q_g = nullptr; // [hd] 1 + q_norm.weight
const float* k_g = nullptr; // [hd] 1 + k_norm.weight
const float* ixq_g = nullptr; // [ixd] 1 + q_layernorm.weight
const float* ixk_g = nullptr; // [ixd] 1 + k_layernorm.weight
};
void attn_gamma_1pw(const float* w, float* out, int n, cudaStream_t st); // out = 1 + w (load time)
// once per process before the first call: builds the float64 RoPE table (device) and registers it; sets STRATA_ROPE_TABLE=1 (the fast-math angles of the
// analytic path are ~1e-3 rad off at 32K). max_pos >= the largest max_ctx.
bool attn_global_init(const AttnShape& s, int max_pos, std::string& err);
void attn_global_release();
// what a speculative window needs to be undone: the indexer's raw tail (an accepted prefix's tokens share its slots with later tokens) and the window's raw keys
struct AttnVerifyBuf {
float* tail_save = nullptr; // [3][ixd]
float* raw = nullptr; // [kAttnVerifyMax][ixd]
int n = 0, pos0 = 0;
};
size_t attn_verify_bytes(const AttnShape& s);
bool attn_verify_assign(const AttnShape& s, void* base, AttnVerifyBuf& out);
struct AttnOptions {
bool score_tc = true; // tensor-core group scores on sm_80+ (3xTF32) when available; false: the FP32 warp kernel everywhere
bool prompt_tc = true; // tensor-core prompt attention on sm_80+ when available; false: the split-K decode kernel (any arch)
bool ix_native = true; // F16 raw-key native indexer append (llama-style rounding); false: per-token FP32 append (no rounding)
bool dump_sel = false; // keep sel_ids of the last call readable in sc.sel_ids (they always are; this only skips nothing)
};
// N tokens at pos0 .. pos0 + N - 1; N <= sc.max_n; pos0 + N <= st.max_ctx. With vb: the window can be undone by attn_rollback (N <= kAttnVerifyMax).
bool attn_run(const AttnShape& s, const AttnWeights& w, const AttnState& st, AttnScratch& sc, const float* q_proj, const float* k_proj, const float* v_proj,
const float* idx_qk, int N, int pos0, float* out, cudaStream_t stream, std::string& err, const AttnOptions& opt = AttnOptions(),
AttnVerifyBuf* vb = nullptr);
// the state after the first n_keep tokens of the window attn_run(..., vb) processed (0 <= n_keep <= vb.n): KV needs nothing (positions are overwritten), the indexer's
// tail is restored and the kept tokens' raw keys re-appended
bool attn_rollback(const AttnShape& s, const AttnWeights& w, const AttnState& st, AttnScratch& sc, AttnVerifyBuf& vb, int n_keep, cudaStream_t stream,
std::string& err, const AttnOptions& opt = AttnOptions());
} // namespace strata::q4lite
+234
View File
@@ -0,0 +1,234 @@
// src/q4lite/q4_gdn.cu - see q4_gdn.hpp. The recurrence kernels are Flash-Next's (fused_gdn.cu, verify_kernels.cu, prefill/gdn_chunk.cu) compiled at the
// q4_lite geometry with STRATA_GDN_PAIR_GROUPED; this file adds the small glue kernels whose contract differs from the GGUF engine's (gates from raw projections,
// a prefill-form conv + silu + l2 kernel, the gated norm of the chunk path). Plain CUDA: no tensor cores, no PTX, warp size 32 only in the reductions.
#include "q4_gdn.hpp"
#include "strata/core/geometry.hpp"
#include "strata/kernels/fused_gdn.hpp"
#include "strata/kernels/verify_kernels.hpp"
#include "strata/prefill/gdn_chunk.hpp"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
namespace strata::q4lite {
namespace {
constexpr int S = 128; // head dim == the kernels' compile-time state size
constexpr int kWarp = 32; // reduction width (the kernels below only need a power of two <= 32)
constexpr float kEps = 1e-6f;
// ssm_a = -exp(A_log)
__global__ void ssm_a_kernel(const float* __restrict__ A_log, float* __restrict__ out, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) out[i] = -expf(A_log[i]);
}
// gate = ssm_a * softplus(a + dt_bias) (ssm_a = -exp(A_log)), beta = sigmoid(b); F.softplus: x > 20 ? x : log1p(exp(x))
__global__ void gates_kernel(const float* __restrict__ a, const float* __restrict__ b, const float* __restrict__ dt,
const float* __restrict__ ssm_a, float* __restrict__ gate, float* __restrict__ beta, int hv, int total) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= total) return;
const int h = i % hv;
const float v = a[i] + dt[h];
const float sp = v > 20.0f ? v : log1pf(expf(v));
gate[i] = sp * ssm_a[h];
beta[i] = 1.0f / (1.0f + expf(-b[i]));
}
// Prefill-form conv: for token t and channel c, out = silu(sum_k w[c][k] * x[t - 3 + k]) with x = [hist(3) | qkv_0 .. qkv_{N-1}] (tap 0 = oldest);
// the first qk_heads 128-channel blocks (q then k) are then l2-normalised (x / sqrt(sum + eps), eps 1e-6). Grid (N, conv_dim / 128), block 128.
// History is read, NOT written (conv_hist_kernel does that after every block has read it).
__global__ void __launch_bounds__(S) conv_l2_kernel(const float* __restrict__ hist, const float* __restrict__ qkv, const float* __restrict__ w,
float* __restrict__ h, int C, int qk_heads, float eps) {
__shared__ float part[S / kWarp];
const int t = blockIdx.x;
const int c = blockIdx.y * S + threadIdx.x;
float x[4];
#pragma unroll
for (int k = 0; k < 4; ++k) {
const int j = t - 3 + k; // index into the new inputs; negative: the history (j + 3 is its slot)
x[k] = j >= 0 ? qkv[(size_t) j * C + c] : hist[(size_t) c * 3 + (j + 3)];
}
const float sum = x[0] * w[(size_t) c * 4] + x[1] * w[(size_t) c * 4 + 1] + x[2] * w[(size_t) c * 4 + 2] + x[3] * w[(size_t) c * 4 + 3];
float y = sum / (1.0f + expf(-sum));
if ((int) blockIdx.y < qk_heads) {
float sq = y * y;
for (int o = kWarp / 2; o > 0; o >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, o);
if ((threadIdx.x & (kWarp - 1)) == 0) part[threadIdx.x / kWarp] = sq;
__syncthreads();
float ss = 0.0f;
#pragma unroll
for (int i = 0; i < S / kWarp; ++i) ss += part[i];
y *= rsqrtf(ss + eps);
}
h[(size_t) t * C + c] = y;
}
// hist <- the last 3 entries of [hist | qkv_0 .. qkv_{N-1}] (each thread owns one channel, in place)
__global__ void conv_hist_kernel(float* __restrict__ hist, const float* __restrict__ qkv, int N, int C) {
const int c = blockIdx.x * blockDim.x + threadIdx.x;
if (c >= C) return;
float nh[3];
#pragma unroll
for (int j = 0; j < 3; ++j) {
const int i = N + j; // index in [hist(3) | inputs]
nh[j] = i < 3 ? hist[(size_t) c * 3 + i] : qkv[(size_t) (i - 3) * C + c];
}
#pragma unroll
for (int j = 0; j < 3; ++j) hist[(size_t) c * 3 + j] = nh[j];
}
// y[r] = oc[r] * rsqrt(mean(oc[r]^2) + eps) * gamma * sigmoid(z[r]) for rows of S (one block of S threads per row)
__global__ void __launch_bounds__(S) out_norm_kernel(const float* __restrict__ oc, const float* __restrict__ z, const float* __restrict__ gamma,
float* __restrict__ y, float eps) {
__shared__ float part[S / kWarp];
const size_t row = blockIdx.x;
const float o = oc[row * S + threadIdx.x];
float sq = o * o;
for (int k = kWarp / 2; k > 0; k >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, k);
if ((threadIdx.x & (kWarp - 1)) == 0) part[threadIdx.x / kWarp] = sq;
__syncthreads();
float ss = 0.0f;
#pragma unroll
for (int i = 0; i < S / kWarp; ++i) ss += part[i];
const float zz = z[row * S + threadIdx.x];
y[row * S + threadIdx.x] = o * rsqrtf(ss / (float) S + eps) * gamma[threadIdx.x] * (1.0f / (1.0f + expf(-zz)));
}
bool fail(std::string& err, const char* what) {
err = what;
return false;
}
bool launch_ok(std::string& err, const char* what) {
const cudaError_t e = cudaGetLastError();
if (e == cudaSuccess) return true;
err = std::string(what) + ": " + cudaGetErrorString(e);
return false;
}
bool shape_ok(const GdnShape& s, std::string& err) {
const auto& g = strata::core::kCompiledGeometry;
if (s.S != g.ssm_state_size || s.hk != g.ssm_k_heads || s.hv != g.ssm_v_heads || s.conv_k != 4 || s.S != S) {
err = "gdn: the shape differs from the compiled geometry (core/geometry.hpp)";
return false;
}
return true;
}
inline size_t al16(size_t x) { return (x + 15) & ~size_t(15); }
void gates(const GdnShape& s, const GdnWeights& w, const float* a, const float* b, float* gate, float* beta, int N, cudaStream_t st) {
const int total = N * s.hv;
gates_kernel<<<(total + 127) / 128, 128, 0, st>>>(a, b, w.dt_bias, w.ssm_a, gate, beta, s.hv, total);
}
__global__ void set_keep_kernel(int32_t* keep, int n) { keep[0] = n; }
void set_keep(GdnScratch& sc, int n, cudaStream_t st) { set_keep_kernel<<<1, 1, 0, st>>>(sc.keep, n); } // no host copy: nothing synchronises the stream
} // namespace
size_t gdn_state_bytes(const GdnShape& s) { return (size_t) s.hv * s.S * s.S * sizeof(float); }
size_t gdn_hist_bytes(const GdnShape& s) { return (size_t) s.conv_dim() * (s.conv_k - 1) * sizeof(float); }
size_t gdn_scratch_bytes(const GdnShape& s, int max_n) {
return al16((size_t) max_n * s.conv_dim() * 4) + 2 * al16((size_t) max_n * s.hv * 4) + al16((size_t) max_n * s.val_dim() * 4) + 16;
}
bool gdn_scratch_assign(const GdnShape& s, int max_n, void* base, GdnScratch& o) {
if (!base) return false;
uint8_t* p = (uint8_t*) base;
o.max_n = max_n;
o.h = (float*) p; p += al16((size_t) max_n * s.conv_dim() * 4);
o.gate = (float*) p; p += al16((size_t) max_n * s.hv * 4);
o.beta = (float*) p; p += al16((size_t) max_n * s.hv * 4);
o.oc = (float*) p; p += al16((size_t) max_n * s.val_dim() * 4);
o.keep = (int32_t*) p;
return true;
}
size_t gdn_verify_bytes(const GdnShape& s) {
const size_t n = kGdnVerifyMax;
return 2 * al16(n * s.conv_dim() * 4) + 2 * al16(n * s.hv * 4) + al16(n * s.val_dim() * 4);
}
bool gdn_verify_assign(const GdnShape& s, void* base, GdnVerifyBuf& o) {
if (!base) return false;
const size_t n = kGdnVerifyMax;
uint8_t* p = (uint8_t*) base;
o.qkv = (float*) p; p += al16(n * s.conv_dim() * 4);
o.h = (float*) p; p += al16(n * s.conv_dim() * 4);
o.gate = (float*) p; p += al16(n * s.hv * 4);
o.beta = (float*) p; p += al16(n * s.hv * 4);
o.z = (float*) p;
o.n = 0;
return true;
}
void gdn_ssm_a_from_alog(const float* A_log, float* ssm_a, int hv, cudaStream_t st) { ssm_a_kernel<<<(hv + 127) / 128, 128, 0, st>>>(A_log, ssm_a, hv); }
void gdn_state_reset(const GdnShape& s, const GdnState& st, cudaStream_t stream) {
cudaMemsetAsync(st.S, 0, gdn_state_bytes(s), stream);
cudaMemsetAsync(st.hist, 0, gdn_hist_bytes(s), stream);
}
bool gdn_run(const GdnShape& s, const GdnWeights& w, const GdnState& st, GdnScratch& sc, const float* qkv, const float* z, const float* a, const float* b,
int N, float* y, cudaStream_t stream, std::string& err) {
if (!shape_ok(s, err)) return false;
if (N < 1 || N > sc.max_n) return fail(err, "gdn_run: N out of range of the scratch");
const int C = s.conv_dim(), qk_heads = 2 * s.hk;
namespace K = strata::kernels;
gates(s, w, a, b, sc.gate, sc.beta, N, stream);
if (N == 1) { // decode: the fused Flash-Next kernels
K::fused_gdn_conv_l2(st.hist, qkv, w.conv, sc.h, C, qk_heads, kEps, stream);
K::fused_gdn_step_norm(st.S, sc.h, sc.h + (size_t) s.hk * S, sc.h + (size_t) 2 * s.hk * S, sc.gate, sc.beta, z, w.norm, kEps, y, s.hk, s.hv, stream);
return launch_ok(err, "gdn_run(decode)");
}
conv_l2_kernel<<<dim3(N, C / S), S, 0, stream>>>(st.hist, qkv, w.conv, sc.h, C, qk_heads, kEps);
conv_hist_kernel<<<(C + 127) / 128, 128, 0, stream>>>(st.hist, qkv, N, C);
if (!launch_ok(err, "gdn_run(conv)")) return false;
// the 64-token chunks (FP32 chunk-parallel scan, prefill/gdn_chunk.cu) then the remainder through the window kernels in groups of <= 16
const int T64 = N / 64 * 64;
if (T64 > 0) {
strata::prefill::gdn_chunk_recurrence(st.S, sc.h, sc.gate, sc.beta, sc.oc, T64, stream);
out_norm_kernel<<<T64 * s.hv, S, 0, stream>>>(sc.oc, z, w.norm, y, kEps);
if (!launch_ok(err, "gdn_run(chunk)")) return false;
}
for (int t0 = T64; t0 < N; t0 += kGdnVerifyMax) {
const int n = std::min(kGdnVerifyMax, N - t0);
set_keep(sc, n, stream);
K::gdn_step_norm_multi(st.S, sc.h + (size_t) t0 * C, C, sc.gate + (size_t) t0 * s.hv, sc.beta + (size_t) t0 * s.hv, z + (size_t) t0 * s.val_dim(), w.norm,
kEps, y + (size_t) t0 * s.val_dim(), s.hk, s.hv, n, nullptr, stream); // outputs, state untouched
K::gdn_step_norm_multi(st.S, sc.h + (size_t) t0 * C, C, sc.gate + (size_t) t0 * s.hv, sc.beta + (size_t) t0 * s.hv, z + (size_t) t0 * s.val_dim(), w.norm,
kEps, y + (size_t) t0 * s.val_dim(), s.hk, s.hv, n, sc.keep, stream); // commit: state advances n tokens
}
return launch_ok(err, "gdn_run(tail)");
}
bool gdn_verify(const GdnShape& s, const GdnWeights& w, const GdnState& st, GdnScratch& sc, GdnVerifyBuf& vb, const float* qkv, const float* z, const float* a,
const float* b, int N, float* y, cudaStream_t stream, std::string& err) {
if (!shape_ok(s, err)) return false;
if (N < 1 || N > kGdnVerifyMax) return fail(err, "gdn_verify: N out of range");
const int C = s.conv_dim(), qk_heads = 2 * s.hk;
namespace K = strata::kernels;
gates(s, w, a, b, vb.gate, vb.beta, N, stream);
cudaMemcpyAsync(vb.qkv, qkv, (size_t) N * C * sizeof(float), cudaMemcpyDeviceToDevice, stream);
cudaMemcpyAsync(vb.z, z, (size_t) N * s.val_dim() * sizeof(float), cudaMemcpyDeviceToDevice, stream);
K::gdn_conv_l2_multi(st.hist, qkv, w.conv, vb.h, C, qk_heads, kEps, N, stream); // history NOT written
K::gdn_step_norm_multi(st.S, vb.h, C, vb.gate, vb.beta, z, w.norm, kEps, y, s.hk, s.hv, N, nullptr, stream); // state NOT written
vb.n = N;
(void) sc;
return launch_ok(err, "gdn_verify");
}
bool gdn_commit(const GdnShape& s, const GdnWeights& w, const GdnState& st, GdnScratch& sc, GdnVerifyBuf& vb, int n_keep, cudaStream_t stream, std::string& err) {
if (!shape_ok(s, err)) return false;
if (n_keep < 0 || n_keep > vb.n) return fail(err, "gdn_commit: n_keep out of range");
if (n_keep == 0) { vb.n = 0; return true; }
namespace K = strata::kernels;
const int C = s.conv_dim();
set_keep(sc, n_keep, stream);
K::gdn_conv_commit(st.hist, vb.qkv, C, sc.keep, stream);
K::gdn_step_norm_multi(st.S, vb.h, C, vb.gate, vb.beta, vb.z, w.norm, kEps, sc.oc, s.hk, s.hv, vb.n, sc.keep, stream);
vb.n = 0;
return launch_ok(err, "gdn_commit");
}
} // namespace strata::q4lite
+90
View File
@@ -0,0 +1,90 @@
// src/q4lite/q4_gdn.hpp - the GatedDeltaNet token mixer of Qwen4-35B-A3B on the Flash-Next kernels (compiled at the q4_lite geometry).
//
// Everything here takes the OUTPUTS OF THE PROJECTIONS as float32 device buffers (the projections themselves, in_proj_qkv / in_proj_z / in_proj_a /
// in_proj_b and out_proj, are the engine's GEMVs) and produces the gated-RMSNorm output y [N, value_dim] that feeds out_proj.
//
// qkv [N, conv_dim] in_proj_qkv rows [q (hk*S) | k (hk*S) | v (hv*S)]
// z [N, value_dim] in_proj_z
// a [N, hv] in_proj_a (raw) gate = -exp(A_log) * softplus(a + dt_bias)
// b [N, hv] in_proj_b (raw) beta = sigmoid(b)
// y [N, value_dim] rmsnorm(o) * norm_w * sigmoid(z) (output_gate_type sigmoid; norm_w is the plain HF weight, not 1 + w)
//
// Layout of the carried state (opaque to the caller, only the sizes matter): S [S rows][hv][S cols] fp32 (hv*S*S floats), conv history [conv_dim][3] fp32.
// The q/k <-> value head pairing is a COMPILE switch of the kernels (STRATA_GDN_PAIR_GROUPED, include/strata/kernels/gdn_pairing.hpp): the q4lite build defines it.
//
// Calls: gdn_run (state advanced: decode N = 1, any prefill chunk), gdn_verify + gdn_commit (speculative window of up to 16 tokens: verify writes the outputs
// and NO state, commit replays the first n_keep tokens into the state - Flash-Next's rollback design, no per-token snapshots).
#pragma once
#include <cuda_runtime.h>
#include <cstddef>
#include <cstdint>
#include <string>
namespace strata::q4lite {
struct GdnShape {
int hk = 16, hv = 32, S = 128, conv_k = 4;
int conv_dim() const { return 2 * S * hk + S * hv; }
int val_dim() const { return S * hv; }
};
inline constexpr int kGdnVerifyMax = 16; // tokens of a verify window (kernels/window_limits.hpp: kWindowMaxT on CUDA)
// bytes of the carried state of one layer
size_t gdn_state_bytes(const GdnShape& s); // recurrent S: hv * S * S * 4
size_t gdn_hist_bytes(const GdnShape& s); // conv history: conv_dim * (conv_k - 1) * 4
struct GdnWeights { // device pointers, all fp32
const float* conv = nullptr; // [conv_dim][conv_k] (HF conv1d.weight [conv_dim, 1, k])
const float* ssm_a = nullptr; // [hv] = -exp(A_log) (gdn_ssm_a_from_alog)
const float* dt_bias = nullptr; // [hv]
const float* norm = nullptr; // [S] gated RMSNorm weight (plain)
};
struct GdnState {
float* S = nullptr; // gdn_state_bytes
float* hist = nullptr; // gdn_hist_bytes
};
// scratch of one gdn_run call / one verify window (device); one set can be shared by all layers of a stream for gdn_run
struct GdnScratch {
float* h = nullptr; // [max_n][conv_dim] conv + silu + l2 output
float* gate = nullptr; // [max_n][hv]
float* beta = nullptr; // [max_n][hv]
float* oc = nullptr; // [max_n][val_dim] un-normed chunk-scan output
int32_t* keep = nullptr; // [4] device ints
int max_n = 0;
};
size_t gdn_scratch_bytes(const GdnShape& s, int max_n);
bool gdn_scratch_assign(const GdnShape& s, int max_n, void* base, GdnScratch& out); // carve a GdnScratch out of gdn_scratch_bytes of memory (16 B aligned)
// the inputs a commit needs again (one per layer while a verify window is pending)
struct GdnVerifyBuf {
float* qkv = nullptr; // [kGdnVerifyMax][conv_dim]
float* h = nullptr; // [kGdnVerifyMax][conv_dim]
float* gate = nullptr; // [kGdnVerifyMax][hv]
float* beta = nullptr; // [kGdnVerifyMax][hv]
float* z = nullptr; // [kGdnVerifyMax][val_dim]
int n = 0; // tokens of the pending window
};
size_t gdn_verify_bytes(const GdnShape& s);
bool gdn_verify_assign(const GdnShape& s, void* base, GdnVerifyBuf& out);
// load-time transform: ssm_a = -exp(A_log)
void gdn_ssm_a_from_alog(const float* A_log, float* ssm_a, int hv, cudaStream_t st);
void gdn_state_reset(const GdnShape& s, const GdnState& st, cudaStream_t stream);
// N tokens, state advanced. N <= sc.max_n. y may not alias the inputs.
bool gdn_run(const GdnShape& s, const GdnWeights& w, const GdnState& st, GdnScratch& sc, const float* qkv, const float* z, const float* a, const float* b,
int N, float* y, cudaStream_t stream, std::string& err);
// speculative window (2 <= N <= kGdnVerifyMax; N = 1 allowed): outputs only, the state and the history are NOT written; the inputs are kept in vb.
bool gdn_verify(const GdnShape& s, const GdnWeights& w, const GdnState& st, GdnScratch& sc, GdnVerifyBuf& vb, const float* qkv, const float* z, const float* a,
const float* b, int N, float* y, cudaStream_t stream, std::string& err);
// after a gdn_verify: the state and history after the first n_keep (0..N) tokens of the window
bool gdn_commit(const GdnShape& s, const GdnWeights& w, const GdnState& st, GdnScratch& sc, GdnVerifyBuf& vb, int n_keep, cudaStream_t stream, std::string& err);
} // namespace strata::q4lite
+12
View File
@@ -0,0 +1,12 @@
# Sources of the Qwen4 token mixers: the Flash-Next kernels (compiled at the q4_lite geometry) + q4_gdn / q4_attn. Included by q4lite/CMakeLists.txt and attn_tests/CMakeLists.txt.
# Needs `engine_root` (the engine/ directory). Sets Q4_MIXER_KERNELS (kernel sources), Q4_MIXER_FASTMATH (the files the engine builds with --use_fast_math)
# and Q4_MIXER_DEFS (compile definitions: the q/k head pairing of the HF checkpoint order).
set(_kc ${engine_root}/src/kernels/cuda)
set(Q4_MIXER_KERNELS
${_kc}/qsa.cu ${_kc}/qsa_decode_attn.cu ${_kc}/qsa_prompt_attn.cu ${_kc}/qsa_select.cu ${_kc}/qsa_pattn.cu
${_kc}/fused_gdn.cu ${_kc}/verify_kernels.cu ${_kc}/rope.cu ${_kc}/kv_q8.cu ${_kc}/kv_q4.cu ${_kc}/kv_stream.cu
${_kc}/native_rope.cu ${_kc}/native_qsa.cu ${_kc}/native_qsa_indexer.cu ${_kc}/native_qsa_score.cu
${engine_root}/src/prefill/gdn_chunk.cu
${engine_root}/src/q4lite/q4_gdn.cu ${engine_root}/src/q4lite/q4_attn.cu)
set(Q4_MIXER_FASTMATH ${_kc}/native_rope.cu ${_kc}/native_qsa.cu ${_kc}/native_qsa_indexer.cu ${_kc}/native_qsa_score.cu)
set(Q4_MIXER_DEFS STRATA_GDN_PAIR_GROUPED=1)
+225
View File
@@ -0,0 +1,225 @@
// src/q4lite/q4_mixers_fn.cu - the production Mixers of strata-q4-lite: GatedDeltaNet (q4_gdn) and QSA attention (q4_attn) layers on the Flash-Next kernels at the q4_lite
// geometry. The projections are Ling's S_K GEMVs (float activations) / fp32 GEMVs on the GpuModel weights; everything between them is q4_gdn.cu / q4_attn.cu.
//
// Speculative verify (checkpoint / rollback): after checkpoint() the next forward of N <= 16 tokens runs every GDN layer in verify mode (outputs only, the recurrent
// state and the conv history are NOT written; the inputs are kept) and every attention layer with an undo record for the indexer's raw tail. rollback(pos0, n_keep)
// then commits the first n_keep tokens (n_keep = N accepts the whole window). A window that is not followed by rollback() is committed in full by the next forward.
#include "q4_attn.hpp"
#include "q4_gdn.hpp"
#include "q4_mixers.hpp"
#include "ling32_kernels.hpp"
#include <algorithm>
#include <cstdio>
#include <vector>
namespace strata::q4lite {
namespace {
#define MX_CK(x, err) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { (err) = std::string(#x) + ": " + cudaGetErrorString(e_); return false; } } while (0)
class Q4Mixers final : public Mixers {
public:
~Q4Mixers() override { destroy(); }
bool init(const GpuModel& m, const EngineOptions& opt, std::string& err) override {
destroy();
m_ = &m;
const Q4Cfg& c = m.cfg;
MX_CK(cudaSetDevice(opt.device), err);
gs_.hk = c.gdn_kheads; gs_.hv = c.gdn_vheads; gs_.S = c.gdn_kdim; gs_.conv_k = c.conv_k;
as_.nh = c.n_head; as_.nkv = c.n_kv; as_.hd = c.head_dim; as_.n_rot = c.rope_dim;
as_.ixh = c.ix_heads; as_.ixd = c.ix_dim; as_.ixb = c.ix_group; as_.ix_budget = c.ix_budget;
maxn_ = std::max(opt.max_tokens, kGdnVerifyMax);
max_ctx_ = (opt.max_ctx + 3) / 4 * 4;
D_ = c.D;
if (!attn_global_init(as_, max_ctx_, err)) return false;
global_ = true;
const int nl = c.n_layers;
gdn_.assign(nl, {});
attn_.assign(nl, {});
pos_.assign(nl, 0);
// arena
size_t total = 0;
auto al = [](size_t x) { return (x + 255) & ~size_t(255); };
const size_t M = (size_t) maxn_;
const size_t proj = al(M * c.conv_dim() * 4) + al(M * c.val_dim() * 4) + 2 * al(M * gs_.hv * 4) + al(M * c.val_dim() * 4) + al(M * 2 * c.q_dim() * 4) + 2 * al(M * c.kv_dim() * 4) +
al(M * as_.ix_width() * 4) + al(M * c.q_dim() * 4) + al(M * c.val_dim() * 4);
const size_t gsc = al(gdn_scratch_bytes(gs_, maxn_)), asc = al(attn_scratch_bytes(as_, maxn_, max_ctx_));
size_t per_gdn = al(gdn_state_bytes(gs_)) + al(gdn_hist_bytes(gs_)) + al((size_t) gs_.hv * 4) + al(gdn_verify_bytes(gs_));
size_t per_attn = al(attn_state_bytes(as_, max_ctx_)) + al((size_t) (2 * as_.hd + 2 * as_.ixd) * 4) + al(attn_verify_bytes(as_));
int n_g = 0, n_a = 0;
for (int il = 0; il < nl; ++il) (c.is_full[il] ? n_a : n_g)++;
total = proj + gsc + asc + per_gdn * n_g + per_attn * n_a;
MX_CK(cudaMalloc(&arena_, total), err);
arena_bytes_ = total;
uint8_t* p = (uint8_t*) arena_;
auto take = [&](size_t b) { uint8_t* r = p; p += al(b); return (void*) r; };
pj_qkv_ = (float*) take((size_t) maxn_ * c.conv_dim() * 4);
pj_z_ = (float*) take((size_t) maxn_ * c.val_dim() * 4);
pj_a_ = (float*) take((size_t) maxn_ * gs_.hv * 4);
pj_b_ = (float*) take((size_t) maxn_ * gs_.hv * 4);
pj_y_ = (float*) take((size_t) maxn_ * c.val_dim() * 4);
pj_q_ = (float*) take((size_t) maxn_ * 2 * c.q_dim() * 4);
pj_k_ = (float*) take((size_t) maxn_ * c.kv_dim() * 4);
pj_v_ = (float*) take((size_t) maxn_ * c.kv_dim() * 4);
pj_ix_ = (float*) take((size_t) maxn_ * as_.ix_width() * 4);
pj_o_ = (float*) take((size_t) maxn_ * c.q_dim() * 4);
pj_r_ = (float*) take((size_t) maxn_ * c.val_dim() * 4);
gdn_assign_scratch(take(gsc));
if (!attn_scratch_assign(as_, maxn_, max_ctx_, take(asc), asc_)) { err = "attn scratch"; return false; }
for (int il = 0; il < nl; ++il) {
if (!c.is_full[il]) {
G& g = gdn_[il];
g.st.S = (float*) take(gdn_state_bytes(gs_));
g.st.hist = (float*) take(gdn_hist_bytes(gs_));
float* ssm_a = (float*) take((size_t) gs_.hv * 4);
const GdnLayer& L = m.layers[il].gdn;
gdn_ssm_a_from_alog(L.A_log, ssm_a, gs_.hv, 0);
g.w = GdnWeights{L.conv, ssm_a, L.dt_bias, L.norm};
if (!gdn_verify_assign(gs_, take(gdn_verify_bytes(gs_)), g.vb)) { err = "gdn verify"; return false; }
} else {
A& a = attn_[il];
if (!attn_state_assign(as_, max_ctx_, take(attn_state_bytes(as_, max_ctx_)), a.st)) { err = "attn state"; return false; }
float* gam = (float*) take((size_t) (2 * as_.hd + 2 * as_.ixd) * 4);
const AttnLayer& L = m.layers[il].attn;
attn_gamma_1pw(L.q_norm, gam, as_.hd, 0);
attn_gamma_1pw(L.k_norm, gam + as_.hd, as_.hd, 0);
attn_gamma_1pw(L.ix_q_ln, gam + 2 * as_.hd, as_.ixd, 0);
attn_gamma_1pw(L.ix_k_ln, gam + 2 * as_.hd + as_.ixd, as_.ixd, 0);
a.w = AttnWeights{gam, gam + as_.hd, gam + 2 * as_.hd, gam + 2 * as_.hd + as_.ixd};
if (!attn_verify_assign(as_, take(attn_verify_bytes(as_)), a.vb)) { err = "attn verify"; return false; }
}
}
MX_CK(cudaDeviceSynchronize(), err);
reset();
MX_CK(cudaDeviceSynchronize(), err);
return true;
}
void destroy() override {
if (arena_) { cudaDeviceSynchronize(); cudaFree(arena_); arena_ = nullptr; }
if (global_) { attn_global_release(); global_ = false; }
}
void reset() override {
if (!m_) return;
for (size_t il = 0; il < gdn_.size(); ++il) {
if (gdn_[il].st.S) { gdn_state_reset(gs_, gdn_[il].st, 0); gdn_[il].pending = false; gdn_[il].vb.n = 0; }
if (attn_[il].st.k_pool) { attn_state_reset(as_, attn_[il].st, 0); attn_[il].vb.n = 0; }
pos_[il] = 0;
}
cudaDeviceSynchronize();
verify_mode_ = false;
}
bool gdn(int il, const float* x, const float* xr, int N, int pos0, float* y, cudaStream_t s, std::string& err) override {
namespace L = strata::ling32::gpu;
G& g = gdn_[il];
if (!g.st.S) { err = "gdn: layer " + std::to_string(il) + " is not a GDN layer"; return false; }
if (g.pending) { // an earlier window that was not rolled back: all of it was accepted
if (!gdn_commit(gs_, g.w, g.st, gsc_, g.vb, g.vb.n, s, err)) return false;
pos_[il] += pending_n_[il];
g.pending = false;
}
if (pos0 != pos_[il]) { err = "gdn: position " + std::to_string(pos0) + " does not continue layer " + std::to_string(il) + " at " + std::to_string(pos_[il]); return false; }
if (N < 1 || N > maxn_) { err = "gdn: N out of range"; return false; }
const GdnLayer& W = m_->layers[il].gdn;
const Q4Cfg& c = m_->cfg;
L::gemv_sk(W.qkv.p, W.qkv.code, c.conv_dim(), D_, xr, false, N, pj_qkv_, c.conv_dim(), false, s);
L::gemv_sk(W.z.p, W.z.code, c.val_dim(), D_, xr, false, N, pj_z_, c.val_dim(), false, s);
L::gemv_f32(W.a, gs_.hv, D_, x, N, pj_a_, s);
L::gemv_f32(W.b, gs_.hv, D_, x, N, pj_b_, s);
if (verify_mode_ && N <= kGdnVerifyMax) {
if (!gdn_verify(gs_, g.w, g.st, gsc_, g.vb, pj_qkv_, pj_z_, pj_a_, pj_b_, N, pj_y_, s, err)) return false;
g.pending = true;
pending_n_[il] = N;
} else {
if (verify_mode_) { err = "gdn: a verify window holds at most 16 tokens"; return false; }
if (!gdn_run(gs_, g.w, g.st, gsc_, pj_qkv_, pj_z_, pj_a_, pj_b_, N, pj_y_, s, err)) return false;
pos_[il] = pos0 + N;
}
L::fwht128(pj_y_, pj_r_, N, c.val_dim(), s); // out_proj is stored in the FWHT-128 domain on K
L::gemv_sk(W.out.p, W.out.code, D_, c.val_dim(), pj_r_, false, N, y, D_, false, s);
return true;
}
bool attn(int il, const float* x, const float* xr, int N, int pos0, float* y, cudaStream_t s, std::string& err) override {
namespace L = strata::ling32::gpu;
A& a = attn_[il];
if (!a.st.k_pool) { err = "attn: layer " + std::to_string(il) + " is not an attention layer"; return false; }
if (a.pending) { a.pending = false; pos_[il] += pending_n_[il]; } // previous window accepted in full
if (pos0 != pos_[il]) { err = "attn: position " + std::to_string(pos0) + " does not continue layer " + std::to_string(il) + " at " + std::to_string(pos_[il]); return false; }
if (N < 1 || N > maxn_) { err = "attn: N out of range"; return false; }
const AttnLayer& W = m_->layers[il].attn;
const Q4Cfg& c = m_->cfg;
L::gemv_sk(W.q.p, W.q.code, 2 * c.q_dim(), D_, xr, false, N, pj_q_, 2 * c.q_dim(), false, s);
L::gemv_sk(W.k.p, W.k.code, c.kv_dim(), D_, xr, false, N, pj_k_, c.kv_dim(), false, s);
L::gemv_sk(W.v.p, W.v.code, c.kv_dim(), D_, xr, false, N, pj_v_, c.kv_dim(), false, s);
L::gemv_sk(W.ix_qk.p, W.ix_qk.code, as_.ix_width(), D_, xr, false, N, pj_ix_, as_.ix_width(), false, s);
const bool vm = verify_mode_ && N <= kAttnVerifyMax;
if (verify_mode_ && !vm) { err = "attn: a verify window holds at most 16 tokens"; return false; }
if (!attn_run(as_, a.w, a.st, asc_, pj_q_, pj_k_, pj_v_, pj_ix_, N, pos0, pj_o_, s, err, opt_, vm ? &a.vb : nullptr)) return false;
if (vm) { a.pending = true; pending_n_[il] = N; } else pos_[il] = pos0 + N;
L::fwht128(pj_o_, pj_r_, N, c.q_dim(), s);
L::gemv_sk(W.o.p, W.o.code, D_, c.q_dim(), pj_r_, false, N, y, D_, false, s);
return true;
}
void checkpoint() override { verify_mode_ = true; }
bool rollback(int pos0, int n_keep, std::string& err) override {
cudaDeviceSynchronize(); // the engine's stream is not ours: order the commit after its work (rollback has no stream argument)
for (size_t il = 0; il < gdn_.size(); ++il) {
G& g = gdn_[il];
if (g.pending) {
if (n_keep > g.vb.n) { err = "rollback: n_keep exceeds the window"; return false; }
if (!gdn_commit(gs_, g.w, g.st, gsc_, g.vb, n_keep, 0, err)) return false;
g.pending = false;
pos_[il] = pos0 + n_keep;
}
A& a = attn_[il];
if (a.pending) {
if (n_keep > a.vb.n) { err = "rollback: n_keep exceeds the window"; return false; }
if (!attn_rollback(as_, a.w, a.st, asc_, a.vb, n_keep, 0, err, opt_)) return false;
a.pending = false;
pos_[il] = pos0 + n_keep;
}
}
cudaDeviceSynchronize();
verify_mode_ = false;
return true;
}
size_t state_bytes() const override { return arena_bytes_; }
private:
struct G { GdnWeights w; GdnState st; GdnVerifyBuf vb; bool pending = false; };
struct A { AttnWeights w; AttnState st; AttnVerifyBuf vb; bool pending = false; };
void gdn_assign_scratch(void* base) { gdn_scratch_assign(gs_, maxn_, base, gsc_); }
const GpuModel* m_ = nullptr;
GdnShape gs_;
AttnShape as_;
AttnOptions opt_;
GdnScratch gsc_;
AttnScratch asc_;
std::vector<G> gdn_;
std::vector<A> attn_;
std::vector<int> pos_;
int pending_n_[64] = {};
int maxn_ = 0, max_ctx_ = 0, D_ = 0;
bool verify_mode_ = false, global_ = false;
void* arena_ = nullptr;
size_t arena_bytes_ = 0;
float *pj_qkv_ = nullptr, *pj_z_ = nullptr, *pj_a_ = nullptr, *pj_b_ = nullptr, *pj_y_ = nullptr, *pj_q_ = nullptr, *pj_k_ = nullptr, *pj_v_ = nullptr, *pj_ix_ = nullptr,
*pj_o_ = nullptr, *pj_r_ = nullptr;
};
} // namespace
std::unique_ptr<Mixers> make_mixers() { return std::unique_ptr<Mixers>(new Q4Mixers()); }
} // namespace strata::q4lite
+508
View File
@@ -0,0 +1,508 @@
#!/usr/bin/env python3
"""Torch reference + test-data generator + comparator for the Qwen4 token mixers (GDN, QSA attention + indexer).
Imports NO transformers internals: the functions below are pure-torch extractions of
phaseA-tests/qwen4/ref/modeling_qwen4_moe.py (torch_recurrent_gated_delta_rule, torch_chunk_gated_delta_rule, RMSNorm (1 + w), the gated RMSNorm,
causal_conv1d_update/fn, rotate_half / apply_rotary_pos_emb, the QSA indexer with prepare_compression_groups / select_compression_indices, eager attention
with the sigmoid output gate), reduced to the single-sequence, unpadded case (attention mask = the plain causal count).
gen --scenario gdn|attn --n N | --ctx L --out DIR [--seed S] write random-weight inputs at the REAL shapes + the float64 reference outputs
cmp --dir DIR compare DIR/gpu/* (written by q4_attn_test) with the reference, print the error table
selftest recurrent vs chunk reference agree; fp32 vs fp64 noise floor
Shapes (Qwen4-35B-A3B): GDN 16 key heads, 32 value heads, S = 128, conv 4; attention 16 q heads, 2 kv heads, head dim 256, partial rope 64, theta 1e7;
indexer 4 query heads + 1 key head of dim 128, group 4, budget 2048 tokens (512 groups).
Data files are raw little-endian float32 / int32 with a manifest.json (shapes), written next to the plan.
"""
import argparse
import json
import math
import os
import sys
import numpy as np
import torch
import torch.nn.functional as F
DT = torch.float64 # the reference runs in float64: it is the truth the float32 GPU kernels are measured against
HK, HV, S, CONVK = 16, 32, 128, 4
CONV_DIM = 2 * HK * S + HV * S # 8192
VAL_DIM = HV * S # 4096
NH, NKV, HD, NROT = 16, 2, 256, 64
IXH, IXD, IXB, IXBUDGET = 4, 128, 4, 2048
THETA = 1e7
EPS = 1e-6
# ------------------------------------------------------------------ extracted reference functions
def l2norm(x, dim=-1, eps=1e-6):
inv_norm = torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps)
return x * inv_norm
def torch_recurrent_gated_delta_rule(query, key, value, g, beta, initial_state=None, output_final_state=False, use_qk_l2norm_in_kernel=False):
initial_dtype = query.dtype
batch_size, sequence_length, num_k_heads, k_head_dim = key.shape
num_v_heads, v_head_dim = value.shape[-2:]
decay = g
if num_k_heads != num_v_heads:
query = query.repeat_interleave(num_v_heads // num_k_heads, dim=2)
key = key.repeat_interleave(num_v_heads // num_k_heads, dim=2)
query, key, value, beta, decay = [x.transpose(1, 2).to(DT, memory_format=torch.contiguous_format) for x in (query, key, value, beta, decay)]
if use_qk_l2norm_in_kernel:
query = l2norm(query, dim=-1, eps=1e-6)
key = l2norm(key, dim=-1, eps=1e-6)
query = query / (query.shape[-1] ** 0.5)
if initial_state is None:
last_recurrent_state = torch.zeros((batch_size, num_v_heads, k_head_dim, v_head_dim), dtype=value.dtype, device=value.device)
else:
last_recurrent_state = initial_state.to(value)
core_attn_out = torch.zeros_like(value)
for i in range(sequence_length):
q_t, k_t, v_t = query[:, :, i], key[:, :, i], value[:, :, i]
decay_t = decay[:, :, i].exp()[..., None, None]
last_recurrent_state = last_recurrent_state * decay_t
beta_t = beta[:, :, i].unsqueeze(-1)
kv_mem = (last_recurrent_state * k_t.unsqueeze(-1)).sum(dim=-2)
delta = (v_t - kv_mem) * beta_t
last_recurrent_state = last_recurrent_state + k_t.unsqueeze(-1) * delta.unsqueeze(-2)
core_attn_out[:, :, i] = (last_recurrent_state * q_t.unsqueeze(-1)).sum(dim=-2)
last_recurrent_state = None if not output_final_state else last_recurrent_state
core_attn_out = core_attn_out.transpose(1, 2).contiguous().to(initial_dtype)
return core_attn_out, last_recurrent_state
def torch_chunk_gated_delta_rule(query, key, value, g, beta, chunk_size=64, initial_state=None, output_final_state=False, use_qk_l2norm_in_kernel=False):
initial_dtype = query.dtype
batch_size, sequence_length, num_k_heads, k_head_dim = key.shape
num_v_heads, v_head_dim = value.shape[-2:]
recurrent_state_shape = (batch_size, num_v_heads, k_head_dim, v_head_dim)
padded_output_shape = (batch_size, num_v_heads, -1, v_head_dim)
decay = g
if num_k_heads != num_v_heads:
query = query.repeat_interleave(num_v_heads // num_k_heads, dim=2)
key = key.repeat_interleave(num_v_heads // num_k_heads, dim=2)
query, key, value, beta, decay = [x.transpose(1, 2).to(DT, memory_format=torch.contiguous_format) for x in (query, key, value, beta, decay)]
if use_qk_l2norm_in_kernel:
query = l2norm(query, dim=-1, eps=1e-6)
key = l2norm(key, dim=-1, eps=1e-6)
scaling = query.shape[-1] ** -0.5
query = query * scaling
pad_size = (chunk_size - sequence_length % chunk_size) % chunk_size
query, key, value = (F.pad(x, (0, 0, 0, pad_size)) for x in (query, key, value))
beta, decay = (F.pad(x, (0, pad_size)) for x in (beta, decay))
total_sequence_length = sequence_length + pad_size
num_chunks = total_sequence_length // chunk_size
v_beta = value * beta.unsqueeze(-1)
k_beta = key * beta.unsqueeze(-1)
query, key, k_beta, v_beta = [x.reshape(x.shape[0], x.shape[1], -1, chunk_size, x.shape[-1]) for x in (query, key, k_beta, v_beta)]
decay = decay.reshape(decay.shape[0], decay.shape[1], -1, chunk_size)
strictly_upper_mask = torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device).triu(1)
cum_decay = decay.cumsum(dim=3)
pairwise_decay = cum_decay.unsqueeze(4) - cum_decay.unsqueeze(3)
pairwise_decay = pairwise_decay.masked_fill(strictly_upper_mask, float("-inf"))
pairwise_decay = pairwise_decay.exp()
ut_system = (k_beta @ key.transpose(-1, -2)) * pairwise_decay
intra_chunk_attn = (query @ key.transpose(-1, -2)) * pairwise_decay
decayed_k_beta = k_beta * cum_decay.exp().unsqueeze(-1)
new_values = torch.linalg.solve_triangular(ut_system, v_beta, upper=False, unitriangular=True)
k_cumdecay = torch.linalg.solve_triangular(ut_system, decayed_k_beta, upper=False, unitriangular=True)
if initial_state is None:
last_recurrent_state = torch.zeros(recurrent_state_shape, dtype=new_values.dtype, device=new_values.device)
else:
last_recurrent_state = initial_state.to(new_values)
core_attn_out = torch.zeros_like(new_values)
query = query * cum_decay.exp().unsqueeze(-1)
key = key * (cum_decay[..., -1:] - cum_decay).exp().unsqueeze(-1)
chunk_decay = cum_decay[..., -1].exp()[..., None, None]
for i in range(num_chunks):
v_new = new_values[:, :, i] - k_cumdecay[:, :, i] @ last_recurrent_state
inter_chunk_attn = query[:, :, i] @ last_recurrent_state
core_attn_out[:, :, i] = inter_chunk_attn + intra_chunk_attn[:, :, i] @ v_new
last_recurrent_state = last_recurrent_state * chunk_decay[:, :, i] + key[:, :, i].transpose(-1, -2) @ v_new
last_recurrent_state = None if not output_final_state else last_recurrent_state
core_attn_out = core_attn_out.reshape(padded_output_shape)
core_attn_out = core_attn_out[:, :, :sequence_length]
core_attn_out = core_attn_out.transpose(1, 2).to(initial_dtype, memory_format=torch.contiguous_format)
return core_attn_out, last_recurrent_state
def rms_1pw(x, w, eps=EPS):
"""Qwen4MoeTextRMSNorm: x * rsqrt(mean(x^2) + eps) * (1 + w)"""
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) * (1.0 + w)
def rms_gated(x, gate, w, eps=EPS):
"""Qwen4MoeTextRMSNormGated with activation sigmoid (config output_gate_type): w * norm(x) * sigmoid(gate)"""
x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
return w * x * torch.sigmoid(gate)
def rotate_half(x):
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2:]
return torch.cat((-x2, x1), dim=-1)
def rope_cos_sin(pos, rot=NROT, theta=THETA):
"""text positions (all three mrope streams equal): cos/sin [len(pos), rot]"""
inv_freq = 1.0 / (theta ** (torch.arange(0, rot, 2, dtype=DT) / rot))
freqs = pos.to(DT)[:, None] * inv_freq[None, :]
emb = torch.cat((freqs, freqs), dim=-1)
return emb.cos(), emb.sin()
def apply_rope(x, cos, sin):
"""x [..., T, heads, D]: rotates the first cos.shape[-1] dims (partial rope), cos/sin [T, rot]"""
rot = cos.shape[-1]
c, s = cos[:, None, :], sin[:, None, :]
xr, xp = x[..., :rot], x[..., rot:]
xr = xr * c + rotate_half(xr) * s
return torch.cat([xr, xp], dim=-1)
# ------------------------------------------------------------------ GDN layer core (everything between the projections)
def gdn_ref(qkv, z, a, b, conv_w, A_log, dt_bias, norm_w, conv_state, S_state, chunk=False):
"""qkv [N, 8192], z [N, 4096], a, b [N, 32] (projection outputs); conv_w [8192, 4]; conv_state [8192, 3]; S_state [32, 128, 128] (h, k, v).
Returns y [N, 4096] (gated norm output), new conv_state, new S_state."""
N = qkv.shape[0]
x = torch.cat([conv_state, qkv.t()], dim=1) # [C, 3 + N]
out = F.conv1d(x[None], conv_w[:, None, :], None, padding=0, groups=CONV_DIM)[0] # [C, N]
out = F.silu(out)
new_conv = x[:, -(CONVK - 1):].clone()
mixed = out.t() # [N, C]
q, k, v = torch.split(mixed, [HK * S, HK * S, HV * S], dim=-1)
q = q.reshape(1, N, HK, S)
k = k.reshape(1, N, HK, S)
v = v.reshape(1, N, HV, S)
beta = b.sigmoid()[None]
g = (-A_log.exp() * F.softplus(a + dt_bias))[None]
fn = torch_chunk_gated_delta_rule if chunk else torch_recurrent_gated_delta_rule
core, S_new = fn(q, k, v, g=g, beta=beta, initial_state=S_state[None], output_final_state=True, use_qk_l2norm_in_kernel=True)
core = core.reshape(-1, S)
zz = z.reshape(-1, S)
y = rms_gated(core, zz, norm_w).reshape(N, VAL_DIM)
return y, new_conv, S_new[0]
# ------------------------------------------------------------------ QSA attention + indexer (single sequence, whole stream at once)
def attn_ref(q_proj, k_proj, v_proj, idx_qk, q_w, k_w, iq_w, ik_w, with_sel=True):
"""The stream of L tokens at positions 0..L-1 -> out [L, 4096] (attention * sigmoid(gate), before o_proj), plus per-query selection data.
q_proj [L, 16*512] per head [q | gate], k_proj, v_proj [L, 512], idx_qk [L, 640]; *_w are the RAW norm weights (the norms apply 1 + w)."""
L = q_proj.shape[0]
pos = torch.arange(L)
cos, sin = rope_cos_sin(pos)
qg = q_proj.reshape(L, NH, 2 * HD)
q, gate = qg[..., :HD], qg[..., HD:]
q = apply_rope(rms_1pw(q, q_w), cos, sin) # [L, 16, 256]
k = apply_rope(rms_1pw(k_proj.reshape(L, NKV, HD), k_w), cos, sin) # [L, 2, 256]
v = v_proj.reshape(L, NKV, HD)
# indexer
qi = idx_qk[:, :IXH * IXD].reshape(L, IXH, IXD)
raw = idx_qk[:, IXH * IXD:] # [L, 128]
qi = apply_rope(rms_1pw(qi, iq_w), cos, sin) # [L, 4, 128]
G = L // IXB # complete groups of the whole stream
pooled = None
if G > 0:
mean = raw[: G * IXB].reshape(G, IXB, IXD).mean(dim=1) # mean of the 4 raw keys
kn = rms_1pw(mean, ik_w)
cg, sg = cos[::IXB][:G], sin[::IXB][:G] # rope at the group's FIRST position
pooled = apply_rope(kn[:, None, :], cg, sg)[:, 0, :] # [G, 128]
out = torch.zeros(L, NH * HD, dtype=DT)
width = IXBUDGET // IXB
sel = torch.full((L, IXBUDGET + IXB - 1), -1, dtype=torch.int32)
cut = torch.zeros(L, 2, dtype=DT)
gscore = [None] * L
scale = HD ** -0.5
rep = NH // NKV
for p in range(L):
n_kv = p + 1
cg_ = n_kv // IXB # complete groups visible to this query
toks = []
if cg_ > 0:
sc = F.relu(torch.einsum("hd,gd->hg", qi[p], pooled[:cg_])).sum(0) / math.sqrt(IXD)
kk = min(width, cg_)
top = torch.topk(sc, kk).indices
srt = torch.sort(sc, descending=True).values
cut[p, 0] = srt[kk - 1]
cut[p, 1] = srt[kk] if kk < cg_ else float("-inf")
gscore[p] = sc
grp = torch.sort(top).values
toks = (grp[:, None] * IXB + torch.arange(IXB)[None, :]).reshape(-1).tolist()
toks += list(range(cg_ * IXB, n_kv)) # the unfinished group's tokens
t = torch.tensor(toks, dtype=torch.long)
sel[p, : len(toks)] = t.to(torch.int32)
kt = k[t] # [T, 2, 256]
vt = v[t]
kh = kt.repeat_interleave(rep, dim=1) # [T, 16, 256] (repeat_kv: head h -> kv head h // rep)
vh = vt.repeat_interleave(rep, dim=1)
s_ = torch.einsum("hd,thd->ht", q[p], kh) * scale
w_ = torch.softmax(s_, dim=-1)
o = torch.einsum("ht,thd->hd", w_, vh)
out[p] = (o * torch.sigmoid(gate[p])).reshape(-1)
return out, sel, cut, gscore
# ------------------------------------------------------------------ data files
def wr(d, name, arr):
a = np.ascontiguousarray(arr)
a.tofile(os.path.join(d, name))
def rd(d, name, dtype, shape=None):
a = np.fromfile(os.path.join(d, name), dtype=dtype)
return a.reshape(shape) if shape is not None else a
def make_ops(total, style):
"""list of (kind, n, keep): the first `keep` rows of an op are real stream tokens ('run': all n); a verify keeps k <= n of its n rows."""
ops = []
left = total
pat = [("run", 1, 1), ("run", 1, 1), ("verify", 8, 5), ("run", 4, 4), ("verify", 16, 16), ("run", 1, 1), ("verify", 4, 0), ("run", 16, 16), ("verify", 16, 11), ("run", 1, 1)]
i = 0
if style[0] == "chunks":
big = style[1]
while left > big + 80:
ops.append(("run", big, big))
left -= big
elif style[0] == "first":
ops.append(("run", style[1], style[1]))
left -= style[1]
while left > 0:
kind, n, keep = pat[i % len(pat)]
i += 1
if kind == "run":
n = keep = min(n, left)
else:
keep = min(keep, left)
ops.append((kind, n, keep))
left -= keep
return ops
def gen(args):
out = args.out
os.makedirs(out, exist_ok=True)
rng = np.random.default_rng(args.seed)
f32 = np.float32
man = {"scenario": args.scenario, "ops": []}
if args.scenario == "gdn":
n = args.n
ops = [("run", n, n)] + [("run", 1, 1)] * 3 + [("verify", 8, 5), ("run", n, n), ("verify", 16, 16), ("run", 1, 1), ("verify", 4, 0), ("run", 1, 1), ("run", 3, 3), ("run", 70, 70)]
if n == 1:
ops = [("run", 1, 1)] * 6 + [("verify", 8, 5), ("run", 1, 1), ("verify", 16, 16), ("run", 1, 1), ("verify", 4, 0), ("run", 1, 1), ("run", 3, 3)]
total = sum(k for _, _, k in ops)
conv_w = (rng.standard_normal((CONV_DIM, CONVK)) * 0.5).astype(f32)
A_log = np.log(rng.uniform(0.01, 16, HV)).astype(f32)
dt_bias = (1.0 + 0.3 * rng.standard_normal(HV)).astype(f32)
norm_w = (1.0 + 0.1 * rng.standard_normal(S)).astype(f32)
for nm, arr in (("conv", conv_w), ("A_log", A_log), ("dt_bias", dt_bias), ("norm", norm_w)):
wr(out, f"w.{nm}.f32", arr)
# the stream
qkv = rng.standard_normal((total, CONV_DIM)).astype(f32)
z = rng.standard_normal((total, VAL_DIM)).astype(f32)
a = rng.standard_normal((total, HV)).astype(f32)
b = rng.standard_normal((total, HV)).astype(f32)
t = lambda x: torch.from_numpy(x.astype(np.float64))
yref = np.zeros((total, VAL_DIM), np.float64)
conv_state = torch.zeros(CONV_DIM, CONVK - 1, dtype=DT)
S_state = torch.zeros(HV, S, S, dtype=DT)
row = 0
for i, (kind, nn, keep) in enumerate(ops):
def pick(arr, width): # rows of this op: real stream rows then garbage
blk = np.empty((nn, width), f32)
blk[:keep] = arr[row:row + keep]
if nn > keep:
blk[keep:] = rng.standard_normal((nn - keep, width)).astype(f32)
return blk
for nm, arr, w_ in (("qkv", qkv, CONV_DIM), ("z", z, VAL_DIM), ("a", a, HV), ("b", b, HV)):
wr(out, f"op{i}.{nm}.f32", pick(arr, w_))
if keep > 0:
y, conv_state, S_state = gdn_ref(t(qkv[row:row + keep]), t(z[row:row + keep]), t(a[row:row + keep]), t(b[row:row + keep]), t(conv_w), t(A_log), t(dt_bias),
t(norm_w), conv_state, S_state)
yref[row:row + keep] = y.numpy()
wr(out, f"op{i}.yref.f64", yref[row:row + keep])
man["ops"].append({"kind": kind, "n": nn, "keep": keep, "row": row})
row += keep
wr(out, "final.S.f64", S_state.numpy()) # [h][k][v]
wr(out, "final.hist.f64", conv_state.numpy()) # [C][3]
man["total"] = total
else:
total = args.ctx
ops = make_ops(total, ("chunks", 1000) if total > 1100 else ("first", min(256, total - 80)))
qw = (0.1 * rng.standard_normal(HD)).astype(f32)
kw = (0.1 * rng.standard_normal(HD)).astype(f32)
iqw = (0.1 * rng.standard_normal(IXD)).astype(f32)
ikw = (0.1 * rng.standard_normal(IXD)).astype(f32)
for nm, arr in (("q_norm", qw), ("k_norm", kw), ("ix_q_ln", iqw), ("ix_k_ln", ikw)):
wr(out, f"w.{nm}.f32", arr)
q_proj = rng.standard_normal((total, NH * 2 * HD)).astype(f32)
k_proj = rng.standard_normal((total, NKV * HD)).astype(f32)
v_proj = rng.standard_normal((total, NKV * HD)).astype(f32)
idx_qk = rng.standard_normal((total, (IXH + 1) * IXD)).astype(f32)
t = lambda x: torch.from_numpy(x.astype(np.float64))
o_ref, sel, cut, gscore = attn_ref(t(q_proj), t(k_proj), t(v_proj), t(idx_qk), t(qw), t(kw), t(iqw), t(ikw))
row = 0
for i, (kind, nn, keep) in enumerate(ops):
for nm, arr in (("q", q_proj), ("k", k_proj), ("v", v_proj), ("idx", idx_qk)):
w_ = arr.shape[1]
blk = np.empty((nn, w_), f32)
blk[:keep] = arr[row:row + keep]
if nn > keep:
blk[keep:] = rng.standard_normal((nn - keep, w_)).astype(f32)
wr(out, f"op{i}.{nm}.f32", blk)
wr(out, f"op{i}.yref.f64", o_ref[row:row + keep].numpy())
wr(out, f"op{i}.selref.i32", sel[row:row + keep].numpy())
wr(out, f"op{i}.cut.f64", cut[row:row + keep].numpy())
# group scores of the queries of this op (needed to explain selection mismatches): [keep][Gmax] float32, -inf padded
gmax = max(1, (row + keep) // IXB)
gs = np.full((keep, gmax), -np.inf, np.float32)
for r in range(keep):
g_ = gscore[row + r]
if g_ is not None:
gs[r, : g_.shape[0]] = g_.numpy()
wr(out, f"op{i}.gscore.f32", gs)
man["ops"].append({"kind": kind, "n": nn, "keep": keep, "row": row, "gmax": gmax})
row += keep
man["total"] = total
with open(os.path.join(out, "manifest.json"), "w") as f:
json.dump(man, f)
print(f"gen {args.scenario}: {len(man['ops'])} ops, {man['total']} stream tokens -> {out}")
def err_line(name, got, ref):
got = got.astype(np.float64)
ref = ref.astype(np.float64)
d = np.abs(got - ref)
scale = np.abs(ref).max() + 1e-30
rel_rms = np.sqrt((d ** 2).mean()) / (np.sqrt((ref ** 2).mean()) + 1e-30)
return d.max(), d.max() / scale, rel_rms
def cmp_(args):
d = args.dir
man = json.load(open(os.path.join(d, "manifest.json")))
g = os.path.join(d, "gpu")
worst = [0.0, 0.0, 0.0]
per_kind = {}
tie_expl = real = total_q = 0
sel_mism_q = 0
for i, op in enumerate(man["ops"]):
n, keep = op["n"], op["keep"]
if keep == 0:
continue
if man["scenario"] == "gdn":
width = VAL_DIM
else:
width = NH * HD
yref = rd(d, f"op{i}.yref.f64", np.float64, (keep, width))
ygpu = rd(g, f"op{i}.y.f32", np.float32, (n, width))[:keep]
if not np.isfinite(ygpu).all():
print(f"op{i} {op['kind']} n={n}: NON-FINITE OUTPUT")
worst = [float("inf")] * 3
continue
e = err_line("y", ygpu, yref)
key = (op["kind"], n if n in (1, 4, 16, 64, 1000) else "other")
cur = per_kind.setdefault(key, [0.0, 0.0, 0.0])
for j in range(3):
cur[j] = max(cur[j], e[j])
worst[j] = max(worst[j], e[j])
if man["scenario"] == "attn":
cap = 2051
selref = rd(d, f"op{i}.selref.i32", np.int32, (keep, IXBUDGET + IXB - 1))
selg = rd(g, f"op{i}.sel.i32", np.int32, (n, cap))[:keep]
gs = rd(d, f"op{i}.gscore.f32", np.float32, (keep, op["gmax"]))
cut = rd(d, f"op{i}.cut.f64", np.float64, (keep, 2))
for r in range(keep):
p = op["row"] + r
n_kv = p + 1
wd = min(n_kv, IXBUDGET + n_kv % IXB)
a_ = set(selg[r, :wd].tolist())
b_ = set(x for x in selref[r].tolist() if x >= 0)
total_q += 1
if a_ != b_:
sel_mism_q += 1
diff = a_.symmetric_difference(b_)
groups = {x // IXB for x in diff}
# explained by a tie (or a near tie within float32 score noise) at the cut-off
tol = 1e-4 * max(1.0, abs(cut[r, 0]))
ok = all(abs(float(gs[r, gi]) - cut[r, 0]) <= tol or abs(float(gs[r, gi]) - cut[r, 1]) <= tol for gi in groups if gi < gs.shape[1]) and all(
(x // IXB) < gs.shape[1] for x in diff)
if ok:
tie_expl += 1
else:
real += 1
if real <= 5:
print(f" REAL selection mismatch op{i} q{p}: only-gpu {sorted(a_ - b_)[:8]} only-ref {sorted(b_ - a_)[:8]} cut={cut[r]} ")
print("---- error table: max abs, max abs / max|ref|, rms / rms(ref)")
for key in sorted(per_kind, key=str):
e = per_kind[key]
print(f" {man['scenario']} {key[0]:7s} n={str(key[1]):6s} max_abs={e[0]:.3e} max_rel={e[1]:.3e} rms_rel={e[2]:.3e}")
print(f" WORST max_abs={worst[0]:.3e} max_rel={worst[1]:.3e} rms_rel={worst[2]:.3e}")
if man["scenario"] == "gdn":
S_ref = rd(d, "final.S.f64", np.float64, (HV, S, S)) # [h][k][v]
S_gpu = rd(g, "final.S.f32", np.float32, (S, HV, S)).astype(np.float64).transpose(1, 0, 2) # engine layout [k][h][v] -> [h][k][v]
h_ref = rd(d, "final.hist.f64", np.float64, (CONV_DIM, 3))
h_gpu = rd(g, "final.hist.f32", np.float32, (CONV_DIM, 3))
es = np.abs(S_gpu - S_ref).max()
eh = np.abs(h_gpu - h_ref).max()
print(f" final state: S max_abs={es:.3e} (max|ref|={np.abs(S_ref).max():.3e}), conv history max_abs={eh:.3e}")
worst_state = max(es / (np.abs(S_ref).max() + 1e-30), eh)
ok = worst[2] < 2e-4 and worst_state < 2e-4
else:
print(f" selection: {total_q} queries, {sel_mism_q} with a different token set: {tie_expl} explained by a (near) tie at the cut-off, {real} REAL")
ok = worst[2] < 5e-4 and real == 0
print("RESULT", "PASS" if ok else "FAIL", man["scenario"])
return 0 if ok else 1
def selftest(args):
rng = np.random.default_rng(1)
N = 200
t = lambda x: torch.from_numpy(x.astype(np.float64))
qkv = t(rng.standard_normal((N, CONV_DIM)))
z = t(rng.standard_normal((N, VAL_DIM)))
a = t(rng.standard_normal((N, HV)))
b = t(rng.standard_normal((N, HV)))
cw = t(rng.standard_normal((CONV_DIM, CONVK)) * 0.5)
A = t(np.log(rng.uniform(0.01, 16, HV)))
dtb = t(1.0 + 0.3 * rng.standard_normal(HV))
nw = t(1.0 + 0.1 * rng.standard_normal(S))
c0 = torch.zeros(CONV_DIM, 3, dtype=DT)
s0 = torch.zeros(HV, S, S, dtype=DT)
y1, c1, s1 = gdn_ref(qkv, z, a, b, cw, A, dtb, nw, c0, s0, chunk=False)
y2, c2, s2 = gdn_ref(qkv, z, a, b, cw, A, dtb, nw, c0, s0, chunk=True)
print("recurrent vs chunk reference: y", float((y1 - y2).abs().max()), "S", float((s1 - s2).abs().max()))
# split in two calls: state continuation
ya, ca, sa = gdn_ref(qkv[:77], z[:77], a[:77], b[:77], cw, A, dtb, nw, c0, s0)
yb, cb, sb = gdn_ref(qkv[77:], z[77:], a[77:], b[77:], cw, A, dtb, nw, ca, sa)
print("continuation: y", float((torch.cat([ya, yb]) - y1).abs().max()), "S", float((sb - s1).abs().max()))
ok = float((y1 - y2).abs().max()) < 1e-9 and float((torch.cat([ya, yb]) - y1).abs().max()) < 1e-12
print("SELFTEST", "PASS" if ok else "FAIL")
return 0 if ok else 1
def main():
ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
g = sub.add_parser("gen")
g.add_argument("--scenario", choices=["gdn", "attn"], required=True)
g.add_argument("--n", type=int, default=1)
g.add_argument("--ctx", type=int, default=300)
g.add_argument("--out", required=True)
g.add_argument("--seed", type=int, default=1)
c = sub.add_parser("cmp")
c.add_argument("--dir", required=True)
sub.add_parser("selftest")
args = ap.parse_args()
if args.cmd == "gen":
gen(args)
elif args.cmd == "cmp":
sys.exit(cmp_(args))
else:
sys.exit(selftest(args))
if __name__ == "__main__":
main()
+212
View File
@@ -0,0 +1,212 @@
// tests/q4lite/q4_attn_test.cu - runs the q4lite token mixers (q4_gdn / q4_attn) on the data written by q4_attn_ref.py gen and writes DIR/gpu/* for q4_attn_ref.py cmp.
// q4_attn_test DIR [--no-tc] [--fp32-indexer] [--time]
// The manifest is read with a tiny scanner (the ops' "kind", "n", "keep" fields in order; the scenario name), no JSON library.
#include "../../src/q4lite/q4_attn.hpp"
#include "../../src/q4lite/q4_gdn.hpp"
#include <cuda_runtime.h>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#if defined(_WIN32)
#include <direct.h>
#define MKDIR(p) _mkdir(p)
#else
#include <sys/stat.h>
#define MKDIR(p) mkdir(p, 0755)
#endif
using namespace strata::q4lite;
#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { std::fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, cudaGetErrorString(e_)); std::exit(2); } } while (0)
static std::string DIR;
static std::vector<char> readfile(const std::string& n) {
std::ifstream f(n, std::ios::binary);
if (!f) { std::fprintf(stderr, "cannot open %s\n", n.c_str()); std::exit(2); }
return std::vector<char>((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
}
static float* upload(const std::string& n, size_t* count = nullptr) {
auto b = readfile(DIR + "/" + n);
float* d = nullptr;
CK(cudaMalloc(&d, b.size()));
CK(cudaMemcpy(d, b.data(), b.size(), cudaMemcpyHostToDevice));
if (count) *count = b.size() / 4;
return d;
}
static void writefile(const std::string& n, const void* p, size_t bytes) {
std::ofstream f(DIR + "/gpu/" + n, std::ios::binary);
f.write((const char*) p, (std::streamsize) bytes);
}
static void dl_write(const std::string& n, const void* dev, size_t bytes) {
std::vector<char> h(bytes);
CK(cudaMemcpy(h.data(), dev, bytes, cudaMemcpyDeviceToHost));
writefile(n, h.data(), bytes);
}
struct Op { std::string kind; int n = 0, keep = 0; };
static std::vector<Op> parse_ops(const std::string& man, std::string& scenario) {
std::vector<Op> ops;
size_t p = man.find("\"scenario\": \"");
scenario = man.substr(p + 13, man.find('"', p + 13) - (p + 13));
size_t at = 0;
while ((at = man.find("{\"kind\": \"", at)) != std::string::npos) {
Op o;
size_t k = at + 10;
o.kind = man.substr(k, man.find('"', k) - k);
size_t pn = man.find("\"n\": ", at), pk = man.find("\"keep\": ", at);
o.n = std::atoi(man.c_str() + pn + 5);
o.keep = std::atoi(man.c_str() + pk + 8);
ops.push_back(o);
at = pk;
}
return ops;
}
int main(int argc, char** argv) {
if (argc < 2) { std::fprintf(stderr, "usage: q4_attn_test DIR [--no-tc] [--fp32-indexer] [--time]\n"); return 2; }
DIR = argv[1];
bool no_tc = false, fp32_ix = false, do_time = false;
for (int i = 2; i < argc; ++i) {
if (!std::strcmp(argv[i], "--no-tc")) no_tc = true;
else if (!std::strcmp(argv[i], "--fp32-indexer")) fp32_ix = true;
else if (!std::strcmp(argv[i], "--time")) do_time = true;
}
MKDIR((DIR + "/gpu").c_str());
auto mb = readfile(DIR + "/manifest.json");
std::string scenario;
std::vector<Op> ops = parse_ops(std::string(mb.begin(), mb.end()), scenario);
cudaDeviceProp prop;
CK(cudaGetDeviceProperties(&prop, 0));
std::printf("device %s sm_%d%d, scenario %s, %zu ops\n", prop.name, prop.major, prop.minor, scenario.c_str(), ops.size());
cudaStream_t st;
CK(cudaStreamCreate(&st));
std::string err;
int bad = 0;
if (scenario == "gdn") {
GdnShape s;
const int max_n = 1024;
float* conv = upload("w.conv.f32");
float* A_log = upload("w.A_log.f32");
float* dt = upload("w.dt_bias.f32");
float* norm = upload("w.norm.f32");
float* ssm_a = nullptr;
CK(cudaMalloc(&ssm_a, s.hv * 4));
gdn_ssm_a_from_alog(A_log, ssm_a, s.hv, st);
GdnWeights w{conv, ssm_a, dt, norm};
GdnState state;
CK(cudaMalloc(&state.S, gdn_state_bytes(s)));
CK(cudaMalloc(&state.hist, gdn_hist_bytes(s)));
gdn_state_reset(s, state, st);
GdnScratch sc;
void* sb = nullptr;
CK(cudaMalloc(&sb, gdn_scratch_bytes(s, max_n)));
gdn_scratch_assign(s, max_n, sb, sc);
GdnVerifyBuf vb;
void* vbm = nullptr;
CK(cudaMalloc(&vbm, gdn_verify_bytes(s)));
gdn_verify_assign(s, vbm, vb);
float* y = nullptr;
CK(cudaMalloc(&y, (size_t) max_n * s.val_dim() * 4));
for (size_t i = 0; i < ops.size(); ++i) {
const Op& o = ops[i];
float* qkv = upload("op" + std::to_string(i) + ".qkv.f32");
float* z = upload("op" + std::to_string(i) + ".z.f32");
float* a = upload("op" + std::to_string(i) + ".a.f32");
float* b = upload("op" + std::to_string(i) + ".b.f32");
bool ok;
if (o.kind == "run") ok = gdn_run(s, w, state, sc, qkv, z, a, b, o.n, y, st, err);
else {
ok = gdn_verify(s, w, state, sc, vb, qkv, z, a, b, o.n, y, st, err);
if (ok) ok = gdn_commit(s, w, state, sc, vb, o.keep, st, err);
}
CK(cudaStreamSynchronize(st));
if (!ok) { std::printf("op%zu %s n=%d FAILED: %s\n", i, o.kind.c_str(), o.n, err.c_str()); bad = 1; break; }
dl_write("op" + std::to_string(i) + ".y.f32", y, (size_t) o.n * s.val_dim() * 4);
cudaFree(qkv); cudaFree(z); cudaFree(a); cudaFree(b);
}
dl_write("final.S.f32", state.S, gdn_state_bytes(s));
dl_write("final.hist.f32", state.hist, gdn_hist_bytes(s));
if (do_time) { // decode step time (state carried, N = 1), 200 steps
float* qkv = upload("op0.qkv.f32"); float* z = upload("op0.z.f32"); float* a = upload("op0.a.f32"); float* b = upload("op0.b.f32");
cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1);
for (int rep = 0; rep < 20; ++rep) gdn_run(s, w, state, sc, qkv, z, a, b, 1, y, st, err);
cudaEventRecord(e0, st);
for (int rep = 0; rep < 200; ++rep) gdn_run(s, w, state, sc, qkv, z, a, b, 1, y, st, err);
cudaEventRecord(e1, st); cudaEventSynchronize(e1);
float ms; cudaEventElapsedTime(&ms, e0, e1);
std::printf("TIME gdn decode step (gates + conv + step + norm, 1 layer): %.1f us\n", ms * 1000.0f / 200);
}
} else {
AttnShape s;
const int max_n = 1024, max_ctx = 8192;
std::string e2;
if (!attn_global_init(s, max_ctx, e2)) { std::fprintf(stderr, "%s\n", e2.c_str()); return 2; }
float *qw = upload("w.q_norm.f32"), *kw = upload("w.k_norm.f32"), *iqw = upload("w.ix_q_ln.f32"), *ikw = upload("w.ix_k_ln.f32");
float* gam = nullptr;
CK(cudaMalloc(&gam, (s.hd * 2 + s.ixd * 2) * 4));
attn_gamma_1pw(qw, gam, s.hd, st);
attn_gamma_1pw(kw, gam + s.hd, s.hd, st);
attn_gamma_1pw(iqw, gam + 2 * s.hd, s.ixd, st);
attn_gamma_1pw(ikw, gam + 2 * s.hd + s.ixd, s.ixd, st);
AttnWeights w{gam, gam + s.hd, gam + 2 * s.hd, gam + 2 * s.hd + s.ixd};
AttnState state;
void* stm = nullptr;
CK(cudaMalloc(&stm, attn_state_bytes(s, max_ctx)));
attn_state_assign(s, max_ctx, stm, state);
attn_state_reset(s, state, st);
AttnScratch sc;
void* scm = nullptr;
CK(cudaMalloc(&scm, attn_scratch_bytes(s, max_n, max_ctx)));
attn_scratch_assign(s, max_n, max_ctx, scm, sc);
AttnVerifyBuf vb;
void* vbm = nullptr;
CK(cudaMalloc(&vbm, attn_verify_bytes(s)));
attn_verify_assign(s, vbm, vb);
float* out = nullptr;
CK(cudaMalloc(&out, (size_t) max_n * s.q_width() * 4));
AttnOptions opt;
opt.score_tc = opt.prompt_tc = !no_tc;
opt.ix_native = !fp32_ix;
int pos = 0;
std::vector<float*> keepbufs;
for (size_t i = 0; i < ops.size(); ++i) {
const Op& o = ops[i];
std::string p = "op" + std::to_string(i);
float* q = upload(p + ".q.f32"); float* k = upload(p + ".k.f32"); float* v = upload(p + ".v.f32"); float* ix = upload(p + ".idx.f32");
bool ok;
if (o.kind == "run") ok = attn_run(s, w, state, sc, q, k, v, ix, o.n, pos, out, st, err, opt);
else {
ok = attn_run(s, w, state, sc, q, k, v, ix, o.n, pos, out, st, err, opt, &vb);
if (ok) ok = attn_rollback(s, w, state, sc, vb, o.keep, st, err, opt);
}
CK(cudaStreamSynchronize(st));
if (!ok) { std::printf("op%zu %s n=%d FAILED: %s\n", i, o.kind.c_str(), o.n, err.c_str()); bad = 1; break; }
dl_write(p + ".y.f32", out, (size_t) o.n * s.q_width() * 4);
dl_write(p + ".sel.i32", sc.sel_ids, (size_t) o.n * sc.cap * 4);
pos += o.keep;
cudaFree(q); cudaFree(k); cudaFree(v); cudaFree(ix);
}
if (do_time && !bad) { // decode step time at the final context: re-run the last token position repeatedly
const int ctx = pos;
float* q = upload("op0.q.f32"); float* k = upload("op0.k.f32"); float* v = upload("op0.v.f32"); float* ix = upload("op0.idx.f32");
cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1);
for (int rep = 0; rep < 10; ++rep) attn_run(s, w, state, sc, q, k, v, ix, 1, ctx - 1, out, st, err, opt);
cudaEventRecord(e0, st);
for (int rep = 0; rep < 100; ++rep) attn_run(s, w, state, sc, q, k, v, ix, 1, ctx - 1, out, st, err, opt);
cudaEventRecord(e1, st); cudaEventSynchronize(e1);
float ms; cudaEventElapsedTime(&ms, e0, e1);
std::printf("TIME attention decode step at ctx %d (norm+rope, kv, indexer, select, attn, gate; 1 layer): %.1f us\n", ctx, ms * 1000.0f / 100);
}
}
CK(cudaStreamSynchronize(st));
std::printf(bad ? "RUN FAILED\n" : "RUN DONE\n");
return bad;
}