Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
bb70017
qwen3_5 cuda: the kernels read the state, its rollback copy and the l…
jschmied Nov 8, 2026
b5dbfb1
contract: the state-table kernels' nvcc 13.0 usage on the five SMs
jschmied Nov 8, 2026
dabbcf7
qwen3_5 cuda: a forward's state tables sit at an address the kernels …
jschmied Nov 8, 2026
2976b90
contract: the forward-table kernels' nvcc 13.0 usage on the five SMs
jschmied Nov 9, 2026
70f8687
qwen3_5 cuda: review: States and its two tests in their own file, cud…
jschmied Nov 9, 2026
aded920
contract: review: the state-table launches' nvcc 13.3 rows are pendin…
jschmied Nov 9, 2026
977add1
contract: review: the state-table launches' nvcc 13.2 usage on the fi…
jschmied Nov 10, 2026
1898acf
qwen3_5 cuda: review: the logits-failure test's comment on its own line
jschmied Nov 10, 2026
ec253ac
qwen3_5 cuda: streams without a pool lane run main's kernels; the sta…
jschmied Nov 10, 2026
6db015d
qwen3_5 cuda: review: the shared and recurrent host tests count the s…
jschmied Nov 10, 2026
11bb06a
contract: review: tf_q35k_apply_pend_table's nvcc 13.2 usage on the f…
jschmied Nov 10, 2026
8c7b1b4
qwen3_5 cuda tests: gdn_pre, conv_commit, gdn_chain and tf_q35k_conv …
jschmied Nov 11, 2026
6587e14
qwen3_5 cuda: deltaScan beside body in cuda_forward.zig, stateEntries…
jschmied Nov 20, 2026
5451b4a
kv pool: a stream's state as pieces on any whole pages of its lease
jschmied Nov 10, 2026
1350872
qwen3_5 cuda: a pool lane's state as pieces on any pages
jschmied Nov 10, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions zig/dense_serving_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@ test "dense serving: owned CUDA images retain their reviewed lane and decode byt
try std.testing.expectEqualStrings("8780fd710be3ce2f04e53fa1e69eb062809d3bec6391d9bd49983d0588e374d0", &hash(group));
// #2825 hoists copy addresses before the K loop; copy order and math match prefill_kernel.
try std.testing.expectEqualStrings("e3724114b87cae6f6f761b2f86357f05b1693d84a0233e4d58ce46349fa853f6", &hash(@embedFile("kernels/cuda/qmm_prefill.cu")));
// the join variant's bytes: tf_q35_attn_rows_join for streams on shared pages; main's kernels' SASS unchanged
try std.testing.expectEqualStrings("77ac41e5764a79cca2313ecd09664479b8b4736747c79188e1ad5cae29fd03e4", &hash(@embedFile("kernels/cuda/qwen35.cu")));
// #1879's bytes: a comment names cuda_scratch.zig, where max_chunks moved; the code is unchanged
try std.testing.expectEqualStrings("f9e4a040cf219aac8db211df25d264dba390fce4a7e8da45557652c6ff0f28ba", &hash(@embedFile("kernels/cuda/qwen35.cuh")));
// #2620: the state kernels moved to qwen35_gdn.cuh/qwen35_slots.cuh, included as main's and as _table copies
try std.testing.expectEqualStrings("7d051c8877b15b24f769f6e26212be2de1e8361e2a04ee2626d616c559a3cd00", &hash(@embedFile("kernels/cuda/qwen35.cu")));
// #2620's bytes: the state table entries and forward_states (SEG_STATES); main's kernels' SASS unchanged
try std.testing.expectEqualStrings("85cf7a5dd5aff724da5bcf1bf76d7bf8762a5ae8a0df5adebd0636c2f37dd949", &hash(@embedFile("kernels/cuda/qwen35.cuh")));
// 67711a6aa7's bytes: the opt-in DSpine draft kernels (#2633); default serving unchanged
try std.testing.expectEqualStrings("df06cb0ef07d12ca2296f7d1691678d0649a148f4abcbb3cb69f0d839e45295c", &hash(@embedFile("kernels/cuda/qwen35_draft.cu")));
try std.testing.expectEqualStrings("403cf841b89ad61da0818bdad8976ed4b286b3282c8c22df7171921b7e06eb6d", &hash(@embedFile("kernels/cuda/qwen35_keep.cu")));
// #2620: apply, apply_pend and conv moved to qwen35_keep_state.cuh, included as main's and as _table copies
try std.testing.expectEqualStrings("1bc333fa8b46407b25e0e100add5f015b77db6ba4e2036bd2627399cd1fcd2fd", &hash(@embedFile("kernels/cuda/qwen35_keep.cu")));
try std.testing.expectEqualStrings("d1a379a98cf7504a7ed3b3f2d24c8ab6a39fe5511bcded6449e598ce5c3c79e7", &hash(@embedFile("kernels/cuda/scan_rows.cu")));
}
test "dense serving: owned launches and projections retain their reviewed argument sequence" {
Expand All @@ -44,6 +45,6 @@ test "dense serving: owned launches and projections retain their reviewed argume
try out.append(std.testing.allocator, c);
};
}
// 4dd870b84d's sequence: the first input norm keys on g.first + i (#2579); BF16 norms take norm_shift (#2383)
try std.testing.expectEqualStrings("7be514892c77ce544d809f73d5a7e2dec2fd33bcb40c68ab67ab6e409a1c02f8", &hash(out.items));
// #2620's sequence: gdn_pre and conv_commit pick their _table copy under shape.table, the same arguments
try std.testing.expectEqualStrings("8ebe2ccf5ae0652345ac2c2e0faf3d3ebc1c905eb6602e8ae1bd9c9ee0431e2b", &hash(out.items));
}
204 changes: 12 additions & 192 deletions zig/kernels/cuda/qwen35.cu
Original file line number Diff line number Diff line change
Expand Up @@ -188,198 +188,13 @@ extern "C" __global__ void __launch_bounds__(64) tf_q35_sums(const __nv_bfloat16
if (g < D / 64) XS[row * (D / 64) + g] = group_sum(X + row * D + g * 64);
}

