Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
751e7f8
cuda: tree attention and DFlash block attention for every family (tre…
jschmied Oct 12, 2026
de31ba9
cuda/tree_attention: a group's 4 slices write their own partials, the…
jschmied Oct 13, 2026
6c3d49d
cuda/tree_attention: four-warp blocks combine a group's slices themse…
jschmied Oct 13, 2026
197cacc
cuda/tree_attention: one-warp blocks fetch their tiles 2 ahead (3 cp.…
jschmied Oct 13, 2026
403549d
cuda/tree_attention: 512-key groups (4x the warps in flight at one ro…
jschmied Oct 13, 2026
591065e
cuda/tree_attention: the merge issues a chunk's partial loads (16 slo…
jschmied Oct 14, 2026
df0ef6b
cuda: sliding-window attention, sigmoid top-k MoE routing and combine…
jschmied Oct 13, 2026
492716b
cuda/tree_attention: each row's own max flag, so a NaN head leaves ot…
jschmied Oct 17, 2026
f812fbe
cuda/block_attention: keys a row cannot see add nothing, so an infini…
jschmied Oct 17, 2026
d18a720
cuda/tree_attention, block_attention: registered with the kernel cont…
jschmied Oct 17, 2026
ce16098
cuda/window_attention: the tensor-core decode keeps each head's own m…
jschmied Oct 17, 2026
63d1507
cuda/window_attention: the split decode's slots outside the window ho…
jschmied Oct 17, 2026
40de67d
cuda/window_attention: prompt rows' keys a row cannot see add nothing…
jschmied Oct 17, 2026
8f93377
cuda/window_attention, moe_glue, dense_rows: registered with the kern…
jschmied Oct 17, 2026
7d59918
cuda/window_attention: the tensor-core decode's per-head max needs no…
jschmied Oct 17, 2026
0ad4f17
tests/cuda/contract_attn: the reference's constructor frees what it t…
jschmied Oct 17, 2026
2ae3b69
cuda/block_attention: the replay takes every NaN and infinite value o…
jschmied Oct 18, 2026
462d952
cuda/window_attention: the prompt replay takes every NaN and infinite…
jschmied Oct 18, 2026
3c82eb3
cuda/block_attention: the replay's block tile keeps the infinities ad…
jschmied Oct 18, 2026
0facb0f
cuda/tree_attention: a NaN or infinite partial runs again with those …
jschmied Oct 18, 2026
8cba69e
cuda/window_attention: the decode kernels run a NaN or infinite tile …
jschmied Oct 18, 2026
965c8cd
cuda/tree_attention, block_attention: the replay's comments on one li…
jschmied Oct 18, 2026
74b749f
cuda/window_attention: the split decode and its merge move to window_…
jschmied Oct 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
cuda/tree_attention: a group's 4 slices write their own partials, the…
… merge combines them in order; a slice takes its own one-warp block where four-warp blocks would leave SMs idle (TreeAttention.sms), the same bits
  • Loading branch information
jschmied committed Oct 16, 2026
commit de31ba9bffe55e1587b77de5226521ffae4c69f0
118 changes: 57 additions & 61 deletions zig/kernels/cuda/tree_attention.cu
Original file line number Diff line number Diff line change
Expand Up @@ -58,17 +58,18 @@ extern "C" __global__ void tf_tree_paths(const int* __restrict__ parents, int* _
}

// Group gi of key head kh for 16 (row, head) pairs from pair pf (pair m: row rq + m / G, head m % G), one mma tile.
template <int D, int HB>
template <int D, int HB, int W>
__device__ __forceinline__ void 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) {
int64_t rq, int pf, int npairs, int64_t row, int slice) {
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[];
const int warp = threadIdx.x / 32, lane = threadIdx.x % 32, g8 = lane / 4, qd = lane % 4, mt = lane / 8;
const int wi = W == 4 ? warp : slice; // the group's slice: key tiles wi, wi + 4, ...
const int64_t r = row; // the row whose stream and depth set the keys
const int kh = blockIdx.y, G = h / hk;
const int s = row_stream[r];
Expand All @@ -80,7 +81,7 @@ __device__ __forceinline__ void tree_group(
uint4* ks = smem + warp * 2 * HB * C;
uint4* vs = ks + HB * C;
uint32_t qa[QREG ? K16 : 1][4];
uint4* qs = smem + 4 * 2 * HB * C; // !QREG: the row's heads [16][D], shared by the warps
uint4* qs = smem + W * 2 * HB * C; // !QREG: the row's heads [16][D], shared by the warps
if constexpr (QREG) {
const int a0 = pf + g8, a1 = pf + g8 + 8;
const bool v0 = a0 < npairs, v1 = a1 < npairs;
Expand Down Expand Up @@ -108,7 +109,7 @@ __device__ __forceinline__ void tree_group(
#pragma unroll
for (int i = 0; i < NB; ++i) o[i][0] = o[i][1] = o[i][2] = o[i][3] = 0.0f;
float m0 = -INFINITY, m1 = -INFINITY, l0 = 0.0f, l1 = 0.0f;
for (int t = k0 / HB + warp; t * HB < k1; t += 4) {
for (int t = k0 / HB + wi; t * HB < k1; t += 4) {
for (int i = lane; i < HB * C; i += 32) {
const int key = t * HB + i / C;
const bool in = key < k1;
Expand Down Expand Up @@ -216,126 +217,121 @@ __device__ __forceinline__ void tree_group(
}
__syncwarp();
}
__syncthreads();
float* os = reinterpret_cast<float*>(smem); // [4 warps][16 heads][D], then max and sum [4][16]
float* ms = os + 4 * 16 * D;
float* ls = ms + 4 * 16;
// each slice's partial (o, max, sum) of its 16 pairs: the merge combines a group's 4 slices in order
#pragma unroll
for (int i = 0; i < NB; ++i) {
const int d = 8 * i + 2 * qd;
os[(warp * 16 + g8) * D + d] = o[i][0];
os[(warp * 16 + g8) * D + d + 1] = o[i][1];
os[(warp * 16 + g8 + 8) * D + d] = o[i][2];
os[(warp * 16 + g8 + 8) * D + d + 1] = o[i][3];
}
if (qd == 0) {
ms[warp * 16 + g8] = m0, ls[warp * 16 + g8] = l0;
ms[warp * 16 + g8 + 8] = m1, ls[warp * 16 + g8 + 8] = l1;
}
__syncthreads();
for (int idx = threadIdx.x; idx < 16 * D; idx += 128) {
const int hd = idx / D, e = idx % D;
for (int half = 0; half < 2; ++half) {
const int hd = g8 + 8 * half;
if (pf + hd >= npairs) continue;
const int64_t part = ((rq + (pf + hd) / G) * hk + kh) * ng + gi;
const int64_t part = (((rq + (pf + hd) / G) * hk + kh) * ng + gi) * 4 + wi;
const int head = (pf + hd) % G;
float mm = -INFINITY;
for (int w = 0; w < 4; ++w) mm = fmaxf(mm, ms[w * 16 + hd]);
float acc = 0.0f, l = 0.0f;
for (int w = 0; w < 4; ++w) {
const float mw = ms[w * 16 + hd];
if (mw == -INFINITY) continue;
const float a = texp(__fsub_rn(mw, mm));
acc = __fmaf_rn(a, os[(w * 16 + hd) * D + e], acc);
l = __fmaf_rn(a, ls[w * 16 + hd], l);
#pragma unroll
for (int i = 0; i < NB; ++i) {
const int d = 8 * i + 2 * qd;
po[(part * 16 + head) * D + d] = o[i][2 * half];
po[(part * 16 + head) * D + d + 1] = o[i][2 * half + 1];
}
po[(part * 16 + head) * D + e] = acc;
if (e == 0) pm[part * 16 + head] = mm, pl[part * 16 + head] = l;
if (qd == 0) pm[part * 16 + head] = half ? m1 : m0, pl[part * 16 + head] = half ? l1 : l0;
}
}

// A stream's full committed groups once for its rows, 16 (row, head) pairs a block: each partial a row block's bits.
template <int D, int HB>
template <int D, int HB, int W>
__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 int G = h / hk;
for (int item = blockIdx.x; item < n * ng; item += gridDim.x) { // (row, group): a fixed grid, no empty blocks
const int64_t r = item / ng;
const int gi = item % ng;
const int per = W == 4 ? 1 : 4; // slices an item takes a block
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;
const int st = row_stream[r];
const int64_t r0 = streams[4 * st];
const int pairs = streams[4 * st + 1] * G, p = streams[4 * st + 2];
const int tile = static_cast<int>(r - r0); // a stream's j-th row hosts its j-th pair tile (tiles <= rows)
if (tile * 16 >= pairs || (gi + 1) * SPAN > p) continue;
tree_group<D, HB>(q, q, q, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, scale, gi, ng, r0,
tile * 16, pairs, r);
tree_group<D, HB, W>(q, q, q, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, scale, gi, ng,
r0, tile * 16, pairs, r, item % per);
__syncthreads();
}
}

#define TF_TREE_SHARED(NAME, D, HB) \
extern "C" __global__ void __launch_bounds__(128) NAME( \
#define TF_TREE_SHARED(NAME, D, HB, W) \
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) { \
tree_shared<D, HB>(q, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, scale, ng, n); \
tree_shared<D, HB, W>(q, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, scale, ng, n); \
}

TF_TREE_SHARED(tf_tree_shared, 128, 32)
TF_TREE_SHARED(tf_tree_shared_256, 256, 16)
TF_TREE_SHARED(tf_tree_shared, 128, 32, 4)
TF_TREE_SHARED(tf_tree_shared_256, 256, 16, 4)
TF_TREE_SHARED(tf_tree_shared_w1, 128, 32, 1)
TF_TREE_SHARED(tf_tree_shared_256_w1, 256, 16, 1)

// Block (row, key head, group slot): the row's groups past its stream's full committed ones, slot, slot + slots, ...
template <int D, int HB>
template <int D, int HB, int W>
__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) {
const int64_t r = blockIdx.x;
const int p = streams[4 * row_stream[r] + 2], total = p + depths[r];
for (int gi = blockIdx.z + p / SPAN; gi < ng && gi * SPAN < total; gi += gridDim.z) { // full committed: shared
tree_group<D, HB>(q, kn, vn, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, scale, gi, ng,
r, 0, h / hk, r);
const int per = W == 4 ? 1 : 4, slot = blockIdx.z / per, slots = gridDim.z / per;
for (int gi = slot + p / SPAN; gi < ng && gi * SPAN < total; gi += slots) { // full committed: shared
tree_group<D, HB, W>(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);
__syncthreads(); // the next group's tiles reuse the partials' shared memory
}
}

#define TF_TREE_PART(NAME, D, HB) \
extern "C" __global__ void __launch_bounds__(128) NAME( \
#define TF_TREE_PART(NAME, D, HB, W) \
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) { \
tree_part<D, HB>(q, kn, vn, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, scale, ng); \
tree_part<D, HB, W>(q, kn, vn, origin, offs, row_stream, streams, paths, depths, po, pm, pl, h, hk, scale, \
ng); \
}

TF_TREE_PART(tf_tree_part, 128, 32)
TF_TREE_PART(tf_tree_part_256, 256, 16)
TF_TREE_PART(tf_tree_part, 128, 32, 4)
TF_TREE_PART(tf_tree_part_256, 256, 16, 4)
TF_TREE_PART(tf_tree_part_w1, 128, 32, 1)
TF_TREE_PART(tf_tree_part_256_w1, 256, 16, 1)

// out [W, H, D] bf16: block (row, key head) folds the row's groups in order.
// out [W, H, D] bf16: block (row, key head, head) folds the row's groups in order, each group's 4 slices first.
extern "C" __global__ void __launch_bounds__(256) tf_tree_merge(
const float* __restrict__ po, const float* __restrict__ pm, const float* __restrict__ pl,
const int* __restrict__ row_stream, const int* __restrict__ streams, const int* __restrict__ depths,
__nv_bfloat16* __restrict__ out, int h, int hk, int ng, int d) {
const int64_t r = blockIdx.x;
const int kh = blockIdx.y, G = h / hk;
const int kh = blockIdx.y, G = h / hk, hd = blockIdx.z; // block (row, key head, head): each element alone
const int total = streams[4 * row_stream[r] + 2] + depths[r];
const int groups = (total + SPAN - 1) / SPAN;
for (int idx = threadIdx.x; idx < G * d; idx += 256) {
const int hd = idx / d, e = idx % d;
for (int e = threadIdx.x; e < d; e += 256) {
float m = -INFINITY, l = 0.0f, acc = 0.0f;
for (int gi = 0; gi < groups; ++gi) {
const int64_t part = (r * hk + kh) * ng + gi;
const float cm = pm[part * 16 + hd], cl = pl[part * 16 + hd];
const int64_t part = ((r * hk + kh) * ng + gi) * 4;
float cm = -INFINITY;
for (int w = 0; w < 4; ++w) cm = fmaxf(cm, pm[(part + w) * 16 + hd]);
float co = 0.0f, cl = 0.0f;
for (int w = 0; w < 4; ++w) {
const float mw = pm[(part + w) * 16 + hd];
if (mw == -INFINITY) continue;
const float aw = texp(__fsub_rn(mw, cm));
co = __fmaf_rn(aw, po[((part + w) * 16 + hd) * d + e], co);
cl = __fmaf_rn(aw, pl[(part + w) * 16 + hd], cl);
}
const bool active = cl > 0.0f;
const float next = active ? fmaxf(m, cm) : m;
const float a = active ? (m == -INFINITY ? 0.0f : texp(__fsub_rn(m, next))) : 1.0f;
const float b = active ? texp(__fsub_rn(cm, next)) : 0.0f;
acc = __fmaf_rn(acc, a, __fmul_rn(po[(part * 16 + hd) * d + e], b));
acc = __fmaf_rn(acc, a, __fmul_rn(co, b));
l = __fmaf_rn(l, a, __fmul_rn(cl, b));
m = next;
}
Expand Down
31 changes: 24 additions & 7 deletions zig/src/cuda/tree_attention.zig
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ const Stream = stream_.Stream;
pub const span = 2048;
pub const max_depth = 128;
const part_smem = [2]u32{ 4 * 2 * 32 * 16 * 16, 4 * 2 * 16 * 32 * 16 + 16 * 32 * 16 };
/// The one-warp blocks' shared memory: one warp's K/V slots (at 256 also the queries).
const part_smem_w1 = [2]u32{ 2 * 32 * 16 * 16, 2 * 16 * 32 * 16 + 16 * 32 * 16 };
/// A group's slices: its key tiles dealt to 4 warps, one partial each, combined in order by the merge.
const slices = 4;

/// 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 };
Expand All @@ -25,9 +29,13 @@ pub const TreeAttention = struct {
paths_fn: Function,
part_fns: [2]Function, // head dim 128, 256
shared_fns: [2]Function,
part_w1: [2]Function, // the same slices, one warp a block
shared_w1: [2]Function,
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,
/// The device's SMs: where the four-warp grid would leave some idle, a slice takes its own block (the same bits).
sms: usize = 0,

pub fn load(d: *const Driver) !TreeAttention {
if (!kernels.available) return error.BuiltWithoutKernels;
Expand All @@ -37,7 +45,11 @@ pub const TreeAttention = struct {
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);
return .{ .mod = mod, .paths_fn = try mod.function("tf_tree_paths"), .part_fns = parts, .shared_fns = shared, .merge_fn = try mod.function("tf_tree_merge") };
var parts1: [2]Function = .{ try mod.function("tf_tree_part_w1"), try mod.function("tf_tree_part_256_w1") };
for (&parts1, part_smem_w1) |*f, b| try f.allowDynamicShared(b);
var shared1: [2]Function = .{ try mod.function("tf_tree_shared_w1"), try mod.function("tf_tree_shared_256_w1") };
for (&shared1, part_smem_w1) |*f, b| try f.allowDynamicShared(b);
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") };
}

pub fn unload(g: *TreeAttention) void {
Expand All @@ -49,13 +61,13 @@ pub const TreeAttention = struct {
return (keys + span - 1) / span;
}

/// The fp32 partials of `rows` rows, `hk` key heads and `ng` groups: o [.., 16, dim], then max and sum [.., 16].
/// fp32 partials of `rows` rows, `hk` key heads, `ng` groups, 4 slices each: o [.., 16, dim], max and sum [.., 16].
pub fn scratchBytes(rows: usize, hk: usize, ng: usize, dim: usize) usize {
return rows * hk * ng * 16 * (dim + 2) * 4;
return rows * hk * ng * slices * 16 * (dim + 2) * 4;
}

pub fn scratch(base: u64, rows: usize, hk: usize, ng: usize, dim: usize) Scratch {
const parts = rows * hk * ng * 16;
const parts = rows * hk * ng * slices * 16;
return .{ .o = base, .m = base + parts * dim * 4, .l = base + parts * dim * 4 + parts * 4 };
}

Expand Down Expand Up @@ -86,15 +98,20 @@ pub const TreeAttention = struct {
c.add(scale);
c.add(@as(i32, @intCast(ng)));
c.add(@as(i32, @intCast(n)));
try launch_.launch(g.shared_fns[which], .{ .grid = .{ .x = @intCast(@min(n * ng, g.shared_blocks)), .y = @intCast(hk), .z = 1 }, .block = .{ .x = 128 }, .shared = part_smem[which] }, s, &c);
// one warp a block where four-warp blocks would leave SMs idle: each slice its own block, the same partials
const one = @min(n * ng, g.shared_blocks) * hk < g.sms;
const per: usize = if (one) slices else 1;
const block: u32 = if (one) 32 else 128;
const smem = if (one) part_smem_w1[which] else part_smem[which];
try launch_.launch(if (one) g.shared_w1[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);
// a row's own block: its boundary group and at most the next (a path is at most 128 keys)
try launch_.launch(g.part_fns[which], .{ .grid = .{ .x = @intCast(n), .y = @intCast(hk), .z = @intCast(@min(ng, 2)) }, .block = .{ .x = 128 }, .shared = part_smem[which] }, s, &a);
try launch_.launch(if (one) g.part_w1[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);
var b: launch_.Args = .{};
for ([_]u64{ sc.o, sc.m, sc.l, rows.row_stream, rows.streams, rows.depths, out }) |v| b.add(v);
b.add(@as(i32, @intCast(h)));
b.add(@as(i32, @intCast(hk)));
b.add(@as(i32, @intCast(ng)));
b.add(@as(i32, @intCast(dim)));
try launch_.launch(g.merge_fn, .{ .grid = .{ .x = @intCast(n), .y = @intCast(hk), .z = 1 }, .block = .{ .x = 256 } }, s, &b);
try launch_.launch(g.merge_fn, .{ .grid = .{ .x = @intCast(n), .y = @intCast(hk), .z = @intCast(h / hk) }, .block = .{ .x = 256 } }, s, &b);
}
};
Loading