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: sliding-window attention, sigmoid top-k MoE routing and combine…
…, and dense rows for every family, checked against float64
  • Loading branch information
jschmied committed Oct 16, 2026
commit df0ef6bcae57d79cb454045f92f4d868b22750cb
3 changes: 3 additions & 0 deletions zig/build/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ const kernels = [_]Kernel{
.{ .name = "prompt16", .flags = &.{"-O3"} }, // nvfp4/prompt.cu's FP4 and FP8 tile 4, tensorfold_nvfp4_prompt_v1
.{ .name = "tree_attention", .flags = &.{"-O3"} }, // ours: committed keys and paths (cuda/tree_attention.zig)
.{ .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 = "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
.{ .name = "glm_kda", .flags = &.{ "-O3", "--fmad=false" } }, // GLM: the Python family's glm5_next/cuda/kda.cu
.{ .name = "glm_glue", .flags = &.{"-O3"} }, // ours: the Python family's Triton glue by hand, its PTX op for op
Expand Down
70 changes: 70 additions & 0 deletions zig/kernels/cuda/dense_rows.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// bf16 rows times bf16 weight rows into fp32 for every CUDA family: routers and output heads (core/dense_ref.zig).

// A warp an output column, RT rows a launch tile; each row's sum runs in one order whatever RT and the row count.

#include <cuda_bf16.h>
#include <stdint.h>

namespace tf_dense {

constexpr int WARPS = 8;
constexpr int VEC = 8; // bf16 a 16-byte load

__device__ __forceinline__ void unpack(const uint4& u, float* f) {
const __nv_bfloat162* h = reinterpret_cast<const __nv_bfloat162*>(&u);
#pragma unroll
for (int i = 0; i < 4; ++i) {
const float2 t = __bfloat1622float2(h[i]);
f[2 * i] = t.x;
f[2 * i + 1] = t.y;
}
}

// out[r, n] = x[r] . w[n] for a tile's rows: lane l sums k = 8 l + 256 j in order, then the fixed shuffle tree.
template <int RT>
__device__ __forceinline__ void tile(const __nv_bfloat16* x, int64_t x_stride, const __nv_bfloat16* w, float* out,
int64_t out_stride, int rows, int n, int k) {
const int lane = threadIdx.x & 31;
const int col = blockIdx.x * WARPS + (threadIdx.x >> 5);
const int r0 = blockIdx.y * RT;
if (col >= n) return;
float acc[RT];
#pragma unroll
for (int r = 0; r < RT; ++r) acc[r] = 0.f;
const __nv_bfloat16* wr = w + static_cast<int64_t>(col) * k;
#pragma unroll 4 // several 16-byte weight loads in flight a lane (memory-level parallelism)
for (int k0 = lane * VEC; k0 < k; k0 += 32 * VEC) {
float wf[VEC];
unpack(*reinterpret_cast<const uint4*>(wr + k0), wf);
#pragma unroll
for (int r = 0; r < RT; ++r) {
if (r0 + r >= rows) break;
float xf[VEC];
unpack(*reinterpret_cast<const uint4*>(x + (r0 + r) * x_stride + k0), xf);
#pragma unroll
for (int i = 0; i < VEC; ++i) acc[r] = __fmaf_rn(xf[i], wf[i], acc[r]);
}
}
#pragma unroll
for (int r = 0; r < RT; ++r) {
float v = acc[r];
for (int m = 16; m > 0; m >>= 1) v = __fadd_rn(v, __shfl_xor_sync(0xFFFFFFFFu, v, m));
if (lane == 0 && r0 + r < rows) out[(r0 + r) * out_stride + col] = v;
}
}

} // namespace tf_dense

using namespace tf_dense;

#define TF_DENSE_ROWS(RT) \
extern "C" __global__ void __launch_bounds__(WARPS * 32) tf_dense_rows_##RT( \
const __nv_bfloat16* x, long long x_stride, const __nv_bfloat16* w, float* out, long long out_stride, \
int rows, int n, int k) { \
tile<RT>(x, x_stride, w, out, out_stride, rows, n, k); \
}

TF_DENSE_ROWS(1)
TF_DENSE_ROWS(4)
TF_DENSE_ROWS(16)
TF_DENSE_ROWS(32)
184 changes: 184 additions & 0 deletions zig/kernels/cuda/moe_glue.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
// MoE glue for every CUDA family (float64 references: core/moe_ref.zig): sigmoid top-k and the weighted combine.

// Every row's bits depend on that row alone; kinds 0 fp32, 1 fp16, 2 bf16 (as norms.cu).

#include <cuda_bf16.h>
#include <cuda_fp16.h>
#include <math.h>
#include <stdint.h>

namespace tf_moe {

constexpr int NT = 256;
constexpr int MOST = 4096; // experts a row ranks

__device__ __forceinline__ float load(const void* p, int kind, int64_t i) {
if (kind == 0) return static_cast<const float*>(p)[i];
if (kind == 1) return __half2float(static_cast<const __half*>(p)[i]);
return __bfloat162float(static_cast<const __nv_bfloat16*>(p)[i]);
}

__device__ __forceinline__ void store(void* p, int kind, int64_t i, float v) {
if (kind == 0) static_cast<float*>(p)[i] = v;
else if (kind == 1) static_cast<__half*>(p)[i] = __float2half_rn(v);
else static_cast<__nv_bfloat16*>(p)[i] = __float2bfloat16_rn(v);
}

// (value, id) wins over (other value, other id): the larger value, the lower id among equals.
__device__ __forceinline__ bool beats(float v, int i, float w, int j) {
return v > w || (v == w && i < j);
}

} // namespace tf_moe

using namespace tf_moe;

// Top `topk` by logit + bias (ties: lower id), weights sigmoid(logit) [normalized] * scale; `shared`: slot topk = ne.
extern "C" __global__ void __launch_bounds__(NT) tf_moe_topk_sigmoid(const float* logits, const float* bias, int* pick,
float* wts, int ne, int topk, int shared,
int normalize, float scale) {
__shared__ float v[MOST];
__shared__ float best_v[NT / 32];
__shared__ int best_i[NT / 32];
__shared__ int picked[64];
const int64_t r = blockIdx.x;
const float* lg = logits + r * ne;
for (int e = threadIdx.x; e < ne; e += NT) v[e] = __fadd_rn(lg[e], bias != nullptr ? bias[e] : 0.f);
__syncthreads();
for (int k = 0; k < topk; ++k) {
float bv = -INFINITY;
int bi = ne;
for (int e = threadIdx.x; e < ne; e += NT)
if (beats(v[e], e, bv, bi)) bv = v[e], bi = e;
for (int m = 16; m > 0; m >>= 1) {
const float ov = __shfl_xor_sync(0xFFFFFFFFu, bv, m);
const int oi = __shfl_xor_sync(0xFFFFFFFFu, bi, m);
if (beats(ov, oi, bv, bi)) bv = ov, bi = oi;
}
if ((threadIdx.x & 31) == 0) best_v[threadIdx.x >> 5] = bv, best_i[threadIdx.x >> 5] = bi;
__syncthreads();
if (threadIdx.x == 0) {
float tv = best_v[0];
int ti = best_i[0];
for (int w = 1; w < NT / 32; ++w)
if (beats(best_v[w], best_i[w], tv, ti)) tv = best_v[w], ti = best_i[w];
picked[k] = ti;
v[ti] = -INFINITY;
}
__syncthreads();
}
if (threadIdx.x == 0) {
const int slots = topk + (shared ? 1 : 0);
float sum = 0.f;
float w[64];
for (int k = 0; k < topk; ++k) {
w[k] = __fdiv_rn(1.f, __fadd_rn(1.f, expf(-lg[picked[k]])));
sum = __fadd_rn(sum, w[k]);
}
for (int k = 0; k < topk; ++k) {
pick[r * slots + k] = picked[k];
wts[r * slots + k] = __fmul_rn(normalize ? __fdiv_rn(w[k], sum) : w[k], scale);
}
if (shared) pick[r * slots + topk] = ne, wts[r * slots + topk] = 1.f;
}
}

// A float's order as an unsigned (-0 as +0, so equal values stay equal).
__device__ __forceinline__ unsigned ordered(float v) {
const unsigned u = __float_as_uint(__fadd_rn(v, 0.f));
return u & 0x80000000u ? ~u : u | 0x80000000u;
}

// tf_moe_topk_sigmoid with a warp a row (up to 32 * PER experts): values in registers, no block barrier.
constexpr int PER = 16;

extern "C" __global__ void __launch_bounds__(256) tf_moe_topk_sigmoid_warp(const float* logits, const float* bias,
int* pick, float* wts, int rows, int ne,
int topk, int shared, int normalize,
float scale) {
const int lane = threadIdx.x & 31;
const int64_t r = static_cast<int64_t>(blockIdx.x) * 8 + (threadIdx.x >> 5);
if (r >= rows) return;
const float* lg = logits + r * ne;
float v[PER], x[PER];
#pragma unroll
for (int j = 0; j < PER; ++j) {
const int e = lane + 32 * j;
x[j] = e < ne ? lg[e] : 0.f;
v[j] = e < ne ? __fadd_rn(x[j], bias != nullptr ? bias[e] : 0.f) : -INFINITY;
}
const int slots = topk + (shared ? 1 : 0);
float xk = 0.f; // lane k's pick's logit
int pk = 0; // lane k's pick
for (int k = 0; k < topk; ++k) {
float bv = -INFINITY;
int bi = ne;
#pragma unroll
for (int j = 0; j < PER; ++j) {
const int e = lane + 32 * j;
if (e < ne && beats(v[j], e, bv, bi)) bv = v[j], bi = e;
}
{ // the warp's best: the largest value (redux on an order-keeping key), then the lowest id among equals
const unsigned key = ordered(bv);
const unsigned top = __reduce_max_sync(0xFFFFFFFFu, key);
bi = static_cast<int>(__reduce_min_sync(0xFFFFFFFFu, key == top ? static_cast<unsigned>(bi) : 0xFFFFFFFFu));
}
float xb = 0.f;
#pragma unroll
for (int j = 0; j < PER; ++j)
if (lane + 32 * j == bi) v[j] = -INFINITY, xb = x[j];
xb = __shfl_sync(0xFFFFFFFFu, xb, bi & 31);
if (lane == k) xk = xb, pk = bi;
}
// the weights after the picks, each in its lane; the sum in pick order
const float wk = __fdiv_rn(1.f, __fadd_rn(1.f, expf(-xk)));
float sum = 0.f;
for (int k = 0; k < topk; ++k) sum = __fadd_rn(sum, __shfl_sync(0xFFFFFFFFu, wk, k));
if (lane < topk) {
pick[r * slots + lane] = pk;
wts[r * slots + lane] = __fmul_rn(normalize ? __fdiv_rn(wk, sum) : wk, scale);
}
if (shared && lane == 0) pick[r * slots + topk] = ne, wts[r * slots + topk] = 1.f;
}

// out[r, d] = sum over the row's slots, in slot order, of w[r, k] * y[r, k, d] (fp32 fma), rounded once to out's kind.
template <int YK, int OK>
__device__ __forceinline__ void combine_row(const void* y, const float* w, void* out, int slots, int dims, int64_t r, int d) {
float acc = 0.f;
int k = 0;
for (; k + 8 <= slots; k += 8) { // eight slots' loads in flight, then folded in order
float v[8], wk[8];
#pragma unroll
for (int i = 0; i < 8; ++i) v[i] = load(y, YK, (r * slots + k + i) * dims + d), wk[i] = w[r * slots + k + i];
#pragma unroll
for (int i = 0; i < 8; ++i) acc = __fmaf_rn(wk[i], v[i], acc);
}
if (k < slots) {
float v[8], wk[8];
#pragma unroll
for (int i = 0; i < 8; ++i) {
v[i] = k + i < slots ? load(y, YK, (r * slots + k + i) * dims + d) : 0.f;
wk[i] = k + i < slots ? w[r * slots + k + i] : 0.f;
}
#pragma unroll
for (int i = 0; i < 8; ++i)
if (k + i < slots) acc = __fmaf_rn(wk[i], v[i], acc);
}
store(out, OK, r * dims + d, acc);
}

extern "C" __global__ void __launch_bounds__(NT) tf_moe_combine(const void* y, int y_kind, const float* w, void* out,
int out_kind, int slots, int dims) {
const int64_t r = blockIdx.x;
const int d = blockIdx.y * NT + threadIdx.x;
if (d >= dims) return;
// the kinds picked once a thread (a branch an element costs instruction fetch on small calls)
if (y_kind == 0 && out_kind == 2) combine_row<0, 2>(y, w, out, slots, dims, r, d);
else if (y_kind == 2 && out_kind == 2) combine_row<2, 2>(y, w, out, slots, dims, r, d);
else if (y_kind == 0 && out_kind == 0) combine_row<0, 0>(y, w, out, slots, dims, r, d);
else {
float acc = 0.f;
for (int k = 0; k < slots; ++k) acc = __fmaf_rn(w[r * slots + k], load(y, y_kind, (r * slots + k) * dims + d), acc);
store(out, out_kind, r * dims + d, acc);
}
}
Loading
Loading