// Conv, silu, q/k norms, the linear heads' decay and write: a warp a (row, head) over q, k, v; taps from the parents.
extern "C" __global__ void __launch_bounds__(32) tf_q35_gdn_pre(Geo geo, const __nv_bfloat16* __restrict__ QKV, const Seg* __restrict__ segs,
const int* __restrict__ rowseg, const int* __restrict__ rowpar, int layer,
const __nv_bfloat16* __restrict__ CW,
const __nv_bfloat16* __restrict__ Ain, const __nv_bfloat16* __restrict__ Bin,
const float* __restrict__ ALOG, const __nv_bfloat16* __restrict__ DT,
__nv_bfloat16* __restrict__ Q, __nv_bfloat16* __restrict__ K,
__nv_bfloat16* __restrict__ V, float* __restrict__ G, __nv_bfloat16* __restrict__ BETA,
const int* __restrict__ P) {
const int lane = threadIdx.x;
const int head = blockIdx.y;
const int w = blockIdx.z;
if (past_rows(P, w)) return;
const int NK = geo.nk, NV = geo.nv, C = geo.conv();
const Seg sg = segs[rowseg[w]];
const __nv_bfloat16* CS = reinterpret_cast<const __nv_bfloat16*>(sg.conv) + (size_t)layer * geo.conv_rows();
const bool isq = head < NK, isk = !isq && head < 2 * NK;
const int c0 = head * DK; // q, k and v channels are consecutive heads of DK
int src[TAPS]; // tap t reads the row TAPS - 1 - t tokens back: a forward row, or -1 - (tail row)
#pragma unroll
for (int tap = 0; tap < TAPS; tap++) src[tap] = back(rowpar, w, TAPS - 1 - tap);
constexpr int PER = DK / 32;
// a recorded window's row logs the tail after it (taps 1..TAPS-1) here, so conv_commit only moves the stream's
__nv_bfloat16* tail = recorded(P) ? log_row(geo, sg, layer, w - sg.row0).conv : nullptr;
// a lane's PER channels in 8-byte loads: each tap's row, the weights (PER x TAPS in a row), the logged tail
static_assert(PER == 4 && TAPS == 4, "a tap's channels and a channel's taps are one uint2");
const int cl = c0 + lane * PER;
uint2 xw[TAPS], ww[TAPS];
#pragma unroll
for (int tap = 0; tap < TAPS; tap++) {
const int at = src[tap];
xw[tap] = *reinterpret_cast<const uint2*>(at < 0 ? CS + (size_t)(-1 - at) * C + cl : QKV + (size_t)at * C + cl);
ww[tap] = *reinterpret_cast<const uint2*>(CW + (size_t)cl * TAPS + tap * PER);
if (tail != nullptr && tap > 0) *reinterpret_cast<uint2*>(tail + (size_t)(tap - 1) * C + cl) = xw[tap];
}
const __nv_bfloat16* cw = reinterpret_cast<const __nv_bfloat16*>(ww);
float vals[PER];
#pragma unroll
for (int j = 0; j < PER; j++) {
float acc = 0.0f;
#pragma unroll
for (int tap = 0; tap < TAPS; tap++) acc += bf(cw[j * TAPS + tap]) * bf(reinterpret_cast<const __nv_bfloat16*>(&xw[tap])[j]);
const float conv = rbf(acc);
const float sig = rbf(1.0f / (1.0f + expf(-conv)));
vals[j] = rbf(conv * sig);
}
if (isq || isk) {
float ss = 0.0f;
#pragma unroll
for (int j = 0; j < PER; j++) ss += vals[j] * vals[j];
ss = warp_sum(ss);
const float inv = rsqrtf(ss / (float)DK + (1e-6f / (float)DK));
const float scale = isq ? rbf(1.0f / (float)DK) : rbf(rsqrtf((float)DK));
__nv_bfloat16* out = isq ? Q + ((size_t)w * NK + head) * DK : K + ((size_t)w * NK + head - NK) * DK;
#pragma unroll
for (int j = 0; j < PER; j++) out[lane * PER + j] = __float2bfloat16_rn(scale * rbf(vals[j] * inv));
} else {
const int hv = head - 2 * NK;
#pragma unroll
for (int j = 0; j < PER; j++) V[((size_t)w * NV + hv) * DK + lane * PER + j] = __float2bfloat16_rn(vals[j]);
if (lane == 0) {
const float s = rbf(bf(Ain[w * NV + hv]) + bf(DT[hv]));
const float sp = rbf(fmaxf(s, 0.0f) + logf(1.0f + expf(-fabsf(s))));
G[w * NV + hv] = expf(-expf(ALOG[hv]) * sp);
BETA[w * NV + hv] = __float2bfloat16_rn(1.0f / (1.0f + expf(-bf(Bin[w * NV + hv]))));
}
}
}

