"""DeepSeek NSA-inspired sparse attention — fused CUDA implementation (SM120). Bench semantics (reference.nsa_attend): per query t: block importance = mean of causal q.k/sqrt(D) over each 64-key block; top-8 blocks union sliding window of last 64 tokens; softmax over the selected keys only. Key structural facts exploited here: * For a full block bi < tb (= t/64), importance == q . mean(k_block) * scale, so scoring uses precomputed block-mean keys (one small compression pass). * The 64-token window ending at t always covers the whole causal part of the diagonal block [tb*64, t]. Hence selected keys = (top-8 blocks bi < tb, truncated at the window start) UNION window [t-63, t]. * For t < 8*64 every causal block is in the top-8 -> dense causal prefix. Pipeline (all real CUDA, mma.sync bf16 tensor cores, SM120): p0 block-mean keys kbar (fp32) + zero counts (+ init merge state for D=128) p1a per-query block importance via tensor cores: kbar split into 3 bf16 planes (hi+mid+lo, residual ~2^-27) so mma scoring is fp32-class exact; diagonal partial means via incremental key prefix sums p1b top-8 per row: thread-per-row insertion select over smem-transposed scores (tie -> higher block index, matching the reference tuple sort) p2b counts -> global list offsets, per-bh tile offsets, tile->block map p2 scatter (query, rank-slot) entries into per-key-block lists (CTA-aggregated atomics) p3 key-block-major attention: tiles of 128 gathered queries x 64 keys, tensor-core QK^T + PV with per-row window-cutoff masks; K smem buffer is reused for V (loaded during softmax) to raise occupancy p3.5 sliding window (+ selected block tb-1) per query tile: banded 64x128 tensor-core tile p4 D=64: merge <= 9 split-K partials (m, l, o) per row, normalize. D=128: partials would exceed L2, so p3/p3.5 instead merge online into a 17 MB L2-resident per-row state under group-local spinlocks, and p4 just normalizes. Forwards are replayed through cached CUDA graphs keyed on input pointers. """ from __future__ import annotations import math import torch import torch.nn as nn from torch.utils.cpp_extension import load_inline _CUDA_SRC = r""" #include #include #include #include #include #include #define DEV_INLINE __device__ __forceinline__ DEV_INLINE uint64_t umax64(uint64_t a, uint64_t b) { return a > b ? a : b; } DEV_INLINE uint64_t shfl_xor_u64(uint64_t v, int off) { unsigned long long x = (unsigned long long)v; x = __shfl_xor_sync(0xffffffffu, x, off); return (uint64_t)x; } DEV_INLINE uint32_t f2u_order(float f) { uint32_t u = __float_as_uint(f); return (u & 0x80000000u) ? ~u : (u | 0x80000000u); } DEV_INLINE int bh_of(int64_t row, int S) { return (int)(row / S); } DEV_INLINE uint64_t pack_key(float score, int bi) { return ((uint64_t)f2u_order(score) << 8) | (uint32_t)bi; } DEV_INLINE uint32_t smem_u32(const void* p) { return static_cast(__cvta_generic_to_shared(p)); } DEV_INLINE void cp_async16(uint32_t saddr, const void* gptr) { asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(saddr), "l"(gptr)); } DEV_INLINE void cp_async_commit() { asm volatile("cp.async.commit_group;\n"); } DEV_INLINE void cp_async_wait_all() { asm volatile("cp.async.wait_group 0;\n"); } DEV_INLINE void ldmatrix_x4(uint32_t& r0, uint32_t& r1, uint32_t& r2, uint32_t& r3, uint32_t addr) { asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n" : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(r3) : "r"(addr)); } DEV_INLINE void ldmatrix_x2(uint32_t& r0, uint32_t& r1, uint32_t addr) { asm volatile("ldmatrix.sync.aligned.m8n8.x2.shared.b16 {%0,%1}, [%2];\n" : "=r"(r0), "=r"(r1) : "r"(addr)); } DEV_INLINE void ldmatrix_x2_trans(uint32_t& r0, uint32_t& r1, uint32_t addr) { asm volatile("ldmatrix.sync.aligned.m8n8.x2.trans.shared.b16 {%0,%1}, [%2];\n" : "=r"(r0), "=r"(r1) : "r"(addr)); } DEV_INLINE void mma_bf16(float* c, const uint32_t* a, const uint32_t* b) { asm volatile( "mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 " "{%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n" : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1])); } // --------------------------------------------------------------------------- // p0: kbar[bh][bi][d] = mean of k over block bi (fp32); also zeroes counts. // grid (nb, bh), block (D) // --------------------------------------------------------------------------- template __global__ void kbar_kernel(const __nv_bfloat16* __restrict__ k, float* __restrict__ kbar, int* __restrict__ counts, __nv_bfloat16* __restrict__ o_state, float* __restrict__ ml_state, int S, int nb, int ncounts, int64_t rows) { int bi = blockIdx.x, bh = blockIdx.y; if (threadIdx.x == 0 && bh * nb + bi < ncounts) counts[bh * nb + bi] = 0; if (INIT_STATE) { int nthreads = gridDim.x * gridDim.y * blockDim.x; for (int64_t i = (int64_t)blockIdx.y * gridDim.x * blockDim.x + blockIdx.x * blockDim.x + threadIdx.x; i < rows * D; i += nthreads) o_state[i] = __float2bfloat16(0.f); for (int64_t i = (int64_t)blockIdx.y * gridDim.x * blockDim.x + blockIdx.x * blockDim.x + threadIdx.x; i < rows; i += nthreads) { ml_state[i * 2] = -INFINITY; ml_state[i * 2 + 1] = 0.f; } } int j0 = bi * 64; int cnt = min(64, S - j0); // 4 warps x 16 keys; lane covers D/32 consecutive dims -> full-row coalesced constexpr int DP = D / 32; int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; const __nv_bfloat16* kp = k + ((int64_t)bh * S + j0) * D + lane * DP; float acc[DP]; #pragma unroll for (int u = 0; u < DP; ++u) acc[u] = 0.f; for (int j = warp * 16; j < min(cnt, warp * 16 + 16); ++j) { if constexpr (DP == 2) { float2 v = __bfloat1622float2(*reinterpret_cast(kp + (int64_t)j * D)); acc[0] += v.x; acc[1] += v.y; } else { uint2 v = *reinterpret_cast(kp + (int64_t)j * D); __nv_bfloat162 p0 = *reinterpret_cast<__nv_bfloat162*>(&v.x); __nv_bfloat162 p1 = *reinterpret_cast<__nv_bfloat162*>(&v.y); float2 f0 = __bfloat1622float2(p0), f1 = __bfloat1622float2(p1); acc[0] += f0.x; acc[1] += f0.y; acc[2] += f1.x; acc[3] += f1.y; } } __shared__ float red[4][D]; #pragma unroll for (int u = 0; u < DP; ++u) red[warp][lane * DP + u] = acc[u]; __syncthreads(); if (threadIdx.x < D) { float s = red[0][threadIdx.x] + red[1][threadIdx.x] + red[2][threadIdx.x] + red[3][threadIdx.x]; kbar[((int64_t)bh * nb + bi) * D + threadIdx.x] = s / cnt; } } // --------------------------------------------------------------------------- // p1: importance + top-8 selection, tensor-core scoring. // grid (ceil(S/64), bh), block (128) = 4 warps x 16 queries. // importance(full block bi) = q . kbar_bi; kbar split bf16 hi+lo (fp32-class). // diagonal importance = q . (prefix sum of K) / (r+1), SIMT incremental. // top-8 via packed (score,bi) argmax in 4-lane groups, tie -> higher bi. // --------------------------------------------------------------------------- template __global__ void __launch_bounds__(128) select_score_kernel( const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ k, const float* __restrict__ kbar, float* __restrict__ scores, int S, int nb) { extern __shared__ char smem_raw[]; const int tb = blockIdx.x, bh = blockIdx.y; const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; const int m0 = warp * 16; const int64_t row0 = (int64_t)bh * S + tb * 64; // trivial prefix: every causal block is selected, no scoring needed if (tb + 1 <= 8) return; __nv_bfloat16* sQ = reinterpret_cast<__nv_bfloat16*>(smem_raw); // 64*D __nv_bfloat16* sKB = sQ + 64 * D; // 3*32*D chunk (hi,mid,lo) float* sDiag = reinterpret_cast(sKB + 3 * 32 * D); // 4*16 constexpr int CH = D / 8; // stage Q tile (swizzled) for (int idx = threadIdx.x; idx < 64 * CH; idx += blockDim.x) { int m = idx / CH, c = idx % CH; int pc = c ^ (m & 7); int t = tb * 64 + m; if (t < S) cp_async16(smem_u32(sQ + m * D + pc * 8), q + ((int64_t)bh * S + t) * D + c * 8); else *reinterpret_cast(sQ + m * D + pc * 8) = make_uint4(0, 0, 0, 0); } cp_async_commit(); cp_async_wait_all(); __syncthreads(); // diagonal importance per row: incremental prefix sums of K, lane-per-dim-pair { float ks[D / 64][2]; #pragma unroll for (int u = 0; u < D / 64; ++u) { ks[u][0] = 0.f; ks[u][1] = 0.f; } const __nv_bfloat16* kblk = k + row0 * D; // prefix must start at key 0 of the block, not at this warp's first row for (int j = 0; j < m0 && tb * 64 + j < S; ++j) { const __nv_bfloat162* kp = reinterpret_cast(kblk + (int64_t)j * D); #pragma unroll for (int u = 0; u < D / 64; ++u) { float2 kv = __bfloat1622float2(kp[lane + u * 32]); ks[u][0] += kv.x; ks[u][1] += kv.y; } } #pragma unroll for (int m = 0; m < 16; ++m) { int t = tb * 64 + m0 + m; if (t < S) { const __nv_bfloat162* kp = reinterpret_cast(kblk + (int64_t)(m0 + m) * D); #pragma unroll for (int u = 0; u < D / 64; ++u) { float2 kv = __bfloat1622float2(kp[lane + u * 32]); ks[u][0] += kv.x; ks[u][1] += kv.y; } float dacc = 0.f; #pragma unroll for (int u = 0; u < D / 64; ++u) { const __nv_bfloat162* qp = reinterpret_cast(q + ((int64_t)bh * S + t) * D); float2 qv = __bfloat1622float2(qp[lane + u * 32]); dacc += qv.x * ks[u][0] + qv.y * ks[u][1]; } #pragma unroll for (int off = 16; off > 0; off >>= 1) dacc += __shfl_xor_sync(0xffffffffu, dacc, off); if (lane == 0) sDiag[warp * 16 + m] = dacc / (m0 + m + 1); } } } __syncthreads(); // scores = Q * kbar^T via mma; kbar = hi+mid+lo bf16 planes (residual ~2^-27) float c[16][4]; #pragma unroll for (int nt = 0; nt < 16; ++nt) #pragma unroll for (int i = 0; i < 4; ++i) c[nt][i] = 0.f; for (int g = 0; g < 4; ++g) { if (32 * g > tb) break; // stage 3 planes x 32 blocks for (int idx = threadIdx.x; idx < 32 * CH; idx += blockDim.x) { int bl = idx / CH, cc = idx % CH; int bi = 32 * g + bl; alignas(16) __nv_bfloat16 pl[3][8]; if (bi < nb) { const float* kp = kbar + ((int64_t)bh * nb + bi) * D + cc * 8; float4 v0 = *reinterpret_cast(kp); float4 v1 = *reinterpret_cast(kp + 4); float vv[8] = {v0.x, v0.y, v0.z, v0.w, v1.x, v1.y, v1.z, v1.w}; #pragma unroll for (int p = 0; p < 8; ++p) { __nv_bfloat16 h = __float2bfloat16_rn(vv[p]); float r1 = vv[p] - __bfloat162float(h); __nv_bfloat16 m = __float2bfloat16_rn(r1); float r2 = r1 - __bfloat162float(m); pl[0][p] = h; pl[1][p] = m; pl[2][p] = __float2bfloat16_rn(r2); } } else { #pragma unroll for (int u = 0; u < 3; ++u) #pragma unroll for (int p = 0; p < 8; ++p) pl[u][p] = __float2bfloat16(0.f); } int pc = cc ^ (bl & 7); #pragma unroll for (int u = 0; u < 3; ++u) *reinterpret_cast(sKB + (u * 32 + bl) * D + pc * 8) = *reinterpret_cast(pl[u]); } __syncthreads(); #pragma unroll for (int ks = 0; ks < D / 16; ++ks) { uint32_t a[4]; int rr = m0 + (lane & 15); int cc = ks * 2 + (lane >> 4); int pc = cc ^ (rr & 7); ldmatrix_x4(a[0], a[1], a[2], a[3], smem_u32(sQ + rr * D + pc * 8)); #pragma unroll for (int plane = 0; plane < 3; ++plane) { const __nv_bfloat16* kb = sKB + plane * 32 * D; #pragma unroll for (int nl = 0; nl < 4; ++nl) { int nt = 4 * g + nl; if (8 * nt <= tb) { uint32_t b[2]; int rr2 = nl * 8 + (lane & 7); int cc2 = ks * 2 + ((lane >> 3) & 1); int pc2 = cc2 ^ (rr2 & 7); ldmatrix_x2(b[0], b[1], smem_u32(kb + rr2 * D + pc2 * 8)); mma_bf16(c[nt], a, b); } } } } __syncthreads(); } // insert diagonal score at block tb (static indices keep c in registers) int row_a = m0 + (lane >> 2), row_b = row_a + 8; #pragma unroll for (int nt = 0; nt < 16; ++nt) { #pragma unroll for (int i = 0; i < 4; ++i) { int bi = 8 * nt + 2 * (lane & 3) + (i & 1); if (bi == tb && (lane & 3) == ((tb & 7) >> 1)) c[nt][i] = sDiag[warp * 16 + (lane >> 2) + ((i < 2) ? 0 : 8)]; } } // write raw scores (masked) for the top-8 kernel #pragma unroll for (int rr = 0; rr < 2; ++rr) { int row = rr ? row_b : row_a; int t = tb * 64 + row; if (t >= S) continue; int64_t rowg = (int64_t)bh * S + t; #pragma unroll for (int nt = 0; nt < 16; ++nt) { #pragma unroll for (int p = 0; p < 2; ++p) { int bi = 8 * nt + 2 * (lane & 3) + p; float sv = (bi <= tb) ? c[nt][2 * rr + p] : -INFINITY; scores[rowg * 128 + bi] = sv; } } } } // --------------------------------------------------------------------------- // p1b: top-8 from scores. warp-per-row, high occupancy. // grid (ceil(rows/8)), block (256). // --------------------------------------------------------------------------- __global__ void __launch_bounds__(256) select_top_kernel( const float* __restrict__ scores, int16_t* __restrict__ sel, int* __restrict__ counts, int S, int nb, int64_t rows) { __shared__ float sm[32][257]; int row0 = blockIdx.x * 256; int tid = threadIdx.x; int64_t row = row0 + tid; bool valid = row < rows; int t = valid ? (int)(row % S) : 0; int tb = t >> 6; bool trivial = tb + 1 <= 8; float val[8]; int idx[8]; #pragma unroll for (int i = 0; i < 8; ++i) { val[i] = -INFINITY; idx[i] = -1; } if (trivial) { #pragma unroll for (int i = 0; i < 8; ++i) { val[i] = 0.f; idx[i] = (i <= tb) ? i : -1; } } int64_t lastrow = min((int64_t)(row0 + 255), rows - 1); // max chunk index needed by this CTA (uniform; CTAs may cross bh boundaries) int gmax = (row0 / S != lastrow / S) ? ((nb - 1) >> 5) : (((int)(lastrow % S) >> 6) >> 5); for (int g = 0; g <= gmax; ++g) { for (int idx2 = tid; idx2 < 256 * 8; idx2 += 256) { int r = idx2 >> 3, bl4 = (idx2 & 7) * 4; int64_t rowg = row0 + r; float4 sv = (rowg < rows) ? *reinterpret_cast(scores + rowg * 128 + 32 * g + bl4) : make_float4(-INFINITY, -INFINITY, -INFINITY, -INFINITY); sm[bl4][r] = sv.x; sm[bl4 + 1][r] = sv.y; sm[bl4 + 2][r] = sv.z; sm[bl4 + 3][r] = sv.w; } __syncthreads(); if (valid && !trivial) { #pragma unroll for (int bl = 0; bl < 32; ++bl) { int bi = 32 * g + bl; if (bi <= tb) { float s = sm[bl][tid]; if (s > val[7] || (s == val[7] && bi > idx[7])) { val[7] = s; idx[7] = bi; #pragma unroll for (int p = 7; p >= 1; --p) { if (val[p] > val[p - 1] || (val[p] == val[p - 1] && idx[p] > idx[p - 1])) { float tv = val[p]; val[p] = val[p - 1]; val[p - 1] = tv; int ti = idx[p]; idx[p] = idx[p - 1]; idx[p - 1] = ti; } } } } } } __syncthreads(); } if (valid) { int bh = (int)(row / S); #pragma unroll for (int i = 0; i < 8; ++i) { sel[row * 8 + i] = (int16_t)idx[i]; int bi = idx[i]; if (bi >= 0 && bi + 1 < tb) atomicAdd(&counts[(int64_t)bh * nb + bi], 1); } } } // --------------------------------------------------------------------------- // p2b: single CTA, warp-parallel. counts -> off (GLOBAL prefix), toff (per-bh // tile prefix), cursor = 0, tile map (bi<<16 | tile_local), T. // --------------------------------------------------------------------------- DEV_INLINE int warp_incl_scan(int v, int lane) { #pragma unroll for (int off = 1; off < 32; off <<= 1) { int n = __shfl_up_sync(0xffffffffu, v, off); if (lane >= off) v += n; } return v; } DEV_INLINE int warp_total(int v) { return __shfl_sync(0xffffffffu, v, 31); } __global__ void __launch_bounds__(1024) scan_kernel( const int* __restrict__ counts, int* __restrict__ off, int* __restrict__ toff, int* __restrict__ cursor, int* __restrict__ T, int* __restrict__ tmap, int nb, int BH, int tiles_upper, int tile_m) { extern __shared__ char smem_raw[]; int n = BH * nb; int* scnt = reinterpret_cast(smem_raw); // n int* soff = scnt + n; // n int* stoff = soff + n; // BH*(nb+1) int* bhsum = stoff + BH * (nb + 1); // BH int* bhtsum = bhsum + BH; // BH int* bhbase = bhtsum + BH; // BH int* bhtbase = bhbase + BH; // BH for (int i = threadIdx.x; i < n; i += blockDim.x) scnt[i] = counts[i]; __syncthreads(); const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; // per-bh prefix sums: one warp per bh (nb <= 128 -> 4 chunks of 32) for (int bh = warp; bh < BH; bh += blockDim.x / 32) { int acc = 0, tacc = 0; #pragma unroll for (int c = 0; c < 4; ++c) { int bi = 32 * c + lane; int v = (bi < nb) ? scnt[bh * nb + bi] : 0; int t = (v + tile_m - 1) / tile_m; int incl = warp_incl_scan(v, lane); int tincl = warp_incl_scan(t, lane); if (bi < nb) { soff[bh * nb + bi] = acc + incl - v; stoff[bh * (nb + 1) + bi] = tacc + tincl - t; } acc += warp_total(incl); tacc += warp_total(tincl); } if (lane == 0) { bhsum[bh] = acc; bhtsum[bh] = tacc; stoff[bh * (nb + 1) + nb] = tacc; } } __syncthreads(); // cross-bh bases if (warp == 0) { int v = (lane < BH) ? bhsum[lane] : 0; int t = (lane < BH) ? bhtsum[lane] : 0; int incl = warp_incl_scan(v, lane); int tincl = warp_incl_scan(t, lane); if (lane < BH) { bhbase[lane] = incl - v; bhtbase[lane] = tincl - t; } if (lane == 31) *T = tincl; } __syncthreads(); for (int i = threadIdx.x; i < n; i += blockDim.x) { int bh = i / nb; off[i] = soff[i] + bhbase[bh]; cursor[i] = 0; } // toff and tmap are PER-BH (remote grid is (tiles_upper, bh)): no cross-bh base for (int i = threadIdx.x; i < BH * (nb + 1); i += blockDim.x) toff[i] = stoff[i]; for (int idx = threadIdx.x; idx < n; idx += blockDim.x) { int bh = idx / nb, bi = idx % nb; int nt = (scnt[idx] + tile_m - 1) / tile_m; int base = stoff[bh * (nb + 1) + bi]; for (int j = 0; j < nt; ++j) tmap[bh * tiles_upper + base + j] = (bi << 16) | j; } } // --------------------------------------------------------------------------- // p2: scatter with CTA-level aggregation. grid (ceil(S/256), bh), block (256). // --------------------------------------------------------------------------- __global__ void scatter_kernel(const int16_t* __restrict__ sel, const int* __restrict__ off, int* __restrict__ cursor, uint32_t* __restrict__ list, int S, int nb) { extern __shared__ char smem_raw[]; int* scnt = reinterpret_cast(smem_raw); // nb int* sbase = scnt + nb; // nb int* scur = sbase + nb; // nb int bh = blockIdx.y; int t = blockIdx.x * blockDim.x + threadIdx.x; bool valid = t < S; for (int i = threadIdx.x; i < nb; i += blockDim.x) scnt[i] = 0; __syncthreads(); if (valid) { int tb = t >> 6; const int16_t* s = sel + ((int64_t)bh * S + t) * 8; #pragma unroll for (int i = 0; i < 8; ++i) { int b = s[i]; if (b >= 0 && b + 1 < tb) atomicAdd(&scnt[b], 1); } } __syncthreads(); if (threadIdx.x < nb) { // reserve this CTA's contiguous chunk of block b's global segment sbase[threadIdx.x] = atomicAdd(&cursor[(int64_t)bh * nb + threadIdx.x], scnt[threadIdx.x]); scur[threadIdx.x] = 0; } __syncthreads(); if (valid) { int64_t row = (int64_t)bh * S + t; const int16_t* s = sel + row * 8; #pragma unroll for (int i = 0; i < 8; ++i) { int b = s[i]; if (b >= 0 && b + 1 < (t >> 6)) { int pos = atomicAdd(&scur[b], 1); list[off[(int64_t)bh * nb + b] + sbase[b] + pos] = ((uint32_t)t << 3) | (uint32_t)i; } } } } // locked per-row online-softmax merge into L2-resident bf16 state (D=128 path) template DEV_INLINE void locked_merge_row(int lane, int64_t row, bool valid, float m2, float l, const float c_pv[][4], int rr, __nv_bfloat16* __restrict__ o_state, float* __restrict__ ml_state, int* __restrict__ locks) { constexpr int NTPV = D / 8; // warp-uniform call; valid is uniform within each 4-lane row group. // barriers must be GROUP-local: a warp-wide barrier would couple the 8 // groups' locks and allow circular wait across CTAs. const int gleader = lane & ~3; const uint32_t gmask = 0xFu << gleader; if (valid && (lane & 3) == 0) { while (atomicCAS(&locks[row], 0, 1) != 0) { __nanosleep(64); } } int bar = 0; bar = __shfl_sync(gmask, bar, gleader); __threadfence(); if (valid) { float mo = ml_state[row * 2], lo = ml_state[row * 2 + 1]; float M = fmaxf(mo, m2); float ao = exp2f(mo - M), an = exp2f(m2 - M); float ln = lo * ao + l * an; __nv_bfloat16* os = o_state + row * D; #pragma unroll for (int nt = 0; nt < NTPV; ++nt) { int d0 = nt * 8 + 2 * (lane & 3); float2 f = __bfloat1622float2(*reinterpret_cast(os + d0)); float r0 = f.x * ao + c_pv[nt][2 * rr] * an; float r1 = f.y * ao + c_pv[nt][2 * rr + 1] * an; *reinterpret_cast<__nv_bfloat162*>(os + d0) = __floats2bfloat162_rn(r0, r1); } if ((lane & 3) == 0) { ml_state[row * 2] = M; ml_state[row * 2 + 1] = ln; } } __threadfence(); bar = __shfl_sync(gmask, bar, gleader); if (valid && (lane & 3) == 0) atomicExch(&locks[row], 0); } // --------------------------------------------------------------------------- // p3: key-block-major sparse attention tiles (M queries x 64 keys x D). // grid (tiles_upper, bh), block (M/16*32), warp w -> queries 16w.. // --------------------------------------------------------------------------- template __global__ void __launch_bounds__(M / 16 * 32) remote_kernel( const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ k, const __nv_bfloat16* __restrict__ v, const uint32_t* __restrict__ list, const int* __restrict__ off, const int* __restrict__ toff, const int* __restrict__ counts, const int* __restrict__ tmap, __nv_bfloat16* __restrict__ o_part, float* __restrict__ ml_part, __nv_bfloat16* __restrict__ o_state, float* __restrict__ ml_state, int* __restrict__ locks, int S, int nb, int tiles_upper, float c_log2e) { extern __shared__ char smem_raw[]; const int bh = blockIdx.y; const int flat = blockIdx.x; __nv_bfloat16* sQ = reinterpret_cast<__nv_bfloat16*>(smem_raw); __nv_bfloat16* sK = sQ + M * D; __nv_bfloat16* sV = sK; // V reuses K's buffer (K dead after QK) uint32_t* sEnt = reinterpret_cast(sK + 64 * D); // M entries int* sMeta = reinterpret_cast(sEnt + M); // bi, n, base if (flat >= toff[(int64_t)bh * (nb + 1) + nb]) return; int mp = tmap[bh * tiles_upper + flat]; int bi = mp >> 16, tile = mp & 0xFFFF; if (threadIdx.x == 0) { sMeta[0] = bi; sMeta[1] = min(M, counts[(int64_t)bh * nb + bi] - tile * M); sMeta[2] = off[(int64_t)bh * nb + bi] + tile * M; } // K cp.async first (independent of entries); V loads later into same buffer const __nv_bfloat16* kg = k + ((int64_t)bh * S + bi * 64) * D; const __nv_bfloat16* vg = v + ((int64_t)bh * S + bi * 64) * D; constexpr int CH = D / 8; for (int idx = threadIdx.x; idx < 64 * CH; idx += blockDim.x) { int j = idx / CH, c = idx % CH; int pc = c ^ (j & 7); cp_async16(smem_u32(sK + j * D + pc * 8), kg + (int64_t)j * D + c * 8); } cp_async_commit(); __syncthreads(); int n = sMeta[1], base = sMeta[2]; for (int i = threadIdx.x; i < M; i += blockDim.x) sEnt[i] = (i < n) ? list[base + i] : 0; __syncthreads(); // Q gather for (int idx = threadIdx.x; idx < M * CH; idx += blockDim.x) { int m = idx / CH, c = idx % CH; int pc = c ^ (m & 7); if (m < n) { int t = sEnt[m] >> 3; cp_async16(smem_u32(sQ + m * D + pc * 8), q + ((int64_t)bh * S + t) * D + c * 8); } else { *reinterpret_cast(sQ + m * D + pc * 8) = make_uint4(0, 0, 0, 0); } } cp_async_commit(); cp_async_wait_all(); __syncthreads(); const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; const int m0 = warp * 16; int row_a = m0 + (lane >> 2), row_b = row_a + 8; bool valid_a = row_a < n, valid_b = row_b < n; int ta = sEnt[row_a] >> 3, tb_a = ta >> 6, ra = ta & 63; int tb_b = (sEnt[row_b] >> 3) >> 6, rb = (sEnt[row_b] >> 3) & 63; int cut_a = valid_a ? ((bi == tb_a - 1) ? ra + 1 : 64) : 0; int cut_b = valid_b ? ((bi == tb_b - 1) ? rb + 1 : 64) : 0; int col0 = 2 * (lane & 3); float c_qk[8][4]; #pragma unroll for (int nt = 0; nt < 8; ++nt) #pragma unroll for (int i = 0; i < 4; ++i) c_qk[nt][i] = 0.f; #pragma unroll for (int ks = 0; ks < D / 16; ++ks) { uint32_t a[4]; int rr = m0 + (lane & 15); int cc = ks * 2 + (lane >> 4); int pc = cc ^ (rr & 7); ldmatrix_x4(a[0], a[1], a[2], a[3], smem_u32(sQ + rr * D + pc * 8)); #pragma unroll for (int nt = 0; nt < 8; ++nt) { uint32_t b[2]; int rr2 = nt * 8 + (lane & 7); int cc2 = ks * 2 + ((lane >> 3) & 1); int pc2 = cc2 ^ (rr2 & 7); ldmatrix_x2(b[0], b[1], smem_u32(sK + rr2 * D + pc2 * 8)); mma_bf16(c_qk[nt], a, b); } } float m_a = -INFINITY, m_b = -INFINITY; #pragma unroll for (int nt = 0; nt < 8; ++nt) { int key0 = nt * 8 + col0; #pragma unroll for (int i = 0; i < 4; ++i) { float s = c_qk[nt][i] * c_log2e; c_qk[nt][i] = s; int key = key0 + (i & 1); if (i < 2) { if (key < cut_a) m_a = fmaxf(m_a, s); } else { if (key < cut_b) m_b = fmaxf(m_b, s); } } } #pragma unroll for (int off = 1; off <= 2; off <<= 1) { m_a = fmaxf(m_a, __shfl_xor_sync(0xffffffffu, m_a, off)); m_b = fmaxf(m_b, __shfl_xor_sync(0xffffffffu, m_b, off)); } float l_a = 0.f, l_b = 0.f; #pragma unroll for (int nt = 0; nt < 8; ++nt) { int key0 = nt * 8 + col0; #pragma unroll for (int i = 0; i < 4; ++i) { int key = key0 + (i & 1); float s = c_qk[nt][i]; float p; if (i < 2) p = (key < cut_a) ? exp2f(s - m_a) : 0.f; else p = (key < cut_b) ? exp2f(s - m_b) : 0.f; c_qk[nt][i] = p; if (i < 2) l_a += p; else l_b += p; } } #pragma unroll for (int off = 1; off <= 2; off <<= 1) { l_a += __shfl_xor_sync(0xffffffffu, l_a, off); l_b += __shfl_xor_sync(0xffffffffu, l_b, off); } // load V into the (now dead) K buffer while P sits in registers __syncthreads(); for (int idx = threadIdx.x; idx < 64 * CH; idx += blockDim.x) { int j = idx / CH, c = idx % CH; int pc = c ^ (j & 7); cp_async16(smem_u32(sV + j * D + pc * 8), vg + (int64_t)j * D + c * 8); } cp_async_commit(); cp_async_wait_all(); __syncthreads(); constexpr int NTPV = D / 8; float c_pv[NTPV][4]; #pragma unroll for (int nt = 0; nt < NTPV; ++nt) #pragma unroll for (int i = 0; i < 4; ++i) c_pv[nt][i] = 0.f; #pragma unroll for (int ks = 0; ks < 4; ++ks) { uint32_t a[4]; __nv_bfloat162 p0 = __floats2bfloat162_rn(c_qk[2 * ks][0], c_qk[2 * ks][1]); __nv_bfloat162 p1 = __floats2bfloat162_rn(c_qk[2 * ks][2], c_qk[2 * ks][3]); __nv_bfloat162 p2 = __floats2bfloat162_rn(c_qk[2 * ks + 1][0], c_qk[2 * ks + 1][1]); __nv_bfloat162 p3 = __floats2bfloat162_rn(c_qk[2 * ks + 1][2], c_qk[2 * ks + 1][3]); a[0] = *reinterpret_cast(&p0); a[1] = *reinterpret_cast(&p1); a[2] = *reinterpret_cast(&p2); a[3] = *reinterpret_cast(&p3); #pragma unroll for (int nt = 0; nt < NTPV; ++nt) { uint32_t b[2]; int rr2 = ks * 16 + (lane & 15); int pc2 = nt ^ (rr2 & 7); ldmatrix_x2_trans(b[0], b[1], smem_u32(sV + rr2 * D + pc2 * 8)); mma_bf16(c_pv[nt], a, b); } } if (LOCKED) { locked_merge_row(lane, (int64_t)bh * S + ta, valid_a, m_a, l_a, c_pv, 0, o_state, ml_state, locks); locked_merge_row(lane, (int64_t)bh * S + (sEnt[row_b] >> 3), valid_b, m_b, l_b, c_pv, 1, o_state, ml_state, locks); return; } if (valid_a) { int slot_a = sEnt[row_a] & 7; int64_t rowg_a = (int64_t)bh * S + ta; __nv_bfloat16* oa = o_part + (rowg_a * 9 + slot_a) * D; #pragma unroll for (int nt = 0; nt < NTPV; ++nt) { __nv_bfloat162 va = __floats2bfloat162_rn(c_pv[nt][0], c_pv[nt][1]); if (D == 128) __stcs(reinterpret_cast(oa + nt * 8 + col0), *reinterpret_cast(&va)); else *reinterpret_cast<__nv_bfloat162*>(oa + nt * 8 + col0) = va; } if ((lane & 3) == 0) { float* mla = ml_part + (rowg_a * 9 + slot_a) * 2; if (D == 128) { __stcs(mla, m_a); __stcs(mla + 1, l_a); } else { mla[0] = m_a; mla[1] = l_a; } } } if (valid_b) { int slot_b = sEnt[row_b] & 7; int64_t rowg_b = (int64_t)bh * S + (sEnt[row_b] >> 3); __nv_bfloat16* ob = o_part + (rowg_b * 9 + slot_b) * D; #pragma unroll for (int nt = 0; nt < NTPV; ++nt) { __nv_bfloat162 vb = __floats2bfloat162_rn(c_pv[nt][2], c_pv[nt][3]); if (D == 128) __stcs(reinterpret_cast(ob + nt * 8 + col0), *reinterpret_cast(&vb)); else *reinterpret_cast<__nv_bfloat162*>(ob + nt * 8 + col0) = vb; } if ((lane & 3) == 0) { float* mlb = ml_part + (rowg_b * 9 + slot_b) * 2; if (D == 128) { __stcs(mlb, m_b); __stcs(mlb + 1, l_b); } else { mlb[0] = m_b; mlb[1] = l_b; } } } } // --------------------------------------------------------------------------- // p3.5: local sliding window as banded 64x128 tensor-core tile. // grid (ceil(S/64), bh), block (128). K/V rows 0..63 = block tb-1, 64..127 = tb. // valid key j for query m: (tb>0 && m+1 <= j < 64) || (64 <= j <= m+64 && j < 64+rem) // writes slot 8 partials. // --------------------------------------------------------------------------- template __global__ void __launch_bounds__(128) local_kernel( const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ k, const __nv_bfloat16* __restrict__ v, const int16_t* __restrict__ sel, __nv_bfloat16* __restrict__ o_part, float* __restrict__ ml_part, __nv_bfloat16* __restrict__ o_state, float* __restrict__ ml_state, int* __restrict__ locks, int S, float c_log2e) { extern __shared__ char smem_raw[]; const int tb = blockIdx.x, bh = blockIdx.y; __nv_bfloat16* sQ = reinterpret_cast<__nv_bfloat16*>(smem_raw); __nv_bfloat16* sK = sQ + 64 * D; __nv_bfloat16* sV = sK; // V reuses K buffer constexpr int CH = D / 8; int rem = S - tb * 64; // keys present in block tb (1..64) // K/V: 128 rows for (int idx = threadIdx.x; idx < 128 * CH; idx += blockDim.x) { int j = idx / CH, c = idx % CH; int pc = c ^ (j & 7); int blk = (j < 64) ? tb - 1 : tb; int gj = blk * 64 + (j & 63); uint32_t da = smem_u32(sK + j * D + pc * 8); uint32_t db = smem_u32(sV + j * D + pc * 8); if (blk >= 0 && gj < S) { cp_async16(da, k + ((int64_t)bh * S + gj) * D + c * 8); } else { *reinterpret_cast(sK + j * D + pc * 8) = make_uint4(0, 0, 0, 0); } } cp_async_commit(); // Q rows for (int idx = threadIdx.x; idx < 64 * CH; idx += blockDim.x) { int m = idx / CH, c = idx % CH; int pc = c ^ (m & 7); int t = tb * 64 + m; if (t < S) cp_async16(smem_u32(sQ + m * D + pc * 8), q + ((int64_t)bh * S + t) * D + c * 8); else *reinterpret_cast(sQ + m * D + pc * 8) = make_uint4(0, 0, 0, 0); } cp_async_commit(); cp_async_wait_all(); __syncthreads(); const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; const int m0 = warp * 16; int row_a = m0 + (lane >> 2), row_b = row_a + 8; bool valid_a = (tb * 64 + row_a) < S, valid_b = (tb * 64 + row_b) < S; int col0 = 2 * (lane & 3); int hi_a = min(64 + rem, row_a + 65); // exclusive upper j bound (j <= m+64, j < 64+rem) int hi_b = min(64 + rem, row_b + 65); int lo_a = row_a + 1; // window part of block tb-1: j >= m+1 int lo_b = row_b + 1; // if block tb-1 was top-8 selected, its FULL causal part joins the window bool prev_a = false, prev_b = false; if (tb > 0 && valid_a) { const int16_t* sa = sel + ((int64_t)bh * S + tb * 64 + row_a) * 8; #pragma unroll for (int s = 0; s < 8; ++s) if (sa[s] == tb - 1) prev_a = true; } if (tb > 0 && valid_b) { const int16_t* sb = sel + ((int64_t)bh * S + tb * 64 + row_b) * 8; #pragma unroll for (int s = 0; s < 8; ++s) if (sb[s] == tb - 1) prev_b = true; } if (prev_a) lo_a = 0; if (prev_b) lo_b = 0; float c_qk[16][4]; #pragma unroll for (int nt = 0; nt < 16; ++nt) #pragma unroll for (int i = 0; i < 4; ++i) c_qk[nt][i] = 0.f; #pragma unroll for (int ks = 0; ks < D / 16; ++ks) { uint32_t a[4]; int rr = m0 + (lane & 15); int cc = ks * 2 + (lane >> 4); int pc = cc ^ (rr & 7); ldmatrix_x4(a[0], a[1], a[2], a[3], smem_u32(sQ + rr * D + pc * 8)); #pragma unroll for (int nt = 0; nt < 16; ++nt) { uint32_t b[2]; int rr2 = nt * 8 + (lane & 7); int cc2 = ks * 2 + ((lane >> 3) & 1); int pc2 = cc2 ^ (rr2 & 7); ldmatrix_x2(b[0], b[1], smem_u32(sK + rr2 * D + pc2 * 8)); mma_bf16(c_qk[nt], a, b); } } float m_a = -INFINITY, m_b = -INFINITY; #pragma unroll for (int nt = 0; nt < 16; ++nt) { int key0 = nt * 8 + col0; #pragma unroll for (int i = 0; i < 4; ++i) { int j = key0 + (i & 1); float s = c_qk[nt][i] * c_log2e; c_qk[nt][i] = s; bool ok_a = valid_a && ((j < 64) ? (tb > 0 && j >= lo_a) : (j < hi_a)); bool ok_b = valid_b && ((j < 64) ? (tb > 0 && j >= lo_b) : (j < hi_b)); if (i < 2) { if (ok_a) m_a = fmaxf(m_a, s); } else { if (ok_b) m_b = fmaxf(m_b, s); } } } #pragma unroll for (int off = 1; off <= 2; off <<= 1) { m_a = fmaxf(m_a, __shfl_xor_sync(0xffffffffu, m_a, off)); m_b = fmaxf(m_b, __shfl_xor_sync(0xffffffffu, m_b, off)); } float l_a = 0.f, l_b = 0.f; #pragma unroll for (int nt = 0; nt < 16; ++nt) { int key0 = nt * 8 + col0; #pragma unroll for (int i = 0; i < 4; ++i) { int j = key0 + (i & 1); float s = c_qk[nt][i]; bool ok_a = valid_a && ((j < 64) ? (tb > 0 && j >= lo_a) : (j < hi_a)); bool ok_b = valid_b && ((j < 64) ? (tb > 0 && j >= lo_b) : (j < hi_b)); float p; if (i < 2) p = ok_a ? exp2f(s - m_a) : 0.f; else p = ok_b ? exp2f(s - m_b) : 0.f; c_qk[nt][i] = p; if (i < 2) l_a += p; else l_b += p; } } #pragma unroll for (int off = 1; off <= 2; off <<= 1) { l_a += __shfl_xor_sync(0xffffffffu, l_a, off); l_b += __shfl_xor_sync(0xffffffffu, l_b, off); } // V into dead K buffer __syncthreads(); for (int idx = threadIdx.x; idx < 128 * CH; idx += blockDim.x) { int j = idx / CH, c = idx % CH; int pc = c ^ (j & 7); int blk = (j < 64) ? tb - 1 : tb; int gj = blk * 64 + (j & 63); if (blk >= 0 && gj < S) cp_async16(smem_u32(sV + j * D + pc * 8), v + ((int64_t)bh * S + gj) * D + c * 8); else *reinterpret_cast(sV + j * D + pc * 8) = make_uint4(0, 0, 0, 0); } cp_async_commit(); cp_async_wait_all(); __syncthreads(); constexpr int NTPV = D / 8; float c_pv[NTPV][4]; #pragma unroll for (int nt = 0; nt < NTPV; ++nt) #pragma unroll for (int i = 0; i < 4; ++i) c_pv[nt][i] = 0.f; #pragma unroll for (int ks = 0; ks < 8; ++ks) { uint32_t a[4]; __nv_bfloat162 p0 = __floats2bfloat162_rn(c_qk[2 * ks][0], c_qk[2 * ks][1]); __nv_bfloat162 p1 = __floats2bfloat162_rn(c_qk[2 * ks][2], c_qk[2 * ks][3]); __nv_bfloat162 p2 = __floats2bfloat162_rn(c_qk[2 * ks + 1][0], c_qk[2 * ks + 1][1]); __nv_bfloat162 p3 = __floats2bfloat162_rn(c_qk[2 * ks + 1][2], c_qk[2 * ks + 1][3]); a[0] = *reinterpret_cast(&p0); a[1] = *reinterpret_cast(&p1); a[2] = *reinterpret_cast(&p2); a[3] = *reinterpret_cast(&p3); #pragma unroll for (int nt = 0; nt < NTPV; ++nt) { uint32_t b[2]; int rr2 = ks * 16 + (lane & 15); int pc2 = nt ^ (rr2 & 7); ldmatrix_x2_trans(b[0], b[1], smem_u32(sV + rr2 * D + pc2 * 8)); mma_bf16(c_pv[nt], a, b); } } int64_t rowg_a = (int64_t)bh * S + tb * 64 + row_a; int64_t rowg_b = (int64_t)bh * S + tb * 64 + row_b; if (LOCKED) { locked_merge_row(lane, rowg_a, valid_a, m_a, l_a, c_pv, 0, o_state, ml_state, locks); locked_merge_row(lane, rowg_b, valid_b, m_b, l_b, c_pv, 1, o_state, ml_state, locks); return; } if (valid_a) { __nv_bfloat16* oa = o_part + (rowg_a * 9 + 8) * D; #pragma unroll for (int nt = 0; nt < NTPV; ++nt) { __nv_bfloat162 va = __floats2bfloat162_rn(c_pv[nt][0], c_pv[nt][1]); if (D == 128) __stcs(reinterpret_cast(oa + nt * 8 + col0), *reinterpret_cast(&va)); else *reinterpret_cast<__nv_bfloat162*>(oa + nt * 8 + col0) = va; } if ((lane & 3) == 0) { float* mla = ml_part + (rowg_a * 9 + 8) * 2; if (D == 128) { __stcs(mla, m_a); __stcs(mla + 1, l_a); } else { mla[0] = m_a; mla[1] = l_a; } } } if (valid_b) { __nv_bfloat16* ob = o_part + (rowg_b * 9 + 8) * D; #pragma unroll for (int nt = 0; nt < NTPV; ++nt) { __nv_bfloat162 vb = __floats2bfloat162_rn(c_pv[nt][2], c_pv[nt][3]); if (D == 128) __stcs(reinterpret_cast(ob + nt * 8 + col0), *reinterpret_cast(&vb)); else *reinterpret_cast<__nv_bfloat162*>(ob + nt * 8 + col0) = vb; } if ((lane & 3) == 0) { float* mlb = ml_part + (rowg_b * 9 + 8) * 2; if (D == 128) { __stcs(mlb, m_b); __stcs(mlb + 1, l_b); } else { mlb[0] = m_b; mlb[1] = l_b; } } } } // --------------------------------------------------------------------------- // p4: merge partials + normalize. grid (ceil(rows/8)), block (256), warp/row. // lanes 0..8 own slots; parallel loads, no local arrays. // --------------------------------------------------------------------------- template __global__ void __launch_bounds__(256) merge_kernel( const int16_t* __restrict__ sel, const __nv_bfloat16* __restrict__ o_part, const float* __restrict__ ml_part, __nv_bfloat16* __restrict__ out, int S, int64_t rows) { int64_t row = (int64_t)blockIdx.x * 8 + (threadIdx.x >> 5); if (row >= rows) return; int lane = threadIdx.x & 31; int t = (int)(row % S); int tb = t >> 6; float m_s = -INFINITY, l_s = 0.f; bool valid = false; if (lane < 8) { int bi = sel[row * 8 + lane]; valid = (bi >= 0 && bi + 1 < tb); } else if (lane == 8) { valid = true; } if (valid) { const float* ml = ml_part + (row * 9 + lane) * 2; m_s = ml[0]; l_s = ml[1]; } float M = m_s; #pragma unroll for (int off = 16; off > 0; off >>= 1) M = fmaxf(M, __shfl_xor_sync(0xffffffffu, M, off)); float alpha = valid ? exp2f(m_s - M) : 0.f; float L = l_s * alpha; #pragma unroll for (int off = 16; off > 0; off >>= 1) L += __shfl_xor_sync(0xffffffffu, L, off); float invL = 1.0f / L; #pragma unroll for (int u = 0; u < D / 64; ++u) { int d0 = 2 * lane + u * 64; float o0 = 0.f, o1 = 0.f; #pragma unroll for (int s = 0; s < 9; ++s) { float a = __shfl_sync(0xffffffffu, alpha, s); uint32_t vm = __shfl_sync(0xffffffffu, valid ? 1u : 0u, s); if (vm) { const __nv_bfloat162* op = reinterpret_cast( o_part + (row * 9 + s) * D + d0); float2 ov = __bfloat1622float2(*op); o0 += a * ov.x; o1 += a * ov.y; } } __nv_bfloat162 o = __floats2bfloat162_rn(o0 * invL, o1 * invL); *reinterpret_cast<__nv_bfloat162*>(out + row * D + d0) = o; } } // --------------------------------------------------------------------------- // p4b: normalize locked state -> bf16 out (D=128 locked path) // --------------------------------------------------------------------------- template __global__ void __launch_bounds__(256) normalize_kernel( const __nv_bfloat16* __restrict__ o_state, const float* __restrict__ ml_state, __nv_bfloat16* __restrict__ out, int64_t rows) { int64_t row = (int64_t)blockIdx.x * 8 + (threadIdx.x >> 5); if (row >= rows) return; int lane = threadIdx.x & 31; float invL = 1.0f / ml_state[row * 2 + 1]; #pragma unroll for (int u = 0; u < D / 64; ++u) { int d0 = 2 * lane + u * 64; float2 f = __bfloat1622float2(*reinterpret_cast(o_state + row * D + d0)); *reinterpret_cast<__nv_bfloat162*>(out + row * D + d0) = __floats2bfloat162_rn(f.x * invL, f.y * invL); } } // --------------------------------------------------------------------------- // host launchers // --------------------------------------------------------------------------- static void set_smem(const void* func, int bytes) { static std::map done; auto it = done.find(func); if (it != done.end() && it->second >= bytes) return; cudaFuncSetAttribute(func, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes); done[func] = bytes; } template void launch_all(const __nv_bfloat16* q, const __nv_bfloat16* k, const __nv_bfloat16* v, float* kbar, float* scores, int16_t* sel, int* counts, int* off, int* toff, int* cursor, int* T, int* tmap, uint32_t* list, __nv_bfloat16* o_part, float* ml_part, __nv_bfloat16* o_state, float* ml_state, int* locks, __nv_bfloat16* out, int B, int H, int S, cudaStream_t stream) { constexpr bool LOCKED = false; int bh = B * H, nb = (S + 63) / 64; int64_t rows = (int64_t)bh * S; float c_log2e = (float)(1.0 / sqrt((double)D) * 1.4426950408889634); int tiles_upper = (8 * S + M - 1) / M + nb; dim3 g0(nb, bh); kbar_kernel<<>>(k, kbar, counts, o_state, ml_state, S, nb, bh * nb, rows); int sel_smem = 64 * D * 2 + 3 * 32 * D * 2 + 4 * 16 * 4; set_smem((const void*)select_score_kernel, sel_smem); dim3 g1((S + 63) / 64, bh); select_score_kernel<<>>(q, k, kbar, scores, S, nb); dim3 g1b((unsigned)((rows + 255) / 256)); select_top_kernel<<>>(scores, sel, counts, S, nb, rows); int scan_smem = (2 * bh * nb + bh * (nb + 1) + 4 * bh) * 4; set_smem((const void*)scan_kernel, scan_smem); scan_kernel<<<1, 1024, scan_smem, stream>>>(counts, off, toff, cursor, T, tmap, nb, bh, tiles_upper, M); dim3 g2((unsigned)((S + 255) / 256), bh); scatter_kernel<<>>(sel, off, cursor, list, S, nb); int rem_smem = (M + 64) * D * 2 + M * 4 + 16; set_smem((const void*)remote_kernel, rem_smem); dim3 g3(tiles_upper, bh); remote_kernel<<>>( q, k, v, list, off, toff, counts, tmap, o_part, ml_part, o_state, ml_state, locks, S, nb, tiles_upper, c_log2e); int loc_smem = (64 + 128) * D * 2; set_smem((const void*)local_kernel, loc_smem); dim3 g4((S + 63) / 64, bh); local_kernel<<>>(q, k, v, sel, o_part, ml_part, o_state, ml_state, locks, S, c_log2e); dim3 g5((unsigned)((rows + 7) / 8)); if (LOCKED) { normalize_kernel<<>>(o_state, ml_state, out, rows); } else { merge_kernel<<>>(sel, o_part, ml_part, out, S, rows); } } void nsa_forward(torch::Tensor q, torch::Tensor k, torch::Tensor v, torch::Tensor kbar, torch::Tensor scores, torch::Tensor sel, torch::Tensor counts, torch::Tensor off, torch::Tensor toff, torch::Tensor cursor, torch::Tensor T, torch::Tensor tmap, torch::Tensor list, torch::Tensor o_part, torch::Tensor ml_part, torch::Tensor o_state, torch::Tensor ml_state, torch::Tensor locks, torch::Tensor out) { int B = q.size(0), H = q.size(1), S = q.size(2), D = q.size(3); auto stream = at::cuda::getCurrentCUDAStream().stream(); const __nv_bfloat16* qp = reinterpret_cast(q.data_ptr()); const __nv_bfloat16* kp = reinterpret_cast(k.data_ptr()); const __nv_bfloat16* vp = reinterpret_cast(v.data_ptr()); __nv_bfloat16* op = reinterpret_cast<__nv_bfloat16*>(out.data_ptr()); __nv_bfloat16* opp = reinterpret_cast<__nv_bfloat16*>(o_part.data_ptr()); if (D == 64) launch_all<64, 128>(qp, kp, vp, kbar.data_ptr(), scores.data_ptr(), (int16_t*)sel.data_ptr(), counts.data_ptr(), off.data_ptr(), toff.data_ptr(), cursor.data_ptr(), T.data_ptr(), tmap.data_ptr(), (uint32_t*)list.data_ptr(), opp, ml_part.data_ptr(), reinterpret_cast<__nv_bfloat16*>(o_state.data_ptr()), ml_state.data_ptr(), locks.data_ptr(), op, B, H, S, stream); else launch_all<128, 128>(qp, kp, vp, kbar.data_ptr(), scores.data_ptr(), (int16_t*)sel.data_ptr(), counts.data_ptr(), off.data_ptr(), toff.data_ptr(), cursor.data_ptr(), T.data_ptr(), tmap.data_ptr(), (uint32_t*)list.data_ptr(), opp, ml_part.data_ptr(), reinterpret_cast<__nv_bfloat16*>(o_state.data_ptr()), ml_state.data_ptr(), locks.data_ptr(), op, B, H, S, stream); } """ _CPP_SRC = r""" #include void nsa_forward(torch::Tensor q, torch::Tensor k, torch::Tensor v, torch::Tensor kbar, torch::Tensor scores, torch::Tensor sel, torch::Tensor counts, torch::Tensor off, torch::Tensor toff, torch::Tensor cursor, torch::Tensor T, torch::Tensor tmap, torch::Tensor list, torch::Tensor o_part, torch::Tensor ml_part, torch::Tensor o_state, torch::Tensor ml_state, torch::Tensor locks, torch::Tensor out); """ _mod = load_inline( name="nsa_cuda_v16", cpp_sources=_CPP_SRC, cuda_sources=_CUDA_SRC, functions=["nsa_forward"], extra_cuda_cflags=[ "-O3", "--use_fast_math", "-lineinfo", "-gencode=arch=compute_120a,code=sm_120a", ], extra_cflags=["-O3"], 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._ws = None self._ws_key = None self._graphs = {} def _workspace(self, dev): key = (self.B, self.H, self.S, self.D, dev) if self._ws_key == key: return self._ws B, H, S, D = self.B, self.H, self.S, self.D bh, nb, rows = B * H, (S + 63) // 64, B * H * S assert D in (64, 128) and bh <= 32 and bh * nb <= 4096 and S <= 16384 M = 128 tiles_upper = (8 * S + M - 1) // M + nb ws = dict( kbar=torch.empty(bh * nb * D, dtype=torch.float32, device=dev), scores=torch.empty(rows * 128, dtype=torch.float32, device=dev), sel=torch.empty(rows * 8, dtype=torch.int16, device=dev), counts=torch.empty(bh * nb, dtype=torch.int32, device=dev), off=torch.empty(bh * nb, dtype=torch.int32, device=dev), toff=torch.empty(bh * (nb + 1), dtype=torch.int32, device=dev), cursor=torch.empty(bh * nb, dtype=torch.int32, device=dev), T=torch.empty(1, dtype=torch.int32, device=dev), tmap=torch.empty(bh * tiles_upper, dtype=torch.int32, device=dev), list=torch.empty(8 * rows, dtype=torch.int32, device=dev), o_part=torch.empty(rows * 9 * D, dtype=torch.bfloat16, device=dev), ml_part=torch.empty(rows * 9 * 2, dtype=torch.float32, device=dev), o_state=torch.empty(16, dtype=torch.bfloat16, device=dev), ml_state=torch.empty(16, dtype=torch.float32, device=dev), locks=torch.zeros(16, dtype=torch.int32, device=dev), out=torch.empty(B, H, S, D, dtype=torch.bfloat16, device=dev), ) self._ws, self._ws_key = ws, key return ws def _launch(self, q, k, v, ws): _mod.nsa_forward(q, k, v, ws["kbar"], ws["scores"], ws["sel"], ws["counts"], ws["off"], ws["toff"], ws["cursor"], ws["T"], ws["tmap"], ws["list"], ws["o_part"], ws["ml_part"], ws["o_state"], ws["ml_state"], ws["locks"], ws["out"]) def forward(self, q, k, v): assert q.is_cuda and q.dtype == torch.bfloat16 if not q.is_contiguous(): q = q.contiguous() if not k.is_contiguous(): k = k.contiguous() if not v.is_contiguous(): v = v.contiguous() ws = self._workspace(q.device) key = (q.data_ptr(), k.data_ptr(), v.data_ptr()) g = self._graphs.get(key) if g is None: if len(self._graphs) >= 64: self._launch(q, k, v, ws) return ws["out"] s = torch.cuda.Stream(device=q.device) s.wait_stream(torch.cuda.current_stream(q.device)) with torch.cuda.stream(s): self._launch(q, k, v, ws) torch.cuda.current_stream(q.device).wait_stream(s) g = torch.cuda.CUDAGraph() with torch.cuda.graph(g): self._launch(q, k, v, ws) self._graphs[key] = g g.replay() return ws["out"] def get_init_inputs(): return [1, 16, 1024, 64] def get_inputs(): q = torch.randn(1, 16, 1024, 64, dtype=torch.bfloat16) k = torch.randn(1, 16, 1024, 64, dtype=torch.bfloat16) v = torch.randn(1, 16, 1024, 64, dtype=torch.bfloat16) return [q, k, v]