"""DeepSeek NSA-inspired sparse attention — fused CUDA kernel (SM120 Blackwell). Bench semantics (reference.nsa_attend): 1. Keys partitioned into blocks of block_size=64. 2. Block importance = mean over causal keys of (q_t . k_j / sqrt(D)). 3. Keep top_n_blocks=8 blocks by importance, unioned with the causal local sliding window of the last sliding_window=64 tokens. 4. Softmax attention over the selected key indices only. Design (two kernels): A) nsa_select: CTA per (bh, 32-query tile). Streams causal K in 64-row chunks, computes the causal score tile S = Q K^T with mma.sync (bf16 in, fp32 accumulate), reduces per-block sums to importances, picks the top-8 blocks (ties -> lower block index, matching the reference sort), unions with the sliding window, and writes a per-query block bitmask (uint64 words, bit b = block w*32+b). B) nsa_attn: CTA per (bh, 64-query tile), 4 warps. Each warp owns 16 query rows; streams the union of its rows' selected K/V blocks with mma.sync QK^T and flash-style online softmax + SIMT PV accumulation in registers. Per-row selection masks scores to -inf for blocks a row did not select. mma fragment recipe (verified on SM120, ldmatrix requires shared memory): - A (Q) fragment, 16x16 row-major tile: ldmatrix.x4, row = (lane&7) + ((lane&8)?8:0), col = (lane&16)?8:0. - B (K^T) fragment: K stored TRANSPOSED in shared as Kt[dim][key]; loaded with ldmatrix.x4.trans (16 keys) or x2.trans (8 keys), dim = (lane&7) + ((lane&8)?8:0), key = (lane&16)?8:0. - C fragment: lane holds C[lane>>2][(lane&3)*2+{0,1}] and C[(lane>>2)+8][same]. Selection uses per-key scores (not a K-sum shortcut) so the selected set matches the reference's accumulation order on near-ties. """ from __future__ import annotations import math import torch import torch.nn as nn from torch.utils.cpp_extension import load_inline B, H, S, D = 1, 16, 1024, 64 BLOCK_SIZE = 64 TOP_N_BLOCKS = 8 SLIDING_WINDOW = 64 _CUDA_SRC = r""" #include #include #include #include #include #define DEVI __device__ __forceinline__ DEVI uint32_t smem_u32addr(const void* p) { return static_cast(__cvta_generic_to_shared(p)); } DEVI void mma_bf16(float d[4], const uint32_t a[4], const uint32_t b[2], const float c[4]) { asm volatile( "mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 " "{%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%10,%11,%12,%13};\n" : "=f"(d[0]), "=f"(d[1]), "=f"(d[2]), "=f"(d[3]) : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1]), "f"(c[0]), "f"(c[1]), "f"(c[2]), "f"(c[3])); } DEVI void ldmatrix_x4(uint32_t r[4], const void* p) { uint32_t addr = smem_u32addr(p); asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n" : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(addr)); } // x4.trans on Kt[dim][key]: yields 16 keys (b0,b1 = keys 0..7, b2,b3 = keys // 8..15). dim = (lane&7)+((lane&8)?8:0), key = (lane&16)?8:0. DEVI void ldmatrix_x4_trans16(uint32_t r[4], const void* p) { uint32_t addr = smem_u32addr(p); asm volatile( "ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0,%1,%2,%3}, [%4];\n" : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(addr)); } // Shared tile: rows of DIM bf16 with stride DIM+8 (16B-aligned rows). template DEVI constexpr int TS() { return DIM + 8; } template DEVI int soff(int r, int c) { return r * TS() + c; } // Load ROWS x DIM bf16 tile from row-major global (stride gstride) to shared. // Rows >= rows are zero-filled. 16B vector loads/stores. template DEVI void load_tile(const __nv_bfloat16* __restrict__ g, int gstride, __nv_bfloat16* __restrict__ s, int rows) { constexpr int CHUNKS = DIM / 8; const int t = threadIdx.x; const int nt = blockDim.x; for (int i = t; i < ROWS * CHUNKS; i += nt) { int r = i / CHUNKS; int c = (i % CHUNKS) * 8; uint4 v = make_uint4(0u, 0u, 0u, 0u); if (r < rows) { v = *reinterpret_cast(g + (int64_t)r * gstride + c); } *reinterpret_cast(s + soff(r, c)) = v; } } // Load ROWS x DIM bf16 tile transposed: shared layout sT[c][r] with row // stride ROWS+8. Used for K so ldmatrix(.trans) yields the mma B fragment. // Only rows < rows are written (callers guarantee the rest is not read or is // masked out). template DEVI void load_tile_t(const __nv_bfloat16* __restrict__ g, int gstride, __nv_bfloat16* __restrict__ s, int rows) { constexpr int CHUNKS = DIM / 8; const int t = threadIdx.x; const int nt = blockDim.x; for (int i = t; i < ROWS * CHUNKS; i += nt) { int r = i / CHUNKS; int c = (i % CHUNKS) * 8; if (r < rows) { uint4 v = *reinterpret_cast(g + (int64_t)r * gstride + c); const __nv_bfloat16* pv = reinterpret_cast(&v); #pragma unroll for (int j = 0; j < 8; j++) { s[(c + j) * (ROWS + 8) + r] = pv[j]; } } } } // --------------------------------------------------------------------------- // Stage A: score + select. // CTA = 128 threads. QTS=32 queries per CTA, K chunk KC=64. // Warps 0-1 own 16 query rows each; block sums reduced into dynamic shared. // --------------------------------------------------------------------------- template __global__ void __launch_bounds__(128) nsa_select( const __nv_bfloat16* __restrict__ q, // (BH, S, DIM) const __nv_bfloat16* __restrict__ k, // (BH, S, DIM) uint64_t* __restrict__ mask, // (BH, S, NW) int S, int NB, int NW, float scale) { constexpr int KC = 64; const int bh = blockIdx.y; const int t0 = blockIdx.x * QTS; const int tid = threadIdx.x; const int warp = tid >> 5; const int lane = tid & 31; __shared__ __nv_bfloat16 sq[QTS * TS()]; __shared__ __nv_bfloat16 skt[DIM * (KC + 8)]; // K chunk transposed [dim][key] extern __shared__ float bsum[]; // dynamic: QTS x NBMAX for (int i = tid; i < QTS * NBMAX; i += 128) { bsum[i] = 0.f; } { const int64_t qbase = (int64_t)bh * S * DIM + (int64_t)t0 * DIM; load_tile(q + qbase, DIM, sq, min(QTS, S - t0)); } __syncthreads(); const int jmax = min(t0 + QTS, S); for (int jc = 0; jc < jmax; jc += KC) { const int rows = min(KC, jmax - jc); const int64_t kbase = (int64_t)bh * S * DIM + (int64_t)jc * DIM; load_tile_t(k + kbase, DIM, skt, rows); __syncthreads(); // Per-chunk score accumulator: reset each iteration so bsum[bi] holds // only block bi's sum (a persistent accumulator would make every block // carry the prefix sum of all earlier chunks). float acc[8][4]; #pragma unroll for (int n = 0; n < 8; n++) #pragma unroll for (int i = 0; i < 4; i++) acc[n][i] = 0.f; if (warp < 2) { #pragma unroll for (int kk = 0; kk < DIM / 16; kk++) { uint32_t a[4]; { const int r = (lane & 7) + ((lane & 8) ? 8 : 0); const int c = kk * 16 + ((lane & 16) ? 8 : 0); ldmatrix_x4(a, sq + soff(warp * 16 + r, c)); } #pragma unroll for (int nn = 0; nn < 4; nn++) { // keys [nn*16, nn*16+16), dims [kk*16, kk*16+16) uint32_t b[4]; { const int dim = kk * 16 + (lane & 7) + ((lane & 8) ? 8 : 0); const int key = nn * 16 + ((lane & 16) ? 8 : 0); ldmatrix_x4_trans16(b, skt + dim * (KC + 8) + key); } mma_bf16(acc[nn * 2], a, b, acc[nn * 2]); mma_bf16(acc[nn * 2 + 1], a, b + 2, acc[nn * 2 + 1]); } } } __syncthreads(); if (warp < 2) { const int bi = jc >> 6; const int r0 = warp * 16 + (lane >> 2); const int c0 = (lane & 3) * 2; #pragma unroll for (int n = 0; n < 8; n++) { int j0 = jc + n * 8 + c0; // global key index (jc is the chunk base) int t_a = t0 + r0; int t_b = t0 + r0 + 8; if (j0 <= t_a && j0 + 1 <= t_a) { atomicAdd(&bsum[r0 * NBMAX + bi], acc[n][0] + acc[n][1]); } else if (j0 <= t_a) { atomicAdd(&bsum[r0 * NBMAX + bi], acc[n][0]); } if (j0 <= t_b && j0 + 1 <= t_b) { atomicAdd(&bsum[(r0 + 8) * NBMAX + bi], acc[n][2] + acc[n][3]); } else if (j0 <= t_b) { atomicAdd(&bsum[(r0 + 8) * NBMAX + bi], acc[n][2]); } } } __syncthreads(); } // selection: one thread per query row. for (int r = tid; r < QTS; r += 128) { int t = t0 + r; if (t >= S) continue; int nvalid = min(NB, (t >> 6) + 1); int sel_idx[8]; float sel_val[8]; int nsel = 0; for (int bi = 0; bi < nvalid; bi++) { int s0 = bi << 6; int cnt = min(64, t + 1 - s0); float v = bsum[r * NBMAX + bi] / (float)cnt; if (nsel < 8) { int p = nsel; while (p > 0 && sel_val[p - 1] < v) p--; for (int z = nsel; z > p; z--) { sel_val[z] = sel_val[z - 1]; sel_idx[z] = sel_idx[z - 1]; } sel_val[p] = v; sel_idx[p] = bi; nsel++; } else if (v > sel_val[7]) { int p = 7; while (p > 0 && sel_val[p - 1] < v) p--; for (int z = 7; z > p; z--) { sel_val[z] = sel_val[z - 1]; sel_idx[z] = sel_idx[z - 1]; } sel_val[p] = v; sel_idx[p] = bi; } } uint64_t words[4] = {0, 0, 0, 0}; for (int z = 0; z < nsel; z++) { int bi = sel_idx[z]; words[bi >> 5] |= 1ull << (bi & 31); } // The sliding window is a TOKEN range [w0, t] in the reference, not whole // blocks; nsa_attn applies it as a per-key condition (ja >= w0). Only the // top-8 block mask is written here. for (int w = 0; w < NW; w++) { mask[((int64_t)bh * S + t) * NW + w] = words[w]; } } } // --------------------------------------------------------------------------- // Stage B: sparse attention. CTA = 128 threads (4 warps), QT=64 queries. // Each warp owns 16 query rows; streams the union of its rows' selected // K/V blocks: mma.sync QK^T into a shared score tile, per-row online softmax // (warp-reduced max/sum), then mma.sync PV. // --------------------------------------------------------------------------- template __global__ void __launch_bounds__(128) nsa_attn( const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ k, const __nv_bfloat16* __restrict__ v, const uint64_t* __restrict__ mask, __nv_bfloat16* __restrict__ o, int S, int NW, float scale) { const int bh = blockIdx.y; const int t0 = blockIdx.x * QT; const int tid = threadIdx.x; const int warp = tid >> 5; const int lane = tid & 31; __shared__ __nv_bfloat16 sq[QT * TS()]; __shared__ float smax[QT]; __shared__ float ssum[QT]; __shared__ uint64_t sselw[QT][NWMAX]; // Dynamic shared: score tile (float), P tile (bf16), and double-buffered // K/V tiles. skt[buf] is K transposed [dim][key], sv[buf] is V [key][dim]. extern __shared__ __nv_bfloat16 dynsm[]; float* sst = reinterpret_cast(dynsm); // 64 x 72 floats __nv_bfloat16* sp = reinterpret_cast<__nv_bfloat16*>(sst + 64 * 72); // 64 x 72 bf16 __nv_bfloat16* skt2 = sp + 64 * 72; // DIM x 72 bf16 __nv_bfloat16* sv2 = skt2 + DIM * 72; // 64 x (DIM+8) bf16 { const int64_t qbase = (int64_t)bh * S * DIM + (int64_t)t0 * DIM; load_tile(q + qbase, DIM, sq, min(QT, S - t0)); } for (int i = tid; i < QT; i += 128) { int t = t0 + i; smax[i] = -INFINITY; ssum[i] = 0.f; if (t < S) { for (int w = 0; w < NW; w++) { sselw[i][w] = mask[((int64_t)bh * S + t) * NW + w]; } } // Words w >= NW are never read for valid rows, but zero them anyway so // uninitialized shared memory cannot leak selection bits. for (int w = NW; w < NWMAX; w++) sselw[i][w] = 0; } __syncthreads(); const int r0 = warp * 16; const int t_base = t0 + r0; const int64_t kbase = (int64_t)bh * S * DIM; // PV accumulator in registers: 16 rows x DIM cols (mma C layout). // Only DIM/8 dim-tiles are used (each holds 8 output dims per row pair). float oacc[DIM / 8][4]; #pragma unroll for (int n = 0; n < DIM / 8; n++) #pragma unroll for (int i = 0; i < 4; i++) oacc[n][i] = 0.f; // Per-row selection bits for the two rows this lane owns (C-fragment rows). const int ra = lane >> 2; const int rb = ra + 8; const int ca = (lane & 3) * 2; uint64_t sel_a[NWMAX], sel_b[NWMAX]; #pragma unroll for (int w = 0; w < NWMAX; w++) { sel_a[w] = sselw[r0 + ra][w]; sel_b[w] = sselw[r0 + rb][w]; } for (int w = 0; w < NW; w++) { // Compute the warp's block union in one thread and broadcast: a // per-thread OR over shared sselw lets the compiler hoist the K/V loads // above the __syncthreads() that guards them, corrupting skt/sv. // CTA-wide union: all warps must iterate the same block list because the // K/V tiles (skt/sv) are CTA-shared and the loop body ends with // __syncthreads(). Per-row selection is enforced by the per-key mask // (sel_a/sel_b) inside the softmax, so a CTA-wide union is safe. // Each warp ORs its own 16 rows; lane 0 of each warp writes its slot. __shared__ uint64_t uni_sh[QT / 16]; if (lane == 0) { uint64_t u = 0; for (int i = 0; i < 16; i++) { int ti = t_base + i; if (ti >= S) continue; u |= sselw[r0 + i][w]; // Sliding-window blocks: the reference unions the token range // [w0, t] (w0 = max(0, t+1-64)) with the top-8 blocks. The partial // edges are masked per key below; the union only needs the blocks. int w0i = max(0, ti + 1 - 64); for (int bi = max(0, w0i >> 6); bi <= (ti >> 6); bi++) { // bi is a global block index; place its bit in the word that owns it. int gw = bi >> 5; int gb = bi & 31; if (gw == w) u |= 1ull << gb; } } uni_sh[warp] = u; } __syncthreads(); // CTA-wide union for the shared K/V load loop. uint64_t uni = 0; #pragma unroll for (int wi = 0; wi < QT / 16; wi++) uni |= uni_sh[wi]; while (uni) { int b = __ffsll((long long)uni) - 1; uni &= uni - 1; int bi = w * 32 + b; int s0 = bi << 6; if (s0 >= S) continue; int rows = min(64, S - s0); load_tile_t<64, DIM>(k + kbase + (int64_t)s0 * DIM, DIM, skt2, rows); load_tile<64, DIM>(v + kbase + (int64_t)s0 * DIM, DIM, sv2, rows); __syncthreads(); __nv_bfloat16* skt = skt2; __nv_bfloat16* sv = sv2; // QK^T: 16 rows x 64 keys -> shared score tile (rows r0..r0+15). // Zero the 16x64 tile: each lane zeroes its C-fragment columns for 8 nn tiles. #pragma unroll for (int nn = 0; nn < 8; nn++) { sst[(r0 + (lane >> 2)) * 72 + nn * 8 + (lane & 3) * 2] = 0.f; sst[(r0 + (lane >> 2)) * 72 + nn * 8 + (lane & 3) * 2 + 1] = 0.f; sst[(r0 + (lane >> 2) + 8) * 72 + nn * 8 + (lane & 3) * 2] = 0.f; sst[(r0 + (lane >> 2) + 8) * 72 + nn * 8 + (lane & 3) * 2 + 1] = 0.f; } __syncwarp(); // Accumulate over all kk dim-tiles into per-lane register accumulators // (two mma C fragments per 16-key nn tile), then write the full 16x64 // score tile to shared once. float sacc[4][8]; #pragma unroll for (int nn = 0; nn < 4; nn++) #pragma unroll for (int i = 0; i < 8; i++) sacc[nn][i] = 0.f; #pragma unroll for (int kk = 0; kk < DIM / 16; kk++) { uint32_t a[4]; { const int r = (lane & 7) + ((lane & 8) ? 8 : 0); const int c = kk * 16 + ((lane & 16) ? 8 : 0); ldmatrix_x4(a, sq + soff(r0 + r, c)); } #pragma unroll for (int nn = 0; nn < 4; nn++) { uint32_t bfr[4]; { const int dim = kk * 16 + (lane & 7) + ((lane & 8) ? 8 : 0); const int key = nn * 16 + ((lane & 16) ? 8 : 0); ldmatrix_x4_trans16(bfr, skt + dim * 72 + key); } // keys nn*16..+7 -> sacc[nn][0..3], keys nn*16+8..+15 -> sacc[nn][4..7] float c0[4] = {0, 0, 0, 0}, c1[4] = {0, 0, 0, 0}; mma_bf16(c0, a, bfr, c0); mma_bf16(c1, a, bfr + 2, c1); sacc[nn][0] += c0[0]; sacc[nn][1] += c0[1]; sacc[nn][2] += c0[2]; sacc[nn][3] += c0[3]; sacc[nn][4] += c1[0]; sacc[nn][5] += c1[1]; sacc[nn][6] += c1[2]; sacc[nn][7] += c1[3]; } } { const int crow = lane >> 2; const int ccol = (lane & 3) * 2; #pragma unroll for (int nn = 0; nn < 4; nn++) { sst[(r0 + crow) * 72 + nn * 16 + ccol] = sacc[nn][0]; sst[(r0 + crow) * 72 + nn * 16 + ccol + 1] = sacc[nn][1]; sst[(r0 + crow + 8) * 72 + nn * 16 + ccol] = sacc[nn][2]; sst[(r0 + crow + 8) * 72 + nn * 16 + ccol + 1] = sacc[nn][3]; sst[(r0 + crow) * 72 + nn * 16 + 8 + ccol] = sacc[nn][4]; sst[(r0 + crow) * 72 + nn * 16 + 8 + ccol + 1] = sacc[nn][5]; sst[(r0 + crow + 8) * 72 + nn * 16 + 8 + ccol] = sacc[nn][6]; sst[(r0 + crow + 8) * 72 + nn * 16 + 8 + ccol + 1] = sacc[nn][7]; } } __syncwarp(); // Per-row online softmax over the 64 keys, then mma PV. // Each lane owns rows ra (0..7) and rb (8..15) of this warp's tile. // A key is attended if its block is in the row's top-8 mask OR the key // falls in the row's sliding window [w0, t] (reference semantics). const int ta = t_base + ra; const int tb = t_base + rb; const int w0a = max(0, ta + 1 - 64); const int w0b = max(0, tb + 1 - 64); float ma = smax[r0 + ra]; float mb = smax[r0 + rb]; float la = ssum[r0 + ra]; float lb = ssum[r0 + rb]; // Step 1: find the row max over the 64 keys (warp-reduced). float blk_a = -INFINITY, blk_b = -INFINITY; #pragma unroll for (int j = 0; j < 64; j++) { float sa = sst[(r0 + ra) * 72 + j] * scale; float sb = sst[(r0 + rb) * 72 + j] * scale; int ja = s0 + j; if (ja > ta || ja >= S || !(((sel_a[w] >> (b & 31)) & 1ull) || (ja >= w0a))) sa = -INFINITY; if (ja > tb || ja >= S || !(((sel_b[w] >> (b & 31)) & 1ull) || (ja >= w0b))) sb = -INFINITY; blk_a = fmaxf(blk_a, sa); blk_b = fmaxf(blk_b, sb); } // blk_a / blk_b already cover all 64 keys for this lane's rows. float mnew_a = fmaxf(ma, blk_a); float mnew_b = fmaxf(mb, blk_b); float so_a = (mnew_a > -INFINITY) ? __expf(ma - mnew_a) : 0.f; float so_b = (mnew_b > -INFINITY) ? __expf(mb - mnew_b) : 0.f; // Step 2: exp, row sum, and P tile (bf16) in shared. float sum_a = 0.f, sum_b = 0.f; #pragma unroll for (int j = 0; j < 64; j++) { float sa = sst[(r0 + ra) * 72 + j] * scale; float sb = sst[(r0 + rb) * 72 + j] * scale; int ja = s0 + j; if (ja > ta || ja >= S || !(((sel_a[w] >> (b & 31)) & 1ull) || (ja >= w0a))) sa = -INFINITY; if (ja > tb || ja >= S || !(((sel_b[w] >> (b & 31)) & 1ull) || (ja >= w0b))) sb = -INFINITY; float pa = (sa > -INFINITY) ? __expf(sa - mnew_a) : 0.f; float pb = (sb > -INFINITY) ? __expf(sb - mnew_b) : 0.f; sum_a += pa; sum_b += pb; sp[(r0 + ra) * 72 + j] = __float2bfloat16(pa); sp[(r0 + rb) * 72 + j] = __float2bfloat16(pb); } // Each lane already summed all 64 keys for its own rows, so the // running sum needs no cross-lane reduction here. la = la * so_a + sum_a; lb = lb * so_b + sum_b; ma = mnew_a; mb = mnew_b; __syncwarp(); // Step 3: rescale the running PV accumulator by so_a / so_b. #pragma unroll for (int n = 0; n < 16; n++) { oacc[n][0] *= so_a; oacc[n][1] *= so_a; oacc[n][2] *= so_b; oacc[n][3] *= so_b; } // Step 4: PV via mma. A-fragment = P (16x64), B-fragment = V (64 keys x DIM). #pragma unroll for (int kk = 0; kk < 4; kk++) { // 64 keys / 16 uint32_t a[4]; { const int r = (lane & 7) + ((lane & 8) ? 8 : 0); const int c = kk * 16 + ((lane & 16) ? 8 : 0); ldmatrix_x4(a, sp + r0 * 72 + r * 72 + c); } #pragma unroll for (int nn = 0; nn < DIM / 16; nn++) { // DIM / 16 dim tiles uint32_t bfr[4]; { const int key = kk * 16 + (lane & 7) + ((lane & 8) ? 8 : 0); const int dim = nn * 16 + ((lane & 16) ? 8 : 0); ldmatrix_x4_trans16(bfr, sv + key * TS() + dim); } // dims nn*16..+7 -> oacc[nn*2], dims nn*16+8..+15 -> oacc[nn*2+1] float c0[4] = {0, 0, 0, 0}, c1[4] = {0, 0, 0, 0}; mma_bf16(c0, a, bfr, c0); mma_bf16(c1, a, bfr + 2, c1); // mma C fragment: c0[0]=C[crow][ccol], c0[1]=C[crow][ccol+1], // c0[2]=C[crow+8][ccol], c0[3]=C[crow+8][ccol+1] (crow=lane>>2, ccol=(lane&3)*2) oacc[nn * 2][0] += c0[0]; oacc[nn * 2][1] += c0[1]; oacc[nn * 2][2] += c0[2]; oacc[nn * 2][3] += c0[3]; oacc[nn * 2 + 1][0] += c1[0]; oacc[nn * 2 + 1][1] += c1[1]; oacc[nn * 2 + 1][2] += c1[2]; oacc[nn * 2 + 1][3] += c1[3]; } } smax[r0 + ra] = ma; smax[r0 + rb] = mb; ssum[r0 + ra] = la; ssum[r0 + rb] = lb; __syncthreads(); } } // write outputs. #pragma unroll for (int nt = 0; nt < DIM / 8; nt++) { { int d0 = nt * 8 + ca; int d1 = d0 + 1; int t_a = t_base + ra; int t_b = t_base + rb; float inv_a = (ssum[r0 + ra] > 0.f) ? 1.f / ssum[r0 + ra] : 0.f; float inv_b = (ssum[r0 + rb] > 0.f) ? 1.f / ssum[r0 + rb] : 0.f; if (t_a < S && d0 < DIM) { o[(int64_t)bh * S * DIM + (int64_t)t_a * DIM + d0] = __float2bfloat16(oacc[nt][0] * inv_a); } if (t_b < S && d0 < DIM) { o[(int64_t)bh * S * DIM + (int64_t)t_b * DIM + d0] = __float2bfloat16(oacc[nt][2] * inv_b); } if (t_a < S && d1 < DIM) { o[(int64_t)bh * S * DIM + (int64_t)t_a * DIM + d1] = __float2bfloat16(oacc[nt][1] * inv_a); } if (t_b < S && d1 < DIM) { o[(int64_t)bh * S * DIM + (int64_t)t_b * DIM + d1] = __float2bfloat16(oacc[nt][3] * inv_b); } } } } void nsa_launch(torch::Tensor q, torch::Tensor k, torch::Tensor v, torch::Tensor mask, torch::Tensor o, int64_t B, int64_t H, int64_t S, int64_t D) { TORCH_CHECK(D == 64 || D == 128, "only D=64/128 supported"); const int NB = (int)((S + 63) / 64); const int NW = (NB + 31) / 32; const float scale = 1.0f / sqrtf((float)D); const int BH = (int)(B * H); cudaStream_t stream = at::cuda::getCurrentCUDAStream(); constexpr int QT = 64; constexpr int QTS = 32; dim3 grid((S + QT - 1) / QT, BH); dim3 grids((S + QTS - 1) / QTS, BH); #define LAUNCH_SELECT(DIMV, NBMAXV) \ nsa_select<<>>( \ (const __nv_bfloat16*)q.data_ptr(), (const __nv_bfloat16*)k.data_ptr(), \ (uint64_t*)mask.data_ptr(), (int)S, NB, NW, scale) if (D == 64) { if (NB <= 32) LAUNCH_SELECT(64, 32); else if (NB <= 64) LAUNCH_SELECT(64, 64); else if (NB <= 96) LAUNCH_SELECT(64, 96); else LAUNCH_SELECT(64, 128); } else { if (NB <= 32) LAUNCH_SELECT(128, 32); else if (NB <= 64) LAUNCH_SELECT(128, 64); else if (NB <= 96) LAUNCH_SELECT(128, 96); else LAUNCH_SELECT(128, 128); } // sst (64x72 f32) + sp (64x72 bf16) + skt (DIMx72 bf16) + sv (64x(DIM+8) bf16) const size_t v_smem = (size_t)(64 * 72 * 4 + 64 * 72 * 2 + D * 72 * 2 + 64 * (D + 8) * 2); #define LAUNCH_ATTN(DIMV, NWMAXV) \ { \ cudaFuncSetAttribute((void*)nsa_attn, \ cudaFuncAttributeMaxDynamicSharedMemorySize, (int)v_smem); \ nsa_attn<<>>( \ (const __nv_bfloat16*)q.data_ptr(), (const __nv_bfloat16*)k.data_ptr(), \ (const __nv_bfloat16*)v.data_ptr(), (const uint64_t*)mask.data_ptr(), \ (__nv_bfloat16*)o.data_ptr(), (int)S, NW, scale); \ } if (D == 64) { if (NB <= 32) { LAUNCH_ATTN(64, 1); } else if (NB <= 64) { LAUNCH_ATTN(64, 2); } else if (NB <= 96) { LAUNCH_ATTN(64, 3); } else { LAUNCH_ATTN(64, 4); } } else if (NB <= 32) { LAUNCH_ATTN(128, 1); } else if (NB <= 64) { LAUNCH_ATTN(128, 2); } else if (NB <= 96) { LAUNCH_ATTN(128, 3); } else { LAUNCH_ATTN(128, 4); } cudaError_t err = cudaGetLastError(); if (err != cudaSuccess) { TORCH_CHECK(false, "nsa_launch failed: ", cudaGetErrorString(err)); } } """ _CPP_SRC = ( "void nsa_launch(torch::Tensor q, torch::Tensor k, torch::Tensor v, " "torch::Tensor mask, torch::Tensor o, int64_t B, int64_t H, int64_t S, int64_t D);" ) def _build(): return load_inline( name="nsa_sm120_v31", cpp_sources=_CPP_SRC, cuda_sources=_CUDA_SRC, functions=["nsa_launch"], extra_cuda_cflags=["-O3", "--use_fast_math", "-std=c++17"], verbose=False, ) class Model(nn.Module): def __init__(self, B: int, H: int, S: int, D: int): super().__init__() self.B, self.H, self.S, self.D = B, H, S, D self.register_buffer("_dummy", torch.zeros(1, dtype=torch.bfloat16)) self._mod = None self._mask = None def _module(self): if self._mod is None: self._mod = _build() return self._mod def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor: B, H, S, D = q.shape mod = self._module() NB = (S + 63) // 64 NW = (NB + 31) // 32 if self._mask is None or self._mask.shape[0] != B * H or self._mask.shape[1] != S: self._mask = torch.empty(B * H, S, NW, dtype=torch.int64, device=q.device) self._mask.zero_() o = torch.empty_like(q) mod.nsa_launch(q.contiguous(), k.contiguous(), v.contiguous(), self._mask, o, B, H, S, D) return o.to(torch.bfloat16) def get_init_inputs(): return [B, H, S, D] def get_inputs(): q = torch.randn(B, H, S, D, dtype=torch.bfloat16) k = torch.randn(B, H, S, D, dtype=torch.bfloat16) v = torch.randn(B, H, S, D, dtype=torch.bfloat16) return [q, k, v]