// A segment's conv tail: a recorded window leaves the stream's (gdn_pre logged its rows'); others update it in place.
extern "C" __global__ void tf_q35_conv_commit(Geo geo, const __nv_bfloat16* __restrict__ QKV, const Seg* __restrict__ segs,
const int* __restrict__ rowpar, int layer, const int* __restrict__ P) {
const int C = geo.conv();
const int c = blockIdx.x * blockDim.x + threadIdx.x;
if (c >= C || past_windows(P, blockIdx.y)) return;
const Seg sg = segs[blockIdx.y];
__nv_bfloat16* CS = reinterpret_cast<__nv_bfloat16*>(sg.conv) + (size_t)layer * geo.conv_rows();
if (recorded(P)) {
// gdn_pre logged each row's tail
if (sg.rows != 1) return;
if (sg.before != 0) {
__nv_bfloat16* before = reinterpret_cast<__nv_bfloat16*>(sg.before + geo.nl * geo.rec() * sizeof(float)) + (size_t)layer * geo.conv_rows();
for (int r = 0; r < TAPS - 1; ++r) before[(size_t)r * C + c] = CS[(size_t)r * C + c];
}
}
// ascending: slot r takes [r + rows], which is either a later state slot (not yet written) or a row
for (int r = 0; r < TAPS - 1; r++) {
const int at = r + sg.rows;
CS[(size_t)r * C + c] = at < TAPS - 1 ? CS[(size_t)at * C + c] : QKV[(size_t)(sg.row0 + at - (TAPS - 1)) * C + c];
}
}

