diff --git a/tools/pdl_early_loads.py b/tools/pdl_early_loads.py index 64a982a891b..d20f9385f8a 100644 --- a/tools/pdl_early_loads.py +++ b/tools/pdl_early_loads.py @@ -17,7 +17,7 @@ WEIGHT_FIRST = re.compile(r"qmmf_kernel|^glm_mm\d+_(\d+|rows)$") ADDR = re.compile(r"/\*([0-9a-f]{4,})\*/") BRANCH = re.compile(r"\b(BRA|BRX|BRXU|JMP|JMX|JMXU|CALL)\b(\S*)\s+(.*?);") -PLAIN = re.compile(r"qmmf_prompt_k32_kernel|^tf_qmmf_shared|^tf_qmmf_native_fp4_check$|^tf_q35_(embed8?|splice|sums|conv_commit|gdn_chain|attn_merge|attn_partial|attn_rows|attn_rows_join|attn_partial_whole|attn_rows_whole)$") # launched plain only +PLAIN = re.compile(r"qmmf_prompt_k32_kernel|^tf_qmmf_shared|^tf_qmmf_native_fp4_check$|^tf_q35_(embed8?|splice|sums|conv_commit|gdn_chain|attn_merge|attn_partial|attn_rows|attn_rows_join|attn_partial_whole|attn_rows_whole)(_table)?$") # launched plain only, as are their _table copies def scan(text): diff --git a/zig/dense_serving_test.zig b/zig/dense_serving_test.zig index e94d10265eb..04130f73f7b 100644 --- a/zig/dense_serving_test.zig +++ b/zig/dense_serving_test.zig @@ -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"))); - // KIA14 adds all_rows (false keeps selection/arithmetic); #4706 adds TF_QWEN_PDL prologues - try std.testing.expectEqualStrings("79e97b0992f82e891ff8a80cdad68b534e07606b98feef3dffe25101477c99e1", &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: state kernels in qwen35_gdn.cuh/qwen35_slots.cuh, main's and _table; KIA14 all_rows; #4706 TF_QWEN_PDL + try std.testing.expectEqualStrings("bc3361568b0526ab79ad432a837c83645936c761ea19a4284609fdacd827ec5e", &hash(@embedFile("kernels/cuda/qwen35.cu"))); + // #2620's bytes: the state table entries, forward_states (SEG_STATES) and log_row_at; main's SASS unchanged + try std.testing.expectEqualStrings("1c46adf3c9d7bb35336bb039143adfd6ad5b91e7cc0cd3332589ab51fe6f7c68", &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" { @@ -51,6 +52,6 @@ test "dense serving: owned launches and projections retain their reviewed argume try out.append(std.testing.allocator, c); }; } - // main's moved delta scan and MTP's retained-row tap argument stay; #4706 adds TF_QWEN_PDL glue - try std.testing.expectEqualStrings("2822d47ae041b6d7051e39209bd389cb5e4f01520efee64838c1c0e0e5428b75", &hash(out.items)); + // #2620: gdn_pre and conv_commit pick _table under shape.table, same arguments; main's delta scan; #4706 PDL glue + try std.testing.expectEqualStrings("9cb172d1b51e97f8a716686b0f2b67923ce1dd580644609f2f03657c15ba05f9", &hash(out.items)); } diff --git a/zig/kernels/cuda/qwen35.cu b/zig/kernels/cuda/qwen35.cu index e309a302fdd..8138cdeaf40 100644 --- a/zig/kernels/cuda/qwen35.cu +++ b/zig/kernels/cuda/qwen35.cu @@ -191,199 +191,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) { - qwen_pdl::enter(); - 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(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(at < 0 ? CS + (size_t)(-1 - at) * C + cl : QKV + (size_t)at * C + cl); - ww[tap] = *reinterpret_cast(CW + (size_t)cl * TAPS + tap * PER); - if (tail != nullptr && tap > 0) *reinterpret_cast(tail + (size_t)(tap - 1) * C + cl) = xw[tap]; - } - const __nv_bfloat16* cw = reinterpret_cast(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(&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(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(k + ((size_t)row * NK + hk) * DK + PT * dk); - const uint2 qw = *reinterpret_cast(q + ((size_t)row * NK + hk) * DK + PT * dk); - const __nv_bfloat16* kb = reinterpret_cast(&kw); - const __nv_bfloat16* qb = reinterpret_cast(&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, @@ -539,7 +353,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" diff --git a/zig/kernels/cuda/qwen35.cuh b/zig/kernels/cuda/qwen35.cuh index d2e0a86defe..c12ffb98b54 100644 --- a/zig/kernels/cuda/qwen35.cuh +++ b/zig/kernels/cuda/qwen35.cuh @@ -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) @@ -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(reinterpret_cast(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(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(__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(__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; @@ -68,6 +90,28 @@ __device__ __forceinline__ LogRow log_row(const Geo& geo, const Seg& sg, int lay return l; } +// A window row's record from its log entry (a state table's `4 * nl + row`), already loaded. +__device__ __forceinline__ LogRow log_row_at(const Geo& geo, unsigned long long entry, int layer) { + char* base = reinterpret_cast(entry) + (size_t)layer * geo.log_bytes(); + LogRow l; + l.g = reinterpret_cast(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; +} + +__device__ __forceinline__ LogRow log_row(const Geo& geo, const unsigned long long* t, int layer, int row) { + return log_row_at(geo, __ldg(t + 4 * geo.nl + row), layer); +} + +// 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); diff --git a/zig/kernels/cuda/qwen35_gdn.cuh b/zig/kernels/cuda/qwen35_gdn.cuh new file mode 100644 index 00000000000..c5f8a199dce --- /dev/null +++ b/zig/kernels/cuda/qwen35_gdn.cuh @@ -0,0 +1,231 @@ +// gdn_pre, conv_commit and gdn_chain. qwen35.cu includes this twice: TF_Q35_TABLE 0 (main's), 1 (_table, TF_Q35_K) + +// 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_K(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) { + qwen_pdl::enter(); + 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(); +#if TF_Q35_TABLE + const int s = rowseg[w]; + const Seg sg = segs[s]; + const unsigned long long* T = forward_states(geo, segs, s); + const __nv_bfloat16* CS = conv_of(geo, T, layer); +#else + const Seg sg = segs[rowseg[w]]; + const __nv_bfloat16* CS = reinterpret_cast(sg.conv) + (size_t)layer * geo.conv_rows(); +#endif + 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 +#if TF_Q35_TABLE + __nv_bfloat16* tail = recorded(P) ? log_row(geo, T, layer, w - sg.row0).conv : nullptr; +#else + __nv_bfloat16* tail = recorded(P) ? log_row(geo, sg, layer, w - sg.row0).conv : nullptr; +#endif + // 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(at < 0 ? CS + (size_t)(-1 - at) * C + cl : QKV + (size_t)at * C + cl); + ww[tap] = *reinterpret_cast(CW + (size_t)cl * TAPS + tap * PER); + if (tail != nullptr && tap > 0) *reinterpret_cast(tail + (size_t)(tap - 1) * C + cl) = xw[tap]; + } + const __nv_bfloat16* cw = reinterpret_cast(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(&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_K(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]; +#if TF_Q35_TABLE + const unsigned long long* T = forward_states(geo, segs, blockIdx.y); + __nv_bfloat16* CS = conv_of(geo, T, layer); + if (recorded(P)) { +#else + __nv_bfloat16* CS = reinterpret_cast<__nv_bfloat16*>(sg.conv) + (size_t)layer * geo.conv_rows(); + if (recorded(P)) { +#endif + // gdn_pre logged each row's tail + if (sg.rows != 1) return; + if (sg.before != 0) { +#if TF_Q35_TABLE + __nv_bfloat16* before = before_conv(geo, T, layer); +#else + __nv_bfloat16* before = reinterpret_cast<__nv_bfloat16*>(sg.before + geo.nl * geo.rec() * sizeof(float)) + (size_t)layer * geo.conv_rows(); +#endif + 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_K(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]; +#if TF_Q35_TABLE + const unsigned long long* T = forward_states(geo, segs, blockIdx.z / NV); +#endif + 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; +#if TF_Q35_TABLE + float* st = rec_of(T, layer) + at; +#else + float* st = reinterpret_cast(sg.rec) + (size_t)layer * geo.rec() + at; +#endif + 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(k + ((size_t)row * NK + hk) * DK + PT * dk); + const uint2 qw = *reinterpret_cast(q + ((size_t)row * NK + hk) * DK + PT * dk); + const __nv_bfloat16* kb = reinterpret_cast(&kw); + const __nv_bfloat16* qb = reinterpret_cast(&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]; +#if TF_Q35_TABLE + const float ga = g[a * NV + hv], da = log_row(geo, T, layer, a - sg.row0).delta[hv * DK + dv]; +#else + const float ga = g[a * NV + hv], da = log_row(geo, sg, layer, a - sg.row0).delta[hv * DK + dv]; +#endif +#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) { +#if TF_Q35_TABLE + const LogRow l = log_row(geo, T, layer, r); +#else + const LogRow l = log_row(geo, sg, layer, r); +#endif + 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]; +} diff --git a/zig/kernels/cuda/qwen35_keep.cu b/zig/kernels/cuda/qwen35_keep.cu index f5fb24a809a..b862bea9d63 100644 --- a/zig/kernels/cuda/qwen35_keep.cu +++ b/zig/kernels/cuda/qwen35_keep.cu @@ -4,67 +4,13 @@ using namespace tf_q35; -// Each linear layer's recurrence through the path's (decay, key, write), as the forward's chain would have left it. -extern "C" __global__ void __launch_bounds__(128) tf_q35k_apply(Geo geo, Seg sg, Path path) { - const int NK = geo.nk, NV = geo.nv; - const int layer = blockIdx.z / NV, hv = blockIdx.z % NV; - const int hk = hv / (NV / NK); - 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(sg.rec) + (size_t)layer * geo.rec() + at; - float state[PT]; -#pragma unroll - for (int i = 0; i < PT; i++) state[i] = st[i]; - for (int j = 0; j < path.n; j++) { - const LogRow l = log_row(geo, sg, layer, path.rows[j]); - const float g = l.g[hv], d = l.delta[hv * DK + dv]; -#pragma unroll - for (int i = 0; i < PT; i++) { - state[i] = state[i] * g; - state[i] = fmaf(bf(l.k[hk * DK + PT * dk + i]), d, state[i]); - } - } -#pragma unroll - for (int i = 0; i < PT; i++) st[i] = state[i]; -} - -// Pending kept rows 0..n-1 into each linear layer's recurrence in order, with tf_q35k_apply's fp32 steps. -extern "C" __global__ void __launch_bounds__(128) tf_q35k_apply_pend(Geo geo, Seg sg, int n) { - const int NK = geo.nk, NV = geo.nv; - const int layer = blockIdx.z / NV, hv = blockIdx.z % NV; - const int hk = hv / (NV / NK); - 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(sg.rec) + (size_t)layer * geo.rec() + at; - float state[PT]; -#pragma unroll - for (int i = 0; i < PT; i++) state[i] = st[i]; - for (int j = 0; j < n; j++) { - const LogRow l = pend_row(geo, sg.plog, layer, j); - const float g = l.g[hv], d = l.delta[hv * DK + dv]; -#pragma unroll - for (int i = 0; i < PT; i++) { - state[i] = state[i] * g; - state[i] = fmaf(bf(l.k[hk * DK + PT * dk + i]), d, state[i]); - } - } -#pragma unroll - for (int i = 0; i < PT; i++) st[i] = state[i]; -} - -// Each linear layer's convolution tail as logged after window row `last`. Grid (nl, tail values / 256), 256 threads. -extern "C" __global__ void tf_q35k_conv(Geo geo, Seg sg, int last) { - const int layer = blockIdx.x; - const size_t n = geo.conv_rows(); - const size_t i = (size_t)blockIdx.y * blockDim.x + threadIdx.x; - if (i >= n) return; - __nv_bfloat16* CS = reinterpret_cast<__nv_bfloat16*>(sg.conv) + (size_t)layer * n; - CS[i] = log_row(geo, sg, layer, last).conv[i]; -} +// apply, apply_pend and conv: main's kernels, then their _table copies (qwen35_keep_state.cuh, TF_Q35_K) +#define TF_Q35_TABLE 0 +#include "qwen35_keep_state.cuh" +#undef TF_Q35_TABLE +#define TF_Q35_TABLE 1 +#include "qwen35_keep_state.cuh" +#undef TF_Q35_TABLE // The path's keys and values move down to the slots after the cache; row j lands at or below j, never on one unread. extern "C" __global__ void __launch_bounds__(256) tf_q35k_compact(Geo geo, Seg sg, Path path) { diff --git a/zig/kernels/cuda/qwen35_keep_state.cuh b/zig/kernels/cuda/qwen35_keep_state.cuh new file mode 100644 index 00000000000..20460778c18 --- /dev/null +++ b/zig/kernels/cuda/qwen35_keep_state.cuh @@ -0,0 +1,80 @@ +// apply, apply_pend and conv. qwen35_keep.cu includes this twice: TF_Q35_TABLE 0 (main's), 1 (_table, TF_Q35_K) + +// Each linear layer's recurrence through the path's (decay, key, write), as the forward's chain would have left it. +extern "C" __global__ void __launch_bounds__(128) TF_Q35_K(tf_q35k_apply)(Geo geo, Seg sg, Path path) { + const int NK = geo.nk, NV = geo.nv; + const int layer = blockIdx.z / NV, hv = blockIdx.z % NV; + const int hk = hv / (NV / NK); + 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; +#if TF_Q35_TABLE + float* st = rec_of(states_of(sg), layer) + at; +#else + float* st = reinterpret_cast(sg.rec) + (size_t)layer * geo.rec() + at; +#endif + float state[PT]; +#pragma unroll + for (int i = 0; i < PT; i++) state[i] = st[i]; + for (int j = 0; j < path.n; j++) { +#if TF_Q35_TABLE + const LogRow l = log_row(geo, states_of(sg), layer, path.rows[j]); +#else + const LogRow l = log_row(geo, sg, layer, path.rows[j]); +#endif + const float g = l.g[hv], d = l.delta[hv * DK + dv]; +#pragma unroll + for (int i = 0; i < PT; i++) { + state[i] = state[i] * g; + state[i] = fmaf(bf(l.k[hk * DK + PT * dk + i]), d, state[i]); + } + } +#pragma unroll + for (int i = 0; i < PT; i++) st[i] = state[i]; +} + +// Pending kept rows 0..n-1 into each linear layer's recurrence in order, with tf_q35k_apply's fp32 steps. +extern "C" __global__ void __launch_bounds__(128) TF_Q35_K(tf_q35k_apply_pend)(Geo geo, Seg sg, int n) { + const int NK = geo.nk, NV = geo.nv; + const int layer = blockIdx.z / NV, hv = blockIdx.z % NV; + const int hk = hv / (NV / NK); + 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; +#if TF_Q35_TABLE + float* st = rec_of(states_of(sg), layer) + at; +#else + float* st = reinterpret_cast(sg.rec) + (size_t)layer * geo.rec() + at; +#endif + float state[PT]; +#pragma unroll + for (int i = 0; i < PT; i++) state[i] = st[i]; + for (int j = 0; j < n; j++) { + const LogRow l = pend_row(geo, sg.plog, layer, j); + const float g = l.g[hv], d = l.delta[hv * DK + dv]; +#pragma unroll + for (int i = 0; i < PT; i++) { + state[i] = state[i] * g; + state[i] = fmaf(bf(l.k[hk * DK + PT * dk + i]), d, state[i]); + } + } +#pragma unroll + for (int i = 0; i < PT; i++) st[i] = state[i]; +} + +// Each linear layer's convolution tail as logged after window row `last`. Grid (nl, tail values / 256), 256 threads. +extern "C" __global__ void TF_Q35_K(tf_q35k_conv)(Geo geo, Seg sg, int last) { + const int layer = blockIdx.x; + const size_t n = geo.conv_rows(); + const size_t i = (size_t)blockIdx.y * blockDim.x + threadIdx.x; + if (i >= n) return; +#if TF_Q35_TABLE + __nv_bfloat16* CS = conv_of(geo, states_of(sg), layer); + CS[i] = log_row(geo, states_of(sg), layer, last).conv[i]; +#else + __nv_bfloat16* CS = reinterpret_cast<__nv_bfloat16*>(sg.conv) + (size_t)layer * n; + CS[i] = log_row(geo, sg, layer, last).conv[i]; +#endif +} diff --git a/zig/kernels/cuda/qwen35_slots.cuh b/zig/kernels/cuda/qwen35_slots.cuh index 87a72a01220..c66ad1f81d5 100644 --- a/zig/kernels/cuda/qwen35_slots.cuh +++ b/zig/kernels/cuda/qwen35_slots.cuh @@ -1,5 +1,8 @@ // Register-slot tree scan: the common CPU schedule preserves parent states and original output rows. -#pragma once + +// qwen35.cu includes this twice: TF_Q35_TABLE 0 builds main's scans, 1 their _table copies (TF_Q35_K) +#ifndef TF_Q35_SLOTS_ONCE +#define TF_Q35_SLOTS_ONCE struct SlotStep { unsigned row; int read_slot, write_slot; }; // spread_sum: N values' warp sums in one butterfly (warp_sum's pairs), value j where lane >> (5 - log2 N) == j. template @@ -23,10 +26,11 @@ __device__ __forceinline__ float spread_sum(float (&v)[N], int lane) { template __host__ __device__ constexpr int q35_log2() { return N <= 1 ? 0 : 1 + q35_log2(); } +#endif // R value rows a warp share a step's loads; its k . state sums reduce with the last step's outputs; slots in shared. template -__device__ __forceinline__ void q35_slots(Geo geo, const __nv_bfloat16* q, const __nv_bfloat16* k, +__device__ __forceinline__ void TF_Q35_K(q35_slots)(Geo geo, const __nv_bfloat16* q, const __nv_bfloat16* k, const __nv_bfloat16* v, const float* g, const __nv_bfloat16* beta, const Seg* segs, const SlotStep* steps, int layer, __nv_bfloat16* y, const int* P) { __shared__ float4 kept[4][SLOTS * R * 32]; @@ -34,11 +38,20 @@ __device__ __forceinline__ void q35_slots(Geo geo, const __nv_bfloat16* q, const if (past_windows(P, blockIdx.z / NV)) return; const int hv = blockIdx.z % NV, hk = hv / (NV / NK); const Seg sg = segs[blockIdx.z / NV]; +#if TF_Q35_TABLE + const unsigned long long* T = forward_states(geo, segs, blockIdx.z / NV); +#endif const int dk = threadIdx.x, dv0 = (blockIdx.y * 4 + threadIdx.y) * R; constexpr int PT = DK / 32; static_assert(PT == 4, "a lane's four state entries are one float4 slot"); const size_t at = ((size_t)hv * DK + dv0) * DK + PT * dk; // row r's entries are r * DK further +#if TF_Q35_TABLE + float* st = rec_of(T, layer) + at; + // the rollback entry is loaded with the recurrence's; zero (no copy) is tested before any offset is formed + float* const before_base = before_rec(geo, T, layer); +#else float* st = reinterpret_cast(sg.rec) + (size_t)layer * geo.rec() + at; +#endif float4* slots = kept[threadIdx.y]; float root[R][PT], state[R][PT]; #pragma unroll @@ -75,11 +88,21 @@ __device__ __forceinline__ void q35_slots(Geo geo, const __nv_bfloat16* q, const } } } - if (sg.rows == 1 && sg.before != 0) +#if TF_Q35_TABLE + const bool undo = sg.rows == 1 && sg.before != 0 && before_base != 0; +#else + const bool undo = sg.rows == 1 && sg.before != 0; +#endif + if (undo) #pragma unroll for (int r = 0; r < R; ++r) +#if TF_Q35_TABLE +#pragma unroll + for (int i = 0; i < PT; ++i) before_base[at + r * DK + i] = root[r][i]; +#else #pragma unroll for (int i = 0; i < PT; ++i) reinterpret_cast(sg.before)[(size_t)layer * geo.rec() + at + r * DK + i] = root[r][i]; +#endif const bool record = recorded(P); // row inputs as stored, the next row's loaded while this one computes struct In { uint2 k, q; __nv_bfloat16 v[R], beta; float g; }; @@ -105,18 +128,30 @@ __device__ __forceinline__ void q35_slots(Geo geo, const __nv_bfloat16* q, const for (int i = 0; i < PT; ++i) state[r][i] = root[r][i]; In next; SlotStep step_next; +#if TF_Q35_TABLE + unsigned long long log_next = 0; // the next row's log entry, loaded with its inputs (not before each store) +#endif if (sg.rows > 0) { step_next = steps[sg.row0]; load(step_next.row, next); +#if TF_Q35_TABLE + if (record) log_next = __ldg(T + 4 * geo.nl + (step_next.row - sg.row0)); +#endif } for (int item = 0; item < sg.rows; ++item) { const SlotStep step = step_next; const In in = next; +#if TF_Q35_TABLE + const unsigned long long log_at = log_next; +#endif if (item + 1 < sg.rows) { step_next = steps[sg.row0 + item + 1]; load(step_next.row, next); +#if TF_Q35_TABLE + if (record) log_next = __ldg(T + 4 * geo.nl + (step_next.row - sg.row0)); +#endif } - const int row = step.row, rr = row - sg.row0; + const int row = step.row; #pragma unroll for (int r = 0; r < R; ++r) { if (step.read_slot >= 0) { @@ -168,7 +203,11 @@ __device__ __forceinline__ void q35_slots(Geo geo, const __nv_bfloat16* q, const } pend_row = row; if (record) { - const LogRow l = log_row(geo, sg, layer, rr); +#if TF_Q35_TABLE + const LogRow l = log_row_at(geo, log_at, layer); +#else + const LogRow l = log_row(geo, sg, layer, row - sg.row0); +#endif if (dk == 0) { #pragma unroll for (int r = 0; r < R; ++r) l.delta[hv * DK + dv0 + r] = delta[r]; @@ -197,12 +236,30 @@ __device__ __forceinline__ void q35_slots(Geo geo, const __nv_bfloat16* q, const #pragma unroll for (int i = 0; i < PT; ++i) st[r * DK + i] = state[r][i]; } +// _table's one- and two-slot scans at main's 72 registers: seven blocks an SM hide the cold table entries' loads +#if TF_Q35_TABLE +#define TF_Q35_SLOTS_BOUNDS(N) TF_Q35_SLOTS_BOUNDS_##N +#else +#define TF_Q35_SLOTS_BOUNDS(N) __launch_bounds__(128) +#endif +#define TF_Q35_SLOTS_BOUNDS_1 __launch_bounds__(128, 7) +#define TF_Q35_SLOTS_BOUNDS_2 __launch_bounds__(128, 7) +#define TF_Q35_SLOTS_BOUNDS_4 __launch_bounds__(128) +#define TF_Q35_SLOTS_BOUNDS_8 __launch_bounds__(128) +#define TF_Q35_SLOTS_BOUNDS_16 __launch_bounds__(128) #define TF_Q35_SLOTS(N, R) \ -extern "C" __global__ void __launch_bounds__(128) tf_q35_gdn_slots_##N(Geo geo, const __nv_bfloat16* q, \ +extern "C" __global__ void TF_Q35_SLOTS_BOUNDS(N) TF_Q35_K(tf_q35_gdn_slots_##N)(Geo geo, const __nv_bfloat16* q, \ const __nv_bfloat16* k, const __nv_bfloat16* v, const float* g, const __nv_bfloat16* beta, const Seg* segs, \ - const SlotStep* steps, int layer, __nv_bfloat16* y, const int* P) { q35_slots(geo, q, k, v, g, beta, segs, steps, layer, y, P); } + const SlotStep* steps, int layer, __nv_bfloat16* y, const int* P) { TF_Q35_K(q35_slots)(geo, q, k, v, g, beta, segs, steps, layer, y, P); } TF_Q35_SLOTS(1, 2) TF_Q35_SLOTS(2, 2) TF_Q35_SLOTS(4, 2) TF_Q35_SLOTS(8, 1) TF_Q35_SLOTS(16, 1) +#undef TF_Q35_SLOTS +#undef TF_Q35_SLOTS_BOUNDS +#undef TF_Q35_SLOTS_BOUNDS_1 +#undef TF_Q35_SLOTS_BOUNDS_2 +#undef TF_Q35_SLOTS_BOUNDS_4 +#undef TF_Q35_SLOTS_BOUNDS_8 +#undef TF_Q35_SLOTS_BOUNDS_16 diff --git a/zig/qwen35_draft_frame_host.zig b/zig/qwen35_draft_frame_host.zig index 0a0be850906..98f1467a750 100644 --- a/zig/qwen35_draft_frame_host.zig +++ b/zig/qwen35_draft_frame_host.zig @@ -292,7 +292,7 @@ test "Draft frames: combined target rows above capacity refuse before even settl e.kv8 = false; e.g = .{ .hidden = 256, .intermediate = 256, .layers = 1, .vocab = 256, .k_heads = 1, .v_heads = 1, .q_heads = 2, .kv_heads = 1, .eps = 1e-6, .tied = true, .context = 256, .linear = @splat(true) }; e.geo = .{ .hid = 256, .nk = 1, .nv = 1, .qh = 1, .kvh = 1, .nl = 1 }; - e.keeps = .{ .apply = function(&driver, 10), .apply_pend = function(&driver, 10), .conv = function(&driver, 10), .compact = function(&driver, 10) }; + e.keeps = .{ .apply = function(&driver, 10), .apply_pend = function(&driver, 10), .conv = function(&driver, 10), .compact = function(&driver, 10), .apply_table = function(&driver, 10), .apply_pend_table = function(&driver, 10), .conv_table = function(&driver, 10) }; const b: cuda.DeviceBuffer = .{ .d = &driver, .ptr = 1, .len = 1 << 20 }; var caches: [2]q.engine.Cache = @splat(.{ .state = b, .kv = b, .log = b, .cap = 256, .len = 2, .logits = &.{} }); caches[0].last = .{ .start = 0, .rows = 2 }; @@ -319,7 +319,7 @@ test "Draft frames: an unsupported prompt geometry is refused at admission" { e.kv8 = false; e.g = .{ .hidden = 256, .intermediate = 256, .layers = 1, .vocab = 256, .k_heads = 1, .v_heads = 1, .q_heads = 1, .kv_heads = 1, .eps = 1e-6, .tied = true, .context = 256, .linear = @splat(true) }; e.geo = .{ .hid = 256, .nk = 1, .nv = 1, .qh = 1, .kvh = 1, .nl = 1 }; - e.keeps = .{ .apply = function(&driver, 10), .apply_pend = function(&driver, 10), .conv = function(&driver, 10), .compact = function(&driver, 10) }; + e.keeps = .{ .apply = function(&driver, 10), .apply_pend = function(&driver, 10), .conv = function(&driver, 10), .compact = function(&driver, 10), .apply_table = function(&driver, 10), .apply_pend_table = function(&driver, 10), .conv_table = function(&driver, 10) }; const b: cuda.DeviceBuffer = .{ .d = &driver, .ptr = 1, .len = 1 << 20 }; var caches: [1]q.engine.Cache = @splat(.{ .state = b, .kv = b, .log = b, .cap = 256, .len = 2, .logits = &.{} }); const ids: [129]u32 = @splat(1); @@ -356,7 +356,7 @@ test "Draft frames: the geometry refusal precedes the request's own state" { e.kv8 = false; e.g = .{ .hidden = 256, .intermediate = 256, .layers = 1, .vocab = 256, .k_heads = 1, .v_heads = 1, .q_heads = 1, .kv_heads = 1, .eps = 1e-6, .tied = true, .context = 256, .linear = @splat(true) }; e.geo = .{ .hid = 256, .nk = 1, .nv = 1, .qh = 1, .kvh = 1, .nl = 1 }; - e.keeps = .{ .apply = function(&driver, 10), .apply_pend = function(&driver, 10), .conv = function(&driver, 10), .compact = function(&driver, 10) }; + e.keeps = .{ .apply = function(&driver, 10), .apply_pend = function(&driver, 10), .conv = function(&driver, 10), .compact = function(&driver, 10), .apply_table = function(&driver, 10), .apply_pend_table = function(&driver, 10), .conv_table = function(&driver, 10) }; const b: cuda.DeviceBuffer = .{ .d = &driver, .ptr = 1, .len = 1 << 20 }; var caches: [1]q.engine.Cache = @splat(.{ .state = b, .kv = b, .log = b, .cap = 256, .len = 2, .logits = &.{} }); caches[0].last = .{ .start = 0, .rows = 2 }; diff --git a/zig/qwen35_live_host.zig b/zig/qwen35_live_host.zig index 3ecaff87891..9e645545b90 100644 --- a/zig/qwen35_live_host.zig +++ b/zig/qwen35_live_host.zig @@ -81,7 +81,7 @@ test "selected live shape reaches real tiled projections and DeltaNet scan dispa Trace.projections = 0; const shape = Shape.init(17, 1, true, false, 1); try e.projSums(proj, 0x10000, 0x20000, 0x30000, shape.total, false, 0); - try e.deltaScan(true, shape.slots, shape.nseg, 0); + try e.deltaScan(true, shape.slots, shape.nseg, 0, shape.table); try std.testing.expectEqual(@as(usize, 2), Trace.projections); try std.testing.expectEqual(@as(u64, 0x30000), Trace.outputs[0]); try std.testing.expectEqual(@as(u64, 0x30000 + 16 * 4096 * 2), Trace.outputs[1]); diff --git a/zig/qwen35_recurrent_host.zig b/zig/qwen35_recurrent_host.zig index c3f719b0f79..30a1e822552 100644 --- a/zig/qwen35_recurrent_host.zig +++ b/zig/qwen35_recurrent_host.zig @@ -85,7 +85,7 @@ fn engine(e: *q.engine.Engine, d: *cuda.Driver) void { e.kv8 = false; e.geo = .{ .hid = 5120, .nk = 16, .nv = 48, .qh = 24, .kvh = 4, .nl = 48 }; const f: cuda.Function = .{ .d = d, .handle = @ptrFromInt(1) }; - e.keeps = .{ .apply = f, .apply_pend = f, .conv = f, .compact = f }; + e.keeps = .{ .apply = f, .apply_pend = f, .conv = f, .compact = f, .apply_table = f, .apply_pend_table = f, .conv_table = f }; e.rec_scratch = rec.Pool.init(a, @intFromPtr(e)); } fn finish(e: *q.engine.Engine, c: *q.engine.Cache) void { @@ -110,8 +110,8 @@ test "Shared verification: recurrent scratch is absent from an idle real 27B cac engine(&e, &d); var c = try q.engine.Cache.init(a, &e, 1); defer finish(&e, &c); - try std.testing.expectEqual(@as(usize, 2), Driver.allocs); - try std.testing.expectEqual(e.g.stateBytes() + e.g.kvBytes(1, false), Driver.bytes); + try std.testing.expectEqual(@as(usize, 3), Driver.allocs); // kv, state and the state table + try std.testing.expectEqual(e.g.stateBytes() + e.g.kvBytes(1, false) + q.cache.States.bytes(e.g), Driver.bytes); try std.testing.expect(c.before == null); try std.testing.expectEqual(@as(usize, 0), c.log.ptr); } @@ -136,7 +136,7 @@ test "Shared verification: all window transitions keep log capacity within the o try std.testing.expect(c.log.len >= e.g.logBytes(rows)); try std.testing.expect((c.before != null) == (rows == 1)); try std.testing.expect(e.rec_scratch.residentBytes() <= bound); - const sg = c.seg(&e, c.len, 0, rows); + const sg = try c.seg(&e, c.len, 0, rows); try std.testing.expectEqual(c.log.ptr, sg.log); try std.testing.expectEqual(if (c.before) |b| b.ptr else 0, sg.before); try forwardDone(&e, &c, rows); @@ -186,7 +186,7 @@ test "Shared verification: a served one-row step leases no rollback copy and an // a fresh cache: no copy leased, and the staged segment reads none try rec.prepare(&e, &c, 1, true, false); try std.testing.expect(c.before == null); - try std.testing.expectEqual(@as(u64, 0), q.engine.Engine.stagedSeg(&c, &e, c.len, 0, 1, false).before); + try std.testing.expectEqual(@as(u64, 0), (try q.engine.Engine.stagedSeg(&c, &e, null, c.len, 0, 1, false)).before); try rec.mark(&c, false); c.advanced(1, true, false); _ = Driver.sync(e.stream.handle); @@ -201,7 +201,7 @@ test "Shared verification: a served one-row step leases no rollback copy and an try std.testing.expect(c.before != null); try rec.prepare(&e, &c, 1, true, false); try std.testing.expect(c.before != null); - try std.testing.expectEqual(@as(u64, 0), q.engine.Engine.stagedSeg(&c, &e, c.len, 0, 1, false).before); + try std.testing.expectEqual(@as(u64, 0), (try q.engine.Engine.stagedSeg(&c, &e, null, c.len, 0, 1, false)).before); try rec.mark(&c, false); c.advanced(1, true, false); _ = Driver.sync(e.stream.handle); diff --git a/zig/qwen35_rounds_host.zig b/zig/qwen35_rounds_host.zig index b6db7425ce3..a8ffa6a4cc2 100644 --- a/zig/qwen35_rounds_host.zig +++ b/zig/qwen35_rounds_host.zig @@ -88,16 +88,26 @@ test "Verify width calibration: actual DeltaNet dispatch selects its register va e.fns.gdn_slots_4 = function(&d, 24); e.fns.gdn_slots_8 = function(&d, 28); e.fns.gdn_slots_16 = function(&d, 36); - for ([_]u8{ 1, 2, 4, 8, 16 }) |slots| { - try e.deltaScan(true, slots, 1, 0); - try std.testing.expectEqual(@as(usize, 20 + slots), Capture.id); - try std.testing.expectEqual(e.tables.ptr + q.round.steps_at, Capture.input); - try std.testing.expectEqual(@as(u32, 128), Capture.threads); + // a pool lane on pieces: the same scans' _table instantiations (main's names stay for every other forward) + e.fns.gdn_chain_table = function(&d, 111); + e.fns.gdn_slots_1_table = function(&d, 121); + e.fns.gdn_slots_2_table = function(&d, 122); + e.fns.gdn_slots_4_table = function(&d, 124); + e.fns.gdn_slots_8_table = function(&d, 128); + e.fns.gdn_slots_16_table = function(&d, 136); + for ([_]bool{ false, true }) |table| { + const off: usize = if (table) 100 else 0; + for ([_]u8{ 1, 2, 4, 8, 16 }) |slots| { + try e.deltaScan(true, slots, 1, 0, table); + try std.testing.expectEqual(off + 20 + slots, Capture.id); + try std.testing.expectEqual(e.tables.ptr + q.round.steps_at, Capture.input); + try std.testing.expectEqual(@as(u32, 128), Capture.threads); + } + try e.deltaScan(false, 1, 1, 0, table); + try std.testing.expectEqual(off + 11, Capture.id); + try std.testing.expectEqual(e.tables.ptr + q.round.rowpar_at, Capture.input); + try std.testing.expectError(error.InvalidGdnSlots, e.deltaScan(true, 3, 1, 0, table)); } - try e.deltaScan(false, 1, 1, 0); - try std.testing.expectEqual(@as(usize, 11), Capture.id); - try std.testing.expectEqual(e.tables.ptr + q.round.rowpar_at, Capture.input); - try std.testing.expectError(error.InvalidGdnSlots, e.deltaScan(true, 3, 1, 0)); } test "Verify width calibration: actual keep launches carry the complete 64-row path" { @@ -112,7 +122,7 @@ test "Verify width calibration: actual keep launches carry the complete 64-row p e.g = .{ .hidden = 512, .intermediate = 256, .layers = 2, .vocab = 248320, .k_heads = 2, .v_heads = 4, .q_heads = 4, .kv_heads = 1, .eps = 1e-6, .tied = true, .context = 4096, .linear = @splat(true) }; e.g.linear[1] = false; e.geo = .{ .hid = 512, .nk = 2, .nv = 4, .qh = 4, .kvh = 1, .nl = 1 }; - e.keeps = .{ .apply = function(&d, 1), .apply_pend = function(&d, 4), .conv = function(&d, 2), .compact = function(&d, 3) }; + e.keeps = .{ .apply = function(&d, 1), .apply_pend = function(&d, 4), .conv = function(&d, 2), .compact = function(&d, 3), .apply_table = function(&d, 1), .apply_pend_table = function(&d, 4), .conv_table = function(&d, 2) }; e.kv8 = false; e.n_taps = 0; const buffer: cuda.DeviceBuffer = .{ .d = &d, .ptr = 0x1000, .len = 1 << 20 }; diff --git a/zig/qwen35_shared_host.zig b/zig/qwen35_shared_host.zig index 9a23ff5e611..29616e98538 100644 --- a/zig/qwen35_shared_host.zig +++ b/zig/qwen35_shared_host.zig @@ -52,7 +52,7 @@ fn engine(d: *cuda.Driver) q.engine.Engine { e.kv8 = false; e.geo = .{ .hid = 256, .nk = 1, .nv = 1, .qh = 1, .kvh = 1, .nl = 1 }; const f: cuda.Function = .{ .d = d, .handle = @ptrFromInt(1) }; - e.keeps = .{ .apply = f, .apply_pend = f, .conv = f, .compact = f }; + e.keeps = .{ .apply = f, .apply_pend = f, .conv = f, .compact = f, .apply_table = f, .apply_pend_table = f, .conv_table = f }; return e; } fn buffer(d: *cuda.Driver, data: []u8) cuda.DeviceBuffer { @@ -119,7 +119,7 @@ test "Shared verification: empty multi-row keep preserves the root and completed // the before copy sits inside the log's bytes (one overlaid block), so a stream holds one state beside it const block = q.cache.overlay(&e); try std.testing.expectEqual(e.g.logBytes(64), block.bytes); - try std.testing.expectEqual(e.g.stateBytes() + block.bytes + e.g.kvBytes(256, false) + q.cache.pendBytes(e.g), e.streamBytes(256)); + try std.testing.expectEqual(e.g.stateBytes() + block.bytes + e.g.kvBytes(256, false) + q.cache.pendBytes(e.g) + q.cache.States.bytes(e.g), e.streamBytes(256)); } const Owners = struct { @@ -190,8 +190,8 @@ test "Shared verification: the actual cache constructor unwinds the before bank e.n_taps = 1; e.g.layers = 2; e.g.linear[1] = false; - // kv, state, the overlaid log and before block, and the tap ring: four device allocations - for (1..5) |fail| { + // kv, state, the overlaid log and before block, the tap ring and the state table: five device allocations + for (1..6) |fail| { Owners.setup(&d, fail, 0); try std.testing.expectError(error.NotReady, q.engine.Cache.init(a, &e, 256)); try Owners.balanced(); @@ -208,7 +208,7 @@ test "Shared verification: the actual cache constructor unwinds the before bank Owners.setup(&d, 0, 0); var cache = try q.engine.Cache.init(a, &e, 256); try std.testing.expect(cache.before != null); - try std.testing.expectEqual(@as(usize, 4), Owners.allocations); + try std.testing.expectEqual(@as(usize, 5), Owners.allocations); const block = cache.block.?; try std.testing.expect(cache.before.?.borrowed and cache.log.borrowed); try std.testing.expectEqual(block.ptr, cache.log.ptr); diff --git a/zig/src/core/contract/cuda_lane_pending.zig b/zig/src/core/contract/cuda_lane_pending.zig index 2c4dedc6f71..ddf1fed294f 100644 --- a/zig/src/core/contract/cuda_lane_pending.zig +++ b/zig/src/core/contract/cuda_lane_pending.zig @@ -28,6 +28,17 @@ pub const records = @import("mlp128_records.zig").records ++ [_]CudaRecord{ .{ .launch = .{ .name = "qwen35 tf_q35_conv_commit", .symbol = "tf_q35_conv_commit", .image = "qwen35", .threads = 256 }, .usage = .{ .{ .regs = 28, .static = 0, .bound = 0 }, .{ .regs = 28, .static = 0, .bound = 0 }, .{ .regs = 28, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 } }, .later_pending = true }, .{ .launch = .{ .name = "qwen35 tf_q35_tap", .symbol = "tf_q35_tap", .image = "qwen35", .threads = 256 }, .usage = .{ .{ .regs = 28, .static = 0, .bound = 256 }, .{ .regs = 26, .static = 0, .bound = 256 }, .{ .regs = 26, .static = 0, .bound = 256 }, .{ .regs = 26, .static = 0, .bound = 256 }, .{ .regs = 26, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "qwen35_keep tf_q35k_conv", .symbol = "tf_q35k_conv", .image = "qwen35_keep", .threads = 256 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 } }, .later_pending = true }, + .{ .launch = .{ .name = "qwen35 tf_q35_gdn_slots_1_table", .symbol = "tf_q35_gdn_slots_1_table", .image = "qwen35", .threads = 128 }, .usage = .{ .{ .regs = 72, .static = 4096, .bound = 128 }, .{ .regs = 71, .static = 4096, .bound = 128 }, .{ .regs = 71, .static = 4096, .bound = 128 }, .{ .regs = 72, .static = 4096, .bound = 128 }, .{ .regs = 72, .static = 4096, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "qwen35 tf_q35_gdn_slots_2_table", .symbol = "tf_q35_gdn_slots_2_table", .image = "qwen35", .threads = 128 }, .usage = .{ .{ .regs = 72, .static = 8192, .bound = 128 }, .{ .regs = 71, .static = 8192, .bound = 128 }, .{ .regs = 71, .static = 8192, .bound = 128 }, .{ .regs = 72, .static = 8192, .bound = 128 }, .{ .regs = 72, .static = 8192, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "qwen35 tf_q35_gdn_slots_4_table", .symbol = "tf_q35_gdn_slots_4_table", .image = "qwen35", .threads = 128 }, .usage = .{ .{ .regs = 80, .static = 16384, .bound = 128 }, .{ .regs = 83, .static = 16384, .bound = 128 }, .{ .regs = 83, .static = 16384, .bound = 128 }, .{ .regs = 94, .static = 16384, .bound = 128 }, .{ .regs = 94, .static = 16384, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "qwen35 tf_q35_gdn_slots_8_table", .symbol = "tf_q35_gdn_slots_8_table", .image = "qwen35", .threads = 128 }, .usage = .{ .{ .regs = 72, .static = 16384, .bound = 128 }, .{ .regs = 76, .static = 16384, .bound = 128 }, .{ .regs = 76, .static = 16384, .bound = 128 }, .{ .regs = 89, .static = 16384, .bound = 128 }, .{ .regs = 89, .static = 16384, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "qwen35 tf_q35_gdn_slots_16_table", .symbol = "tf_q35_gdn_slots_16_table", .image = "qwen35", .threads = 128 }, .usage = .{ .{ .regs = 112, .static = 32768, .bound = 128 }, .{ .regs = 111, .static = 32768, .bound = 128 }, .{ .regs = 111, .static = 32768, .bound = 128 }, .{ .regs = 92, .static = 32768, .bound = 128 }, .{ .regs = 92, .static = 32768, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "qwen35 tf_q35_gdn_chain_table", .symbol = "tf_q35_gdn_chain_table", .image = "qwen35", .threads = 128 }, .usage = .{ .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 56, .static = 0, .bound = 128 }, .{ .regs = 56, .static = 0, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "qwen35_keep tf_q35k_apply_table", .symbol = "tf_q35k_apply_table", .image = "qwen35_keep", .threads = 128 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "qwen35_keep tf_q35k_apply_pend_table", .symbol = "tf_q35k_apply_pend_table", .image = "qwen35_keep", .threads = 128 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 39, .static = 0, .bound = 128 }, .{ .regs = 39, .static = 0, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "qwen35 tf_q35_gdn_pre_table", .symbol = "tf_q35_gdn_pre_table", .image = "qwen35", .threads = 32 }, .usage = .{ .{ .regs = 40, .static = 0, .bound = 32 }, .{ .regs = 42, .static = 0, .bound = 32 }, .{ .regs = 42, .static = 0, .bound = 32 }, .{ .regs = 38, .static = 0, .bound = 32 }, .{ .regs = 38, .static = 0, .bound = 32 } }, .later_pending = true }, + .{ .launch = .{ .name = "qwen35 tf_q35_conv_commit_table", .symbol = "tf_q35_conv_commit_table", .image = "qwen35", .threads = 256 }, .usage = .{ .{ .regs = 28, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 } }, .later_pending = true }, + .{ .launch = .{ .name = "qwen35_keep tf_q35k_conv_table", .symbol = "tf_q35k_conv_table", .image = "qwen35_keep", .threads = 256 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 } }, .later_pending = true }, .{ .launch = .{ .name = "qwen35_draft tf_q35d_dyn_conv_batch", .symbol = "tf_q35d_dyn_conv_batch", .image = "qwen35_draft", .threads = 256 }, .usage = .{ .{ .regs = 29, .static = 0, .bound = 0 }, .{ .regs = 28, .static = 0, .bound = 0 }, .{ .regs = 28, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 } }, .later_pending = true }, .{ .launch = .{ .name = "qwen35_draft tf_q35d_norm_rope_batch", .symbol = "tf_q35d_norm_rope_batch", .image = "qwen35_draft", .threads = 32 }, .usage = .{ .{ .regs = 30, .static = 0, .bound = 32 }, .{ .regs = 32, .static = 0, .bound = 32 }, .{ .regs = 32, .static = 0, .bound = 32 }, .{ .regs = 36, .static = 0, .bound = 32 }, .{ .regs = 36, .static = 0, .bound = 32 } }, .later_pending = true }, .{ .launch = .{ .name = "qwen35_draft tf_q35d_mask_rows", .symbol = "tf_q35d_mask_rows", .image = "qwen35_draft", .threads = 256 }, .usage = .{ .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 } }, .later_pending = true }, diff --git a/zig/src/core/contract/measurements/pending_133.zig b/zig/src/core/contract/measurements/pending_133.zig index 91d12231586..aa2076e7a8d 100644 --- a/zig/src/core/contract/measurements/pending_133.zig +++ b/zig/src/core/contract/measurements/pending_133.zig @@ -61,8 +61,16 @@ pub const records = [_]Override{ .{ .name = "qwen35 tf_q35_attn_partial_contiguous", .usage = .{ .{ .regs = 48, .static = 0, .bound = 0 }, .{ .regs = 48, .static = 0, .bound = 0 }, .{ .regs = 48, .static = 0, .bound = 0 }, .{ .regs = 39, .static = 0, .bound = 0 }, .{ .regs = 39, .static = 0, .bound = 0 } } }, .{ .name = "qwen35 tf_q35_attn_partial_legacy", .usage = .{ .{ .regs = 54, .static = 0, .bound = 0 }, .{ .regs = 56, .static = 0, .bound = 0 }, .{ .regs = 56, .static = 0, .bound = 0 }, .{ .regs = 46, .static = 0, .bound = 0 }, .{ .regs = 46, .static = 0, .bound = 0 } } }, .{ .name = "qwen35 tf_q35_attn_partial_paged", .usage = .{ .{ .regs = 56, .static = 0, .bound = 0 }, .{ .regs = 56, .static = 0, .bound = 0 }, .{ .regs = 56, .static = 0, .bound = 0 }, .{ .regs = 56, .static = 0, .bound = 0 }, .{ .regs = 56, .static = 0, .bound = 0 } } }, + .{ .name = "qwen35 tf_q35_conv_commit_table", .usage = .{ .{ .regs = 28, .static = 0, .bound = 0 }, .{ .regs = 28, .static = 0, .bound = 0 }, .{ .regs = 28, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 } } }, + .{ .name = "qwen35 tf_q35_gdn_pre_table", .usage = .{ .{ .regs = 36, .static = 0, .bound = 32 }, .{ .regs = 38, .static = 0, .bound = 32 }, .{ .regs = 38, .static = 0, .bound = 32 }, .{ .regs = 38, .static = 0, .bound = 32 }, .{ .regs = 38, .static = 0, .bound = 32 } } }, + .{ .name = "qwen35 tf_q35_gdn_slots_16_table", .usage = .{ .{ .regs = 109, .static = 32768, .bound = 128 }, .{ .regs = 112, .static = 32768, .bound = 128 }, .{ .regs = 112, .static = 32768, .bound = 128 }, .{ .regs = 94, .static = 32768, .bound = 128 }, .{ .regs = 94, .static = 32768, .bound = 128 } } }, + .{ .name = "qwen35 tf_q35_gdn_slots_1_table", .usage = .{ .{ .regs = 77, .static = 4096, .bound = 128 }, .{ .regs = 80, .static = 4096, .bound = 128 }, .{ .regs = 80, .static = 4096, .bound = 128 }, .{ .regs = 72, .static = 4096, .bound = 128 }, .{ .regs = 72, .static = 4096, .bound = 128 } } }, + .{ .name = "qwen35 tf_q35_gdn_slots_2_table", .usage = .{ .{ .regs = 77, .static = 8192, .bound = 128 }, .{ .regs = 80, .static = 8192, .bound = 128 }, .{ .regs = 80, .static = 8192, .bound = 128 }, .{ .regs = 72, .static = 8192, .bound = 128 }, .{ .regs = 72, .static = 8192, .bound = 128 } } }, + .{ .name = "qwen35 tf_q35_gdn_slots_4_table", .usage = .{ .{ .regs = 77, .static = 16384, .bound = 128 }, .{ .regs = 90, .static = 16384, .bound = 128 }, .{ .regs = 90, .static = 16384, .bound = 128 }, .{ .regs = 82, .static = 16384, .bound = 128 }, .{ .regs = 82, .static = 16384, .bound = 128 } } }, + .{ .name = "qwen35 tf_q35_gdn_slots_8_table", .usage = .{ .{ .regs = 72, .static = 16384, .bound = 128 }, .{ .regs = 70, .static = 16384, .bound = 128 }, .{ .regs = 70, .static = 16384, .bound = 128 }, .{ .regs = 87, .static = 16384, .bound = 128 }, .{ .regs = 87, .static = 16384, .bound = 128 } } }, .{ .name = "qwen35_bf16_rows tf_q35_dense_bf16", .usage = .{ .{ .regs = 34, .static = 32, .bound = 256 }, .{ .regs = 40, .static = 32, .bound = 256 }, .{ .regs = 40, .static = 32, .bound = 256 }, .{ .regs = 42, .static = 32, .bound = 256 }, .{ .regs = 42, .static = 32, .bound = 256 } } }, .{ .name = "qwen35_bf16_rows tf_q35_embed_bf16", .usage = .{ .{ .regs = 16, .static = 0, .bound = 256 }, .{ .regs = 16, .static = 0, .bound = 256 }, .{ .regs = 16, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 } } }, + .{ .name = "qwen35_keep tf_q35k_apply_pend_table", .usage = .{ .{ .regs = 32, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 } } }, .{ .name = "qwen35_kv8 tf_q35_attn_partial8_contiguous", .usage = .{ .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 56, .static = 0, .bound = 0 }, .{ .regs = 37, .static = 0, .bound = 0 }, .{ .regs = 37, .static = 0, .bound = 0 } } }, .{ .name = "qwen35_kv8 tf_q35_attn_partial8_legacy", .usage = .{ .{ .regs = 60, .static = 0, .bound = 0 }, .{ .regs = 62, .static = 0, .bound = 0 }, .{ .regs = 56, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } } }, .{ .name = "qwen35_kv8 tf_q35_attn_partial8_paged", .usage = .{ .{ .regs = 61, .static = 0, .bound = 0 }, .{ .regs = 62, .static = 0, .bound = 0 }, .{ .regs = 56, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } } }, diff --git a/zig/src/core/contract/measurements/qwen_lanes_132.zig b/zig/src/core/contract/measurements/qwen_lanes_132.zig index e930a85b8e5..0dbed473ff0 100644 --- a/zig/src/core/contract/measurements/qwen_lanes_132.zig +++ b/zig/src/core/contract/measurements/qwen_lanes_132.zig @@ -3,13 +3,21 @@ const Override = @import("../registry.zig").Override; pub const records = [_]Override{ .{ .name = "qwen35 tf_q35_attn_merge", .usage = .{ .{ .regs = 40, .static = 0, .bound = 32 }, .{ .regs = 38, .static = 0, .bound = 32 }, .{ .regs = 37, .static = 0, .bound = 32 }, .{ .regs = 42, .static = 0, .bound = 32 }, .{ .regs = 42, .static = 0, .bound = 32 } } }, .{ .name = "qwen35 tf_q35_conv_commit", .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 } } }, + .{ .name = "qwen35 tf_q35_conv_commit_table", .usage = .{ .{ .regs = 28, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 } } }, .{ .name = "qwen35 tf_q35_gdn_chain", .usage = .{ .{ .regs = 72, .static = 0, .bound = 128 }, .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 56, .static = 0, .bound = 128 }, .{ .regs = 56, .static = 0, .bound = 128 } } }, + .{ .name = "qwen35 tf_q35_gdn_chain_table", .usage = .{ .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 56, .static = 0, .bound = 128 }, .{ .regs = 56, .static = 0, .bound = 128 } } }, .{ .name = "qwen35 tf_q35_gdn_pre", .usage = .{ .{ .regs = 50, .static = 0, .bound = 32 }, .{ .regs = 52, .static = 0, .bound = 32 }, .{ .regs = 52, .static = 0, .bound = 32 }, .{ .regs = 40, .static = 0, .bound = 32 }, .{ .regs = 40, .static = 0, .bound = 32 } } }, + .{ .name = "qwen35 tf_q35_gdn_pre_table", .usage = .{ .{ .regs = 40, .static = 0, .bound = 32 }, .{ .regs = 42, .static = 0, .bound = 32 }, .{ .regs = 42, .static = 0, .bound = 32 }, .{ .regs = 38, .static = 0, .bound = 32 }, .{ .regs = 38, .static = 0, .bound = 32 } } }, .{ .name = "qwen35 tf_q35_gdn_slots_1", .usage = .{ .{ .regs = 56, .static = 5120, .bound = 128 }, .{ .regs = 55, .static = 5120, .bound = 128 }, .{ .regs = 55, .static = 5120, .bound = 128 }, .{ .regs = 40, .static = 5120, .bound = 128 }, .{ .regs = 40, .static = 5120, .bound = 128 } } }, .{ .name = "qwen35 tf_q35_gdn_slots_16", .usage = .{ .{ .regs = 150, .static = 33792, .bound = 128 }, .{ .regs = 149, .static = 33792, .bound = 128 }, .{ .regs = 149, .static = 33792, .bound = 128 }, .{ .regs = 112, .static = 33792, .bound = 128 }, .{ .regs = 112, .static = 33792, .bound = 128 } } }, + .{ .name = "qwen35 tf_q35_gdn_slots_16_table", .usage = .{ .{ .regs = 112, .static = 32768, .bound = 128 }, .{ .regs = 111, .static = 32768, .bound = 128 }, .{ .regs = 111, .static = 32768, .bound = 128 }, .{ .regs = 90, .static = 32768, .bound = 128 }, .{ .regs = 90, .static = 32768, .bound = 128 } } }, + .{ .name = "qwen35 tf_q35_gdn_slots_1_table", .usage = .{ .{ .regs = 72, .static = 4096, .bound = 128 }, .{ .regs = 71, .static = 4096, .bound = 128 }, .{ .regs = 71, .static = 4096, .bound = 128 }, .{ .regs = 72, .static = 4096, .bound = 128 }, .{ .regs = 72, .static = 4096, .bound = 128 } } }, .{ .name = "qwen35 tf_q35_gdn_slots_2", .usage = .{ .{ .regs = 64, .static = 9216, .bound = 128 }, .{ .regs = 64, .static = 9216, .bound = 128 }, .{ .regs = 64, .static = 9216, .bound = 128 }, .{ .regs = 48, .static = 9216, .bound = 128 }, .{ .regs = 48, .static = 9216, .bound = 128 } } }, + .{ .name = "qwen35 tf_q35_gdn_slots_2_table", .usage = .{ .{ .regs = 72, .static = 8192, .bound = 128 }, .{ .regs = 71, .static = 8192, .bound = 128 }, .{ .regs = 71, .static = 8192, .bound = 128 }, .{ .regs = 72, .static = 8192, .bound = 128 }, .{ .regs = 72, .static = 8192, .bound = 128 } } }, .{ .name = "qwen35 tf_q35_gdn_slots_4", .usage = .{ .{ .regs = 72, .static = 17408, .bound = 128 }, .{ .regs = 72, .static = 17408, .bound = 128 }, .{ .regs = 72, .static = 17408, .bound = 128 }, .{ .regs = 56, .static = 17408, .bound = 128 }, .{ .regs = 56, .static = 17408, .bound = 128 } } }, + .{ .name = "qwen35 tf_q35_gdn_slots_4_table", .usage = .{ .{ .regs = 80, .static = 16384, .bound = 128 }, .{ .regs = 83, .static = 16384, .bound = 128 }, .{ .regs = 83, .static = 16384, .bound = 128 }, .{ .regs = 96, .static = 16384, .bound = 128 }, .{ .regs = 96, .static = 16384, .bound = 128 } } }, .{ .name = "qwen35 tf_q35_gdn_slots_8", .usage = .{ .{ .regs = 96, .static = 17408, .bound = 128 }, .{ .regs = 96, .static = 17408, .bound = 128 }, .{ .regs = 96, .static = 17408, .bound = 128 }, .{ .regs = 72, .static = 17408, .bound = 128 }, .{ .regs = 72, .static = 17408, .bound = 128 } } }, + .{ .name = "qwen35 tf_q35_gdn_slots_8_table", .usage = .{ .{ .regs = 72, .static = 16384, .bound = 128 }, .{ .regs = 76, .static = 16384, .bound = 128 }, .{ .regs = 76, .static = 16384, .bound = 128 }, .{ .regs = 87, .static = 16384, .bound = 128 }, .{ .regs = 87, .static = 16384, .bound = 128 } } }, .{ .name = "qwen35 tf_q35_tap", .usage = .{ .{ .regs = 24, .static = 0, .bound = 256 }, .{ .regs = 24, .static = 0, .bound = 256 }, .{ .regs = 24, .static = 0, .bound = 256 }, .{ .regs = 26, .static = 0, .bound = 256 }, .{ .regs = 26, .static = 0, .bound = 256 } } }, .{ .name = "qwen35_draft tf_q35d_attn_merge", .usage = .{ .{ .regs = 34, .static = 0, .bound = 32 }, .{ .regs = 34, .static = 0, .bound = 32 }, .{ .regs = 32, .static = 0, .bound = 32 }, .{ .regs = 36, .static = 0, .bound = 32 }, .{ .regs = 36, .static = 0, .bound = 32 } } }, .{ .name = "qwen35_draft tf_q35d_attn_partial", .usage = .{ .{ .regs = 72, .static = 3616, .bound = 128 }, .{ .regs = 72, .static = 3616, .bound = 128 }, .{ .regs = 72, .static = 3616, .bound = 128 }, .{ .regs = 77, .static = 3616, .bound = 128 }, .{ .regs = 77, .static = 3616, .bound = 128 } } }, @@ -26,7 +34,10 @@ pub const records = [_]Override{ .{ .name = "qwen35_draft tf_q35d_table", .usage = .{ .{ .regs = 40, .static = 160, .bound = 256 }, .{ .regs = 40, .static = 160, .bound = 256 }, .{ .regs = 40, .static = 160, .bound = 256 }, .{ .regs = 40, .static = 160, .bound = 256 }, .{ .regs = 40, .static = 160, .bound = 256 } } }, .{ .name = "qwen35_draft tf_q35d_transpose", .usage = .{ .{ .regs = 28, .static = 2112, .bound = 0 }, .{ .regs = 30, .static = 2112, .bound = 0 }, .{ .regs = 30, .static = 2112, .bound = 0 }, .{ .regs = 18, .static = 2112, .bound = 0 }, .{ .regs = 18, .static = 2112, .bound = 0 } } }, .{ .name = "qwen35_keep tf_q35k_apply", .usage = .{ .{ .regs = 32, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 } } }, + .{ .name = "qwen35_keep tf_q35k_apply_pend_table", .usage = .{ .{ .regs = 32, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 } } }, + .{ .name = "qwen35_keep tf_q35k_apply_table", .usage = .{ .{ .regs = 32, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 } } }, .{ .name = "qwen35_keep tf_q35k_compact", .usage = .{ .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 17, .static = 0, .bound = 256 }, .{ .regs = 17, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 } } }, .{ .name = "qwen35_keep tf_q35k_conv", .usage = .{ .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 } } }, + .{ .name = "qwen35_keep tf_q35k_conv_table", .usage = .{ .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 } } }, .{ .name = "qwen35_kv8 tf_q35k_compact8", .usage = .{ .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 22, .static = 0, .bound = 256 }, .{ .regs = 22, .static = 0, .bound = 256 } } }, }; diff --git a/zig/src/families/qwen3_5/cuda.zig b/zig/src/families/qwen3_5/cuda.zig index 4d3375563b5..35734319466 100644 --- a/zig/src/families/qwen3_5/cuda.zig +++ b/zig/src/families/qwen3_5/cuda.zig @@ -63,6 +63,7 @@ test { _ = @import("cuda_prefix.zig"); _ = @import("cuda_prefix_fault_test.zig"); _ = @import("cuda_pend_test.zig"); + _ = @import("cuda_states.zig"); _ = @import("cuda_reuse_pages_test.zig"); _ = @import("cuda_warm_turns_test.zig"); _ = @import("cuda_spares.zig"); diff --git a/zig/src/families/qwen3_5/cuda_cache.zig b/zig/src/families/qwen3_5/cuda_cache.zig index ae132b86b6f..140b3cf2ec3 100644 --- a/zig/src/families/qwen3_5/cuda_cache.zig +++ b/zig/src/families/qwen3_5/cuda_cache.zig @@ -37,7 +37,7 @@ pub fn pendBytes(g: anytype) usize { return pend_cap * g.deltas() * headBytes(g); } -/// qwen35.cuh's Seg and Path. +/// qwen35.cuh's Seg and Path: rec, conv, before and log point into the stream's States table. pub const Seg = extern struct { rec: u64, conv: u64, kv: u64, tap: u64, log: u64, before: u64, cap: c_int, len: c_int, row0: c_int, rows: c_int, tap_rows: c_int, taps: c_int, delta: c_int, pt: u64 = 0, ps: u64 = 0, ptok: c_int = 0, pn: c_int = 0, plog: u64 = 0 }; pub const Path = extern struct { n: c_int, rows: [engine.most_window]c_int }; @@ -52,6 +52,9 @@ fn firstPage(c: *const Cache) ?u32 { return if (p.ids.len > 0) p.ids[0] else null; } +/// A stream's state table: cuda_states.zig. +pub const States = @import("cuda_states.zig").States; + /// A cache's keys and values as pages (qwen35.cuh kv_row): page i of the stream's positions at `base` + ids[i] pages. pub const Paged = struct { /// Where page 0 of the arena starts: the core pool's, or the cache's own buffer under TF_QWEN_KV_PAGE_TEST. @@ -137,6 +140,8 @@ pub const Cache = struct { paged: ?Paged = null, /// A pool lane's drafter ring in its run (the drafter borrows it for the lane's stream). drafter_ring: ?u64 = null, + /// A pool lane (its run mapped): its kernels read `states` (the _table kernels); false: its blocks, as on main. + on_table: bool = false, delta: i32 = 0, state: DeviceBuffer, /// The exact state before a recorded one-row round advances its stable slot in place. @@ -144,6 +149,8 @@ pub const Cache = struct { /// A window's log and before in one block (recurrent_workspace.Overlay); runs and adaptive caches have none. block: ?DeviceBuffer = null, kv: DeviceBuffer, + /// The state table the kernels read the state, before and log through (null: a test's cache without one). + states: ?States = null, /// A drafter's tapped rows (`Engine.taps`), a ring of tapRows(): the row at position p in slot p % tapRows(). tap: ?DeviceBuffer = null, /// The newest verify window's records (qwen35.cuh's LogRow), held until its keep completes. @@ -193,8 +200,10 @@ pub const Cache = struct { pub fn initPaged(gpa: std.mem.Allocator, e: *Engine, pages: usize, tokens: usize, base: u64) !Cache { var table = try DeviceBuffer.alloc(e.d, pages * 4); errdefer table.free(); + var states = try States.init(gpa, e); + errdefer states.deinit(gpa); const none = try DeviceBuffer.alloc(e.d, 0); - return .{ .state = none, .before = none, .kv = none, .paged = .{ .base = base, .table = table, .ids = &.{}, .tokens = tokens, .own_ids = false }, .log = none, .cap = 0, .logits = try gpa.alloc(u16, e.g.vocab) }; + return .{ .state = none, .before = none, .kv = none, .paged = .{ .base = base, .table = table, .ids = &.{}, .tokens = tokens, .own_ids = false }, .states = states, .log = none, .cap = 0, .logits = try gpa.alloc(u16, e.g.vocab) }; } /// Bytes of a pool lane's run: state, log with its rollback copy, tap ring and a drafter's ring, each 256-aligned. @@ -223,6 +232,7 @@ pub const Cache = struct { self.before = beforeView(e, views[1].ptr); self.tap = if (e.n_taps > 0) views[2] else null; self.drafter_ring = if (ring > 0) views[3].ptr else null; + self.on_table = true; for ([_]DeviceBuffer{ self.log, views[2], views[3] }) |v| if (v.len > 0) try v.fill8(0, e.stream.handle); } @@ -235,6 +245,7 @@ pub const Cache = struct { self.log = none; self.tap = null; self.drafter_ring = null; + self.on_table = false; } /// The parts every cache holds itself beside `kv` and `paged` (the caller's to free on failure). @@ -253,6 +264,8 @@ pub const Cache = struct { if (e.n_taps > 0) { tap = try DeviceBuffer.alloc(e.d, e.tapBytes()); } + var states = try States.init(gpa, e); + errdefer states.deinit(gpa); const logits = try gpa.alloc(u16, e.g.vocab); errdefer gpa.free(logits); errdefer cuda.completion.drain(e.d, e.stream, "qwen3_5: failed cache state initialization did not drain"); @@ -262,7 +275,7 @@ pub const Cache = struct { try e.stream.synchronize(); const scratch = if (adaptive) recurrent.bound(e) else 0; e.rec_scratch.cap += scratch; - var c: Cache = .{ .owner = if (adaptive) &e.rec_scratch else null, .scratch = scratch, .state = state, .before = before, .kv = kv, .paged = paged, .tap = tap, .log = log, .cap = cap, .logits = logits }; + var c: Cache = .{ .owner = if (adaptive) &e.rec_scratch else null, .scratch = scratch, .state = state, .before = before, .kv = kv, .paged = paged, .tap = tap, .states = states, .log = log, .cap = cap, .logits = logits }; c.block = block; return c; } @@ -297,13 +310,33 @@ pub const Cache = struct { self.log.free(); if (self.tap) |*t| t.free(); if (self.pbuf) |*b| b.free(); + if (self.states) |*t| t.deinit(gpa); gpa.free(self.logits); } - /// The stream's window of `rows` rows from forward row `row0`, after `len` cached positions. - pub fn seg(self: *const Cache, e: *const Engine, len: usize, row0: usize, rows: usize) Seg { + /// The state table rewritten (on the engine's stream, before the launches that read it) if a block moved. + pub fn stateTable(self: *Cache, e: *const Engine) !States { + const t = &(self.states orelse return error.MissingQwenStates); + const from: [3]u64 = .{ self.state.ptr, if (self.before) |b| b.ptr else 0, self.log.ptr }; + if (t.from) |f| if (std.mem.eql(u64, &f, &from)) return t.*; + States.fill(t.host, e.g, from[0], from[1], from[2]); + try t.dev.uploadAsync(0, std.mem.sliceAsBytes(t.host), e.stream.handle); + t.from = from; + return t.*; + } + + /// The stream's window of `rows` rows from forward row `row0` after `len` cached positions (pool lane: its table). + pub fn seg(self: *Cache, e: *const Engine, len: usize, row0: usize, rows: usize) !Seg { + if (self.on_table) return self.segIn(e, (try self.stateTable(e)).at(e.g), len, row0, rows); + const g = e.g; + const at: [4]u64 = .{ self.state.ptr, self.state.ptr + g.deltas() * g.recBytes(), if (self.before) |b| b.ptr else 0, self.log.ptr }; + return self.segIn(e, at, len, row0, rows); + } + + /// `seg` with `t` (rec, conv, before, log): its blocks, or a state table's entries (States.parts). + pub fn segIn(self: *Cache, e: *const Engine, t: [4]u64, len: usize, row0: usize, rows: usize) Seg { const g = e.g; - var sg: Seg = .{ .rec = self.state.ptr, .conv = self.state.ptr + g.deltas() * g.recBytes(), .kv = self.kv.ptr, .tap = if (self.tap) |t| t.ptr else 0, .log = self.log.ptr, .before = if (self.before) |b| b.ptr else 0, .cap = @intCast(self.cap), .len = @intCast(len), .row0 = @intCast(row0), .rows = @intCast(rows), .tap_rows = @intCast(e.tapRows()), .taps = @intCast(e.n_taps), .delta = self.delta }; + var sg: Seg = .{ .rec = t[0], .conv = t[1], .kv = self.kv.ptr, .tap = if (self.tap) |x| x.ptr else 0, .log = t[3], .before = t[2], .cap = @intCast(self.cap), .len = @intCast(len), .row0 = @intCast(row0), .rows = @intCast(rows), .tap_rows = @intCast(e.tapRows()), .taps = @intCast(e.n_taps), .delta = self.delta }; if (self.paged) |p| { sg.kv = p.base; sg.pt = p.table.ptr; @@ -340,37 +373,42 @@ pub const Cache = struct { return; } const g = e.g; - const sg = self.seg(e, last.start, 0, last.rows); + const sg = try self.seg(e, last.start, 0, last.rows); try recurrent.mark(self, false); // the path's rows join the pending ones; without a log, with the switch off or past pend_cap they land now const deferred = keepLate() and self.log.len > 0 and path.len <= pend_cap; + const tab = self.on_table; if (!deferred) { try self.flush(e); - try e.run(e.keeps.apply, .{ 1, geometry.dk / 4, g.v_heads * g.deltas() }, .{ 32, 4, 1 }, .{ e.geo, sg, p }); + try e.run(if (tab) e.keeps.apply_table else e.keeps.apply, .{ 1, geometry.dk / 4, g.v_heads * g.deltas() }, .{ 32, 4, 1 }, .{ e.geo, sg, p }); } - try e.run(e.keeps.conv, .{ g.deltas(), (g.convBytes() / 2 + 255) / 256, 1 }, .{ 256, 1, 1 }, .{ e.geo, sg, @as(c_int, @intCast(path[path.len - 1])) }); + try e.run(if (tab) e.keeps.conv_table else e.keeps.conv, .{ g.deltas(), (g.convBytes() / 2 + 255) / 256, 1 }, .{ 256, 1, 1 }, .{ e.geo, sg, @as(c_int, @intCast(path[path.len - 1])) }); if (!prefix and g.attentions() > 0) try e.run(if (e.kv8) e.fp8.compact else e.keeps.compact, .{ g.attentions(), g.kv_heads, 1 }, .{ geometry.head_dim, 1, 1 }, .{ e.geo, sg, p }); - if (deferred) try self.pendRows(e, sg.log, path); + if (deferred) try self.pendRows(e, path); self.last = null; self.len = last.start + path.len; } /// The kept path's heads after the pending rows, a run of consecutive rows one copy; a full buffer lands first. - fn pendRows(self: *Cache, e: *Engine, log: u64, path: []const u32) !void { + fn pendRows(self: *Cache, e: *Engine, path: []const u32) !void { const g = e.g; if (self.pbuf == null) self.pbuf = try DeviceBuffer.alloc(e.d, pendBytes(g)); if (@as(usize, @intCast(self.pend)) + path.len > pend_cap) try self.flush(e); const hb = headBytes(g); const row_log = g.deltas() * g.logRowBytes(); + const tab = self.on_table; + const t: ?States = if (tab) try self.stateTable(e) else null; // a window stream: main's rows, no table + const log = self.log.ptr; const base = self.pbuf.?.ptr; var j: usize = 0; while (j < path.len) { + // consecutive window rows whose records follow each other in the log, one copy var run: usize = 1; - while (j + run < path.len and path[j + run] == path[j] + run) run += 1; + while (j + run < path.len and path[j + run] == path[j] + run and (!tab or t.?.logRow(g, path[j + run]) == t.?.logRow(g, path[j]) + run * row_log)) run += 1; const at: usize = @as(usize, @intCast(self.pend)) + j; - const m: cuda.abi.Memcpy2D = .{ .src = log + path[j] * row_log, .src_pitch = g.logRowBytes(), .dst = base + at * g.deltas() * hb, .dst_pitch = hb, .width = hb, .height = run * g.deltas() }; + const m: cuda.abi.Memcpy2D = .{ .src = if (tab) t.?.logRow(g, path[j]) else log + path[j] * row_log, .src_pitch = g.logRowBytes(), .dst = base + at * g.deltas() * hb, .dst_pitch = hb, .width = hb, .height = run * g.deltas() }; // a copy past the log or the pending buffer is refused here, not by the driver mid-reply - const src_end = m.src - log + (m.height - 1) * m.src_pitch + m.width; + const src_end = if (m.src < log) std.math.maxInt(u64) else m.src - log + (m.height - 1) * m.src_pitch + m.width; const dst_end = m.dst - base + (m.height - 1) * m.dst_pitch + m.width; if (src_end > self.log.len or dst_end > self.pbuf.?.len) { std.log.err("qwen3_5 pending keep: path {d} rows after {d} pending, path row {d} (window row {d}), run {d}: source end {d} of a {d}-byte log, destination end {d} of a {d}-byte buffer; head {d} bytes, log row {d}", .{ path.len, self.pend, j, path[j], run, src_end, self.log.len, dst_end, self.pbuf.?.len, hb, g.logRowBytes() }); @@ -385,12 +423,12 @@ pub const Cache = struct { /// The pending rows landed in the state now (before anything but a recorded slot scan reads it). pub fn flush(self: *Cache, e: *Engine) !void { if (self.pend == 0) return; - var sg = self.seg(e, self.len, 0, 0); + var sg = try self.seg(e, self.len, 0, 0); sg.plog = self.pbuf.?.ptr; const n = self.pend; self.pend = 0; const g = e.g; - try e.run(e.keeps.apply_pend, .{ 1, geometry.dk / 4, g.v_heads * g.deltas() }, .{ 32, 4, 1 }, .{ e.geo, sg, n }); + try e.run(if (self.on_table) e.keeps.apply_pend_table else e.keeps.apply_pend, .{ 1, geometry.dk / 4, g.v_heads * g.deltas() }, .{ 32, 4, 1 }, .{ e.geo, sg, n }); } /// This forward's scan entry with the pending rows, written back (a positive count) at one row or pend_commit. diff --git a/zig/src/families/qwen3_5/cuda_engine.zig b/zig/src/families/qwen3_5/cuda_engine.zig index 4e5ea046815..e00be0937f4 100644 --- a/zig/src/families/qwen3_5/cuda_engine.zig +++ b/zig/src/families/qwen3_5/cuda_engine.zig @@ -157,6 +157,8 @@ pub const Engine = struct { hop: ?stage_fwd.Hop = null, // pipeline stage ring and host boundary boundary: ?cuda.HostBuffer = null, held: ?*stage_fwd.Held = null, // rank 0 with rounds in flight: head reads later + prompt_states: []const u64 = &.{}, // a prompt chunk's stream state table on the host (cuda_prompt.zig's delta) + forward_from: [Round.max_segs]?[3]u64 = @splat(null), // state addresses each segment's table holds (null: none yet) pub const ids_at = Round.ids_at; pub const segs_at = Round.segs_at; pub const rowseg_at = Round.rowseg_at; @@ -217,6 +219,8 @@ pub const Engine = struct { e.hop = null; e.boundary = null; e.held = null; + e.prompt_states = &.{}; + e.forward_from = @splat(null); e.stream = try cuda.Stream.init(d, true); errdefer e.stream.deinit(); if (span != null) e.boundary = try cuda.HostBuffer.alloc(d, stage_fwd.bytes(g.hidden, grid_rows)); @@ -338,7 +342,7 @@ pub const Engine = struct { e.gpa.destroy(e); } - /// A stream's device bytes at a `cap`-token window: recurrences, convolution tails, keys and values, taps, log. + /// A stream's device bytes at a `cap`-token window: state, keys and values, taps, log and its state table. pub fn streamBytes(e: *const Engine, cap: usize) usize { return e.streamBytesWithTaps(cap, e.n_taps); } @@ -346,7 +350,7 @@ pub const Engine = struct { /// The same allocation plan for a tap count known before `setTaps` mutates the engine. pub fn streamBytesWithTaps(e: *const Engine, cap: usize, taps: usize) usize { const c = @import("cuda_cache.zig"); - return e.g.stateBytes() + c.scratchBytes(e) + e.g.kvBytes(cap, e.kv8) + e.tapRows() * taps * e.g.hidden * 2 + c.pendBytes(e.g); + return e.g.stateBytes() + c.scratchBytes(e) + e.g.kvBytes(cap, e.kv8) + e.tapRows() * taps * e.g.hidden * 2 + c.pendBytes(e.g) + c.States.bytes(e.g); } /// A stream's tap ring: tapRows() rows of the tapped layers' residuals. @@ -437,33 +441,12 @@ pub const Engine = struct { try e.runPdl(if (e.g.bf16) e.fns.norm_shift else e.fns.norm, .{ rows, 1, 1 }, .{ 256, 1, 1 }, .{ e.h, if (residual) e.r else @as(u64, 0), w, e.x, e.g.eps, @as(c_int, @intCast(e.g.hidden)), e.tables.ptr + params_at, e.xs }); } - /// Refuse the whole frame before settling any prior window or launching work. - pub fn admit(e: *const Engine, parts: []const Part, ids: []const u32, keep: Keep) !void { - const g = e.g; - if (!geometry.supported(g, ids.len, !keep.verifies(), most_verify)) return error.UnsupportedQwenGeometry; - var total: usize = 0; - if (parts.len == 0 or parts.len > max_segs) return error.InvalidQwenSegments; - for (parts, 0..) |p, index| { - for (parts[0..index]) |prior| if (prior.cache == p.cache) return error.InvalidQwenSegments; - if (p.rows == 0 or p.cache.len > p.cache.cap or p.rows > p.cache.cap - p.cache.len) return error.QwenContextFull; - if (p.rows > max_rows - total) return error.InvalidQwenSegments; - total += p.rows; - } - if (parts.len == 0 or parts.len > max_segs or total != ids.len or total > max_rows) return error.InvalidQwenSegments; - if (e.learning != null and total != 1) return error.BadLearningRows; - if (keep == .hidden and e.learning == null) return error.BadLearningRows; - const record = keep.verifies(); - if (record and total > e.verify_rows) return error.InvalidQwenSegments; - if (!record and parts.len != 1) return error.InvalidQwenSegments; - if (keep == .draws and keep.draws.len != total) return error.InvalidQwenSegments; - for (ids) |id| if (id >= g.vocab) return error.InvalidQwenToken; - for (parts) |p| if (p.parents != null and !record) return error.InvalidQwenParents; - for (parts) |p| if (p.images != null and record) return error.InvalidQwenImages; - } + /// Refuse the whole frame before settling any prior window or launching work (cuda_round.zig). + pub const admit = Round.admit; /// A window's staged segment: one-row windows that skip their rollback copy read no `before`. - pub fn stagedSeg(c: *Cache, e: *const Engine, len: usize, row0: usize, rows: usize, undo: bool) Seg { - var sg = c.fold(c.seg(e, len, row0, rows)); + pub fn stagedSeg(c: *Cache, e: *const Engine, t: ?[4]u64, len: usize, row0: usize, rows: usize, undo: bool) !Seg { + var sg = c.fold(if (t) |x| c.segIn(e, x, len, row0, rows) else try c.seg(e, len, row0, rows)); if (rows == 1 and !undo) sg.before = 0; return sg; } @@ -488,11 +471,15 @@ pub const Engine = struct { if (!(record and keep != .hidden)) try p.cache.flush(e); try recurrent.prepare(e, p.cache, p.rows, record, p.undo); } + const table = Round.onTable(parts); // a pool lane among the parts: every scan reads state tables, else main's var row0: usize = 0; for (parts, 0..) |p, i| { - segs[i] = stagedSeg(p.cache, e, p.cache.len, row0, p.rows, p.undo); + segs[i] = try stagedSeg(p.cache, e, if (table) try Round.forwardStates(e, i, p.cache) else null, p.cache.len, row0, p.rows, p.undo); row0 += p.rows; } + // a pool lane's prompt chunk is one stream's: its delta rule takes the recurrences' addresses on the host + e.prompt_states = if (!record and table) parts[0].cache.states.?.host else &.{}; + defer e.prompt_states = &.{}; if (keep == .draws) { const rules = std.mem.bytesAsSlice(cuda.sample.Rule, st[rules_at..][0 .. total * @sizeOf(cuda.sample.Rule)]); const meta = std.mem.bytesAsSlice(c_int, st[meta_at..][0 .. total * 4]); @@ -530,6 +517,7 @@ pub const Engine = struct { shape.unread = keep == .none; shape.paged = @import("cuda_attention.zig").hasPages(segs); shape.join = shape.paged and caches.anyShares(parts); + shape.table = table; shape.mt2 = @import("cuda_shapes.zig").useMt2(e.mt2.enabled, e.kv8, !record, total, parts.len, parts[0].cache.len); if (e.learning != null or e.pockets.any()) { shape.total = @intCast(total); @@ -581,6 +569,8 @@ pub const Engine = struct { pub const Shape = @import("cuda_shapes.zig").Shape; /// One shape's launches: uncaptured for a prompt chunk or the exact path, else its captured graph replayed. pub const launchShape = @import("cuda_shapes.zig").launch; + /// A state table's entries (cuda_cache.zig States): `tables` holds one for each forward segment. + pub const stateEntries = Round.stateEntries; /// The same scan selected by body, exposed for host launch-contract fixtures. pub const deltaScan = @import("cuda_forward.zig").deltaScan; /// The launches of a forward of `shape`, from the embedding to the kept rows' logits (captured once a shape). diff --git a/zig/src/families/qwen3_5/cuda_engine_tail.zig b/zig/src/families/qwen3_5/cuda_engine_tail.zig index 7ddf3a99166..ff8049540a6 100644 --- a/zig/src/families/qwen3_5/cuda_engine_tail.zig +++ b/zig/src/families/qwen3_5/cuda_engine_tail.zig @@ -2,12 +2,13 @@ const std = @import("std"); const cuda = @import("cuda"); const DeviceBuffer = cuda.DeviceBuffer; -const tables_len = @import("cuda_round.zig").bytes; +const Round = @import("cuda_round.zig"); +const tables_len = Round.bytes; pub fn finish(e: anytype, io: std.Io, started: i96) !void { errdefer if (e.kit) |k| k.deinit(e.gpa); errdefer if (comptime @hasField(@TypeOf(e.*), "tfq3")) if (e.tfq3) |t| t.deinit(e.gpa); - e.tables = try DeviceBuffer.alloc(e.d, tables_len); + e.tables = try DeviceBuffer.alloc(e.d, Round.tableBytes(e.stateEntries())); errdefer e.tables.free(); e.staged = try cuda.HostBuffer.alloc(e.d, tables_len); errdefer e.staged.free(); diff --git a/zig/src/families/qwen3_5/cuda_engine_tail_test.zig b/zig/src/families/qwen3_5/cuda_engine_tail_test.zig index 2991e213a9f..1efc690e968 100644 --- a/zig/src/families/qwen3_5/cuda_engine_tail_test.zig +++ b/zig/src/families/qwen3_5/cuda_engine_tail_test.zig @@ -52,6 +52,9 @@ const Engine = struct { tables: cuda.DeviceBuffer = undefined, staged: cuda.HostBuffer = undefined, host_logits: cuda.HostBuffer = undefined, + pub fn stateEntries(_: *const @This()) usize { + return 0; + } pub fn scratch(_: *@This(), _: enum { allocate }) !usize { return 0; } diff --git a/zig/src/families/qwen3_5/cuda_forward.zig b/zig/src/families/qwen3_5/cuda_forward.zig index 16c01482778..5a143769ada 100644 --- a/zig/src/families/qwen3_5/cuda_forward.zig +++ b/zig/src/families/qwen3_5/cuda_forward.zig @@ -97,10 +97,10 @@ pub fn body(e: *E.Engine, shape: anytype) !void { const layer: c_int = @intCast(di); try e.projManyPrompt(&.{ m.qkv, m.z, m.a, m.b }, e.x, &.{ e.qkv, e.z, e.a, e.b }, total, prompt); if (e.learning) |k| try k.delta(i, e.qkv, e.z, e.b, e.a, total); - try e.runPdl(e.fns.gdn_pre, .{ 1, 2 * g.k_heads + g.v_heads, total }, .{ 32, 1, 1 }, .{ geo, e.qkv, t_segs, t_rows, t_par, layer, m.conv, e.a, e.b, m.a_log, m.dt_bias, e.q, e.k, e.v, e.g_, e.beta, t_params }); + try e.runPdl(if (shape.table) e.fns.gdn_pre_table else e.fns.gdn_pre, .{ 1, 2 * g.k_heads + g.v_heads, total }, .{ 32, 1, 1 }, .{ geo, e.qkv, t_segs, t_rows, t_par, layer, m.conv, e.a, e.b, m.a_log, m.dt_bias, e.q, e.k, e.v, e.g_, e.beta, t_params }); // one recorded window of 2+ rows: gdn_pre logged its tails, conv_commit would only return - if (!(record and nseg == 1 and total > 1)) try e.run(e.fns.conv_commit, .{ (g.convWidth() + 255) / 256, nseg, 1 }, .{ 256, 1, 1 }, .{ geo, e.qkv, t_segs, t_par, layer, t_params }); - if (prompt and nseg == 1) try @import("cuda_prompt.zig").delta(e, di, total) else try e.deltaScan(record, shape.slots, nseg, layer); + if (!(record and nseg == 1 and total > 1)) try e.run(if (shape.table) e.fns.conv_commit_table else e.fns.conv_commit, .{ (g.convWidth() + 255) / 256, nseg, 1 }, .{ 256, 1, 1 }, .{ geo, e.qkv, t_segs, t_par, layer, t_params }); + if (prompt and nseg == 1) try @import("cuda_prompt.zig").delta(e, di, total) else try e.deltaScan(record, shape.slots, nseg, layer, shape.table); try e.runPdl(e.fns.gdn_post, .{ 1, g.v_heads, total }, .{ 32, 1, 1 }, .{ geo, e.y, e.z, m.norm, g.eps, e.mix, t_params, sums }); try e.projAgain(m.out, e.mix, e.r, total, prompt); di += 1; @@ -241,13 +241,14 @@ test "prompt MoE precision: every prompt piece through 128 and admitted verify w } /// The same scan selected by body, exposed for host launch-contract fixtures. -pub fn deltaScan(e: anytype, record: bool, slot_count: u8, segments: usize, layer: c_int) !void { - const scan = if (!record) e.fns.gdn_chain else switch (slot_count) { - 1 => e.fns.gdn_slots_1, - 2 => e.fns.gdn_slots_2, - 4 => e.fns.gdn_slots_4, - 8 => e.fns.gdn_slots_8, - 16 => e.fns.gdn_slots_16, +pub fn deltaScan(e: anytype, record: bool, slot_count: u8, segments: usize, layer: c_int, table: bool) !void { + const f = &e.fns; + const scan = if (!record) (if (table) f.gdn_chain_table else f.gdn_chain) else switch (slot_count) { + 1 => if (table) f.gdn_slots_1_table else f.gdn_slots_1, + 2 => if (table) f.gdn_slots_2_table else f.gdn_slots_2, + 4 => if (table) f.gdn_slots_4_table else f.gdn_slots_4, + 8 => if (table) f.gdn_slots_8_table else f.gdn_slots_8, + 16 => if (table) f.gdn_slots_16_table else f.gdn_slots_16, else => return error.InvalidGdnSlots, }; const input = e.tables.ptr + @as(usize, if (record) @import("cuda_round.zig").steps_at else rowpar_at); diff --git a/zig/src/families/qwen3_5/cuda_layers.zig b/zig/src/families/qwen3_5/cuda_layers.zig index 1aada33037d..6eb6e9f5b59 100644 --- a/zig/src/families/qwen3_5/cuda_layers.zig +++ b/zig/src/families/qwen3_5/cuda_layers.zig @@ -59,6 +59,15 @@ pub const Fns = struct { gdn_slots_4: cuda.Function, gdn_slots_8: cuda.Function, gdn_slots_16: cuda.Function, + // the same scans reading a pool lane's state table (qwen35.cuh TF_Q35_TWICE) + gdn_pre_table: cuda.Function, + conv_commit_table: cuda.Function, + gdn_chain_table: cuda.Function, + gdn_slots_1_table: cuda.Function, + gdn_slots_2_table: cuda.Function, + gdn_slots_4_table: cuda.Function, + gdn_slots_8_table: cuda.Function, + gdn_slots_16_table: cuda.Function, gdn_post: cuda.Function, head_norm: cuda.Function, head_norm_shift: cuda.Function, @@ -79,7 +88,7 @@ pub const Fns = struct { }; /// qwen35_keep.cu's kernels (Cache.keep). -pub const Keeps = struct { apply: cuda.Function, apply_pend: cuda.Function, conv: cuda.Function, compact: cuda.Function }; +pub const Keeps = struct { apply: cuda.Function, apply_pend: cuda.Function, conv: cuda.Function, compact: cuda.Function, apply_table: cuda.Function, apply_pend_table: cuda.Function, conv_table: cuda.Function }; /// qwen35_kv8.cu's kernels: the cache writes, attention reads and keep's moves over e4m3 rows (--kv-cache fp8). pub const Kv8 = struct { rope: cuda.Function, attn_partial: cuda.Function, attn_rows: cuda.Function, attn_rows_join: cuda.Function, attn_partial8_whole: cuda.Function, attn_rows8_whole: cuda.Function, compact: cuda.Function }; diff --git a/zig/src/families/qwen3_5/cuda_pages.zig b/zig/src/families/qwen3_5/cuda_pages.zig index 182810ff731..64d141e4b38 100644 --- a/zig/src/families/qwen3_5/cuda_pages.zig +++ b/zig/src/families/qwen3_5/cuda_pages.zig @@ -46,9 +46,9 @@ fn mostPages(capacity: usize, tokens: usize) usize { return (capacity + window_rows + tokens - 1) / tokens; } -/// A lane's table and `fixed` bytes; its keys and values a token; a run of its state, log, taps and a `ring`-byte ring. +/// A lane's tables and `fixed` bytes; its keys and values a token; a run of its state, log, taps and `ring` bytes. pub fn layout(e: *const Engine, capacity: usize, tokens: usize, ring: usize, fixed: usize) kv.Layout { - return .{ .fixed_bytes = mostPages(capacity, tokens) * 4 + fixed, .token_bytes = e.g.kvBytes(1, e.kv8), .page_tokens = @intCast(tokens), .snap_bytes = e.g.stateBytes(), .run_bytes = Cache.runBytes(e, ring) }; + return .{ .fixed_bytes = mostPages(capacity, tokens) * 4 + caches.States.bytes(e.g) + fixed, .token_bytes = e.g.kvBytes(1, e.kv8), .page_tokens = @intCast(tokens), .snap_bytes = e.g.stateBytes(), .run_bytes = Cache.runBytes(e, ring) }; } /// One pool lane: a cache whose table maps its stream's pages, that stream's lease and its run's first page. diff --git a/zig/src/families/qwen3_5/cuda_pages_init_test.zig b/zig/src/families/qwen3_5/cuda_pages_init_test.zig index 9dcb440f7ca..864473bd947 100644 --- a/zig/src/families/qwen3_5/cuda_pages_init_test.zig +++ b/zig/src/families/qwen3_5/cuda_pages_init_test.zig @@ -88,6 +88,9 @@ fn engine(d: *cuda.Driver) E { e.d = d; e.stream = .{ .d = d, .handle = Device.stream }; e.g.vocab = 8; + e.g.layers = 0; // no linear layer: a lane's state table holds only the log rows' entries + e.g.first = 0; // one engine, the whole model: Geometry.deltas reads first + e.g.whole = 0; return e; } @@ -119,7 +122,7 @@ test "kv safety: Qwen second table allocation refusal precedes every fill" { var d = Device.driver(); var e = engine(&d); defer finish(&d, e.stream); - Device.fail_alloc = 3; + Device.fail_alloc = 4; // the arena, lane 0's page and state tables, then lane 1's page table try expectPoolError(error.NotReady, pages.Pages.init(gpa, &e, layout, 64, 0, 2, 8), &d, e.stream); try Device.released(); try std.testing.expectEqual(@as(usize, 0), Device.fills); @@ -129,11 +132,12 @@ test "kv safety: Qwen initPaged logits allocation failure precedes every fill" { var d = Device.driver(); var e = engine(&d); defer finish(&d, e.stream); - var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); + // the state table's host copy, then the logits + var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 1 }); try std.testing.expectError(error.OutOfMemory, caches.Cache.initPaged(failing.allocator(), &e, 3, 16, 0x1000)); try Device.released(); try std.testing.expect(failing.has_induced_failure); - try std.testing.expectEqual(@as(usize, 1), Device.allocs); + try std.testing.expectEqual(@as(usize, 2), Device.allocs); try std.testing.expectEqual(@as(usize, 0), Device.fills); } diff --git a/zig/src/families/qwen3_5/cuda_pend_test.zig b/zig/src/families/qwen3_5/cuda_pend_test.zig index 558b1340e4c..88afda4ac3e 100644 --- a/zig/src/families/qwen3_5/cuda_pend_test.zig +++ b/zig/src/families/qwen3_5/cuda_pend_test.zig @@ -82,13 +82,18 @@ fn engine(d: *cuda.Driver) E { return .{ .d = dd, .handle = @ptrFromInt(i) }; } }.at; - e.keeps = .{ .apply = f(d, apply), .apply_pend = f(d, apply_pend), .conv = f(d, 3), .compact = f(d, 4) }; + e.keeps = .{ .apply = f(d, apply), .apply_pend = f(d, apply_pend), .conv = f(d, 3), .compact = f(d, 4), .apply_table = f(d, 5), .apply_pend_table = f(d, 6), .conv_table = f(d, 7) }; return e; } -/// A cache with its own log of a widest window, as a cache outside a pool has. +/// A cache with its own log of a widest window, as a cache outside a pool has; its state table already written. fn cache(d: *cuda.Driver, g: geometry.Geometry) !caches.Cache { - return .{ .state = try cuda.DeviceBuffer.alloc(d, g.stateBytes()), .kv = try cuda.DeviceBuffer.alloc(d, g.kvBytes(4096, false)), .log = try cuda.DeviceBuffer.alloc(d, g.logBytes(most)), .cap = 4096, .logits = &.{} }; + var c: caches.Cache = .{ .state = try cuda.DeviceBuffer.alloc(d, g.stateBytes()), .kv = try cuda.DeviceBuffer.alloc(d, g.kvBytes(4096, false)), .log = try cuda.DeviceBuffer.alloc(d, g.logBytes(most)), .cap = 4096, .logits = &.{} }; + var states: caches.States = .{ .dev = try cuda.DeviceBuffer.alloc(d, caches.States.bytes(g)), .host = try t.allocator.alloc(u64, caches.States.len(g)) }; + caches.States.fill(states.host, g, c.state.ptr, 0, c.log.ptr); + states.from = .{ c.state.ptr, 0, c.log.ptr }; + c.states = states; + return c; } fn release(c: *caches.Cache) void { @@ -96,6 +101,7 @@ fn release(c: *caches.Cache) void { c.kv.free(); c.log.free(); if (c.pbuf) |*b| b.free(); + if (c.states) |*s| s.deinit(t.allocator); } /// A recorded window of `most` rows, then `path` kept. diff --git a/zig/src/families/qwen3_5/cuda_prompt.zig b/zig/src/families/qwen3_5/cuda_prompt.zig index d6e4fdd0bb2..5e4a8bf6e51 100644 --- a/zig/src/families/qwen3_5/cuda_prompt.zig +++ b/zig/src/families/qwen3_5/cuda_prompt.zig @@ -104,7 +104,8 @@ pub fn runFrom(e: *E.Engine, layer: usize, from: usize, end: usize) !void { pub fn delta(e: *E.Engine, layer: usize, rows: usize) !void { const g = e.g; const sg = std.mem.bytesToValue(Seg, e.staged.bytes[E.Engine.segs_at..][0..@sizeOf(Seg)]); - const state = sg.rec + layer * g.v_heads * geometry.dk * geometry.dk * 4; + // a pool lane: its state table's entry; else layer's recurrence in the stream's block, as on main + const state = if (e.prompt_states.len > 0) e.prompt_states[layer] else sg.rec + layer * g.v_heads * geometry.dk * geometry.dk * 4; var a: cuda.Args = .{}; for ([_]u64{ e.q, e.k, e.v, e.g_, e.beta, state, state, e.y }) |v| a.add(v); for ([_]usize{ rows, g.k_heads, g.v_heads }) |v| a.add(@as(c_int, @intCast(v))); diff --git a/zig/src/families/qwen3_5/cuda_round.zig b/zig/src/families/qwen3_5/cuda_round.zig index 1195a50791a..e481d52b47f 100644 --- a/zig/src/families/qwen3_5/cuda_round.zig +++ b/zig/src/families/qwen3_5/cuda_round.zig @@ -4,6 +4,7 @@ const slots = @import("core").tree_slots; const Seg = @import("cuda_cache.zig").Seg; const Rule = @import("cuda").sample.Rule; pub const Path = @import("cuda_cache.zig").Path; +const E = @import("cuda_engine.zig"); pub const max_rows = 8192; // a forward's rows at most: a solo prompt pass (TF_QWEN35_CHUNK_SOLO); verify, most_verify pub const grid_rows = 4096; // the cold pass's chunk: where cuts land, states are kept and passes resume pub const max_segs = 128; @@ -23,6 +24,59 @@ pub const params_at = tokens_at + most_verify * 4; pub const src_at = params_at + 8 * 4; pub const mpos_at = src_at + max_rows * 4; pub const bytes = mpos_at + 3 * max_rows * 4; +/// Each forward segment's state table (cuda_cache.zig States) after the planes, past the per-forward upload. +pub const states_at = std.mem.alignForward(usize, bytes, 8); +comptime { + std.debug.assert(states_at - segs_at == 445472); // qwen35.cuh SEG_STATES +} +/// The tables buffer: the planes, then max_segs state tables of `entries` addresses each. +pub fn tableBytes(entries: usize) usize { + return states_at + max_segs * entries * 8; +} +/// A state table's entries (Engine.stateEntries): the engine's `tables` hold one for each forward segment. +pub fn stateEntries(e: anytype) usize { + return @import("cuda_cache.zig").States.len(e.g); +} +/// Segment i's state table in the tables (qwen35.cuh forward_states): the stream's own, copied when it moved. +pub fn forwardStates(e: anytype, i: usize, c: anytype) ![4]u64 { + const States = @import("cuda_cache.zig").States; + const t = try c.stateTable(e); + const n = States.bytes(e.g); + const at = states_at + i * n; + if (!std.meta.eql(e.forward_from[i], t.from)) { + try e.tables.copyFrom(at, t.dev.ptr, n, e.stream.handle); + e.forward_from[i] = t.from; + } + return States.parts(e.tables.ptr + at, e.g); +} +/// Whether a pool lane is among a forward's parts: then every segment's scans read state tables (_table kernels). +pub fn onTable(parts: anytype) bool { + for (parts) |p| if (p.cache.on_table) return true; + return false; +} +/// Refuse the whole frame before settling any prior window or launching work. +pub fn admit(e: *const E.Engine, parts: []const E.Part, ids: []const u32, keep: E.Keep) !void { + const g = e.g; + if (!@import("cuda_geometry.zig").supported(g, ids.len, !keep.verifies(), most_verify)) return error.UnsupportedQwenGeometry; + var total: usize = 0; + if (parts.len == 0 or parts.len > max_segs) return error.InvalidQwenSegments; + for (parts, 0..) |p, index| { + for (parts[0..index]) |prior| if (prior.cache == p.cache) return error.InvalidQwenSegments; + if (p.rows == 0 or p.cache.len > p.cache.cap or p.rows > p.cache.cap - p.cache.len) return error.QwenContextFull; + if (p.rows > max_rows - total) return error.InvalidQwenSegments; + total += p.rows; + } + if (parts.len == 0 or parts.len > max_segs or total != ids.len or total > max_rows) return error.InvalidQwenSegments; + if (e.learning != null and total != 1) return error.BadLearningRows; + if (keep == .hidden and e.learning == null) return error.BadLearningRows; + const record = keep.verifies(); + if (record and total > e.verify_rows) return error.InvalidQwenSegments; + if (!record and parts.len != 1) return error.InvalidQwenSegments; + if (keep == .draws and keep.draws.len != total) return error.InvalidQwenSegments; + for (ids) |id| if (id >= g.vocab) return error.InvalidQwenToken; + for (parts) |p| if (p.parents != null and !record) return error.InvalidQwenParents; + for (parts) |p| if (p.images != null and record) return error.InvalidQwenImages; +} /// An image prompt's rows for its prompt chunks: device feature rows, each prompt row's feature row, its positions. pub const Images = struct { features: u64, // bf16 [image rows, hidden] diff --git a/zig/src/families/qwen3_5/cuda_shapes.zig b/zig/src/families/qwen3_5/cuda_shapes.zig index 3aa4e7453a0..ef5b490a01a 100644 --- a/zig/src/families/qwen3_5/cuda_shapes.zig +++ b/zig/src/families/qwen3_5/cuda_shapes.zig @@ -20,6 +20,7 @@ pub const Shape = struct { tap_from: ?usize = null, /// A pipeline stage's piece of the forward (cuda_stage_forward.zig); one engine runs the whole. part: @import("cuda_stage_forward.zig").Part = .whole, + table: bool = false, // a pool lane among the segments: the scans read state tables (_table kernels) pub fn init(rows: usize, segments: usize, record: bool, taps: bool, slots: u8) Shape { std.debug.assert(rows > 0 and rows <= @as(usize, if (record) Round.most_verify else Round.max_rows) and segments > 0 and segments <= rows); @@ -30,7 +31,7 @@ pub const Shape = struct { pub fn key(s: Shape) u64 { // Captured shapes only: prompt tap_from is live; a window bucket's rows fit the low byte. - return @as(u32, @as(u8, @intCast(s.total))) | @as(u32, s.nseg) << 8 | @as(u32, @intFromBool(s.record)) << 16 | @as(u32, @intFromBool(s.prompt)) << 17 | @as(u32, @intFromBool(s.taps)) << 18 | @as(u32, s.slots) << 19 | @as(u32, @intFromBool(s.hidden)) << 27 | @as(u32, @intFromBool(s.paged)) << 28 | @as(u32, @intFromBool(s.mt2)) << 29 | @as(u32, @intFromBool(s.rows)) << 30 | @as(u32, @intFromBool(s.part == .head)) << 31 | @as(u64, @intFromBool(s.join)) << 32; + return @as(u32, @as(u8, @intCast(s.total))) | @as(u32, s.nseg) << 8 | @as(u32, @intFromBool(s.record)) << 16 | @as(u32, @intFromBool(s.prompt)) << 17 | @as(u32, @intFromBool(s.taps)) << 18 | @as(u32, s.slots) << 19 | @as(u32, @intFromBool(s.hidden)) << 27 | @as(u32, @intFromBool(s.paged)) << 28 | @as(u32, @intFromBool(s.mt2)) << 29 | @as(u32, @intFromBool(s.rows)) << 30 | @as(u32, @intFromBool(s.part == .head)) << 31 | @as(u64, @intFromBool(s.join)) << 32 | @as(u64, @intFromBool(s.table)) << 33; } }; @@ -91,12 +92,14 @@ test "every captured verify shape keys its own graph: a shape after another neve const variants = [_]u8{ 1, 2, 4, 8, 16 }; // every slot count a window's register peak gives for (1..Round.most_window + 1) |peak| try std.testing.expect(std.mem.indexOfScalar(u8, &variants, @intCast(Round.variant(peak))) != null); for (1..Round.most_verify + 1) |rows| for (1..@min(rows, Round.max_segs) + 1) |segments| for ([_]bool{ false, true }) |taps| { - for (variants) |slots| for (0..16) |bits| { + for (variants) |slots| for (0..64) |bits| { var s = Shape.init(rows, segments, true, taps, slots); s.hidden = bits & 1 != 0; s.paged = bits & 2 != 0; s.mt2 = bits & 4 != 0; s.join = bits & 8 != 0; + s.table = bits & 16 != 0; + s.part = if (bits & 32 != 0) .head else .whole; // a shared bit with table fails here try distinct.put(gpa, s, {}); const got = try keys.getOrPut(gpa, s.key()); if (got.found_existing) try std.testing.expectEqual(got.value_ptr.*, s) else got.value_ptr.* = s; diff --git a/zig/src/families/qwen3_5/cuda_states.zig b/zig/src/families/qwen3_5/cuda_states.zig new file mode 100644 index 00000000000..675269d52d2 --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_states.zig @@ -0,0 +1,116 @@ +//! A stream's state table on CUDA: the addresses of its state, rollback copy and log rows (qwen35.cuh Seg). +const std = @import("std"); +const cuda = @import("cuda"); +const geometry = @import("cuda_geometry.zig"); +const engine = @import("cuda_engine.zig"); + +const Engine = engine.Engine; +const DeviceBuffer = cuda.DeviceBuffer; + +/// A stream's state table (qwen35.cuh Seg.rec, .conv, .before, .log): addresses of its state, copy and log rows. +pub const States = struct { + dev: DeviceBuffer, + host: []u64, + /// The state, before and log addresses `dev` holds the entries of (null: not written yet). + from: ?[3]u64 = null, + + pub fn len(g: geometry.Geometry) usize { + return 4 * g.deltas() + engine.most_window; + } + + pub fn bytes(g: geometry.Geometry) usize { + return len(g) * 8; + } + + pub fn init(gpa: std.mem.Allocator, e: *const Engine) !States { + const host = try gpa.alloc(u64, len(e.g)); + errdefer gpa.free(host); + return .{ .dev = try DeviceBuffer.alloc(e.d, bytes(e.g)), .host = host }; + } + + pub fn deinit(self: *States, gpa: std.mem.Allocator) void { + self.dev.free(); + gpa.free(self.host); + } + + /// The entries of a state block (recurrences, then tails), its copy and a log of whole rows; 0 gives 0 entries. + pub fn fill(t: []u64, g: geometry.Geometry, state: u64, before: u64, log: u64) void { + const n = g.deltas(); + const in = struct { + fn f(base: u64, off: usize) u64 { + return if (base == 0) 0 else base + off; + } + }.f; + for (0..n) |l| { + t[l] = in(state, l * g.recBytes()); + t[n + l] = in(state, n * g.recBytes() + l * g.convBytes()); + t[2 * n + l] = in(before, l * g.recBytes()); + t[3 * n + l] = in(before, n * g.recBytes() + l * g.convBytes()); + } + for (0..engine.most_window) |r| t[4 * n + r] = in(log, r * n * g.logRowBytes()); + } + + /// Where the tables start in `dev` (Seg.rec, .conv, .before, .log). + pub fn at(self: States, g: geometry.Geometry) [4]u64 { + return parts(self.dev.ptr, g); + } + + /// A table at `base`'s recurrence, tail, copy and log row entries (qwen35.cuh Seg.rec, .conv, .before, .log). + pub fn parts(base: u64, g: geometry.Geometry) [4]u64 { + const n = g.deltas(); + return .{ base, base + n * 8, base + 2 * n * 8, base + 4 * n * 8 }; + } + + /// Window row `row`'s record base (cuda_cache.zig's pending copy). + pub fn logRow(self: States, g: geometry.Geometry, row: usize) u64 { + return self.host[4 * g.deltas() + row]; + } +}; + +/// The dense 27B's and the 35B-A3B's linear widths: every fourth layer attention. +fn stateGeometry(layers: usize, v_heads: usize) geometry.Geometry { + var linear: [geometry.max_layers]bool = @splat(false); + for (linear[0..layers], 0..) |*l, i| l.* = i % 4 != 3; + return .{ .hidden = 256, .intermediate = 256, .layers = layers, .vocab = 8, .k_heads = 16, .v_heads = v_heads, .q_heads = 16, .kv_heads = 2, .eps = 1e-6, .tied = true, .context = 64, .linear = linear }; +} + +test "Qwen state table: every entry is the address the kernels computed from one block before the table" { + const t = std.testing; + for ([_][2]usize{ .{ 64, 48 }, .{ 40, 32 } }) |shape| { + const g = stateGeometry(shape[0], shape[1]); + const nl = g.deltas(); + const host = try t.allocator.alloc(u64, States.len(g)); + defer t.allocator.free(host); + const state: u64 = 0x7f00_0000_0000; + const before: u64 = 0x7f10_0000_0100; + const log: u64 = 0x7f20_0000_0200; + States.fill(host, g, state, before, log); + // qwen35.cuh before the table: rec() floats and conv_rows() bf16 a layer, the log's (row * nl + layer) records + const rec: u64 = g.v_heads * 128 * 128; + const conv_rows: u64 = 3 * (2 * g.k_heads + g.v_heads) * 128; + const log_bytes: u64 = g.v_heads * 4 + g.v_heads * 128 * 4 + g.k_heads * 128 * 2 + conv_rows * 2; + for (0..nl) |l| { + try t.expectEqual(state + l * rec * 4, host[l]); + try t.expectEqual(state + nl * rec * 4 + l * conv_rows * 2, host[nl + l]); + try t.expectEqual(before + l * rec * 4, host[2 * nl + l]); + try t.expectEqual(before + nl * rec * 4 + l * conv_rows * 2, host[3 * nl + l]); + } + for (0..engine.most_window) |r| try t.expectEqual(log + r * nl * log_bytes, host[4 * nl + r]); + // the last entries end inside their blocks + try t.expectEqual(state + g.stateBytes(), host[2 * nl - 1] + g.convBytes()); + try t.expectEqual(log + g.logBytes(engine.most_window), host[4 * nl + engine.most_window - 1] + nl * g.logRowBytes()); + } +} + +test "Qwen state table: a block that is not there gives zero entries, the others stay" { + const t = std.testing; + const g = stateGeometry(64, 48); + const nl = g.deltas(); + const host = try t.allocator.alloc(u64, States.len(g)); + defer t.allocator.free(host); + @memset(host, 0xaa); + States.fill(host, g, 0x1000_0000, 0, 0); + for (host[2 * nl ..]) |x| try t.expectEqual(@as(u64, 0), x); + try t.expectEqual(@as(u64, 0x1000_0000), host[0]); + try t.expectEqual(@as(u64, 4 * nl + engine.most_window), States.len(g)); +} diff --git a/zig/tests/cuda/contract_after.zig b/zig/tests/cuda/contract_after.zig index 9c931e5997f..be1f2ddca9e 100644 --- a/zig/tests/cuda/contract_after.zig +++ b/zig/tests/cuda/contract_after.zig @@ -31,13 +31,14 @@ pub fn keep(kernels: *std.ArrayList(g.Kernel), only: []const []const u8) void { kernels.shrinkRetainingCapacity(kept); } -/// The served, paged, pending, learning, lane and SwiGLU pair suites of a full run. +/// The served, paged, pending, table, learning, lane and SwiGLU pair suites of a full run. pub fn suites(gpu: check.Gpu) !void { try @import("tfq3_tests.zig").run(gpu); try @import("contract_qwen_served.zig").run(gpu); try @import("contract_qwen_pages.zig").run(gpu); try @import("contract_qwen_shared_prefix.zig").run(gpu, &.{}); try @import("contract_qwen_pending.zig").run(gpu); + try @import("contract_qwen_table.zig").run(gpu); try @import("contract_qwen_learning.zig").numerical(gpu); try @import("contract_fn_lanes.zig").run(gpu); try @import("contract_prompt_swiglu.zig").run(gpu); diff --git a/zig/tests/cuda/contract_q35_launch_args_host.zig b/zig/tests/cuda/contract_q35_launch_args_host.zig index 0c4219cc73b..65b4068130e 100644 --- a/zig/tests/cuda/contract_q35_launch_args_host.zig +++ b/zig/tests/cuda/contract_q35_launch_args_host.zig @@ -405,13 +405,15 @@ test "Qwen3.5 prompt tiles predicate padded rows against the actual forward tota defer a.free(common); const qwen = try std.Io.Dir.cwd().readFileAlloc(io, "zig/kernels/cuda/qwen35.cu", a, .limited(8 << 20)); defer a.free(qwen); + const gdn = try std.Io.Dir.cwd().readFileAlloc(io, "zig/kernels/cuda/qwen35_gdn.cuh", a, .limited(1 << 20)); + defer a.free(gdn); const int8 = try std.Io.Dir.cwd().readFileAlloc(io, "zig/kernels/cuda/w4a8_prefill.cu", a, .limited(4 << 20)); defer a.free(int8); // Qwen3.5 row kernels return when their block's row reaches P[2] (the forward's total). try std.testing.expect(std.mem.indexOf(u8, common, "return P != nullptr && m >= P[2];") != null); try std.testing.expect(std.mem.indexOf(u8, qwen, "if (past_rows(P, blockIdx.x)) return;") != null); - try std.testing.expect(std.mem.indexOf(u8, qwen, "if (past_rows(P, w)) return;") != null); + try std.testing.expect(std.mem.indexOf(u8, gdn, "if (past_rows(P, w)) return;") != null); // gdn_pre try std.testing.expect(std.mem.indexOf(u8, qwen, "if (past_rows(P, blockIdx.z)) return;") != null); try std.testing.expect(std.mem.indexOf(u8, qwen, "if (past_rows(P, blockIdx.x / heads)) return;") != null); try std.testing.expect(std.mem.indexOf(u8, qwen, "if (past_rows(P, blockIdx.y)) return;") != null); diff --git a/zig/tests/cuda/contract_qwen_pending.zig b/zig/tests/cuda/contract_qwen_pending.zig index 4cc57593daf..7722cccfcce 100644 --- a/zig/tests/cuda/contract_qwen_pending.zig +++ b/zig/tests/cuda/contract_qwen_pending.zig @@ -130,6 +130,34 @@ const Fixture = struct { } }; +/// A forward's state tables start this far past its segments (qwen35.cuh SEG_STATES, cuda_round.zig states_at). +const seg_states = 445472; +const entries = 4 * nl + most; + +/// A stream's state table (cuda_cache.zig States) for these blocks (0: none); tails 0, no scan reads them. +fn table(state: u64, before: u64, log: u64) [entries]u64 { + var t: [entries]u64 = @splat(0); + for (0..nl) |l| { + t[l] = state + l * rec * 4; + if (before != 0) t[2 * nl + l] = before + l * rec * 4; + } + if (log != 0) for (0..most) |r| { + t[4 * nl + r] = log + r * nl * log_row; + }; + return t; +} + +/// Which instantiation runs: main's name (Seg's blocks) or _table (the state table, a pool lane's on pieces). +var tab = false; + +/// A keep launch's Seg: the blocks as main's kernels take them, or for _table a table input holding them. +fn tabled(rig: *rig_.Rig, state: u64, before: u64, log: u64) !Seg { + if (!tab) return .{ .rec = state, .before = before, .log = log }; + const t = table(state, before, log); + const at = try rig.input(std.mem.sliceAsBytes(&t)); + return .{ .rec = at, .conv = at + nl * 8, .before = at + 2 * nl * 8, .log = at + 4 * nl * 8 }; +} + /// Pending rows i and j of a buffer swapped, every layer's heads. fn swapRows(pend: []u8, i: usize, j: usize) void { for (pend[i * nl * head ..][0 .. nl * head], pend[j * nl * head ..][0 .. nl * head]) |*x, *y| std.mem.swap(u8, x, y); @@ -145,21 +173,42 @@ fn launch(gpu: check.Gpu, s: cuda.Stream, apply: ?cuda.Function, scan: cuda.Func const total = 2 * f.rows; var segs: [2]Seg = undefined; var src: [2]u64 = .{ 0, 0 }; + // each stream's state, window log and pre-round state, which its Seg reaches through its table + var states: [2]u64 = undefined; + var logs: [2]u64 = undefined; + var befores: [2]u64 = .{ 0, 0 }; + var kept: [2]Seg = undefined; // tf_q35k_apply's: the state and the path's source log for (0..2, &segs) |st, *sg| { const state = try rig.scratch(nl * rec * 4); try (cuda.DeviceBuffer{ .d = gpu.d, .ptr = state, .len = nl * rec * 4 }).upload(0, std.mem.sliceAsBytes(f.state[st])); - sg.* = .{ .rec = state, .log = try rig.scratch(f.rows * nl * log_row), .row0 = @intCast(st * f.rows), .rows = @intCast(f.rows) }; - if (f.rows == 1) sg.before = try rig.scratch(nl * rec * 4); + states[st] = state; + logs[st] = try rig.scratch(f.rows * nl * log_row); + if (f.rows == 1) befores[st] = try rig.scratch(nl * rec * 4); + sg.* = try tabled(&rig, state, befores[st], logs[st]); + sg.row0 = @intCast(st * f.rows); + sg.rows = @intCast(f.rows); const n = f.n[st] - (if (st == 0) drop else 0); if (apply != null) { - if (f.n[st] > 0) src[st] = try rig.input(f.src[st]); + if (f.n[st] > 0) { + src[st] = try rig.input(f.src[st]); + kept[st] = try tabled(&rig, state, 0, src[st]); + } } else if (n > 0) { sg.pn = sign * @as(c_int, @intCast(n)); sg.plog = try rig.input(if (st == 0) pend0 else f.pend[st]); } } const params = [5]c_int{ 0, 0, @intCast(total), 2, 1 }; // P: the forward's rows, its windows, recorded - const segs_d = try rig.input(std.mem.sliceAsBytes(&segs)); + // the segments, then each one's table where the scans find it + const block = try a.alignedAlloc(u8, .@"8", seg_states + 2 * entries * 8); + defer a.free(block); + @memset(block, 0); + @memcpy(block[0 .. 2 * @sizeOf(Seg)], std.mem.sliceAsBytes(&segs)); + for (0..2) |st| { + const t = table(states[st], befores[st], logs[st]); + @memcpy(block[seg_states + st * entries * 8 ..][0 .. entries * 8], std.mem.sliceAsBytes(&t)); + } + const segs_d = try rig.input(block); const q = try rig.input(std.mem.sliceAsBytes(f.q)); const k = try rig.input(std.mem.sliceAsBytes(f.k)); const v = try rig.input(std.mem.sliceAsBytes(f.v)); @@ -173,7 +222,7 @@ fn launch(gpu: check.Gpu, s: cuda.Stream, apply: ?cuda.Function, scan: cuda.Func if (apply) |ap| { for (0..2) |st| if (src[st] != 0) { var args: cuda.Args = .{}; - inline for (.{ geo, Seg{ .rec = segs[st].rec, .log = src[st] }, f.path[st] }) |x| args.add(x); + inline for (.{ geo, kept[st], f.path[st] }) |x| args.add(x); try cuda.launch.launch(ap, .{ .grid = .{ .x = 1, .y = dk / 4, .z = nv * nl }, .block = .{ .x = 32, .y = 4 } }, s, &args); }; } @@ -185,9 +234,9 @@ fn launch(gpu: check.Gpu, s: cuda.Stream, apply: ?cuda.Function, scan: cuda.Func var out: Out = undefined; for (0..nl) |l| out.y[l] = try a.dupe(u8, try rig.bytes(y[l], total * nv * dk * 2)); for (0..2) |st| { - out.state[st] = try a.dupe(u8, try rig.bytes(segs[st].rec, nl * rec * 4)); - out.log[st] = try a.dupe(u8, try rig.bytes(segs[st].log, f.rows * nl * log_row)); - out.before[st] = if (f.rows == 1) try a.dupe(u8, try rig.bytes(segs[st].before, nl * rec * 4)) else &.{}; + out.state[st] = try a.dupe(u8, try rig.bytes(states[st], nl * rec * 4)); + out.log[st] = try a.dupe(u8, try rig.bytes(logs[st], f.rows * nl * log_row)); + out.before[st] = if (f.rows == 1) try a.dupe(u8, try rig.bytes(befores[st], nl * rec * 4)) else &.{}; } try check.expect(try rig.intact() and !rig.overlap() and std.mem.eql(u8, seen, try rig.inputBytes()), "qwen35 pending: a launch changed an input or a guard", .{}); return out; @@ -212,11 +261,13 @@ fn landed(gpu: check.Gpu, s: cuda.Stream, fun: cuda.Function, from_pend: bool, f try (cuda.DeviceBuffer{ .d = gpu.d, .ptr = state, .len = nl * rec * 4 }).upload(0, std.mem.sliceAsBytes(f.state[0])); const n = f.n[0] - drop; const rows = if (from_pend) (if (n > 0) try rig.input(pend) else 0) else try rig.input(f.src[0]); + var sg = try tabled(&rig, state, 0, if (from_pend) 0 else rows); + if (from_pend) sg.plog = rows; const seen = try a.dupe(u8, try rig.inputBytes()); var args: cuda.Args = .{}; if (from_pend) { - inline for (.{ geo, Seg{ .rec = state, .plog = rows }, @as(c_int, @intCast(n)) }) |x| args.add(x); - } else inline for (.{ geo, Seg{ .rec = state, .log = rows }, f.path[0] }) |x| args.add(x); + inline for (.{ geo, sg, @as(c_int, @intCast(n)) }) |x| args.add(x); + } else inline for (.{ geo, sg, f.path[0] }) |x| args.add(x); try cuda.launch.launch(fun, .{ .grid = .{ .x = 1, .y = dk / 4, .z = nv * nl }, .block = .{ .x = 32, .y = 4 } }, s, &args); const out = try a.dupe(u8, try rig.bytes(state, nl * rec * 4)); try check.expect(try rig.intact() and !rig.overlap() and std.mem.eql(u8, seen, try rig.inputBytes()), "qwen35 pending: a keep launch changed an input or a guard", .{}); @@ -230,10 +281,21 @@ pub fn run(gpu: check.Gpu) !void { defer mod.unload(); var keep = try cuda.Module.load(gpu.d, cuda.kernels.qwen35_keep); defer keep.unload(); - const apply = try keep.function("tf_q35k_apply"); - const apply_pend = try keep.function("tf_q35k_apply_pend"); + for ([_]bool{ false, true }) |t| { + tab = t; + defer tab = false; + try runOne(gpu, s, &mod, &keep); + } +} + +/// Every case on one instantiation (`tab`): main's kernels, or the _table ones. +fn runOne(gpu: check.Gpu, s: cuda.Stream, mod: *cuda.Module, keep: *cuda.Module) !void { + const what = if (tab) "_table" else ""; + std.debug.print("qwen35 pending: the {s} instantiation\n", .{if (tab) "_table (state table)" else "main (Seg's blocks)"}); + const apply = try keep.function(if (tab) "tf_q35k_apply_table" else "tf_q35k_apply"); + const apply_pend = try keep.function(if (tab) "tf_q35k_apply_pend_table" else "tf_q35k_apply_pend"); var fns: [scans.len]cuda.Function = undefined; - inline for (scans, 0..) |sc, i| fns[i] = try mod.function(std.fmt.comptimePrint("tf_q35_gdn_slots_{d}", .{sc.slots})); + inline for (scans, 0..) |sc, i| fns[i] = try mod.function(if (tab) std.fmt.comptimePrint("tf_q35_gdn_slots_{d}_table", .{sc.slots}) else std.fmt.comptimePrint("tf_q35_gdn_slots_{d}", .{sc.slots})); var red: [scans.len + 1][2]bool = @splat(@splat(false)); // each scan's, then tf_q35k_apply_pend's: dropped, swapped var cases: [scans.len]usize = @splat(0); var scratch = std.heap.ArenaAllocator.init(gpu.gpa); @@ -254,7 +316,7 @@ pub fn run(gpu: check.Gpu) !void { red[scans.len][c] = red[scans.len][c] or moved; try check.expect(moved, "qwen35 pending tf_q35k_apply_pend: {s} still landed tf_q35k_apply's state (control missed) at {d} rows", .{ if (c == 0) "a dropped row" else "two swapped rows", n }); }; - std.debug.print("PASS qwen35 pending tf_q35k_apply_pend: {d} rows equal tf_q35k_apply's path, 5 repeats, guards\n", .{n}); + std.debug.print("PASS qwen35 pending tf_q35k_apply_pend{s}: {d} rows equal tf_q35k_apply's path, 5 repeats, guards\n", .{ what, n }); } for (windows, 0..) |win, wi| { var arena = std.heap.ArenaAllocator.init(gpu.gpa); @@ -273,7 +335,7 @@ pub fn run(gpu: check.Gpu) !void { defer _ = scratch.reset(.retain_capacity); const got = try launch(gpu, s, null, scan, sc.r, f, sign, f.pend[0], 0, scratch.allocator()); same(f, sign, got, want) catch |err| { - std.debug.print(" at tf_q35_gdn_slots_{d}, {s}, {d} rows pending, sign {d}\n", .{ sc.slots, win.what, n, sign }); + std.debug.print(" at tf_q35_gdn_slots_{d}{s}, {s}, {d} rows pending, sign {d}\n", .{ sc.slots, what, win.what, n, sign }); return err; }; } @@ -289,10 +351,10 @@ pub fn run(gpu: check.Gpu) !void { cases[si] += 1; ran += 1; } - std.debug.print("PASS qwen35 pending: {s}, {d} rows pending, {d} scans (slot peak {d}): rows out, logs and states equal tf_q35k_apply then the scan, {s}, 5 repeats, guards\n", .{ win.what, n, ran, f.peak, if (f.rows == 1) "written back" else "written back and not" }); + std.debug.print("PASS qwen35 pending{s}: {s}, {d} rows pending, {d} scans (slot peak {d}): rows out, logs and states equal tf_q35k_apply then the scan, {s}, 5 repeats, guards\n", .{ what, win.what, n, ran, f.peak, if (f.rows == 1) "written back" else "written back and not" }); } } for (scans, cases, 0..) |sc, nc, si| try check.expect(nc > 0 and red[si][0] and red[si][1], "qwen35 pending tf_q35_gdn_slots_{d}: no case, or a control never fired", .{sc.slots}); try check.expect(red[scans.len][0] and red[scans.len][1], "qwen35 pending tf_q35k_apply_pend: a control never fired", .{}); - std.debug.print("PASS qwen35 pending: controls RED as planted (a dropped pending row, two swapped) on every scan and tf_q35k_apply_pend\n", .{}); + std.debug.print("PASS qwen35 pending{s}: controls RED as planted (a dropped pending row, two swapped) on every scan and tf_q35k_apply_pend\n", .{what}); } diff --git a/zig/tests/cuda/contract_qwen_table.zig b/zig/tests/cuda/contract_qwen_table.zig new file mode 100644 index 00000000000..a5b4fd9bd50 --- /dev/null +++ b/zig/tests/cuda/contract_qwen_table.zig @@ -0,0 +1,318 @@ +//! qwen35's gdn_pre, conv_commit, gdn_chain, slot scans and tf_q35k_conv: _table on pieces == main's on blocks. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); + +const dk = 128; +const nk = 16; // the 27B's linear key heads +const nv = 48; // and value heads +const nl = 2; // linear layers: every launch runs layer 1, so a table entry's layer counts +const layer = 1; +const taps = 4; +const most = 64; // qwen35.cuh MAXW: a table's log rows +const logs = 8; // log rows the fixture holds (its windows' rows at most) +const width = (2 * nk + nv) * dk; // Geo.conv(): the channels the convolution sees +const tail = (taps - 1) * width; // Geo.conv_rows(): a layer's conv tail +const rec = nv * dk * dk; // floats of one layer's recurrence +const log_bytes = nv * 4 + nv * dk * 4 + nk * dk * 2 + tail * 2; // Geo.log_bytes() +const streams = 2; // a forward's segments: the plants sit in segment 1's table, so its offset counts +const seg_states = 445472; // qwen35.cuh SEG_STATES +const entries = 4 * nl + most; // cuda_cache.zig States: recurrences, tails, both copies, log rows + +// qwen35.cuh's Geo and Seg (contract_qwen_pending.zig mirrors them too) +const Geo = extern struct { hid: c_int, nk: c_int, nv: c_int, qh: c_int, kvh: c_int, nl: c_int }; +const Seg = extern struct { rec: u64 = 0, conv: u64 = 0, kv: u64 = 0, tap: u64 = 0, log: u64 = 0, before: u64 = 0, cap: c_int = 0, len: c_int = 0, row0: c_int = 0, rows: c_int = 0, tap_rows: c_int = 0, taps: c_int = 0, delta: c_int = 0, pt: u64 = 0, ps: u64 = 0, ptok: c_int = 0, pn: c_int = 0, plog: u64 = 0 }; +const geo: Geo = .{ .hid = 0, .nk = nk, .nv = nv, .qh = 0, .kvh = 0, .nl = nl }; + +// A stream's state in main's block layout: recurrences, tails, pre-round recurrences then tails, log rows. +const at_conv = nl * rec * 4; +const at_before = at_conv + nl * tail * 2; +const at_log = at_before + nl * rec * 4 + nl * tail * 2; +const state_bytes = at_log + logs * nl * log_bytes; + +const Kernel = enum { pre, commit, chain, conv, slots1, slots2 }; +const names = [_][:0]const u8{ "tf_q35_gdn_pre", "tf_q35_conv_commit", "tf_q35_gdn_chain", "tf_q35k_conv", "tf_q35_gdn_slots_1", "tf_q35_gdn_slots_2" }; +const tables = [_][:0]const u8{ "tf_q35_gdn_pre_table", "tf_q35_conv_commit_table", "tf_q35_gdn_chain_table", "tf_q35k_conv_table", "tf_q35_gdn_slots_1_table", "tf_q35_gdn_slots_2_table" }; +/// Each kernel's planted fault in segment 1's table: layer 1's entry pointing at layer 0's piece, or another log row. +const plants = [_][]const u8{ "the tail entry", "the tail entry", "the recurrence entry", "the log row entry", "the log row entry", "the log row entry" }; +/// A slot scan's register slots (deltaScan's selection): it runs recorded windows whose tree fits them. +fn slotCount(k: Kernel) ?usize { + return switch (k) { + .slots1 => 1, + .slots2 => 2, + else => null, + }; +} + +const decode_row = [_]i32{-1}; +const chain4 = [_]i32{ -1, 0, 1, 2 }; +const tree8 = [_]i32{ -1, 0, 0, 2, 2, 4, 4, 6 }; // a drafted tree: a true row has a junk leaf and the next +const Window = struct { what: []const u8, parents: []const i32 }; +const windows = [_]Window{ + .{ .what = "a decode row", .parents = &decode_row }, + .{ .what = "a 4-row chain", .parents = &chain4 }, + .{ .what = "an 8-row drafted tree", .parents = &tree8 }, +}; + +fn bf16(x: f32) u16 { + return @truncate(@as(u32, @bitCast(x)) >> 16); +} + +fn fillBf16(rng: std.Random, out: []align(1) u16) void { + for (out) |*x| x.* = bf16(rng.float(f32) * 2 - 1); +} + +/// A stream's starting state: random recurrences, tails and copies; log rows with decays near 1. +fn startState(a: std.mem.Allocator, rng: std.Random) ![]u8 { + const s = try a.alignedAlloc(u8, .@"8", state_bytes); + for (std.mem.bytesAsSlice(f32, s[0..at_conv])) |*x| x.* = rng.float(f32) * 2 - 1; + fillBf16(rng, std.mem.bytesAsSlice(u16, s[at_conv..at_before])); + for (std.mem.bytesAsSlice(f32, s[at_before..][0 .. nl * rec * 4])) |*x| x.* = rng.float(f32) * 2 - 1; + fillBf16(rng, std.mem.bytesAsSlice(u16, s[at_before + nl * rec * 4 .. at_log])); + for (0..logs * nl) |i| { + const r = s[at_log + i * log_bytes ..][0..log_bytes]; + for (std.mem.bytesAsSlice(f32, r[0 .. nv * 4 + nv * dk * 4]), 0..) |*x, j| x.* = if (j < nv) 0.9 + rng.float(f32) / 10 else rng.float(f32) * 2 - 1; + fillBf16(rng, std.mem.bytesAsSlice(u16, r[nv * 4 + nv * dk * 4 ..])); + } + return s; +} + +/// One device allocation holding bytes [off, off + len) of a stream's block-layout state. +const Piece = struct { off: usize, len: usize, ptr: u64 }; + +/// A stream's state on the device: main's four blocks, or one piece a layer's region and a log row (in reverse). +const Placed = struct { + pieces: [4 * nl + logs]Piece = undefined, + n: usize = 0, + seg: Seg = .{}, // main: the blocks + table: [entries]u64 = @splat(0), // _table: every piece's address + + fn add(p: *Placed, rig: *rig_.Rig, state: []const u8, off: usize, len: usize) !u64 { + const ptr = try rig.scratch(len); + try (cuda.DeviceBuffer{ .d = rig.gpu.d, .ptr = ptr, .len = len }).upload(0, state[off..][0..len]); + p.pieces[p.n] = .{ .off = off, .len = len, .ptr = ptr }; + p.n += 1; + return ptr; + } + + fn make(rig: *rig_.Rig, state: []const u8, tab: bool) !Placed { + var p: Placed = .{}; + if (!tab) { + p.seg.rec = try p.add(rig, state, 0, at_conv); + p.seg.conv = try p.add(rig, state, at_conv, nl * tail * 2); + p.seg.before = try p.add(rig, state, at_before, at_log - at_before); + p.seg.log = try p.add(rig, state, at_log, logs * nl * log_bytes); + return p; + } + var l: usize = nl; + while (l > 0) { + l -= 1; + p.table[l] = try p.add(rig, state, l * rec * 4, rec * 4); + p.table[nl + l] = try p.add(rig, state, at_conv + l * tail * 2, tail * 2); + p.table[2 * nl + l] = try p.add(rig, state, at_before + l * rec * 4, rec * 4); + p.table[3 * nl + l] = try p.add(rig, state, at_before + nl * rec * 4 + l * tail * 2, tail * 2); + } + var r: usize = logs; + while (r > 0) { + r -= 1; + p.table[4 * nl + r] = try p.add(rig, state, at_log + r * nl * log_bytes, nl * log_bytes); + } + return p; + } + + /// The state back in block layout. + fn gather(p: Placed, rig: *rig_.Rig, a: std.mem.Allocator) ![]u8 { + const out = try a.alloc(u8, state_bytes); + @memset(out, 0); + for (p.pieces[0..p.n]) |pc| @memcpy(out[pc.off..][0..pc.len], try rig.bytes(pc.ptr, pc.len)); + return out; + } +}; + +/// The planted fault in a table: `k`'s entry of layer 1 now names layer 0's piece, or log row `row` another row. +fn plant(t: *[entries]u64, k: Kernel, row: usize) void { + switch (k) { + .pre, .commit => t[nl + layer] = t[nl], + .chain => t[layer] = t[0], + .conv, .slots1, .slots2 => t[4 * nl + row] = t[4 * nl + (row + 1) % logs], + } +} + +/// One case's inputs: a window per stream, the forward's rows and the inputs its launches read. +const Case = struct { + rows: usize, + record: bool, + last: usize, // tf_q35k_conv's kept row + rowseg: []i32, + rowpar: []i32, + steps: []core.tree_slots.Step, // the slot scans' schedule, a stream's window at a time + peak: usize, // register slots it holds at once + state: [streams][]u8, + qkv: []u16, + cw: []u16, + ain: []u16, + bin: []u16, + alog: []f32, + dt: []u16, + q: []u16, + k: []u16, + v: []u16, + g: []f32, + beta: []u16, + + fn make(a: std.mem.Allocator, parents: []const i32, record: bool, last: usize, seed: u64) !Case { + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const rows = parents.len; + const total = streams * rows; + var c: Case = undefined; + c.rows = rows; + c.record = record; + c.last = last; + c.rowseg = try a.alloc(i32, total); + c.rowpar = try a.alloc(i32, total); + for (0..streams) |st| for (parents, 0..) |p, i| { + c.rowseg[st * rows + i] = @intCast(st); + c.rowpar[st * rows + i] = if (p < 0) -1 else @as(i32, @intCast(st * rows)) + p; + }; + c.steps = try a.alloc(core.tree_slots.Step, total); + c.peak = 0; + for (0..streams) |st| c.peak = @max(c.peak, try core.tree_slots.build(a, parents, c.steps[st * rows ..][0..rows], @intCast(st * rows), core.tree_slots.max_slots)); + for (&c.state) |*s| s.* = try startState(a, rng); + inline for (.{ .{ "qkv", total * width }, .{ "cw", width * taps }, .{ "ain", total * nv }, .{ "bin", total * nv }, .{ "dt", nv }, .{ "q", total * nk * dk }, .{ "k", total * nk * dk }, .{ "v", total * nv * dk }, .{ "beta", total * nv } }) |f| { + @field(c, f[0]) = try a.alloc(u16, f[1]); + fillBf16(rng, @field(c, f[0])); + } + c.alog = try a.alloc(f32, nv); + for (c.alog) |*x| x.* = rng.float(f32) - 0.5; + c.g = try a.alloc(f32, total * nv); + for (c.g) |*x| x.* = 0.9 + rng.float(f32) / 10; + return c; + } +}; + +/// One launch of `fun` (main's or _table) on the case: its outputs, then each stream's state in block layout. +fn launch(gpu: check.Gpu, s: cuda.Stream, k: Kernel, fun: cuda.Function, tab: bool, planted: bool, c: Case, a: std.mem.Allocator) ![]const []const u8 { + var rig = rig_.Rig{ .gpu = gpu, .s = s }; + defer rig.deinit(); + const total = streams * c.rows; + var placed: [streams]Placed = undefined; + for (&placed, c.state) |*p, st| p.* = try Placed.make(&rig, st, tab); + // segment 1 keeps row last + 1; a slot scan's plant moves its window's last row + if (planted) plant(&placed[1].table, k, if (slotCount(k) != null) c.rows - 1 else c.last + 1); + var outs: std.ArrayList([]const u8) = .empty; + var y: [5]u64 = @splat(0); + if (k == .conv) { + var segs: [streams]Seg = undefined; + for (&segs, placed) |*sg, p| sg.* = if (tab) .{ .rec = try rig.input(std.mem.sliceAsBytes(&p.table)) } else p.seg; + const seen = try a.dupe(u8, try rig.inputBytes()); + for (segs, 0..) |sg, st| { + var args: cuda.Args = .{}; + inline for (.{ geo, sg, @as(c_int, @intCast(c.last + st)) }) |x| args.add(x); + try cuda.launch.launch(fun, .{ .grid = .{ .x = nl, .y = (tail + 255) / 256, .z = 1 }, .block = .{ .x = 256 } }, s, &args); + } + try check.expect(std.mem.eql(u8, seen, try rig.inputBytes()), "qwen35 table tf_q35k_conv: a launch changed an input", .{}); + } else { + // the forward's segments, then (_table) each one's table where forward_states finds it; Seg's blocks 0 there + const block = try a.alignedAlloc(u8, .@"8", seg_states + streams * entries * 8); + @memset(block, 0); + var segs: [streams]Seg = undefined; + for (&segs, placed, 0..) |*sg, p, st| { + sg.* = if (tab) .{ .before = p.table[2 * nl] } else p.seg; // segIn: before != 0 keeps a one-row copy + sg.row0 = @intCast(st * c.rows); + sg.rows = @intCast(c.rows); + if (tab) @memcpy(block[seg_states + st * entries * 8 ..][0 .. entries * 8], std.mem.sliceAsBytes(&p.table)); + } + @memcpy(block[0 .. streams * @sizeOf(Seg)], std.mem.sliceAsBytes(&segs)); + const segs_d = try rig.input(if (tab) block else block[0 .. streams * @sizeOf(Seg)]); + const params = [5]c_int{ 0, 0, @intCast(total), streams, @intFromBool(c.record) }; // P: rows, windows, recorded + const p_d = try rig.input(std.mem.sliceAsBytes(¶ms)); + const par = try rig.input(std.mem.sliceAsBytes(c.rowpar)); + var in: [11]u64 = undefined; // qkv, rowseg, cw, ain, bin, alog, dt, q, k, v, g; beta follows + inline for (.{ c.qkv, c.rowseg, c.cw, c.ain, c.bin, c.alog, c.dt, c.q, c.k, c.v, c.g }, 0..) |x, i| in[i] = try rig.input(std.mem.sliceAsBytes(x)); + const beta = try rig.input(std.mem.sliceAsBytes(c.beta)); + const steps = try rig.input(std.mem.sliceAsBytes(c.steps)); // the slot scans' + const sizes = [5]usize{ total * nk * dk * 2, total * nk * dk * 2, total * nv * dk * 2, total * nv * 4, total * nv * 2 }; + if (k == .pre) { + for (&y, sizes) |*o, n| o.* = try rig.output(n); + } else if (k == .chain or slotCount(k) != null) y[0] = try rig.output(total * nv * dk * 2); + const seen = try a.dupe(u8, try rig.inputBytes()); + var args: cuda.Args = .{}; + switch (k) { + .pre => { + inline for (.{ geo, in[0], segs_d, in[1], par, @as(c_int, layer), in[2], in[3], in[4], in[5], in[6], y[0], y[1], y[2], y[3], y[4], p_d }) |x| args.add(x); + try cuda.launch.launch(fun, .{ .grid = .{ .x = 1, .y = 2 * nk + nv, .z = @intCast(total) }, .block = .{ .x = 32 } }, s, &args); + for (y, sizes) |o, n| try outs.append(a, try a.dupe(u8, try rig.bytes(o, n))); + }, + .commit => { + inline for (.{ geo, in[0], segs_d, par, @as(c_int, layer), p_d }) |x| args.add(x); + try cuda.launch.launch(fun, .{ .grid = .{ .x = (width + 255) / 256, .y = streams, .z = 1 }, .block = .{ .x = 256 } }, s, &args); + }, + .chain => { + inline for (.{ geo, in[7], in[8], in[9], in[10], beta, segs_d, par, @as(c_int, layer), y[0], p_d }) |x| args.add(x); + try cuda.launch.launch(fun, .{ .grid = .{ .x = 1, .y = dk / 4, .z = nv * streams }, .block = .{ .x = 32, .y = 4 } }, s, &args); + try outs.append(a, try a.dupe(u8, try rig.bytes(y[0], total * nv * dk * 2))); + }, + .slots1, .slots2 => { + inline for (.{ geo, in[7], in[8], in[9], in[10], beta, segs_d, steps, @as(c_int, layer), y[0], p_d }) |x| args.add(x); + // deltaScan's grid: up to four slots scan two value rows a warp + try cuda.launch.launch(fun, .{ .grid = .{ .x = 1, .y = dk / 8, .z = nv * streams }, .block = .{ .x = 32, .y = 4 } }, s, &args); + try outs.append(a, try a.dupe(u8, try rig.bytes(y[0], total * nv * dk * 2))); + }, + .conv => unreachable, + } + try check.expect(std.mem.eql(u8, seen, try rig.inputBytes()), "qwen35 table {s}: a launch changed an input", .{names[@backingInt(k)]}); + } + for (placed) |p| try outs.append(a, try p.gather(&rig, a)); + try check.expect(try rig.intact() and !rig.overlap(), "qwen35 table {s}: a launch wrote past a buffer", .{names[@backingInt(k)]}); + return outs.items; +} + +fn equal(x: []const []const u8, y: []const []const u8) bool { + if (x.len != y.len) return false; + for (x, y) |p, q| if (!std.mem.eql(u8, p, q)) return false; + return true; +} + +pub fn run(gpu: check.Gpu) !void { + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var mod = try cuda.Module.load(gpu.d, cuda.kernels.qwen35); + defer mod.unload(); + var keep = try cuda.Module.load(gpu.d, cuda.kernels.qwen35_keep); + defer keep.unload(); + var red: [names.len]bool = @splat(false); + for (names, 0..) |name, ki| { + const k: Kernel = @fromBackingInt(@intCast(ki)); + const m = if (k == .conv) &keep else &mod; + const main_fn = try m.function(name); + const tab_fn = try m.function(tables[ki]); + for (windows, 0..) |win, wi| for ([_]bool{ false, true }) |record| { + if (slotCount(k) != null and !record) continue; // deltaScan runs a slot scan on recorded windows only + var arena = std.heap.ArenaAllocator.init(gpu.gpa); + defer arena.deinit(); + const a = arena.allocator(); + const last = (wi * 3) % (logs - 1); // tf_q35k_conv: stream 0 keeps row last, stream 1 row last + 1 + const c = try Case.make(a, win.parents, record, last, 0x7ab1 + 16 * ki + 2 * wi + @intFromBool(record)); + if (slotCount(k)) |n| if (c.peak > n) continue; + const want = try launch(gpu, s, k, main_fn, false, false, c, a); + for (0..3) |_| { + const got = try launch(gpu, s, k, tab_fn, true, false, c, a); + for (got, want, 0..) |x, w, i| check.sameBytes("qwen35 table: _table on pieces against main on blocks", x, w) catch |err| { + std.debug.print(" at {s}_table, {s}, recorded {}, output {d}\n", .{ name, win.what, record, i }); + return err; + }; + } + // a recorded window of 2+ rows: conv_commit returns early (gdn_pre logged the tails), no plant can show + const live = !(k == .commit and record and c.rows != 1); + const moved = !equal(try launch(gpu, s, k, tab_fn, true, true, c, a), want); + red[ki] = red[ki] or moved; + try check.expect(moved == live, "qwen35 table {s}_table: {s} planted in segment 1's table {s} (control) at {s}, recorded {}", .{ name, plants[ki], if (live) "still gave main's bytes" else "changed a launch that returns early", win.what, record }); + std.debug.print("PASS qwen35 table {s}_table: {s}, recorded {}: outputs and both streams' state on pieces equal {s} on blocks, 3 repeats, guards\n", .{ name, win.what, record, name }); + }; + } + for (names, red, plants) |name, r, p| try check.expect(r, "qwen35 table {s}_table: the control ({s}) never fired", .{ name, p }); + std.debug.print("PASS qwen35 table: controls RED as planted (gdn_pre and conv_commit: tail entry; gdn_chain: recurrence entry; tf_q35k_conv and slot scans: log row entry)\n", .{}); +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 22340b7ec49..e01fd5b8389 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -384,6 +384,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "clef")) return @import("clef_tests.zig").run(gpu, rest); if (std.mem.startsWith(u8, cmd, "dots-")) return @import("dots_tests.zig").run(gpu, cmd, rest); if (std.mem.eql(u8, cmd, "qwen-pending")) return @import("contract_qwen_pending.zig").run(gpu); + if (std.mem.eql(u8, cmd, "qwen-table")) return @import("contract_qwen_table.zig").run(gpu); if (std.mem.eql(u8, cmd, "dspine-table")) return @import("dspine_table_tests.zig").runAll(gpu); if (std.mem.eql(u8, cmd, "minimax-contract")) return @import("contract_minimax.zig").run(gpu); if (try ripple.run(gpu, cmd)) return; diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index dca628c91e4..4e805d8ede3 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -161,6 +161,7 @@ pub const usage = \\ clef tiny DIR | head MODEL CASES OUT [--piece N] Clef's joint schema head: the tiny fixture, gate 3's logits \\ dots-help dots.mocr's tower and image prompt checks (dots-*): their usage \\ qwen-pending qwen35's pending kept rows: the slot scans and tf_q35k_apply_pend == tf_q35k_apply, red controls + \\ qwen-table qwen35's gdn_pre, conv_commit, gdn_chain, tf_q35k_conv: _table on pieces == main's, red controls \\ rope-yarn YaRN rope in tf_q35_rope, tf_q35_rope8 and tf_q36m_norm_rope against float64, to 1M \\ kernel-contract-limits DIR each registered launch against release SMs or sm_110 in DIR's fatbins \\ pocket-contract Nemotron's pocket kernels (learned neurons) through gates 1-4, controls red diff --git a/zig/tests/qwen35_mtp_cuda.zig b/zig/tests/qwen35_mtp_cuda.zig index 93ad27e29a1..65983c61a63 100644 --- a/zig/tests/qwen35_mtp_cuda.zig +++ b/zig/tests/qwen35_mtp_cuda.zig @@ -49,7 +49,7 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, e: *E.Engine, dir: []const u8, id const last_rows = test_ids.len - last_start; const comparable_rows = last_rows - 1; if (comparable_rows > 0) { - const seg = cache.seg(e, last_start, 0, comparable_rows); + const seg = try cache.seg(e, last_start, 0, comparable_rows); std.debug.print(" tap check setup: n_taps={d} layer={d}/{d} mode={s} cache={d}/{d} tap_ptr=0x{x} seg.tap=0x{x} seg.taps={d} seg.len={d} rows={d}\n", .{ e.n_taps, e.taps[0],