From 9eb4dac35f46c462c7dda9a9ba8adfdb560afe91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Thu, 29 Oct 2026 12:17:38 +0100 Subject: [PATCH 1/5] cuda: tree attention reads committed keys from a page table (_pg kernels), SASS of the others unchanged --- zig/kernels/cuda/common/kv_pages.cuh | 13 +++ zig/kernels/cuda/tree_attention.cu | 99 ++++++++++++------- zig/kernels/cuda/window_rows.cuh | 9 +- .../contract/registry_shared_attention.zig | 14 ++- zig/src/cuda/tree_attention.zig | 52 ++++++---- zig/tests/cuda/tree_tests.zig | 70 ++++++++++--- 6 files changed, 188 insertions(+), 69 deletions(-) create mode 100644 zig/kernels/cuda/common/kv_pages.cuh diff --git a/zig/kernels/cuda/common/kv_pages.cuh b/zig/kernels/cuda/common/kv_pages.cuh new file mode 100644 index 00000000000..ee8d727ba2e --- /dev/null +++ b/zig/kernels/cuda/common/kv_pages.cuh @@ -0,0 +1,13 @@ +// A paged cache's address: a stream's table row of page ids, elements a page holds across its caches, positions a page. +#pragma once + +namespace tf_common { + +struct Pg { + const int* tab; + long long page; + int tok; + int stride; // table entries a slot (decode); a prompt kernel is given its stream's row +}; + +} // namespace tf_common diff --git a/zig/kernels/cuda/tree_attention.cu b/zig/kernels/cuda/tree_attention.cu index 2539d6210ce..a0c818960fd 100644 --- a/zig/kernels/cuda/tree_attention.cu +++ b/zig/kernels/cuda/tree_attention.cu @@ -6,11 +6,13 @@ #include #include "attn_odd.cuh" +#include "common/kv_pages.cuh" #include "common/qmm_frag.cuh" #include "common/cp_async.cuh" namespace tf_tree { +using tf_common::Pg; using qmm_frag::commit; using qmm_frag::cp16z; using qmm_frag::ldmatrix4; @@ -55,13 +57,13 @@ extern "C" __global__ void tf_tree_paths(const int* __restrict__ parents, int* _ } // Group gi of key head kh for 16 (row, head) pairs from pf (m: row rq + m / G, head m % G); !ODD true: run tree_odd. -template +template __device__ __forceinline__ bool tree_group( const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ kn, const __nv_bfloat16* __restrict__ vn, const __nv_bfloat16* __restrict__ origin, const long long* __restrict__ offs, const int* __restrict__ row_stream, const int* __restrict__ streams, const int* __restrict__ paths, const int* __restrict__ depths, float* __restrict__ po, float* __restrict__ pm, float* __restrict__ pl, int h, int hk, float scale, int gi, int ng, - int64_t rq, int pf, int npairs, int64_t row, int slice) { + int64_t rq, int pf, int npairs, int64_t row, int slice, const P&... pg) { constexpr int C = D / 8, K16 = D / 16, NB = D / 8, NT8 = HB / 8, PK = HB / 16; constexpr bool QREG = D <= 128; extern __shared__ uint4 smem[]; @@ -75,6 +77,14 @@ __device__ __forceinline__ bool tree_group( if (k0 >= total) return false; // the merge reads only the row's own groups const __nv_bfloat16* kc = origin + offs[2 * s]; const __nv_bfloat16* vc = origin + offs[2 * s + 1]; + // committed key `key` of K or V part c: in its stream's run, or (PG) at its page's slot of the stream's table row + const auto committed = [&](const __nv_bfloat16* c, int key) { + if constexpr (sizeof...(P) != 0) { + const Pg& t = (pg, ...); + return c + (int64_t)t.tab[s * t.stride + key / t.tok] * t.page + ((int64_t)(key % t.tok) * hk + kh) * D; + } else + return c + ((int64_t)key * hk + kh) * D; + }; // ST tile stages: a one-warp block fetches ST - 1 tiles ahead while it computes one (stages never change bits) uint4* const kv0 = smem + warp * ST * 2 * HB * C; uint4* ks = kv0; @@ -117,8 +127,8 @@ __device__ __forceinline__ bool tree_group( const __nv_bfloat16* ksrc; const __nv_bfloat16* vsrc; if (key < p) { - ksrc = kc + ((int64_t)key * hk + kh) * D; - vsrc = vc + ((int64_t)key * hk + kh) * D; + ksrc = committed(kc, key); + vsrc = committed(vc, key); } else { // the row's own path: key p + j is path row j const int node = in ? paths[r * MAXD + (key - p)] : 0; ksrc = kn + ((int64_t)node * hk + kh) * D; @@ -240,12 +250,18 @@ __device__ __forceinline__ bool tree_group( } else { // key k of the group's row: committed, then the row's path; pair m: row rq + (pf + m) / G, head (pf + m) % G const auto at = [&](const __nv_bfloat16* c, const __nv_bfloat16* n, int k) { - return k < p ? c + ((int64_t)k * hk + kh) * D : n + ((int64_t)paths[r * MAXD + (k - p)] * hk + kh) * D; + if constexpr (sizeof...(P) != 0) // the replay's own expressions when not paged: its code as before + return k < p ? committed(c, k) : n + ((int64_t)paths[r * MAXD + (k - p)] * hk + kh) * D; + else + return k < p ? c + ((int64_t)k * hk + kh) * D : n + ((int64_t)paths[r * MAXD + (k - p)] * hk + kh) * D; }; const auto qrow = [&](int m) { return q + ((rq + (pf + m) / G) * h + kh * G + (pf + m) % G) * D; }; const auto each = [&](int m, auto f) { // pair m's keys: its stream's committed ones, then its own row's path const int64_t pr = rq + (pf + m) / G; - for (int k = 0; k < p; ++k) f(kc + ((int64_t)k * hk + kh) * D); + if constexpr (sizeof...(P) != 0) + for (int k = 0; k < p; ++k) f(committed(kc, k)); + else + for (int k = 0; k < p; ++k) f(kc + ((int64_t)k * hk + kh) * D); for (int j = 0; j < depths[pr]; ++j) f(kn + ((int64_t)paths[pr * MAXD + j] * hk + kh) * D); }; auto w = attn_odd::weights(qrow, each, scale, lane); @@ -318,25 +334,29 @@ __device__ __forceinline__ bool tree_group( } // A block with a NaN or infinite partial, again as ODD: those values out of the mma, added back at float64's weights. -template +template __device__ __noinline__ void tree_odd( const __nv_bfloat16* q, const __nv_bfloat16* kn, const __nv_bfloat16* vn, const __nv_bfloat16* origin, const long long* offs, const int* row_stream, const int* streams, const int* paths, const int* depths, float* po, float* pm, float* pl, int h, int hk, float scale, int gi, int ng, int64_t rq, int pf, int npairs, int64_t row, - int slice) { + int slice, P... pg) { tree_group(q, kn, vn, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, scale, - gi, ng, rq, pf, npairs, row, slice); + gi, ng, rq, pf, npairs, row, slice, pg...); } // A stream's full committed groups once for its rows, 16 (row, head) pairs a block: each partial a row block's bits. -template +template __device__ __forceinline__ void tree_shared( const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ origin, const long long* __restrict__ offs, const int* __restrict__ row_stream, const int* __restrict__ streams, const int* __restrict__ paths, const int* __restrict__ depths, float* __restrict__ po, float* __restrict__ pm, float* __restrict__ pl, int h, int hk, - float scale, int ng, int n, const __nv_bfloat16* __restrict__ kn) { + float scale, int ng, int n, const __nv_bfloat16* __restrict__ kn, P... pg) { const int G = h / hk; const int per = W == 4 ? 1 : 4; // slices an item takes a block + const auto odd = [&](const __nv_bfloat16* v, int gi, int64_t rq, int pf, int npairs, int64_t row, int slice) { + tree_odd(q, kn, v, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, scale, gi, ng, + rq, pf, npairs, row, slice, pg...); + }; for (int item = blockIdx.x; item < n * ng * per; item += gridDim.x) { // (row, group[, slice]): a fixed grid const int64_t r = item / per / ng; const int gi = item / per % ng; @@ -347,22 +367,26 @@ __device__ __forceinline__ void tree_shared( if (tile * 16 >= pairs || (gi + 1) * SPAN > p) continue; // vn: never read, a full committed group has no path keys (the replay weighs them, from kn) if (tree_group(q, kn, q, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, - scale, gi, ng, r0, tile * 16, pairs, r, item % per)) - tree_odd(q, kn, q, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, scale, gi, - ng, r0, tile * 16, pairs, r, item % per); + scale, gi, ng, r0, tile * 16, pairs, r, item % per, pg...)) + odd(q, gi, r0, tile * 16, pairs, r, item % per); __syncthreads(); } } +#define TF_TREE_SHARED_ARGS \ + const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ origin, const long long* __restrict__ offs, \ + const int* __restrict__ row_stream, const int* __restrict__ streams, const int* __restrict__ paths, \ + const int* __restrict__ depths, float* __restrict__ po, float* __restrict__ pm, float* __restrict__ pl, int h, \ + int hk, float scale, int ng, int n, const __nv_bfloat16* __restrict__ kn #define TF_TREE_SHARED(NAME, D, HB, W, ST) \ - extern "C" __global__ void __launch_bounds__(32 * W) NAME( \ - const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ origin, \ - const long long* __restrict__ offs, const int* __restrict__ row_stream, const int* __restrict__ streams, \ - const int* __restrict__ paths, const int* __restrict__ depths, float* __restrict__ po, \ - float* __restrict__ pm, float* __restrict__ pl, int h, int hk, float scale, int ng, int n, \ - const __nv_bfloat16* __restrict__ kn) { \ + extern "C" __global__ void __launch_bounds__(32 * W) NAME(TF_TREE_SHARED_ARGS) { \ tree_shared(q, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, scale, ng, n, \ kn); \ + } \ + extern "C" __global__ void __launch_bounds__(32 * W) \ + NAME##_pg(TF_TREE_SHARED_ARGS, const int* __restrict__ tab, long long page, int tok, int stride) { \ + tree_shared(q, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, scale, \ + ng, n, kn, Pg{tab, page, tok, stride}); \ } TF_TREE_SHARED(tf_tree_shared, 128, 32, 4, 1) @@ -373,33 +397,42 @@ TF_TREE_SHARED(tf_tree_shared_w1s3, 128, 32, 1, 3) TF_TREE_SHARED(tf_tree_shared_256_w1s3, 256, 16, 1, 3) // Block (row, key head, group slot): the row's groups past its stream's full committed ones, slot, slot + slots, ... -template +template __device__ __forceinline__ void tree_part( const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ kn, const __nv_bfloat16* __restrict__ vn, const __nv_bfloat16* __restrict__ origin, const long long* __restrict__ offs, const int* __restrict__ row_stream, const int* __restrict__ streams, const int* __restrict__ paths, const int* __restrict__ depths, - float* __restrict__ po, float* __restrict__ pm, float* __restrict__ pl, int h, int hk, float scale, int ng) { + float* __restrict__ po, float* __restrict__ pm, float* __restrict__ pl, int h, int hk, float scale, int ng, P... pg) { const int64_t r = blockIdx.x; const int p = streams[4 * row_stream[r] + 2], total = p + depths[r]; const int per = W == 4 ? 1 : 4, slot = blockIdx.z / per, slots = gridDim.z / per; + const auto odd = [&](const __nv_bfloat16* v, int gi, int64_t rq, int pf, int npairs, int64_t row, int slice) { + tree_odd(q, kn, v, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, scale, gi, ng, + rq, pf, npairs, row, slice, pg...); + }; for (int gi = slot + p / SPAN; gi < ng && gi * SPAN < total; gi += slots) { // full committed: shared if (tree_group(q, kn, vn, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, - scale, gi, ng, r, 0, h / hk, r, blockIdx.z % per)) - tree_odd(q, kn, vn, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, scale, gi, - ng, r, 0, h / hk, r, blockIdx.z % per); + scale, gi, ng, r, 0, h / hk, r, blockIdx.z % per, pg...)) + odd(vn, gi, r, 0, h / hk, r, blockIdx.z % per); __syncthreads(); // the next group's tiles reuse the partials' shared memory } } -#define TF_TREE_PART(NAME, D, HB, W, ST) \ - extern "C" __global__ void __launch_bounds__(32 * W) NAME( \ - const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ kn, \ - const __nv_bfloat16* __restrict__ vn, const __nv_bfloat16* __restrict__ origin, \ - const long long* __restrict__ offs, const int* __restrict__ row_stream, const int* __restrict__ streams, \ - const int* __restrict__ paths, const int* __restrict__ depths, float* __restrict__ po, \ - float* __restrict__ pm, float* __restrict__ pl, int h, int hk, float scale, int ng) { \ +#define TF_TREE_PART_ARGS \ + const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ kn, const __nv_bfloat16* __restrict__ vn, \ + const __nv_bfloat16* __restrict__ origin, const long long* __restrict__ offs, \ + const int* __restrict__ row_stream, const int* __restrict__ streams, const int* __restrict__ paths, \ + const int* __restrict__ depths, float* __restrict__ po, float* __restrict__ pm, float* __restrict__ pl, int h, \ + int hk, float scale, int ng +#define TF_TREE_PART(NAME, D, HB, W, ST) \ + extern "C" __global__ void __launch_bounds__(32 * W) NAME(TF_TREE_PART_ARGS) { \ tree_part(q, kn, vn, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, scale, \ - ng); \ + ng); \ + } \ + extern "C" __global__ void __launch_bounds__(32 * W) \ + NAME##_pg(TF_TREE_PART_ARGS, const int* __restrict__ tab, long long page, int tok, int stride) { \ + tree_part(q, kn, vn, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, \ + scale, ng, Pg{tab, page, tok, stride}); \ } TF_TREE_PART(tf_tree_part, 128, 32, 4, 1) diff --git a/zig/kernels/cuda/window_rows.cuh b/zig/kernels/cuda/window_rows.cuh index fb369b2dd4f..0a2524f58e5 100644 --- a/zig/kernels/cuda/window_rows.cuh +++ b/zig/kernels/cuda/window_rows.cuh @@ -6,6 +6,7 @@ #include #include +#include "common/kv_pages.cuh" #include "common/qmm_frag.cuh" #include "common/cp_async.cuh" #include "window_fallback.h" @@ -29,13 +30,7 @@ enum Fault : int { TRUNC = 4, // the merge's output rounded toward zero }; -// A paged cache's address: a stream's table row of page ids, elements a page holds across its caches, positions a page. -struct Pg { - const int* tab; - long long page; - int tok; - int stride; // table entries a slot (decode); a prompt kernel is given its stream's row -}; +using tf_common::Pg; // common/kv_pages.cuh using qmm_frag::commit; using qmm_frag::cp16z; diff --git a/zig/src/core/contract/registry_shared_attention.zig b/zig/src/core/contract/registry_shared_attention.zig index 79350081930..e2dc834d58a 100644 --- a/zig/src/core/contract/registry_shared_attention.zig +++ b/zig/src/core/contract/registry_shared_attention.zig @@ -1,7 +1,7 @@ //! The shared attention, sigmoid routing and dense-row CUDA launch records; values retained from their fixtures. const std = @import("std"); const wattn_symbol = "_ZN16tf_window_prompt12wattn_kernelILi128ELi8ELi{d}ELi8EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifii"; -pub fn records(comptime Record: type) [27]Record { +pub fn records(comptime Record: type) [39]Record { return .{ .{ .launch = .{ .name = "tree attention tf_tree_paths", .symbol = "tf_tree_paths", .image = "tree_attention", .threads = 128 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 } } }, .{ .launch = .{ .name = "tree attention tf_tree_shared", .symbol = "tf_tree_shared", .image = "tree_attention", .threads = 128, .dynamic = 65536, .opt_in = true }, .usage = .{ .{ .regs = 202, .static = 0, .bound = 128 }, .{ .regs = 202, .static = 0, .bound = 128 }, .{ .regs = 202, .static = 0, .bound = 128 }, .{ .regs = 212, .static = 0, .bound = 128 }, .{ .regs = 212, .static = 0, .bound = 128 } } }, @@ -17,6 +17,18 @@ pub fn records(comptime Record: type) [27]Record { .{ .launch = .{ .name = "tree attention tf_tree_part_256_w1", .symbol = "tf_tree_part_256_w1", .image = "tree_attention", .threads = 32, .dynamic = 40960, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 253, .static = 0, .bound = 32 }, .{ .regs = 253, .static = 0, .bound = 32 } } }, .{ .launch = .{ .name = "tree attention tf_tree_part_256_w1s3", .symbol = "tf_tree_part_256_w1s3", .image = "tree_attention", .threads = 32, .dynamic = 57344, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 251, .static = 0, .bound = 32 }, .{ .regs = 251, .static = 0, .bound = 32 } } }, .{ .launch = .{ .name = "tree attention tf_tree_merge", .symbol = "tf_tree_merge", .image = "tree_attention", .threads = 256 }, .usage = .{ .{ .regs = 114, .static = 0, .bound = 256 }, .{ .regs = 114, .static = 0, .bound = 256 }, .{ .regs = 114, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_shared_pg", .symbol = "tf_tree_shared_pg", .image = "tree_attention", .threads = 128, .dynamic = 65536, .opt_in = true }, .usage = .{ .{ .regs = 199, .static = 0, .bound = 128 }, .{ .regs = 199, .static = 0, .bound = 128 }, .{ .regs = 199, .static = 0, .bound = 128 }, .{ .regs = 208, .static = 0, .bound = 128 }, .{ .regs = 208, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_shared_w1_pg", .symbol = "tf_tree_shared_w1_pg", .image = "tree_attention", .threads = 32, .dynamic = 32768, .opt_in = true }, .usage = .{ .{ .regs = 195, .static = 0, .bound = 32 }, .{ .regs = 195, .static = 0, .bound = 32 }, .{ .regs = 195, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_shared_w1s3_pg", .symbol = "tf_tree_shared_w1s3_pg", .image = "tree_attention", .threads = 32, .dynamic = 49152, .opt_in = true }, .usage = .{ .{ .regs = 192, .static = 0, .bound = 32 }, .{ .regs = 192, .static = 0, .bound = 32 }, .{ .regs = 192, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_part_pg", .symbol = "tf_tree_part_pg", .image = "tree_attention", .threads = 128, .dynamic = 65536, .opt_in = true }, .usage = .{ .{ .regs = 202, .static = 0, .bound = 128 }, .{ .regs = 202, .static = 0, .bound = 128 }, .{ .regs = 202, .static = 0, .bound = 128 }, .{ .regs = 204, .static = 0, .bound = 128 }, .{ .regs = 204, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_part_w1_pg", .symbol = "tf_tree_part_w1_pg", .image = "tree_attention", .threads = 32, .dynamic = 32768, .opt_in = true }, .usage = .{ .{ .regs = 198, .static = 0, .bound = 32 }, .{ .regs = 198, .static = 0, .bound = 32 }, .{ .regs = 198, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_part_w1s3_pg", .symbol = "tf_tree_part_w1s3_pg", .image = "tree_attention", .threads = 32, .dynamic = 49152, .opt_in = true }, .usage = .{ .{ .regs = 199, .static = 0, .bound = 32 }, .{ .regs = 199, .static = 0, .bound = 32 }, .{ .regs = 199, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_shared_256_pg", .symbol = "tf_tree_shared_256_pg", .image = "tree_attention", .threads = 128, .dynamic = 73728, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_shared_256_w1_pg", .symbol = "tf_tree_shared_256_w1_pg", .image = "tree_attention", .threads = 32, .dynamic = 40960, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 249, .static = 0, .bound = 32 }, .{ .regs = 249, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_shared_256_w1s3_pg", .symbol = "tf_tree_shared_256_w1s3_pg", .image = "tree_attention", .threads = 32, .dynamic = 57344, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 248, .static = 0, .bound = 32 }, .{ .regs = 248, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_part_256_pg", .symbol = "tf_tree_part_256_pg", .image = "tree_attention", .threads = 128, .dynamic = 73728, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_part_256_w1_pg", .symbol = "tf_tree_part_256_w1_pg", .image = "tree_attention", .threads = 32, .dynamic = 40960, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_part_256_w1s3_pg", .symbol = "tf_tree_part_256_w1s3_pg", .image = "tree_attention", .threads = 32, .dynamic = 57344, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 } } }, .{ .launch = .{ .name = "block attention tf_block_attention (up to 8 query heads a key head)", .symbol = "tf_block_attention", .image = "block_attention", .threads = 256, .dynamic = 16384, .opt_in = true }, .usage = .{ .{ .regs = 230, .static = 0, .bound = 256 }, .{ .regs = 230, .static = 0, .bound = 256 }, .{ .regs = 230, .static = 0, .bound = 256 }, .{ .regs = 228, .static = 0, .bound = 256 }, .{ .regs = 228, .static = 0, .bound = 256 } } }, .{ .launch = .{ .name = "window attention tf_window_part", .symbol = "tf_window_part", .image = "window_attention", .threads = 256 }, .usage = .{ .{ .regs = 55, .static = 45824, .bound = 256 }, .{ .regs = 50, .static = 45824, .bound = 256 }, .{ .regs = 50, .static = 45824, .bound = 256 }, .{ .regs = 56, .static = 45824, .bound = 256 }, .{ .regs = 56, .static = 45824, .bound = 256 } } }, .{ .launch = .{ .name = "window attention tf_window_merge", .symbol = "tf_window_merge", .image = "window_attention", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 48, .static = 0, .bound = 256 }, .{ .regs = 48, .static = 0, .bound = 256 } } }, diff --git a/zig/src/cuda/tree_attention.zig b/zig/src/cuda/tree_attention.zig index d4fc29afb2f..7f62d507372 100644 --- a/zig/src/cuda/tree_attention.zig +++ b/zig/src/cuda/tree_attention.zig @@ -23,18 +23,21 @@ const slices = 4; /// (row, key head, group) items one-warp blocks may take: their slices' partials sit apart from the combined ones. pub const slice_items = 1024; -/// row_stream [n], streams [s, 4] (committed at [2]), offs [s, 2] (K, V from origin), paths [n, max_depth], depths. -pub const Rows = struct { row_stream: u64, streams: u64, offs: u64, origin: u64, paths: u64, depths: u64 }; +/// row_stream [n], streams [s, 4] (committed at [2]), offs [s, 2] (K, V from origin, or their pools'), paths, depths. +pub const Rows = struct { row_stream: u64, streams: u64, offs: u64, origin: u64, paths: u64, depths: u64, pages: ?Pages = null }; + +/// int32 page ids [streams, stride] (a stream's row), elements a page id steps in each cache, positions a page. +pub const Pages = struct { table: u64, page: u64, tok: usize, stride: usize }; + +/// The kernels of one addressing: head dims 128, 256; one-warp blocks by [2 stages, 3 stages][head dim]. +const Kernels = struct { part: [2]Function, shared: [2]Function, part_w1: [2][2]Function, shared_w1: [2][2]Function }; pub const Scratch = struct { o: u64, m: u64, l: u64, so: u64, sm: u64, sl: u64 }; pub const TreeAttention = struct { mod: Module, paths_fn: Function, - part_fns: [2]Function, // head dim 128, 256 - shared_fns: [2]Function, - part_w1: [2][2]Function, // the same slices, one warp a block: [2 stages, 3 stages][head dim] - shared_w1: [2][2]Function, + fns: [2]Kernels, // contiguous, paged merge_fn: Function, /// The shared kernel's blocks a key head: a fixed grid walking every (row, group) (bits do not depend on it). shared_blocks: usize = 96, @@ -45,17 +48,25 @@ pub const TreeAttention = struct { if (!kernels.available) return error.BuiltWithoutKernels; var mod = try Module.load(d, kernels.tree_attention); errdefer mod.unload(); - var parts: [2]Function = .{ try mod.function("tf_tree_part"), try mod.function("tf_tree_part_256") }; - for (&parts, part_smem) |*f, b| try f.allowDynamicShared(b); - var shared: [2]Function = .{ try mod.function("tf_tree_shared"), try mod.function("tf_tree_shared_256") }; - for (&shared, part_smem) |*f, b| try f.allowDynamicShared(b); - var parts1: [2][2]Function = .{ .{ try mod.function("tf_tree_part_w1"), try mod.function("tf_tree_part_256_w1") }, .{ try mod.function("tf_tree_part_w1s3"), try mod.function("tf_tree_part_256_w1s3") } }; - var shared1: [2][2]Function = .{ .{ try mod.function("tf_tree_shared_w1"), try mod.function("tf_tree_shared_256_w1") }, .{ try mod.function("tf_tree_shared_w1s3"), try mod.function("tf_tree_shared_256_w1s3") } }; + return .{ .mod = mod, .paths_fn = try mod.function("tf_tree_paths"), .fns = .{ try kernelsOf(&mod, ""), try kernelsOf(&mod, "_pg") }, .merge_fn = try mod.function("tf_tree_merge") }; + } + + fn kernelsOf(mod: *Module, comptime sfx: []const u8) !Kernels { + var k: Kernels = .{ + .part = .{ try mod.function("tf_tree_part" ++ sfx), try mod.function("tf_tree_part_256" ++ sfx) }, + .shared = .{ try mod.function("tf_tree_shared" ++ sfx), try mod.function("tf_tree_shared_256" ++ sfx) }, + .part_w1 = .{ .{ try mod.function("tf_tree_part_w1" ++ sfx), try mod.function("tf_tree_part_256_w1" ++ sfx) }, .{ try mod.function("tf_tree_part_w1s3" ++ sfx), try mod.function("tf_tree_part_256_w1s3" ++ sfx) } }, + .shared_w1 = .{ .{ try mod.function("tf_tree_shared_w1" ++ sfx), try mod.function("tf_tree_shared_256_w1" ++ sfx) }, .{ try mod.function("tf_tree_shared_w1s3" ++ sfx), try mod.function("tf_tree_shared_256_w1s3" ++ sfx) } }, + }; + for (&k.part, &k.shared, part_smem) |*p, *sh, b| { + try p.allowDynamicShared(b); + try sh.allowDynamicShared(b); + } for (0..2) |st| for (0..2) |which| { - try parts1[st][which].allowDynamicShared(smemW1(@intCast(st + 2), which)); - try shared1[st][which].allowDynamicShared(smemW1(@intCast(st + 2), which)); + try k.part_w1[st][which].allowDynamicShared(smemW1(@intCast(st + 2), which)); + try k.shared_w1[st][which].allowDynamicShared(smemW1(@intCast(st + 2), which)); }; - return .{ .mod = mod, .paths_fn = try mod.function("tf_tree_paths"), .part_fns = parts, .shared_fns = shared, .part_w1 = parts1, .shared_w1 = shared1, .merge_fn = try mod.function("tf_tree_merge") }; + return k; } pub fn unload(g: *TreeAttention) void { @@ -110,14 +121,21 @@ pub const TreeAttention = struct { c.add(@as(i32, @intCast(ng))); c.add(@as(i32, @intCast(n))); c.add(kn); // the replay of a NaN or infinite partial weighs a row's path keys too + if (rows.pages) |pg| for ([_]*launch_.Args{ &a, &c }) |x| { + x.add(pg.table); + x.add(@as(i64, @intCast(pg.page))); + x.add(@as(i32, @intCast(pg.tok))); + x.add(@as(i32, @intCast(pg.stride))); + }; + const k = &g.fns[@intFromBool(rows.pages != null)]; const per: usize = if (one) slices else 1; const block: u32 = if (one) 32 else 128; // three stages where the one-warp grid fits one wave of the SMs (a block each), else two (two blocks an SM) const deep: usize = if (@min(n * ng, g.shared_blocks) * slices * hk <= g.sms) 1 else 0; const smem = if (one) smemW1(@intCast(deep + 2), which) else part_smem[which]; - try launch_.launch(if (one) g.shared_w1[deep][which] else g.shared_fns[which], .{ .grid = .{ .x = @intCast(@min(n * ng, g.shared_blocks) * per), .y = @intCast(hk), .z = 1 }, .block = .{ .x = block }, .shared = smem }, s, &c); + try launch_.launch(if (one) k.shared_w1[deep][which] else k.shared[which], .{ .grid = .{ .x = @intCast(@min(n * ng, g.shared_blocks) * per), .y = @intCast(hk), .z = 1 }, .block = .{ .x = block }, .shared = smem }, s, &c); // a row's own block: its boundary group and at most the next (a path is at most 128 keys) - try launch_.launch(if (one) g.part_w1[deep][which] else g.part_fns[which], .{ .grid = .{ .x = @intCast(n), .y = @intCast(hk), .z = @intCast(@min(ng, 2) * per) }, .block = .{ .x = block }, .shared = smem }, s, &a); + try launch_.launch(if (one) k.part_w1[deep][which] else k.part[which], .{ .grid = .{ .x = @intCast(n), .y = @intCast(hk), .z = @intCast(@min(ng, 2) * per) }, .block = .{ .x = block }, .shared = smem }, s, &a); var b: launch_.Args = .{}; for ([_]u64{ o[0], o[1], o[2], rows.row_stream, rows.streams, rows.depths, out }) |v| b.add(v); b.add(@as(i32, @intCast(h))); diff --git a/zig/tests/cuda/tree_tests.zig b/zig/tests/cuda/tree_tests.zig index 7c7f17fe07e..57ea9e61515 100644 --- a/zig/tests/cuda/tree_tests.zig +++ b/zig/tests/cuda/tree_tests.zig @@ -1,4 +1,4 @@ -//! tree_attention.cu against core/attention_ref.zig, and one stream's rows alone giving the same bits. +//! tree_attention.cu against core/attention_ref.zig, one stream's rows alone and paged caches giving the same bits. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -43,7 +43,7 @@ const Set = struct { }; /// One call over `rows` (global window rows of the given streams, in order): their outputs. -fn call(x: *Set, s: cuda.Stream, g: *const tree.TreeAttention, d: usize, rows: []const usize, row_stream_all: []const i32, parents_all: []const i32, qs: []const u16, kns: []const u16, vns: []const u16, h: usize, hk: usize, streams_all: []const i32, offs: u64, origin: u64, ng: usize, scale: f32) ![]u16 { +fn call(x: *Set, s: cuda.Stream, g: *const tree.TreeAttention, d: usize, rows: []const usize, row_stream_all: []const i32, parents_all: []const i32, qs: []const u16, kns: []const u16, vns: []const u16, h: usize, hk: usize, streams_all: []const i32, offs: u64, origin: u64, ng: usize, scale: f32, pages: ?tree.Pages) ![]u16 { const n = rows.len; var local: std.AutoHashMap(usize, i32) = .init(x.a); for (rows, 0..) |r, i| try local.put(r, @intCast(i)); @@ -76,7 +76,7 @@ fn call(x: *Set, s: cuda.Stream, g: *const tree.TreeAttention, d: usize, rows: [ try g.paths(s, try x.up(std.mem.sliceAsBytes(par)), paths, depths, n); const sc_base = try x.zero(s, tree.TreeAttention.scratchBytes(n, h, hk, ng, d)); const out = try x.zero(s, n * h * d * 2); - const rws: tree.Rows = .{ .row_stream = try x.up(std.mem.sliceAsBytes(rs)), .streams = streams_dev, .offs = offs, .origin = origin, .paths = paths, .depths = depths }; + const rws: tree.Rows = .{ .row_stream = try x.up(std.mem.sliceAsBytes(rs)), .streams = streams_dev, .offs = offs, .origin = origin, .paths = paths, .depths = depths, .pages = pages }; try g.run(s, try x.up(std.mem.sliceAsBytes(q)), try x.up(std.mem.sliceAsBytes(kn)), try x.up(std.mem.sliceAsBytes(vn)), rws, tree.TreeAttention.scratch(sc_base, n, h, hk, ng, d), out, n, h, hk, d, ng, scale); try s.synchronize(); const got = try x.down(u16, out, n * h * d); @@ -84,6 +84,45 @@ fn call(x: *Set, s: cuda.Stream, g: *const tree.TreeAttention, d: usize, rows: [ return got; } +const Paged = struct { origin: u64, offs: u64, pages: tree.Pages }; + +/// The streams' committed keys (K at offs[2s], V at offs[2s + 1] of kcache) copied to `tok`-position pages, shuffled. +fn paged(x: *Set, rng: std.Random, kcache: []const u16, committed: []const usize, offs: []const i64, hk: usize, d: usize, tok: usize) !Paged { + var stride: usize = 0; + var count: usize = 0; + for (committed) |p| { + stride = @max(stride, (p + tok - 1) / tok); + count += (p + tok - 1) / tok; + } + count += 3; // pages no stream holds + const page = tok * hk * d; + const ids = try x.a.alloc(i32, count); + for (ids, 0..) |*v, i| v.* = @intCast(i); + rng.shuffle(i32, ids); + const table = try x.a.alloc(i32, committed.len * stride); + @memset(table, -1); + const pool = try x.a.alloc(u16, 2 * count * page); + @memset(pool, 0x7fc0); // a NaN in every position no key fills + var next: usize = 0; + for (committed, 0..) |p, si| { + for (0..(p + tok - 1) / tok) |j| { + table[si * stride + j] = ids[next]; + next += 1; + } + for (0..p) |j| for (0..2) |part| { + const src: usize = @as(usize, @intCast(offs[2 * si + part])) + j * hk * d; + const dst = part * count * page + @as(usize, @intCast(table[si * stride + j / tok])) * page + (j % tok) * hk * d; + @memcpy(pool[dst..][0 .. hk * d], kcache[src..][0 .. hk * d]); + }; + } + var o = try x.a.alloc(i64, 2 * committed.len); + for (0..committed.len) |si| { + o[2 * si] = 0; + o[2 * si + 1] = @intCast(count * page); + } + return .{ .origin = try x.up(std.mem.sliceAsBytes(pool)), .offs = try x.up(std.mem.sliceAsBytes(o)), .pages = .{ .table = try x.up(std.mem.sliceAsBytes(table)), .page = page, .tok = tok, .stride = stride } }; +} + fn case(gpu: check.Gpu, d: usize, h: usize, hk: usize, seed: u64, worst_all: *f64) !void { var arena: std.heap.ArenaAllocator = .init(gpu.gpa); defer arena.deinit(); @@ -140,7 +179,7 @@ fn case(gpu: check.Gpu, d: usize, h: usize, hk: usize, seed: u64, worst_all: *f6 const scale: f32 = @floatCast(1 / @sqrt(@as(f64, @floatFromInt(d)))); const all = try a.alloc(usize, total); for (all, 0..) |*r, i| r.* = i; - const got = try call(&x, s, &g, d, all, row_stream, parents, qs, kns, vns, h, hk, &streams, offs_dev, origin, ng, scale); + const got = try call(&x, s, &g, d, all, row_stream, parents, qs, kns, vns, h, hk, &streams, offs_dev, origin, ng, scale, null); // the reference: committed keys, then the path root first var worst: f64 = 0; const kd = try a.alloc(f64, (4200 + 128) * d); @@ -185,14 +224,20 @@ fn case(gpu: check.Gpu, d: usize, h: usize, hk: usize, seed: u64, worst_all: *f6 // stream 1's rows alone (re-indexed): the same bits const only = try a.alloc(usize, widths[1]); for (only, 0..) |*r, i| r.* = widths[0] + i; - const alone = try call(&x, s, &g, d, only, row_stream, parents, qs, kns, vns, h, hk, &streams, offs_dev, origin, ng, scale); + const alone = try call(&x, s, &g, d, only, row_stream, parents, qs, kns, vns, h, hk, &streams, offs_dev, origin, ng, scale, null); try check.sameBytes("tree attention: one stream's rows alone", std.mem.sliceAsBytes(alone), std.mem.sliceAsBytes(got[widths[0] * h * d ..][0 .. widths[1] * h * d])); + // the committed keys scattered over shuffled pages of a few sizes: the same bits + for ([_]usize{ 16, 37, 256 }) |tok| { + const pg = try paged(&x, rng, kcache, &committed, &offs, hk, d, tok); + const at_pages = try call(&x, s, &g, d, all, row_stream, parents, qs, kns, vns, h, hk, &streams, pg.offs, pg.origin, ng, scale, pg.pages); + try check.sameBytes("tree attention: paged committed keys", std.mem.sliceAsBytes(at_pages), std.mem.sliceAsBytes(got)); + } // one shared block walking every (row, group), and a grid sized for a long context: the same bits g.shared_blocks = 1; - const strided = try call(&x, s, &g, d, all, row_stream, parents, qs, kns, vns, h, hk, &streams, offs_dev, origin, ng, scale); + const strided = try call(&x, s, &g, d, all, row_stream, parents, qs, kns, vns, h, hk, &streams, offs_dev, origin, ng, scale, null); try check.sameBytes("tree attention: one shared block", std.mem.sliceAsBytes(strided), std.mem.sliceAsBytes(got)); g.shared_blocks = 96; - const wide = try call(&x, s, &g, d, all, row_stream, parents, qs, kns, vns, h, hk, &streams, offs_dev, origin, 513, scale); + const wide = try call(&x, s, &g, d, all, row_stream, parents, qs, kns, vns, h, hk, &streams, offs_dev, origin, 513, scale, null); try check.sameBytes("tree attention: groups for a 262k context", std.mem.sliceAsBytes(wide), std.mem.sliceAsBytes(got)); // one warp a block (a device with SMs to spare): stream 2's rows alone, its full groups too, the batch's bits g.sms = 1 << 20; @@ -200,14 +245,17 @@ fn case(gpu: check.Gpu, d: usize, h: usize, hk: usize, seed: u64, worst_all: *f6 const third = try a.alloc(usize, widths[2]); for (third, 0..) |*r, i| r.* = widths[0] + widths[1] + i; try check.expect(widths[2] * ng * hk <= tree.slice_items, "tree attention: the one-warp case fits the slices", .{}); - const one = try call(&x, s, &g, d, third, row_stream, parents, qs, kns, vns, h, hk, &streams, offs_dev, origin, ng, scale); + const one = try call(&x, s, &g, d, third, row_stream, parents, qs, kns, vns, h, hk, &streams, offs_dev, origin, ng, scale, null); try check.sameBytes("tree attention: one warp a block", std.mem.sliceAsBytes(one), std.mem.sliceAsBytes(got[(widths[0] + widths[1]) * h * d ..][0 .. widths[2] * h * d])); + const pg1 = try paged(&x, rng, kcache, &committed, &offs, hk, d, 16); + const one_paged = try call(&x, s, &g, d, third, row_stream, parents, qs, kns, vns, h, hk, &streams, pg1.offs, pg1.origin, ng, scale, pg1.pages); + try check.sameBytes("tree attention: one warp a block, paged", std.mem.sliceAsBytes(one_paged), std.mem.sliceAsBytes(one)); g.shared_blocks = 1; - const one_strided = try call(&x, s, &g, d, third, row_stream, parents, qs, kns, vns, h, hk, &streams, offs_dev, origin, ng, scale); + const one_strided = try call(&x, s, &g, d, third, row_stream, parents, qs, kns, vns, h, hk, &streams, offs_dev, origin, ng, scale, null); try check.sameBytes("tree attention: one warp a block, one shared block", std.mem.sliceAsBytes(one_strided), std.mem.sliceAsBytes(one)); g.shared_blocks = 96; g.sms = 1; // more one-warp blocks than SMs: two tile stages instead of three - const two = try call(&x, s, &g, d, third, row_stream, parents, qs, kns, vns, h, hk, &streams, offs_dev, origin, ng, scale); + const two = try call(&x, s, &g, d, third, row_stream, parents, qs, kns, vns, h, hk, &streams, offs_dev, origin, ng, scale, null); try check.sameBytes("tree attention: one warp a block, two stages", std.mem.sliceAsBytes(two), std.mem.sliceAsBytes(one)); g.shared_blocks = 96; } @@ -216,5 +264,5 @@ pub fn run(gpu: check.Gpu) !void { var worst: f64 = 0; try case(gpu, 128, 48, 4, 41, &worst); // Kolibri try case(gpu, 256, 24, 4, 42, &worst); // Qwen3.8-27B - check.pass("tree attention: dim 128 and 256, committed keys and paths within float64 tolerance (worst {d:.3}), a stream's bits alone, any group slots, four-warp or one-warp blocks", .{worst}); + check.pass("tree attention: dim 128 and 256, committed keys and paths within float64 tolerance (worst {d:.3}), a stream's bits alone, paged caches, any group slots, four-warp or one-warp blocks", .{worst}); } From ade8bada0e0d27617eeb9b7beb9675921899d61b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Thu, 29 Oct 2026 11:49:38 +0000 Subject: [PATCH 2/5] cuda window_pages: head dim 512 decode reads keys from a page table (_pg kernels), SASS of the others unchanged part_staged takes the pages as an empty template pack: tf_wrows_part_512 and tf_wrows_merge_512 keep their code, and window_pages.cu adds tf_wrows_part_512_pg (a key's page from the table at any tok, a staged tile may cross pages) and tf_wrows_merge_512_pg (merge<512>'s existing PG replay). loadPages loads them into wide_fns[1].paged; 512 has no paged prompt, so Paged.prompt is optional and promptRows refuses one. The records copy the base kernels' (regs TODO). window-pages-512: the 12B, 31B and a GQA 5 shape decoded over shuffled pages of 16, 37 and 256 positions (NaN in every unused slot) give the contiguous bits, the merge's float64 replay included. --- zig/build/cuda_kernels.zig | 2 +- zig/kernels/cuda/window_pages.cu | 19 +++- zig/kernels/cuda/window_rows512.cuh | 20 +++- zig/src/core/contract/window_rows_records.zig | 2 + zig/src/cuda/window_attention.zig | 40 +++++-- zig/tests/cuda/main.zig | 3 + zig/tests/cuda/window_pages512_tests.zig | 106 ++++++++++++++++++ 7 files changed, 176 insertions(+), 16 deletions(-) create mode 100644 zig/tests/cuda/window_pages512_tests.zig diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index 887b2d84bae..ab8ac37def2 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -94,7 +94,7 @@ pub const kernels = [_]Kernel{ .{ .name = "block_attention", .flags = &.{"-O3"} }, // ours: a drafter's block over its context (cuda/block_attention.zig) .{ .name = "window_attention", .flags = &.{"-O3"} }, // ours: sliding-window attention (cuda/window_attention.zig) .{ .name = "window_rows", .flags = &.{"-O3"} }, // ours: window attention at head dims 256 and 512 (cuda/window_attention.zig) - .{ .name = "window_pages", .flags = &.{"-O3"} }, // ours: window_rows.cuh over Dory's paged caches (cuda/window_attention.zig) + .{ .name = "window_pages", .flags = &.{"-O3"} }, // ours: window_rows.cuh over paged caches, Dory's and Gemma 4's global decode (cuda/window_attention.zig) .{ .name = "moe_glue", .flags = &.{"-O3"} }, // ours: sigmoid top-k and the weighted combine (cuda/moe_glue.zig) .{ .name = "dense_rows", .flags = &.{"-O3"} }, // ours: bf16 rows times weight rows into fp32 (cuda/dense_rows.zig) .{ .name = "modelopt_pack", .flags = &.{"-O3"} }, // ours: ModelOpt tensors into the lane, prompt and expert layouts diff --git a/zig/kernels/cuda/window_pages.cu b/zig/kernels/cuda/window_pages.cu index 5d34a6e8147..1788ee72db2 100644 --- a/zig/kernels/cuda/window_pages.cu +++ b/zig/kernels/cuda/window_pages.cu @@ -1,6 +1,7 @@ -// window_rows.cuh over paged caches (Dory's full-attention layers, head dim 256): the kernels, and the rows' writer. +// window_rows.cuh over paged caches (Dory's head dim 256; Gemma 4's global decode, 512): the kernels, the rows' writer. #include "window_rows.cuh" +#include "window_rows512.cuh" using namespace tf_wrows; @@ -28,6 +29,22 @@ extern "C" __global__ void __launch_bounds__(NT, 1) tf_wrows_prompt_256_pg( Pg{tab, page, tok, 0}); } +// Gemma 4's global decode over pages (512, no window): each key's page from tab at any tok, the replay's reads too. +extern "C" __global__ void __launch_bounds__(NT) tf_wrows_part_512_pg( + const __nv_bfloat16* q, const __nv_bfloat16* kc, const __nv_bfloat16* vc, const int* pos, const int* slot, + float* po, float* pm, float* pl, int h, int hk, int win, long long ring, float scale, const int* tab, + long long page, int tok, int stride) { + part_staged<512, NONE>(q, kc, vc, pos, slot, po, pm, pl, h, hk, win, ring, scale, Pg{tab, page, tok, stride}); +} + +extern "C" __global__ void __launch_bounds__(NT) tf_wrows_merge_512_pg( + const float* po, const float* pm, const float* pl, __nv_bfloat16* out, int h, int hk, int chunks, + const __nv_bfloat16* q, const __nv_bfloat16* kc, const __nv_bfloat16* vc, const int* pos, const int* slot, int win, + long long ring, float scale, const int* tab, long long page, int tok, int stride) { + merge<512, NONE, true>(po, pm, pl, out, h, hk, chunks, q, kc, vc, pos, slot, win, ring, scale, + Pg{tab, page, tok, stride}); +} + // Rows k, v [n, row] (row = hk * D elements) into the pages at their positions: a block a row, 16 bytes a thread. extern "C" __global__ void __launch_bounds__(128) tf_wrows_put(const __nv_bfloat16* k, const __nv_bfloat16* v, __nv_bfloat16* kc, __nv_bfloat16* vc, const int* pos, diff --git a/zig/kernels/cuda/window_rows512.cuh b/zig/kernels/cuda/window_rows512.cuh index e974967e3c2..e5c962009ef 100644 --- a/zig/kernels/cuda/window_rows512.cuh +++ b/zig/kernels/cuda/window_rows512.cuh @@ -8,11 +8,13 @@ namespace tf_wrows { // part's arithmetic for head dim 512: a block 4 heads, K and V tiles in shared memory, a warp a key run. constexpr int TK = 32, NSG = 2; -template +// P: empty, or one Pg (window_pages.cu): key k of slot s at its page, tab[s * stride + k / tok] (no window). +template __device__ __forceinline__ void part_staged(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ kc, const __nv_bfloat16* __restrict__ vc, const int* __restrict__ pos, const int* __restrict__ slot, float* __restrict__ po, float* __restrict__ pm, - float* __restrict__ pl, int h, int hk, int win, long long ring, float scale) { + float* __restrict__ pl, int h, int hk, int win, long long ring, float scale, + P... pg) { constexpr int DPL = D / 32, HW = 4, C = D / 8; // a lane's dims and columns, heads a block (and warp), uint4 a key extern __shared__ uint4 tiles[]; // [NSG][TK][C] K or V tiles; then the runs' partial o __shared__ float sp[CK * SP]; @@ -42,9 +44,17 @@ __device__ __forceinline__ void part_staged(const __nv_bfloat16* __restrict__ q, uint4* dst = tiles + (t % NSG) * TK * C; for (int i = threadIdx.x; i < TK * C; i += NT) { const int jj = t * TK + i / C; - int64_t row = r0 + min(jj, nk - 1); - if (row >= ring) row -= ring; - cp16z(dst + i, cache + ((base + row) * hk + kh) * D + (i % C) * 8, jj < nk); + if constexpr (sizeof...(P) != 0) { // a page a key: any tok, a tile may cross pages + const Pg& g = (pg, ...); + const int key = k0 + min(jj, nk - 1); + const int64_t id = g.tab[(slot != nullptr ? slot[r] : 0) * g.stride + key / g.tok]; + cp16z(dst + i, cache + id * g.page + (static_cast(key % g.tok) * hk + kh) * D + (i % C) * 8, + jj < nk); + } else { + int64_t row = r0 + min(jj, nk - 1); + if (row >= ring) row -= ring; + cp16z(dst + i, cache + ((base + row) * hk + kh) * D + (i % C) * 8, jj < nk); + } } commit(); }; diff --git a/zig/src/core/contract/window_rows_records.zig b/zig/src/core/contract/window_rows_records.zig index 8ac7b012726..35bd98967ab 100644 --- a/zig/src/core/contract/window_rows_records.zig +++ b/zig/src/core/contract/window_rows_records.zig @@ -14,5 +14,7 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "window_pages tf_wrows_part_256_pg", .symbol = "tf_wrows_part_256_pg", .image = "window_pages", .threads = 256 }, .usage = .{ .{ .regs = 98, .static = 46208, .bound = 256 }, .{ .regs = 104, .static = 46208, .bound = 256 }, .{ .regs = 104, .static = 46208, .bound = 256 }, .{ .regs = 108, .static = 46208, .bound = 256 }, .{ .regs = 108, .static = 46208, .bound = 256 } } }, .{ .launch = .{ .name = "window_pages tf_wrows_merge_256_pg", .symbol = "tf_wrows_merge_256_pg", .image = "window_pages", .threads = 256 }, .usage = .{ .{ .regs = 62, .static = 128, .bound = 256 }, .{ .regs = 64, .static = 128, .bound = 256 }, .{ .regs = 64, .static = 128, .bound = 256 }, .{ .regs = 40, .static = 128, .bound = 256 }, .{ .regs = 40, .static = 128, .bound = 256 } } }, .{ .launch = .{ .name = "window_pages tf_wrows_prompt_256_pg", .symbol = "tf_wrows_prompt_256_pg", .image = "window_pages", .threads = 256, .dynamic = 81920, .opt_in = true }, .usage = .{ .{ .regs = 241, .static = 144, .bound = 256 }, .{ .regs = 244, .static = 144, .bound = 256 }, .{ .regs = 244, .static = 144, .bound = 256 }, .{ .regs = 255, .static = 144, .bound = 256 }, .{ .regs = 255, .static = 144, .bound = 256 } } }, + .{ .launch = .{ .name = "window_pages tf_wrows_part_512_pg", .symbol = "tf_wrows_part_512_pg", .image = "window_pages", .threads = 256, .dynamic = 65536, .opt_in = true }, .usage = .{ .{ .regs = 154, .static = 17536, .bound = 256 }, .{ .regs = 157, .static = 17536, .bound = 256 }, .{ .regs = 157, .static = 17536, .bound = 256 }, .{ .regs = 128, .static = 17536, .bound = 256 }, .{ .regs = 128, .static = 17536, .bound = 256 } } }, + .{ .launch = .{ .name = "window_pages tf_wrows_merge_512_pg", .symbol = "tf_wrows_merge_512_pg", .image = "window_pages", .threads = 256 }, .usage = .{ .{ .regs = 62, .static = 128, .bound = 256 }, .{ .regs = 64, .static = 128, .bound = 256 }, .{ .regs = 64, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 } } }, .{ .launch = .{ .name = "window_pages tf_wrows_put", .symbol = "tf_wrows_put", .image = "window_pages", .threads = 128 }, .usage = .{ .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 44, .static = 0, .bound = 128 }, .{ .regs = 44, .static = 0, .bound = 128 }, .{ .regs = 38, .static = 0, .bound = 128 }, .{ .regs = 38, .static = 0, .bound = 128 } } }, }; diff --git a/zig/src/cuda/window_attention.zig b/zig/src/cuda/window_attention.zig index f806a038bc0..07963ebaadb 100644 --- a/zig/src/cuda/window_attention.zig +++ b/zig/src/cuda/window_attention.zig @@ -10,18 +10,20 @@ const Module = module.Module; const Function = module.Function; const Stream = stream_.Stream; -/// A Window's `pg` (win 0, head dim 256): cache pointers name a layer in page 0; `table` rows of ids, `stride` a slot. +/// A Window's `pg` (win 0; head dim 256, or 512's decode): caches name a layer in page 0, `table` `stride` ids a slot. pub const Pages = struct { table: u64, page_elems: usize, tokens: usize, stride: usize = 0 }; /// A row's heads and keys (pos - win, pos] (win 0: all) at cache row slot * ring + key % ring; p32: wide P in halves. pub const Window = struct { h: usize, hk: usize, d: usize, win: usize, ring: usize, scale: f32, p32: bool = false, pg: ?Pages = null }; -/// Positions a page holds at least (a multiple of it): the decode chunk, so a chunk and a prompt tile stay in a page. +/// A head dim 256 page's positions are a multiple of this, the decode chunk: a chunk and a prompt tile stay in a page. pub const page_unit = chunk_keys; +/// Head dim 256 pages hold whole chunks; 512's decode looks up each key's page, so its pages hold any count. fn pagedShape(w: Window) bool { const p = w.pg orelse return true; - return w.d == 256 and w.win == 0 and p.tokens > 0 and p.tokens % page_unit == 0 and p.page_elems <= std.math.maxInt(i63); + if (w.win != 0 or p.tokens == 0 or p.page_elems > std.math.maxInt(i63)) return false; + return if (w.d == 256) p.tokens % page_unit == 0 else w.d == 512; } /// Head dims window_rows.cu serves, with any query heads a key head up to 16. @@ -60,8 +62,8 @@ pub const WindowAttention = struct { /// window_rows.cu's kernels at one head dim: decode partials and merge, prompt rows (bf16 P, then P32). pub const Wide = struct { part: Function, merge: Function, prompt: [2]Function, paged: ?Paged = null }; - /// The head dim 256 kernels over paged caches: decode partials, their merge, prompt rows (P as bf16). - pub const Paged = struct { part: Function, merge: Function, prompt: Function }; + /// The kernels over paged caches: decode partials, their merge, prompt rows (P as bf16; head dim 256 only). + pub const Paged = struct { part: Function, merge: Function, prompt: ?Function = null }; pub fn load(d: *const Driver) !WindowAttention { if (!kernels.available) return error.BuiltWithoutKernels; @@ -87,15 +89,18 @@ pub const WindowAttention = struct { }, .prompt_fns = p, .rows = rows, .wide_fns = wf }; } - /// Loads window_pages.cu: decode, prompt rows and `put` over caches in pages (head dim 256). + /// Loads window_pages.cu: decode, prompt rows and `put` over caches in pages (head dim 256; 512's decode). pub fn loadPages(g: *WindowAttention, d: *const Driver) !void { if (g.pages != null) return; var pages = try Module.load(d, kernels.window_pages); errdefer pages.unload(); const p: Paged = .{ .part = try pages.function("tf_wrows_part_256_pg"), .merge = try pages.function("tf_wrows_merge_256_pg"), .prompt = try pages.function("tf_wrows_prompt_256_pg") }; - try p.prompt.allowDynamicShared(rows_smem[0]); + try p.prompt.?.allowDynamicShared(rows_smem[0]); + const p512: Paged = .{ .part = try pages.function("tf_wrows_part_512_pg"), .merge = try pages.function("tf_wrows_merge_512_pg") }; + try p512.part.allowDynamicShared(staged_smem); g.put_fn = try pages.function("tf_wrows_put"); g.wide_fns[0].paged = p; + g.wide_fns[1].paged = p512; g.pages = pages; } @@ -256,7 +261,7 @@ pub const WindowAttention = struct { /// promptRows by `f` (wideFns, or the contract's controls). pub fn promptWith(f: *const Wide, s: Stream, q: u64, kc: u64, vc: u64, out: u64, p0: usize, n: usize, w: Window, hi: ?u64) !void { const grp = if (w.hk > 0) w.h / w.hk else 0; - if (!wideShape(w) or p0 + n > std.math.maxInt(i32) or !pagedShape(w) or (w.pg != null and (w.p32 or f.paged == null))) return error.WindowShape; + if (!wideShape(w) or p0 + n > std.math.maxInt(i32) or !pagedShape(w) or (w.pg != null and (w.p32 or f.paged == null or f.paged.?.prompt == null))) return error.WindowShape; if (n == 0) return; const ng = 1024 / w.d; // 16-row groups a block: 8 warps, a 128-dim slice each const hb = if (grp % ng == 0) ng else 1; @@ -269,10 +274,27 @@ pub const WindowAttention = struct { a.add(@as(i32, @intCast(w.ring))); if (w.pg) |p| addPages(&a, p, false); const cfg: launch_.Config = .{ .grid = .{ .x = @intCast((n + rows - 1) / rows), .y = @intCast(w.hk * (grp / hb)), .z = 1 }, .block = .{ .x = 256 }, .shared = promptShared(w.d) }; - try launch_.launch(if (w.pg != null) f.paged.?.prompt else f.prompt[@intFromBool(w.p32)], cfg, s, &a); + try launch_.launch(if (w.pg != null) f.paged.?.prompt.? else f.prompt[@intFromBool(w.p32)], cfg, s, &a); } }; +test "paged shapes: head dim 256 pages hold whole chunks, 512's decode pages any count, no window either way" { + var w: Window = .{ .h = 16, .hk = 1, .d = 512, .win = 0, .ring = 4096, .scale = 1, .pg = .{ .table = 0, .page_elems = 37 * 512, .tokens = 37 } }; + try std.testing.expect(pagedShape(w)); + w.win = 1024; + try std.testing.expect(!pagedShape(w)); + w.win = 0; + w.d = 256; + try std.testing.expect(!pagedShape(w)); + w.pg.?.tokens = 512; + try std.testing.expect(pagedShape(w)); + w.d = 128; + try std.testing.expect(!pagedShape(w)); + w.d = 512; + w.pg.?.tokens = 0; + try std.testing.expect(!pagedShape(w)); +} + test "wide geometry rejects empty heads and preserves all sixteen GQA ratios" { for ([_]usize{ 256, 512 }) |d| for (0..18) |ratio| { const w: Window = .{ .h = 2 * ratio, .hk = 2, .d = d, .win = 0, .ring = 4096, .scale = 1 }; diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 2d37fc734aa..aceda81e1fb 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -74,6 +74,7 @@ const gdn_prep_tests = @import("gdn_prep_tests.zig"); const qk_rows_tests = @import("qk_rows_tests.zig"); const window_tests = @import("window_tests.zig"); const window_rows_tests = @import("window_rows_tests.zig"); +const window_pages512_tests = @import("window_pages512_tests.zig"); const window_bench = @import("window_bench.zig"); const moe_glue_tests = @import("moe_glue_tests.zig"); const dense_rows_tests = @import("dense_rows_tests.zig"); @@ -218,6 +219,7 @@ const usage = \\ block DFlash block attention over windowed contexts against float64 (synthetic) \\ window sliding-window attention against float64 references (synthetic) \\ window-rows window attention at head dims 256 and 512 against float64 ranges (synthetic) + \\ window-pages-512 head dim 512 decode over shuffled pages bit-equal to the contiguous cache (synthetic) \\ window-bench WHICH window attention's GPU time: callers (Kolibri-1's shapes) or gemma (head dims 256, 512) \\ moe-glue sigmoid top-k routing and the weighted combine against float64 references (synthetic) \\ dense-rows bf16 rows times weight rows (routers, heads) against float64 references (synthetic) @@ -454,6 +456,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "block")) return block_tests.run(gpu); if (std.mem.eql(u8, cmd, "window")) return window_tests.run(gpu); if (std.mem.eql(u8, cmd, "window-rows")) return window_rows_tests.run(gpu); + if (std.mem.eql(u8, cmd, "window-pages-512")) return window_pages512_tests.run(gpu); if (std.mem.eql(u8, cmd, "window-bench")) return window_bench.run(gpu, try arg(rest, 0)); if (std.mem.eql(u8, cmd, "moe-glue")) return moe_glue_tests.run(gpu); if (std.mem.eql(u8, cmd, "dense-rows")) return dense_rows_tests.run(gpu); diff --git a/zig/tests/cuda/window_pages512_tests.zig b/zig/tests/cuda/window_pages512_tests.zig new file mode 100644 index 00000000000..d99bf5ac6cd --- /dev/null +++ b/zig/tests/cuda/window_pages512_tests.zig @@ -0,0 +1,106 @@ +//! window_pages.cu's head dim 512 decode (Gemma 4's global layers) over shuffled pages: the contiguous run's bits. +const std = @import("std"); +const cuda = @import("cuda"); +const check = @import("check.zig"); +const rows = @import("window_rows_tests.zig"); + +const wa = cuda.window_attention; + +const d = 512; +/// bf16 NaN: every page slot no key fills, and every page no stream holds. +const nan: u16 = 0x7fc0; + +const Case = struct { name: []const u8, h: usize, hk: usize, streams: usize, top: usize, rows: usize }; + +const cases = [_]Case{ + .{ .name = "12B global (16/1 heads of 512), 5000 positions", .h = 16, .hk = 1, .streams = 1, .top = 5000, .rows = 17 }, + .{ .name = "31B global (32/4 heads of 512), 3000 positions, 2 streams", .h = 32, .hk = 4, .streams = 2, .top = 3000, .rows = 17 }, + .{ .name = "GQA 5 (10/2 heads of 512), 1200 positions, 3 streams", .h = 10, .hk = 2, .streams = 3, .top = 1200, .rows = 9 }, +}; + +/// Positions a page: a 16-byte row's worth of keys, an odd count whose pages a chunk and a staged tile cross, a chunk. +const toks = [_]usize{ 16, 37, 256 }; + +const Pool = struct { kc: u64, vc: u64, pages: wa.Pages }; + +/// Stream s's keys (rows s * top .. of kc and vc) copied to `tok`-position pages in shuffled order, NaN elsewhere. +fn paged(b: *rows.Bufs, a: std.mem.Allocator, rng: std.Random, kc: []const u16, vc: []const u16, c: Case, tok: usize) !Pool { + const stride = (c.top + tok - 1) / tok; + const count = c.streams * stride + 3; // pages no stream holds + const row = c.hk * d; + const page = tok * row; + const ids = try a.alloc(i32, count); + for (ids, 0..) |*v, i| v.* = @intCast(i); + rng.shuffle(i32, ids); + const table = try a.alloc(i32, c.streams * stride); + for (table, 0..) |*v, i| v.* = ids[i]; + const kp = try a.alloc(u16, count * page); + const vp = try a.alloc(u16, count * page); + @memset(kp, nan); + @memset(vp, nan); + for (0..c.streams) |s| for (0..c.top) |j| { + const src = (s * c.top + j) * row; + const dst = @as(usize, @intCast(table[s * stride + j / tok])) * page + (j % tok) * row; + @memcpy(kp[dst..][0..row], kc[src..][0..row]); + @memcpy(vp[dst..][0..row], vc[src..][0..row]); + }; + return .{ .kc = try b.up(std.mem.sliceAsBytes(kp)), .vc = try b.up(std.mem.sliceAsBytes(vp)), .pages = .{ .table = try b.up(std.mem.sliceAsBytes(table)), .page_elems = page, .tokens = tok, .stride = stride } }; +} + +fn case(gpu: check.Gpu, a: std.mem.Allocator, s: cuda.Stream, g: *const wa.WindowAttention, rng: std.Random, c: Case) !void { + var b: rows.Bufs = .{ .gpu = gpu }; + defer b.deinit(); + const q = try a.alloc(u16, c.rows * c.h * d); + const kc = try a.alloc(u16, c.streams * c.top * c.hk * d); + const vc = try a.alloc(u16, kc.len); + rows.fill(rng, q, kc, vc, d); + const pos = try a.alloc(i32, c.rows); + const slot = try a.alloc(i32, c.rows); + for (pos, slot, 0..) |*p, *sl, i| { // the first key alone, short rows, chunk edges, scattered, the cache's end + p.* = @intCast(if (i == 0) 0 else if (i == c.rows - 1) c.top - 1 else if (i % 4 == 0) (i * 64 - 1) % c.top else (i * 7919) % c.top); + sl.* = @intCast(i % c.streams); + } + // row 1's own key holds +inf in a value: its heads of key head 0 run the merge's float64 replay over the keys + vc[((@as(usize, @intCast(slot[1])) * c.top + @as(usize, @intCast(pos[1]))) * c.hk) * d + 7] = 0x7f80; + var w: wa.Window = .{ .h = c.h, .hk = c.hk, .d = d, .win = 0, .ring = c.top, .scale = @floatCast(1 / @sqrt(@as(f64, d))) }; + const dq = try b.up(std.mem.sliceAsBytes(q)); + const dp = try b.up(std.mem.sliceAsBytes(pos)); + const ds = try b.up(std.mem.sliceAsBytes(slot)); + const scratch = try b.out(s, wa.WindowAttention.scratchBytes(w, c.rows)); + const n = c.rows * c.h * d; + const flat = try b.out(s, n * 2); + try g.decode(s, dq, try b.up(std.mem.sliceAsBytes(kc)), try b.up(std.mem.sliceAsBytes(vc)), flat, dp, ds, w, scratch, c.rows); + try s.synchronize(); + const want = try a.alloc(u16, n); + try b.get(flat, want); + var odd: usize = 0; + for (want) |x| odd += @intFromBool(x & 0x7f80 == 0x7f80); + try check.expect(odd > 0, "window pages 512 {s}: the planted +inf reaches the merge's replay", .{c.name}); + for (toks) |tok| { + const pool = try paged(&b, a, rng, kc, vc, c, tok); + w.pg = pool.pages; + const out = try b.out(s, n * 2); + try g.decode(s, dq, pool.kc, pool.vc, out, dp, ds, w, scratch, c.rows); + try s.synchronize(); + const got = try a.alloc(u16, n); + try b.get(out, got); + var what: [160]u8 = undefined; + try check.sameBytes(try std.fmt.bufPrint(&what, "window pages 512 {s}: pages of {d} give the contiguous bits", .{ c.name, tok }), std.mem.sliceAsBytes(got), std.mem.sliceAsBytes(want)); + } +} + +pub fn run(gpu: check.Gpu) !void { + var arena: std.heap.ArenaAllocator = .init(gpu.gpa); + defer arena.deinit(); + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var g = try wa.WindowAttention.load(gpu.d); + defer g.unload(); + try g.loadPages(gpu.d); + var prng = std.Random.DefaultPrng.init(0x9a6e); + for (cases) |c| { + _ = arena.reset(.retain_capacity); + try case(gpu, arena.allocator(), s, &g, prng.random(), c); + } + check.pass("window pages 512: decode over shuffled pages of 16, 37 and 256 positions (NaN in every unused slot) bit-equal to the contiguous cache, the float64 replay included", .{}); +} From 1c28188d52e8d135ab34196d3a70ef0db795d052 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Thu, 29 Oct 2026 12:13:50 +0000 Subject: [PATCH 3/5] cuda window_pages: head dim 512 prompt rows read keys from a page table (_pg twins), SASS of the others unchanged window_pages.cu instantiates prompt::kernel<512, P32, NONE, true> as tf_wrows_prompt_512_pg and tf_wrows_prompt_512_p32_pg; window_rows.cuh is unchanged (its bool PG path already serves 256's paged prompt). A 32-key tile takes one page base, so promptWith refuses pages whose tok is not a multiple of 32 (prompt_tile). Paged.prompt is now [bf16 P, P32] like Wide.prompt; 256 keeps bf16 P only. The records copy the base kernels' (regs TODO). window-pages-512 adds prompt rows: the 12B and 31B shapes, chunks over many pages starting mid-page and at a page start, P as bf16 and P32, pages of 32, 64 and 256 (NaN in every unused slot), bit-equal to the contiguous cache with the float64 replay included, and pages of 48 refused. --- zig/build/cuda_kernels.zig | 2 +- zig/kernels/cuda/window_pages.cu | 19 ++++- zig/src/core/contract/window_rows_records.zig | 2 + zig/src/cuda/window_attention.zig | 31 +++++--- zig/tests/cuda/main.zig | 2 +- zig/tests/cuda/window_pages512_tests.zig | 74 ++++++++++++++++--- 6 files changed, 105 insertions(+), 25 deletions(-) diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index ab8ac37def2..929297fc3b8 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -94,7 +94,7 @@ pub const kernels = [_]Kernel{ .{ .name = "block_attention", .flags = &.{"-O3"} }, // ours: a drafter's block over its context (cuda/block_attention.zig) .{ .name = "window_attention", .flags = &.{"-O3"} }, // ours: sliding-window attention (cuda/window_attention.zig) .{ .name = "window_rows", .flags = &.{"-O3"} }, // ours: window attention at head dims 256 and 512 (cuda/window_attention.zig) - .{ .name = "window_pages", .flags = &.{"-O3"} }, // ours: window_rows.cuh over paged caches, Dory's and Gemma 4's global decode (cuda/window_attention.zig) + .{ .name = "window_pages", .flags = &.{"-O3"} }, // ours: window_rows.cuh over paged caches (Dory, Gemma 4) .{ .name = "moe_glue", .flags = &.{"-O3"} }, // ours: sigmoid top-k and the weighted combine (cuda/moe_glue.zig) .{ .name = "dense_rows", .flags = &.{"-O3"} }, // ours: bf16 rows times weight rows into fp32 (cuda/dense_rows.zig) .{ .name = "modelopt_pack", .flags = &.{"-O3"} }, // ours: ModelOpt tensors into the lane, prompt and expert layouts diff --git a/zig/kernels/cuda/window_pages.cu b/zig/kernels/cuda/window_pages.cu index 1788ee72db2..272236b6f06 100644 --- a/zig/kernels/cuda/window_pages.cu +++ b/zig/kernels/cuda/window_pages.cu @@ -1,4 +1,4 @@ -// window_rows.cuh over paged caches (Dory's head dim 256; Gemma 4's global decode, 512): the kernels, the rows' writer. +// window_rows.cuh over paged caches (Dory's full attention at 256, Gemma 4's global layers at 512), and the writer. #include "window_rows.cuh" #include "window_rows512.cuh" @@ -29,7 +29,7 @@ extern "C" __global__ void __launch_bounds__(NT, 1) tf_wrows_prompt_256_pg( Pg{tab, page, tok, 0}); } -// Gemma 4's global decode over pages (512, no window): each key's page from tab at any tok, the replay's reads too. +// Gemma 4's global decode over pages (head dim 512, no window): each key's page from tab, any tok; merge's replay too. extern "C" __global__ void __launch_bounds__(NT) tf_wrows_part_512_pg( const __nv_bfloat16* q, const __nv_bfloat16* kc, const __nv_bfloat16* vc, const int* pos, const int* slot, float* po, float* pm, float* pl, int h, int hk, int win, long long ring, float scale, const int* tab, @@ -45,6 +45,21 @@ extern "C" __global__ void __launch_bounds__(NT) tf_wrows_merge_512_pg( Pg{tab, page, tok, stride}); } +// Gemma 4's global prompt rows over pages: tab the stream's row; a 32-key tile takes one page base, so tok % 32 == 0. +extern "C" __global__ void __launch_bounds__(NT, 1) tf_wrows_prompt_512_pg( + const __nv_bfloat16* q, const __nv_bfloat16* kc, const __nv_bfloat16* vc, __nv_bfloat16* out, const int* hi, + int p0, int W, int H, int HK, int G, float scale, int win, int ring, const int* tab, long long page, int tok) { + prompt::kernel<512, false, NONE, true>(q, kc, vc, out, hi, p0, W, H, HK, G, scale, win, ring, + Pg{tab, page, tok, 0}); +} + +extern "C" __global__ void __launch_bounds__(NT, 1) tf_wrows_prompt_512_p32_pg( + const __nv_bfloat16* q, const __nv_bfloat16* kc, const __nv_bfloat16* vc, __nv_bfloat16* out, const int* hi, + int p0, int W, int H, int HK, int G, float scale, int win, int ring, const int* tab, long long page, int tok) { + prompt::kernel<512, true, NONE, true>(q, kc, vc, out, hi, p0, W, H, HK, G, scale, win, ring, + Pg{tab, page, tok, 0}); +} + // Rows k, v [n, row] (row = hk * D elements) into the pages at their positions: a block a row, 16 bytes a thread. extern "C" __global__ void __launch_bounds__(128) tf_wrows_put(const __nv_bfloat16* k, const __nv_bfloat16* v, __nv_bfloat16* kc, __nv_bfloat16* vc, const int* pos, diff --git a/zig/src/core/contract/window_rows_records.zig b/zig/src/core/contract/window_rows_records.zig index 35bd98967ab..c59fe82edae 100644 --- a/zig/src/core/contract/window_rows_records.zig +++ b/zig/src/core/contract/window_rows_records.zig @@ -16,5 +16,7 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "window_pages tf_wrows_prompt_256_pg", .symbol = "tf_wrows_prompt_256_pg", .image = "window_pages", .threads = 256, .dynamic = 81920, .opt_in = true }, .usage = .{ .{ .regs = 241, .static = 144, .bound = 256 }, .{ .regs = 244, .static = 144, .bound = 256 }, .{ .regs = 244, .static = 144, .bound = 256 }, .{ .regs = 255, .static = 144, .bound = 256 }, .{ .regs = 255, .static = 144, .bound = 256 } } }, .{ .launch = .{ .name = "window_pages tf_wrows_part_512_pg", .symbol = "tf_wrows_part_512_pg", .image = "window_pages", .threads = 256, .dynamic = 65536, .opt_in = true }, .usage = .{ .{ .regs = 154, .static = 17536, .bound = 256 }, .{ .regs = 157, .static = 17536, .bound = 256 }, .{ .regs = 157, .static = 17536, .bound = 256 }, .{ .regs = 128, .static = 17536, .bound = 256 }, .{ .regs = 128, .static = 17536, .bound = 256 } } }, .{ .launch = .{ .name = "window_pages tf_wrows_merge_512_pg", .symbol = "tf_wrows_merge_512_pg", .image = "window_pages", .threads = 256 }, .usage = .{ .{ .regs = 62, .static = 128, .bound = 256 }, .{ .regs = 64, .static = 128, .bound = 256 }, .{ .regs = 64, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 } } }, + .{ .launch = .{ .name = "window_pages tf_wrows_prompt_512_pg", .symbol = "tf_wrows_prompt_512_pg", .image = "window_pages", .threads = 256, .dynamic = 81920, .opt_in = true }, .usage = .{ .{ .regs = 245, .static = 144, .bound = 256 }, .{ .regs = 246, .static = 144, .bound = 256 }, .{ .regs = 246, .static = 144, .bound = 256 }, .{ .regs = 254, .static = 144, .bound = 256 }, .{ .regs = 254, .static = 144, .bound = 256 } } }, + .{ .launch = .{ .name = "window_pages tf_wrows_prompt_512_p32_pg", .symbol = "tf_wrows_prompt_512_p32_pg", .image = "window_pages", .threads = 256, .dynamic = 81920, .opt_in = true }, .usage = .{ .{ .regs = 251, .static = 144, .bound = 256 }, .{ .regs = 251, .static = 144, .bound = 256 }, .{ .regs = 251, .static = 144, .bound = 256 }, .{ .regs = 254, .static = 144, .bound = 256 }, .{ .regs = 254, .static = 144, .bound = 256 } } }, .{ .launch = .{ .name = "window_pages tf_wrows_put", .symbol = "tf_wrows_put", .image = "window_pages", .threads = 128 }, .usage = .{ .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 44, .static = 0, .bound = 128 }, .{ .regs = 44, .static = 0, .bound = 128 }, .{ .regs = 38, .static = 0, .bound = 128 }, .{ .regs = 38, .static = 0, .bound = 128 } } }, }; diff --git a/zig/src/cuda/window_attention.zig b/zig/src/cuda/window_attention.zig index 07963ebaadb..9b8ad09c8b6 100644 --- a/zig/src/cuda/window_attention.zig +++ b/zig/src/cuda/window_attention.zig @@ -10,16 +10,19 @@ const Module = module.Module; const Function = module.Function; const Stream = stream_.Stream; -/// A Window's `pg` (win 0; head dim 256, or 512's decode): caches name a layer in page 0, `table` `stride` ids a slot. +/// A Window's `pg` (win 0, head dims 256, 512): caches name a layer in page 0; `table` rows of ids, `stride` a slot. pub const Pages = struct { table: u64, page_elems: usize, tokens: usize, stride: usize = 0 }; /// A row's heads and keys (pos - win, pos] (win 0: all) at cache row slot * ring + key % ring; p32: wide P in halves. pub const Window = struct { h: usize, hk: usize, d: usize, win: usize, ring: usize, scale: f32, p32: bool = false, pg: ?Pages = null }; -/// A head dim 256 page's positions are a multiple of this, the decode chunk: a chunk and a prompt tile stay in a page. +/// Positions a head dim 256 page holds (a multiple of): the decode chunk, so a chunk and a prompt tile stay in a page. pub const page_unit = chunk_keys; -/// Head dim 256 pages hold whole chunks; 512's decode looks up each key's page, so its pages hold any count. +/// Keys a prompt tile (window_rows.cuh's BN): a paged tile takes one page base, so prompt pages hold whole tiles. +pub const prompt_tile = 32; + +/// Head dim 256 pages hold whole chunks; 512's decode looks up each key's page (prompt rows: whole tiles, promptWith). fn pagedShape(w: Window) bool { const p = w.pg orelse return true; if (w.win != 0 or p.tokens == 0 or p.page_elems > std.math.maxInt(i63)) return false; @@ -62,8 +65,8 @@ pub const WindowAttention = struct { /// window_rows.cu's kernels at one head dim: decode partials and merge, prompt rows (bf16 P, then P32). pub const Wide = struct { part: Function, merge: Function, prompt: [2]Function, paged: ?Paged = null }; - /// The kernels over paged caches: decode partials, their merge, prompt rows (P as bf16; head dim 256 only). - pub const Paged = struct { part: Function, merge: Function, prompt: ?Function = null }; + /// The kernels over paged caches: decode partials, their merge, prompt rows (P as bf16, then P32; null: none). + pub const Paged = struct { part: Function, merge: Function, prompt: [2]?Function = .{ null, null } }; pub fn load(d: *const Driver) !WindowAttention { if (!kernels.available) return error.BuiltWithoutKernels; @@ -89,15 +92,16 @@ pub const WindowAttention = struct { }, .prompt_fns = p, .rows = rows, .wide_fns = wf }; } - /// Loads window_pages.cu: decode, prompt rows and `put` over caches in pages (head dim 256; 512's decode). + /// Loads window_pages.cu: decode, prompt rows and `put` over caches in pages (head dims 256 and 512; P32 at 512). pub fn loadPages(g: *WindowAttention, d: *const Driver) !void { if (g.pages != null) return; var pages = try Module.load(d, kernels.window_pages); errdefer pages.unload(); - const p: Paged = .{ .part = try pages.function("tf_wrows_part_256_pg"), .merge = try pages.function("tf_wrows_merge_256_pg"), .prompt = try pages.function("tf_wrows_prompt_256_pg") }; - try p.prompt.?.allowDynamicShared(rows_smem[0]); - const p512: Paged = .{ .part = try pages.function("tf_wrows_part_512_pg"), .merge = try pages.function("tf_wrows_merge_512_pg") }; + const p: Paged = .{ .part = try pages.function("tf_wrows_part_256_pg"), .merge = try pages.function("tf_wrows_merge_256_pg"), .prompt = .{ try pages.function("tf_wrows_prompt_256_pg"), null } }; + try p.prompt[0].?.allowDynamicShared(rows_smem[0]); + const p512: Paged = .{ .part = try pages.function("tf_wrows_part_512_pg"), .merge = try pages.function("tf_wrows_merge_512_pg"), .prompt = .{ try pages.function("tf_wrows_prompt_512_pg"), try pages.function("tf_wrows_prompt_512_p32_pg") } }; try p512.part.allowDynamicShared(staged_smem); + for (p512.prompt) |pf| try pf.?.allowDynamicShared(rows_smem[1]); g.put_fn = try pages.function("tf_wrows_put"); g.wide_fns[0].paged = p; g.wide_fns[1].paged = p512; @@ -261,7 +265,12 @@ pub const WindowAttention = struct { /// promptRows by `f` (wideFns, or the contract's controls). pub fn promptWith(f: *const Wide, s: Stream, q: u64, kc: u64, vc: u64, out: u64, p0: usize, n: usize, w: Window, hi: ?u64) !void { const grp = if (w.hk > 0) w.h / w.hk else 0; - if (!wideShape(w) or p0 + n > std.math.maxInt(i32) or !pagedShape(w) or (w.pg != null and (w.p32 or f.paged == null or f.paged.?.prompt == null))) return error.WindowShape; + if (!wideShape(w) or p0 + n > std.math.maxInt(i32) or !pagedShape(w)) return error.WindowShape; + var paged: ?Function = null; + if (w.pg) |p| { // pages hold whole prompt tiles (prompt_tile), and the head dim has this P's paged twin + if (p.tokens % prompt_tile != 0) return error.WindowShape; + paged = (f.paged orelse return error.WindowShape).prompt[@intFromBool(w.p32)] orelse return error.WindowShape; + } if (n == 0) return; const ng = 1024 / w.d; // 16-row groups a block: 8 warps, a 128-dim slice each const hb = if (grp % ng == 0) ng else 1; @@ -274,7 +283,7 @@ pub const WindowAttention = struct { a.add(@as(i32, @intCast(w.ring))); if (w.pg) |p| addPages(&a, p, false); const cfg: launch_.Config = .{ .grid = .{ .x = @intCast((n + rows - 1) / rows), .y = @intCast(w.hk * (grp / hb)), .z = 1 }, .block = .{ .x = 256 }, .shared = promptShared(w.d) }; - try launch_.launch(if (w.pg != null) f.paged.?.prompt.? else f.prompt[@intFromBool(w.p32)], cfg, s, &a); + try launch_.launch(paged orelse f.prompt[@intFromBool(w.p32)], cfg, s, &a); } }; diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index aceda81e1fb..8f77f46dae0 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -219,7 +219,7 @@ const usage = \\ block DFlash block attention over windowed contexts against float64 (synthetic) \\ window sliding-window attention against float64 references (synthetic) \\ window-rows window attention at head dims 256 and 512 against float64 ranges (synthetic) - \\ window-pages-512 head dim 512 decode over shuffled pages bit-equal to the contiguous cache (synthetic) + \\ window-pages-512 head dim 512 decode and prompt rows over shuffled pages: the contiguous bits (synthetic) \\ window-bench WHICH window attention's GPU time: callers (Kolibri-1's shapes) or gemma (head dims 256, 512) \\ moe-glue sigmoid top-k routing and the weighted combine against float64 references (synthetic) \\ dense-rows bf16 rows times weight rows (routers, heads) against float64 references (synthetic) diff --git a/zig/tests/cuda/window_pages512_tests.zig b/zig/tests/cuda/window_pages512_tests.zig index d99bf5ac6cd..0b757fc4214 100644 --- a/zig/tests/cuda/window_pages512_tests.zig +++ b/zig/tests/cuda/window_pages512_tests.zig @@ -1,4 +1,4 @@ -//! window_pages.cu's head dim 512 decode (Gemma 4's global layers) over shuffled pages: the contiguous run's bits. +//! window_pages.cu at head dim 512 (Gemma 4's global layers): paged decode and prompt rows give the contiguous bits. const std = @import("std"); const cuda = @import("cuda"); const check = @import("check.zig"); @@ -24,22 +24,22 @@ const toks = [_]usize{ 16, 37, 256 }; const Pool = struct { kc: u64, vc: u64, pages: wa.Pages }; /// Stream s's keys (rows s * top .. of kc and vc) copied to `tok`-position pages in shuffled order, NaN elsewhere. -fn paged(b: *rows.Bufs, a: std.mem.Allocator, rng: std.Random, kc: []const u16, vc: []const u16, c: Case, tok: usize) !Pool { - const stride = (c.top + tok - 1) / tok; - const count = c.streams * stride + 3; // pages no stream holds - const row = c.hk * d; +fn paged(b: *rows.Bufs, a: std.mem.Allocator, rng: std.Random, kc: []const u16, vc: []const u16, streams: usize, top: usize, hk: usize, tok: usize) !Pool { + const stride = (top + tok - 1) / tok; + const count = streams * stride + 3; // pages no stream holds + const row = hk * d; const page = tok * row; const ids = try a.alloc(i32, count); for (ids, 0..) |*v, i| v.* = @intCast(i); rng.shuffle(i32, ids); - const table = try a.alloc(i32, c.streams * stride); + const table = try a.alloc(i32, streams * stride); for (table, 0..) |*v, i| v.* = ids[i]; const kp = try a.alloc(u16, count * page); const vp = try a.alloc(u16, count * page); @memset(kp, nan); @memset(vp, nan); - for (0..c.streams) |s| for (0..c.top) |j| { - const src = (s * c.top + j) * row; + for (0..streams) |s| for (0..top) |j| { + const src = (s * top + j) * row; const dst = @as(usize, @intCast(table[s * stride + j / tok])) * page + (j % tok) * row; @memcpy(kp[dst..][0..row], kc[src..][0..row]); @memcpy(vp[dst..][0..row], vc[src..][0..row]); @@ -77,7 +77,7 @@ fn case(gpu: check.Gpu, a: std.mem.Allocator, s: cuda.Stream, g: *const wa.Windo for (want) |x| odd += @intFromBool(x & 0x7f80 == 0x7f80); try check.expect(odd > 0, "window pages 512 {s}: the planted +inf reaches the merge's replay", .{c.name}); for (toks) |tok| { - const pool = try paged(&b, a, rng, kc, vc, c, tok); + const pool = try paged(&b, a, rng, kc, vc, c.streams, c.top, c.hk, tok); w.pg = pool.pages; const out = try b.out(s, n * 2); try g.decode(s, dq, pool.kc, pool.vc, out, dp, ds, w, scratch, c.rows); @@ -89,6 +89,56 @@ fn case(gpu: check.Gpu, a: std.mem.Allocator, s: cuda.Stream, g: *const wa.Windo } } +const PCase = struct { name: []const u8, h: usize, hk: usize, p0: usize, n: usize }; + +/// One stream's prompt chunk after p0 cached positions: chunks over many pages, starting mid-page or at a page's start. +const prompt_cases = [_]PCase{ + .{ .name = "12B global prompt (16/1 heads of 512), 300 rows at 1000", .h = 16, .hk = 1, .p0 = 1000, .n = 300 }, + .{ .name = "31B global prompt (32/4 heads of 512), 200 rows at 0", .h = 32, .hk = 4, .p0 = 0, .n = 200 }, + .{ .name = "31B global prompt (32/4 heads of 512), 96 rows at 3013", .h = 32, .hk = 4, .p0 = 3013, .n = 96 }, +}; + +/// A prompt page holds whole 32-key tiles (wa.prompt_tile): one tile, two, and a decode chunk. +const prompt_toks = [_]usize{ 32, 64, 256 }; + +fn prompt(gpu: check.Gpu, a: std.mem.Allocator, s: cuda.Stream, g: *const wa.WindowAttention, rng: std.Random, c: PCase, p32: bool) !void { + var b: rows.Bufs = .{ .gpu = gpu }; + defer b.deinit(); + const top = c.p0 + c.n; + const q = try a.alloc(u16, c.n * c.h * d); + const kc = try a.alloc(u16, top * c.hk * d); + const vc = try a.alloc(u16, kc.len); + rows.fill(rng, q, kc, vc, d); + // the last row's own key holds +inf in a value: its heads of key head 0 run the float64 replay over the pages + vc[(top - 1) * c.hk * d + 7] = 0x7f80; + var w: wa.Window = .{ .h = c.h, .hk = c.hk, .d = d, .win = 0, .ring = 0, .scale = @floatCast(1 / @sqrt(@as(f64, d))), .p32 = p32 }; + const dq = try b.up(std.mem.sliceAsBytes(q)); + const n = c.n * c.h * d; + const flat = try b.out(s, n * 2); + try g.promptRows(s, dq, try b.up(std.mem.sliceAsBytes(kc)), try b.up(std.mem.sliceAsBytes(vc)), flat, c.p0, c.n, w, null); + try s.synchronize(); + const want = try a.alloc(u16, n); + try b.get(flat, want); + var odd: usize = 0; + for (want) |x| odd += @intFromBool(x & 0x7f80 == 0x7f80); + try check.expect(odd > 0, "window pages 512 {s}: the planted +inf reaches the float64 replay", .{c.name}); + for (prompt_toks) |tok| { + const pool = try paged(&b, a, rng, kc, vc, 1, top, c.hk, tok); + w.pg = pool.pages; // the prompt kernel's table is the stream's own row + const out = try b.out(s, n * 2); + try g.promptRows(s, dq, pool.kc, pool.vc, out, c.p0, c.n, w, null); + try s.synchronize(); + const got = try a.alloc(u16, n); + try b.get(out, got); + var what: [160]u8 = undefined; + const p = if (p32) "P32" else "P as bf16"; + try check.sameBytes(try std.fmt.bufPrint(&what, "window pages 512 {s}, {s}: pages of {d} give the contiguous bits", .{ c.name, p, tok }), std.mem.sliceAsBytes(got), std.mem.sliceAsBytes(want)); + } + w.pg.?.tokens = 48; // not whole prompt tiles: refused + const refused = if (g.promptRows(s, dq, 0, 0, flat, c.p0, c.n, w, null)) |_| false else |e| e == error.WindowShape; + try check.expect(refused, "window pages 512: prompt pages of 48 positions refused", .{}); +} + pub fn run(gpu: check.Gpu) !void { var arena: std.heap.ArenaAllocator = .init(gpu.gpa); defer arena.deinit(); @@ -102,5 +152,9 @@ pub fn run(gpu: check.Gpu) !void { _ = arena.reset(.retain_capacity); try case(gpu, arena.allocator(), s, &g, prng.random(), c); } - check.pass("window pages 512: decode over shuffled pages of 16, 37 and 256 positions (NaN in every unused slot) bit-equal to the contiguous cache, the float64 replay included", .{}); + for (prompt_cases) |c| for ([_]bool{ false, true }) |p32| { + _ = arena.reset(.retain_capacity); + try prompt(gpu, arena.allocator(), s, &g, prng.random(), c, p32); + }; + check.pass("window pages 512: decode over shuffled pages of 16, 37 and 256 positions and prompt rows (P as bf16 and P32) over pages of 32, 64 and 256 (NaN in every unused slot) bit-equal to the contiguous cache, the float64 replays included", .{}); } From 4f4d0e70dac08e2c0e96b086179f6da97ffc409c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:19:59 +0100 Subject: [PATCH 4/5] kernel contract: tree attention's _pg kernels and head dim 512's paged decode and prompt rows, with controls --- zig/tests/cuda/contract_tree_attn.zig | 66 +++++++++++++++++++++++-- zig/tests/cuda/contract_window_rows.zig | 9 ++++ 2 files changed, 71 insertions(+), 4 deletions(-) diff --git a/zig/tests/cuda/contract_tree_attn.zig b/zig/tests/cuda/contract_tree_attn.zig index a81f6493dfa..39ad1e6d3a1 100644 --- a/zig/tests/cuda/contract_tree_attn.zig +++ b/zig/tests/cuda/contract_tree_attn.zig @@ -18,8 +18,8 @@ fn keyChain(s: c.Shape) usize { return s.k + tree.max_depth + 16; } -/// A tree attention call's blocks: four warps (sms 0), or one warp a slice with 2 (sms 1) or 3 tile stages. -pub const Variant = struct { d: usize, h: usize, hk: usize, sms: usize, name: []const u8 }; +/// Blocks: four warps (sms 0) or one warp with 2 (sms 1) or 3 stages; `pages`: the _pg kernels, `swap`: their control. +pub const Variant = struct { d: usize, h: usize, hk: usize, sms: usize, name: []const u8, pages: usize = 0, swap: bool = false }; pub const variants = [_]Variant{ .{ .d = 128, .h = 48, .hk = 4, .sms = 0, .name = "cuda tree attention dim 128, four-warp blocks (tf_tree_shared, tf_tree_part, tf_tree_merge)" }, @@ -28,6 +28,14 @@ pub const variants = [_]Variant{ .{ .d = 256, .h = 24, .hk = 4, .sms = 0, .name = "cuda tree attention dim 256, four-warp blocks (tf_tree_shared_256, tf_tree_part_256, tf_tree_merge)" }, .{ .d = 256, .h = 24, .hk = 4, .sms = 1, .name = "cuda tree attention dim 256, one-warp blocks (tf_tree_shared_256_w1, tf_tree_part_256_w1)" }, .{ .d = 256, .h = 24, .hk = 4, .sms = 1 << 20, .name = "cuda tree attention dim 256, one-warp blocks, 3 stages (tf_tree_shared_256_w1s3)" }, + .{ .d = 128, .h = 48, .hk = 4, .sms = 0, .pages = 16, .name = "cuda tree attention dim 128 over pages of 16, four-warp blocks (tf_tree_shared_pg, tf_tree_part_pg)" }, + .{ .d = 128, .h = 48, .hk = 4, .sms = 1, .pages = 37, .name = "cuda tree attention dim 128 over pages of 37, one-warp blocks (tf_tree_shared_w1_pg, tf_tree_part_w1_pg)" }, + .{ .d = 128, .h = 48, .hk = 4, .sms = 1 << 20, .pages = 256, .name = "cuda tree attention dim 128 over pages of 256, 3 stages (tf_tree_shared_w1s3_pg, tf_tree_part_w1s3_pg)" }, + .{ .d = 256, .h = 24, .hk = 4, .sms = 0, .pages = 37, .name = "cuda tree attention dim 256 over pages of 37, four-warp blocks (tf_tree_shared_256_pg, tf_tree_part_256_pg)" }, + .{ .d = 256, .h = 24, .hk = 4, .sms = 1, .pages = 16, .name = "cuda tree attention dim 256 over pages of 16, one-warp blocks (tf_tree_shared_256_w1_pg, tf_tree_part_256_w1_pg)" }, + .{ .d = 256, .h = 24, .hk = 4, .sms = 1 << 20, .pages = 256, .name = "cuda tree attention dim 256 over pages of 256, 3 stages (tf_tree_shared_256_w1s3_pg, tf_tree_part_256_w1s3_pg)" }, + .{ .d = 128, .h = 48, .hk = 4, .sms = 0, .pages = 16, .swap = true, .name = "control: dim 128 paged tree attention whose first page id is an unheld page" }, + .{ .d = 256, .h = 24, .hk = 4, .sms = 1, .pages = 16, .swap = true, .name = "control: dim 256 one-warp paged tree attention whose first page id is an unheld page" }, }; /// Shape: drafted rows (trees of 16 over the streams), query heads (n) and stream 0's committed keys (k). @@ -55,6 +63,7 @@ pub const Tree = struct { vn: std.ArrayList(u16) = .empty, cache: std.ArrayList(u16) = .empty, dev: [9]u64 = @splat(0), + pages: ?tree.Pages = null, sc: tree.Scratch = undefined, out: u64 = 0, @@ -66,7 +75,7 @@ pub const Tree = struct { } pub fn kernel(self: *Tree) g.Kernel { - return .{ .spec = treeSpec(self.v), .ctx = self, .vt = &vt }; + return .{ .spec = treeSpec(self.v), .ctx = self, .vt = &vt, .control = if (self.v.swap) .shapes else null }; } const vt = g.hooks(Tree); @@ -147,12 +156,61 @@ pub const Tree = struct { } self.scale = @floatCast(1 / @sqrt(@as(f64, @floatFromInt(v.d)))); for ([_][]const u8{ std.mem.sliceAsBytes(self.q.items), std.mem.sliceAsBytes(self.kn.items), std.mem.sliceAsBytes(self.vn.items), std.mem.sliceAsBytes(self.cache.items), std.mem.sliceAsBytes(self.offs.items), std.mem.sliceAsBytes(self.row_stream.items), std.mem.sliceAsBytes(streams), std.mem.sliceAsBytes(self.paths.items), std.mem.sliceAsBytes(self.depths.items) }, &self.dev) |bytes, *p| p.* = try self.rig.input(bytes); + self.pages = if (v.pages > 0) try self.paged(rng) else null; const base = try self.rig.scratch(tree.TreeAttention.scratchBytes(n, v.h, v.hk, self.ng, v.d)); self.sc = tree.TreeAttention.scratch(base, n, v.h, v.hk, self.ng, v.d); self.out = try self.rig.output(n * v.h * v.d * 2); return true; } + /// The committed keys copied to shuffled `pages`-position pages (NaN in the rest): origin, offs and the table. + fn paged(self: *Tree, rng: std.Random) !tree.Pages { + const a = self.rig.gpu.gpa; + const v = self.v; + const kv = v.hk * v.d; + const tok = v.pages; + var stride: usize = 0; + var npages: usize = 2; // pages no stream holds + for (self.committed.items) |p| { + stride = @max(stride, (p + tok - 1) / tok); + npages += (p + tok - 1) / tok; + } + const ids = try a.alloc(i32, npages); + defer a.free(ids); + for (ids, 0..) |*x, i| x.* = @intCast(i); + rng.shuffle(i32, ids); + const ns = self.committed.items.len; + const table = try a.alloc(i32, ns * stride); + defer a.free(table); + @memset(table, -1); + const page = tok * kv; + const pool = try a.alloc(u16, 2 * npages * page); + defer a.free(pool); + @memset(pool, c.toBf16(std.math.nan(f32))); + var next: usize = 0; + for (self.committed.items, 0..) |p, si| { + for (0..(p + tok - 1) / tok) |j| { + table[si * stride + j] = ids[next]; + next += 1; + } + for (0..p) |j| for (0..2) |part| { + const src: usize = @as(usize, @intCast(self.offs.items[2 * si + part])) + j * kv; + const dst = part * npages * page + @as(usize, @intCast(table[si * stride + j / tok])) * page + j % tok * kv; + @memcpy(pool[dst..][0..kv], self.cache.items[src..][0..kv]); + }; + } + if (v.swap) table[0] = ids[next]; // the control: stream 0's first page is one no stream holds (NaN) + const offs = try a.alloc(i64, 2 * ns); + defer a.free(offs); + for (0..ns) |si| { + offs[2 * si] = 0; + offs[2 * si + 1] = @intCast(npages * page); + } + self.dev[3] = try self.rig.input(std.mem.sliceAsBytes(pool)); + self.dev[4] = try self.rig.input(std.mem.sliceAsBytes(offs)); + return .{ .table = try self.rig.input(std.mem.sliceAsBytes(table)), .page = page, .tok = tok, .stride = stride }; + } + /// NaN in a query, +inf and -inf in values (committed, on a path, in one column), a NaN key, +inf at tiny weights. fn plant(self: *Tree) void { const d = self.v.d; @@ -215,7 +273,7 @@ pub const Tree = struct { pub fn run(self: *Tree) !void { const v = self.v; - const rws: tree.Rows = .{ .row_stream = self.dev[5], .streams = self.dev[6], .offs = self.dev[4], .origin = self.dev[3], .paths = self.dev[7], .depths = self.dev[8] }; + const rws: tree.Rows = .{ .row_stream = self.dev[5], .streams = self.dev[6], .offs = self.dev[4], .origin = self.dev[3], .paths = self.dev[7], .depths = self.dev[8], .pages = self.pages }; try self.ta.run(self.rig.s, self.dev[0], self.dev[1], self.dev[2], rws, self.sc, self.out, self.shape.rows, v.h, v.hk, v.d, self.ng, self.scale); try self.rig.s.synchronize(); } diff --git a/zig/tests/cuda/contract_window_rows.zig b/zig/tests/cuda/contract_window_rows.zig index 8f4a5c6f316..1d1e1561d79 100644 --- a/zig/tests/cuda/contract_window_rows.zig +++ b/zig/tests/cuda/contract_window_rows.zig @@ -81,6 +81,15 @@ const paged = [_]Cfg{ .{ .name = "cuda window_pages prompt tf_wrows_prompt_256_pg (P as bf16), 16/4 heads, no window, pages of 1024", .h = 16, .hk = 4, .win = 0, .ring = 0, .prompt = true, .pages = 1024, .served = paged_prompt }, .{ .name = "control: paged decode whose first two streams' tables are swapped", .h = 16, .hk = 4, .win = 0, .ring = 32768, .streams = 2, .pages = 256, .ctl = .swap, .served = paged_decode }, .{ .name = "control: paged prompt rows whose first page id is a later page's", .h = 16, .hk = 4, .win = 0, .ring = 0, .prompt = true, .pages = 256, .ctl = .stale, .served = paged_prompt }, + // Gemma 4's global layers (head dim 512) over pages: the decode looks up each key's page, a prompt tile one + .{ .name = "cuda window_pages decode tf_wrows_part_512_pg + tf_wrows_merge_512_pg, 16/1 heads of 512, pages of 256", .h = 16, .hk = 1, .d = 512, .win = 0, .ring = 32768, .streams = 2, .pages = 256, .served = global_decode }, + .{ .name = "cuda window_pages decode tf_wrows_part_512_pg + tf_wrows_merge_512_pg, 16/1 heads of 512, pages of 37", .h = 16, .hk = 1, .d = 512, .win = 0, .ring = 32768, .streams = 2, .pages = 37, .served = global_decode }, + .{ .name = "cuda window_pages decode tf_wrows_part_512_pg + tf_wrows_merge_512_pg, 10/2 heads of 512 (GQA 5), pages of 256", .h = 10, .hk = 2, .d = 512, .win = 0, .ring = 32768, .streams = 2, .pages = 256, .served = gqa5_decode }, + .{ .name = "cuda window_pages prompt tf_wrows_prompt_512_p32_pg, 16/1 heads of 512, pages of 256", .h = 16, .hk = 1, .d = 512, .win = 0, .ring = 0, .prompt = true, .p32 = true, .pages = 256, .served = global_prompt }, + .{ .name = "cuda window_pages prompt tf_wrows_prompt_512_pg (P as bf16), 32/4 heads of 512, pages of 64", .h = 32, .hk = 4, .d = 512, .win = 0, .ring = 0, .prompt = true, .pages = 64, .served = global31_prompt }, + .{ .name = "cuda window_pages prompt tf_wrows_prompt_512_p32_pg, 10/2 heads of 512 (GQA 5), pages of 32", .h = 10, .hk = 2, .d = 512, .win = 0, .ring = 0, .prompt = true, .p32 = true, .pages = 32, .served = gqa5_prompt }, + .{ .name = "control: head dim 512 paged decode whose first two streams' tables are swapped", .h = 16, .hk = 1, .d = 512, .win = 0, .ring = 32768, .streams = 2, .pages = 37, .ctl = .swap, .served = global_decode }, + .{ .name = "control: head dim 512 paged prompt rows whose first page id is a later page's", .h = 16, .hk = 1, .d = 512, .win = 0, .ring = 0, .prompt = true, .p32 = true, .pages = 256, .ctl = .stale, .served = global_prompt }, }; fn decodeAt(comptime h: usize) []const c.Shape { From 69ae32c970f8ce08f4a5ed84eab747554869cd50 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:46:15 +0000 Subject: [PATCH 5/5] changelog: paged tree attention and head dim 512 window kernels (#1618) --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 418830e84d3..95173afb1e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- CUDA: tree attention (head dims 128 and 256) and head dim 512 window decode and prompt rows gain kernels that read committed keys from a page table, so a family can keep its full-attention caches in the shared KV page pool (#1618; Gemma 4 and Kolibri-1 adopt them in follow-ups). Nothing launches them yet: the existing kernels' SASS is unchanged on sm_80, 86, 89, 120 and 121, and paged results are byte-equal to the contiguous cache over shuffled pages of 16, 37 and 256 positions. Thanks to @jschmied. + - Nemotron 3.5 on Metal: `TF_NEMOTRON_METAL_KV_PAGES=1` (off by default) keeps each stream's keys and values in pages of the shared KV pool instead of a buffer per layer, with paged versions of Nemotron's six K/V kernels for decode, MTP drafts, trees, GPU rounds and prompts, and admission counted in pages (#1537, step 3 of #1293). Each paged kernel is bit-equal to the one it replaces, and the kernel contract now checks Nemotron's attention kernels against float64, with launch records for the 288 to 512 thread partials. Replies are the same tokens with the setting on or off and as before: on an M3 Pro and an M5 Max, at 1 and 4 streams, prompts up to 20k tokens, greedy and sampled, drafted and plain, and on resumed turns; on the M3 Pro, prompt and decode speed were within 0.3%. A stream still takes pages for its whole context when it opens, so it saves no memory yet. Thanks to @jschmied and @swbiggart. - Vulkan: the first part of an opt-in Vulkan backend for Linux GPUs, built only with `-Dvulkan=true`: the runtime (loader, device, buffers, fenced submits) and one kernel, the MLX affine 4-bit group-64 projection, registered in the kernel contract with its float64 cases, planted controls and measured per-chip limits. `zig build vulkan-kernel-contract -Dvulkan=true` runs it; the author's runs pass gates 1 to 4 and catch all 8 controls on Apple M1, M1 Max and M2 Max under Mesa Honeykrisp. No model runs on it yet, and default builds are unchanged (#1526, for #1420). Thanks to @joshuaswarren.