// Gated delta rule, each row's state its parent's: a chain keeps it in registers, a branch rebuilds it from the log.
extern "C" __global__ void __launch_bounds__(128) tf_q35_gdn_chain(Geo geo, const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ k,
const __nv_bfloat16* __restrict__ v, const float* __restrict__ g,
const __nv_bfloat16* __restrict__ beta, const Seg* __restrict__ segs,
const int* __restrict__ rowpar, int layer, __nv_bfloat16* __restrict__ y,
const int* __restrict__ P) {
const int NK = geo.nk, NV = geo.nv;
if (past_windows(P, blockIdx.z / NV)) return;
const int hv = blockIdx.z % NV;
const int hk = hv / (NV / NK);
const Seg sg = segs[blockIdx.z / NV];
const int dk = threadIdx.x;
const int dv = blockIdx.y * 4 + threadIdx.y;
constexpr int PT = DK / 32;
const size_t at = ((size_t)hv * DK + dv) * DK + PT * dk;
float* st = reinterpret_cast<float*>(sg.rec) + (size_t)layer * geo.rec() + at;
const bool record = recorded(P);
float state[PT];
#pragma unroll
for (int i = 0; i < PT; i++) state[i] = st[i];
int prev = -1; // the row the registers' state follows
// row r's inputs, loaded while row r - 1 computes
float kn[PT], qn[PT], vn = 0.0f, gn = 0.0f, bn = 0.0f;
int pn = -1;
auto load = [&](int row) {
const uint2 kw = *reinterpret_cast<const uint2*>(k + ((size_t)row * NK + hk) * DK + PT * dk);
const uint2 qw = *reinterpret_cast<const uint2*>(q + ((size_t)row * NK + hk) * DK + PT * dk);
const __nv_bfloat16* kb = reinterpret_cast<const __nv_bfloat16*>(&kw);
const __nv_bfloat16* qb = reinterpret_cast<const __nv_bfloat16*>(&qw);
#pragma unroll
for (int i = 0; i < PT; i++) {
kn[i] = bf(kb[i]);
qn[i] = bf(qb[i]);
}
vn = bf(v[((size_t)row * NV + hv) * DK + dv]);
gn = g[row * NV + hv];
bn = bf(beta[row * NV + hv]);
pn = rowpar[row];
};
if (sg.rows > 0) load(sg.row0);
for (int r = 0; r < sg.rows; r++) {
const int row = sg.row0 + r;
float kc[PT], qc[PT];
#pragma unroll
for (int i = 0; i < PT; i++) {
kc[i] = kn[i];
qc[i] = qn[i];
}
const float vc = vn, gc = gn, bc = bn;
const int parent = pn;
if (r + 1 < sg.rows) load(row + 1);
if (parent != prev) {
// a branch: its parent's state from the stream's and the ancestors' logged updates, oldest first
int anc[MAXW];
int n = 0;
for (int a = parent; a >= 0; a = rowpar[a]) anc[n++] = a;
#pragma unroll
for (int i = 0; i < PT; i++) state[i] = st[i];
for (int j = n - 1; j >= 0; j--) {
const int a = anc[j];
const float ga = g[a * NV + hv], da = log_row(geo, sg, layer, a - sg.row0).delta[hv * DK + dv];
#pragma unroll
for (int i = 0; i < PT; i++) {
state[i] = state[i] * ga;
state[i] = fmaf(bf(k[((size_t)a * NK + hk) * DK + PT * dk + i]), da, state[i]);
}
}
}
prev = row;
float kv_mem = 0.0f;
#pragma unroll
for (int i = 0; i < PT; i++) {
state[i] = state[i] * gc;
kv_mem += state[i] * kc[i];
}
kv_mem = warp_sum(kv_mem);
const float delta = (vc - kv_mem) * bc;
float out = 0.0f;
#pragma unroll
for (int i = 0; i < PT; i++) {
state[i] = fmaf(kc[i], delta, state[i]);
out += state[i] * qc[i];
}
out = warp_sum(out);
if (dk == 0) y[((size_t)row * NV + hv) * DK + dv] = __float2bfloat16_rn(out);
if (record) {
const LogRow l = log_row(geo, sg, layer, r);
if (dk == 0) {
l.delta[hv * DK + dv] = delta;
if (dv == 0) l.g[hv] = gc;
}
if (dv == 0 && hv % (NV / NK) == 0)
#pragma unroll
for (int i = 0; i < PT; i++) l.k[hk * DK + PT * dk + i] = k[((size_t)row * NK + hk) * DK + PT * dk + i];
}
}
if (record && sg.rows != 1) return;
#pragma unroll
for (int i = 0; i < PT; i++) st[i] = state[i];
}
// gdn_pre, conv_commit and gdn_chain: main's kernels, then their _table copies (qwen35_gdn.cuh, TF_Q35_K)
#define TF_Q35_TABLE 0
#include "qwen35_gdn.cuh"
#undef TF_Q35_TABLE
#define TF_Q35_TABLE 1
#include "qwen35_gdn.cuh"
#undef TF_Q35_TABLE

// out = bf16(silu(z) * bf16(w * rmsnorm(y))) per linear value head; rows nv * DK wide. Grid (1, nv, rows), a warp each.
extern "C" __global__ void __launch_bounds__(32) tf_q35_gdn_post(Geo geo, const __nv_bfloat16* __restrict__ Y, const __nv_bfloat16* __restrict__ Z,
Expand Down Expand Up @@ -530,7 +345,12 @@ extern "C" __global__ void tf_q35_attn_gate(Geo geo, const __nv_bfloat16* __rest
}

#include "qwen35_rows.cuh"
#define TF_Q35_TABLE 0
#include "qwen35_slots.cuh"
#undef TF_Q35_TABLE
#define TF_Q35_TABLE 1
#include "qwen35_slots.cuh"
#undef TF_Q35_TABLE
#include "qwen35_argmax.cuh"


Expand Down
49 changes: 44 additions & 5 deletions zig/kernels/cuda/qwen35.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ struct Geo {
__device__ size_t log_bytes() const { return (size_t)nv * 4 + (size_t)nv * DK * 4 + (size_t)nk * DK * 2 + conv_rows() * 2; }
};

// One stream's window in this forward: its state blocks, cache length before the window, and rows.
// One stream's window in this forward: its state blocks (a _table kernel: its state table), cache length, and rows.
struct Seg {
unsigned long long rec; // float recurrences, one rec() block a linear layer
unsigned long long conv; // bf16 convolution tails, conv_rows() a linear layer
unsigned long long rec; // float recurrences, one rec() block a linear layer (_table: the cuda_states.zig table)
unsigned long long conv; // bf16 convolution tails, conv_rows() a linear layer (_table: the table's tail entries)
unsigned long long kv; // bf16 keys then values, kvh * cap * HD each, an attention layer at a time
unsigned long long tap; // a drafter's ring of tapped rows (0: none): slot pos % tap_rows, taps * hid bf16 each
unsigned long long log; // the window's rows' records (MAXW rows of nl layers of log_bytes), for keep
unsigned long long before; // exact pre-round state for a one-row in-place update
unsigned long long log; // the window's rows' records (MAXW rows, nl layers of log_bytes); _table: its entries
unsigned long long before; // exact pre-round state for a one-row in-place update (_table: the copy entries)
int cap, len, row0, rows, tap_rows, taps;
int delta; // an image prompt's rotary shift: rows past it rotate at position + delta
unsigned long long pt; // the stream's KV page table (int a page; 0: kv holds cap contiguous rows)
Expand All @@ -42,6 +42,28 @@ struct Seg {
unsigned long long plog; // their heads: cuda_cache.zig's pending buffer (pend_row)
};

// A forward's state tables follow its staged planes: cuda_round.zig's states_at - segs_at bytes past segs.
constexpr size_t SEG_STATES = 445472;

// Segment s's state table in a forward, found from segs without waiting for the Seg (cuda_cache.zig States).
__device__ __forceinline__ const unsigned long long* forward_states(const Geo& geo, const Seg* segs, int s) {
return reinterpret_cast<const unsigned long long*>(reinterpret_cast<const char*>(segs) + SEG_STATES) + (size_t)s * (4 * geo.nl + MAXW);
}
// A Seg passed by value: Seg.rec is its state table.
__device__ __forceinline__ const unsigned long long* states_of(const Seg& sg) { return reinterpret_cast<const unsigned long long*>(sg.rec); }

// Linear layer `layer`'s recurrence and convolution tail, and their pre-round copies, from a state table.
__device__ __forceinline__ float* rec_of(const unsigned long long* t, int layer) { return reinterpret_cast<float*>(__ldg(t + layer)); }
__device__ __forceinline__ __nv_bfloat16* conv_of(const Geo& geo, const unsigned long long* t, int layer) {
return reinterpret_cast<__nv_bfloat16*>(__ldg(t + geo.nl + layer));
}
__device__ __forceinline__ float* before_rec(const Geo& geo, const unsigned long long* t, int layer) {
return reinterpret_cast<float*>(__ldg(t + 2 * geo.nl + layer));
}
__device__ __forceinline__ __nv_bfloat16* before_conv(const Geo& geo, const unsigned long long* t, int layer) {
return reinterpret_cast<__nv_bfloat16*>(__ldg(t + 3 * geo.nl + layer));
}

// Seg.kv's element of layer a's key (s 0) or value (s 1) at pos, head h: cap rows a head, or pos's page's row.
__device__ __forceinline__ size_t kv_row(const Seg& sg, int kvh, int a, int s, int h, int pos) {
const size_t blk = ((size_t)a * 2 + s) * kvh + h;
Expand All @@ -68,6 +90,23 @@ __device__ __forceinline__ LogRow log_row(const Geo& geo, const Seg& sg, int lay
return l;
}

__device__ __forceinline__ LogRow log_row(const Geo& geo, const unsigned long long* t, int layer, int row) {
char* base = reinterpret_cast<char*>(__ldg(t + 4 * geo.nl + row)) + (size_t)layer * geo.log_bytes();
LogRow l;
l.g = reinterpret_cast<float*>(base);
l.delta = l.g + geo.nv;
l.k = reinterpret_cast<__nv_bfloat16*>(l.delta + (size_t)geo.nv * DK);
l.conv = l.k + (size_t)geo.nk * DK;
return l;
}

// A state kernel's source, included twice: TF_Q35_TABLE 0 is main's kernel, 1 its name_table copy (state table).
#define TF_Q35_CAT(a, b) a##b
#define TF_Q35_PICK(name, table) TF_Q35_CAT(TF_Q35_PICK_, table)(name)
#define TF_Q35_PICK_0(name) name
#define TF_Q35_PICK_1(name) name##_table
#define TF_Q35_K(name) TF_Q35_PICK(name, TF_Q35_TABLE)

// A pending kept row's decay, write and key (cuda_cache.zig's pending buffer): rows of nl layers' heads, packed.
__device__ __forceinline__ LogRow pend_row(const Geo& geo, unsigned long long plog, int layer, int row) {
const size_t hb = (size_t)(geo.nv + (size_t)geo.nv * DK) * sizeof(float) + (size_t)geo.nk * DK * sizeof(__nv_bfloat16);
Expand Down
Loading
Loading