from __future__ import annotations import torch import torch.nn as nn from torch.utils.cpp_extension import load_inline _CPP_SOURCE = r""" torch::Tensor nsa_forward(torch::Tensor q, torch::Tensor k, torch::Tensor v); """ _CUDA_SOURCE = r""" #include #include #include #include #include #include #include using namespace nvcuda; constexpr int BLOCK_SIZE = 64; constexpr int TOP_N = 8; __device__ __forceinline__ bool better_block( float score, int block, float old_score, int old_block) { return score > old_score || (score == old_score && block > old_block); } template __global__ __launch_bounds__(256) void select_blocks_kernel( const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ k, int* __restrict__ selected, int S) { constexpr int SCORE_STRIDE = D == 64 ? 68 : 64; const int tile = blockIdx.x; const int bh = blockIdx.y; const int tid = threadIdx.x; const int warp = tid >> 5; const int key_segment = warp & 3; const int query_half = warp >> 2; const int lane = tid & 31; const int row_in_group = lane >> 3; const int reduce_lane = lane & 7; const int local_row = query_half * 16 + key_segment * 4 + row_in_group; const int row = tile * 32 + local_row; const int t = row; if (min(S - 1, tile * 32 + 31) < 512) { return; } const int64_t head_offset = static_cast(bh) * S * D; __shared__ __nv_bfloat16 q_shared[32 * D]; __shared__ __nv_bfloat16 k_shared[64 * D]; __shared__ float scores[32][SCORE_STRIDE]; for (int i = tid; i < 32 * D / 8; i += 256) { const int r = i / (D / 8); const int c = i % (D / 8); const int global_row = tile * 32 + r; uint4 value = make_uint4(0, 0, 0, 0); if (global_row < S) { value = *reinterpret_cast( q + head_offset + static_cast(global_row) * D + c * 8); } *reinterpret_cast(q_shared + r * D + c * 8) = value; } __syncthreads(); wmma::fragment a_frag[D / 16]; #pragma unroll for (int kd = 0; kd < D / 16; ++kd) { wmma::load_matrix_sync(a_frag[kd], q_shared + query_half * 16 * D + kd * 16, D); } float best_score[TOP_N]; int best_block[TOP_N]; #pragma unroll for (int i = 0; i < TOP_N; ++i) { best_score[i] = -CUDART_INF_F; best_block[i] = -1; } const int last_row = min(S - 1, tile * 32 + 31); const int num_blocks = last_row >= tile * 32 ? (last_row + 64) / 64 : 0; for (int bi = 0; bi < num_blocks; ++bi) { const int key0 = bi * 64; for (int i = tid; i < 64 * D / 8; i += 256) { const int r = i / (D / 8); const int c = i % (D / 8); uint4 value = make_uint4(0, 0, 0, 0); if (key0 + r < S) { value = *reinterpret_cast( k + head_offset + static_cast(key0 + r) * D + c * 8); } *reinterpret_cast(k_shared + r * D + c * 8) = value; } __syncthreads(); wmma::fragment c_frag; wmma::fill_fragment(c_frag, 0.0f); #pragma unroll for (int kd = 0; kd < D / 16; ++kd) { wmma::fragment b_frag; wmma::load_matrix_sync(b_frag, k_shared + key_segment * 16 * D + kd * 16, D); wmma::mma_sync(c_frag, a_frag[kd], b_frag, c_frag); } wmma::store_matrix_sync(&scores[query_half * 16][key_segment * 16], c_frag, SCORE_STRIDE, wmma::mem_row_major); __syncthreads(); if (row < S && key0 <= t) { const int valid = min(64, t - key0 + 1); float sum = 0.0f; #pragma unroll for (int j = 0; j < 8; ++j) { const int col = reduce_lane * 8 + j; if (col < valid) { sum += scores[local_row][col]; } } #pragma unroll for (int offset = 4; offset > 0; offset >>= 1) { sum += __shfl_xor_sync(0xffu << (threadIdx.x & 24), sum, offset, 8); } sum /= static_cast(valid); if (reduce_lane == 0 && better_block(sum, bi, best_score[TOP_N - 1], best_block[TOP_N - 1])) { best_score[TOP_N - 1] = sum; best_block[TOP_N - 1] = bi; #pragma unroll for (int i = TOP_N - 2; i >= 0; --i) { if (better_block(best_score[i + 1], best_block[i + 1], best_score[i], best_block[i])) { float tmp_score = best_score[i]; int tmp_block = best_block[i]; best_score[i] = best_score[i + 1]; best_block[i] = best_block[i + 1]; best_score[i + 1] = tmp_score; best_block[i + 1] = tmp_block; } } } } __syncthreads(); } if (row < S && reduce_lane == 0) { int* dst = selected + (static_cast(bh) * S + row) * TOP_N; #pragma unroll for (int i = 0; i < TOP_N; ++i) { dst[i] = best_block[i]; } } } __device__ __forceinline__ float2 bf16_pair_to_float2(uint32_t value) { return make_float2(__uint_as_float(value << 16), __uint_as_float(value & 0xffff0000u)); } template struct OnlineState { static constexpr int DP = D / 8; float m; float l; float acc[DP]; }; template __device__ __forceinline__ void score_segment( int begin, int end, int slot_begin, int group, int r, const __nv_bfloat16* __restrict__ k_head, const float* __restrict__ q_reg, float scale, float* __restrict__ score_storage, OnlineState& state) { constexpr int DP = D / 8; for (int base = begin; base < end; base += 4) { const int key = base + group; if (key < end) { const uint4* k_ptr = reinterpret_cast( k_head + static_cast(key) * D + r * DP); float dot = 0.0f; #pragma unroll for (int chunk = 0; chunk < DP / 8; ++chunk) { const uint4 raw = k_ptr[chunk]; const float2 k0 = bf16_pair_to_float2(raw.x); const float2 k1 = bf16_pair_to_float2(raw.y); const float2 k2 = bf16_pair_to_float2(raw.z); const float2 k3 = bf16_pair_to_float2(raw.w); const int d = chunk * 8; dot = fmaf(q_reg[d + 0], k0.x, dot); dot = fmaf(q_reg[d + 1], k0.y, dot); dot = fmaf(q_reg[d + 2], k1.x, dot); dot = fmaf(q_reg[d + 3], k1.y, dot); dot = fmaf(q_reg[d + 4], k2.x, dot); dot = fmaf(q_reg[d + 5], k2.y, dot); dot = fmaf(q_reg[d + 6], k3.x, dot); dot = fmaf(q_reg[d + 7], k3.y, dot); } #pragma unroll for (int offset = 4; offset > 0; offset >>= 1) { dot += __shfl_xor_sync(0xffu << (threadIdx.x & 24), dot, offset, 8); } const float score = dot * scale; if (r == 0) { score_storage[slot_begin + base - begin + group] = score; } state.m = fmaxf(state.m, score); } } } template __device__ __forceinline__ void value_segment( int begin, int end, int slot_begin, int group, int r, const __nv_bfloat16* __restrict__ v_head, const float* __restrict__ score_storage, float max_m, OnlineState& state) { constexpr int DP = D / 8; for (int base = begin; base < end; base += 4) { const int key = base + group; if (key < end) { const float weight = __expf( score_storage[slot_begin + base - begin + group] - max_m); state.l += weight; const uint4* v_ptr = reinterpret_cast( v_head + static_cast(key) * D + r * DP); #pragma unroll for (int chunk = 0; chunk < DP / 8; ++chunk) { const uint4 raw = v_ptr[chunk]; const float2 v0 = bf16_pair_to_float2(raw.x); const float2 v1 = bf16_pair_to_float2(raw.y); const float2 v2 = bf16_pair_to_float2(raw.z); const float2 v3 = bf16_pair_to_float2(raw.w); const int d = chunk * 8; state.acc[d + 0] = fmaf(weight, v0.x, state.acc[d + 0]); state.acc[d + 1] = fmaf(weight, v0.y, state.acc[d + 1]); state.acc[d + 2] = fmaf(weight, v1.x, state.acc[d + 2]); state.acc[d + 3] = fmaf(weight, v1.y, state.acc[d + 3]); state.acc[d + 4] = fmaf(weight, v2.x, state.acc[d + 4]); state.acc[d + 5] = fmaf(weight, v2.y, state.acc[d + 5]); state.acc[d + 6] = fmaf(weight, v3.x, state.acc[d + 6]); state.acc[d + 7] = fmaf(weight, v3.y, state.acc[d + 7]); } } } } template __global__ __launch_bounds__(256) void sparse_attend_kernel( const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ k, const __nv_bfloat16* __restrict__ v, const int* __restrict__ selected, __nv_bfloat16* __restrict__ out, int S, int total_queries) { constexpr int DP = D / 8; const int query = blockIdx.x * 8 + (threadIdx.x >> 5); if (query >= total_queries) { return; } const int t = query % S; const int bh = query / S; const int lane = threadIdx.x & 31; const int group = lane >> 3; const int r = lane & 7; const int64_t head_offset = static_cast(bh) * S * D; float q_reg[DP]; const uint4* q_ptr = reinterpret_cast( q + head_offset + static_cast(t) * D + r * DP); #pragma unroll for (int chunk = 0; chunk < DP / 8; ++chunk) { const uint4 raw = q_ptr[chunk]; const float2 q0 = bf16_pair_to_float2(raw.x); const float2 q1 = bf16_pair_to_float2(raw.y); const float2 q2 = bf16_pair_to_float2(raw.z); const float2 q3 = bf16_pair_to_float2(raw.w); const int d = chunk * 8; q_reg[d + 0] = q0.x; q_reg[d + 1] = q0.y; q_reg[d + 2] = q1.x; q_reg[d + 3] = q1.y; q_reg[d + 4] = q2.x; q_reg[d + 5] = q2.y; q_reg[d + 6] = q3.x; q_reg[d + 7] = q3.y; } OnlineState state; state.m = -CUDART_INF_F; state.l = 0.0f; #pragma unroll for (int d = 0; d < DP; ++d) { state.acc[d] = 0.0f; } __shared__ float shared_scores[8][576]; float* score_storage = shared_scores[threadIdx.x >> 5]; const float scale = rsqrtf(static_cast(D)); if (t < 512) { score_segment(0, t + 1, 0, group, r, k + head_offset, q_reg, scale, score_storage, state); } else { const int* blocks = selected + static_cast(query) * TOP_N; const int local_begin = t - 63; int count = 0; #pragma unroll for (int i = 0; i < TOP_N; ++i) { const int bi = blocks[i]; if (bi >= 0) { const int begin = bi * 64; const int end = min(begin + 64, local_begin); if (begin < end) { score_segment(begin, end, count, group, r, k + head_offset, q_reg, scale, score_storage, state); count += end - begin; } } } score_segment(local_begin, t + 1, count, group, r, k + head_offset, q_reg, scale, score_storage, state); } __syncwarp(); float max_m = -CUDART_INF_F; #pragma unroll for (int g = 0; g < 4; ++g) { max_m = fmaxf(max_m, __shfl_sync(0xffffffff, state.m, g * 8 + r)); } if (t < 512) { value_segment(0, t + 1, 0, group, r, v + head_offset, score_storage, max_m, state); } else { const int* blocks = selected + static_cast(query) * TOP_N; const int local_begin = t - 63; int count = 0; #pragma unroll for (int i = 0; i < TOP_N; ++i) { const int bi = blocks[i]; if (bi >= 0) { const int begin = bi * 64; const int end = min(begin + 64, local_begin); if (begin < end) { value_segment(begin, end, count, group, r, v + head_offset, score_storage, max_m, state); count += end - begin; } } } value_segment(local_begin, t + 1, count, group, r, v + head_offset, score_storage, max_m, state); } float denominator = 0.0f; #pragma unroll for (int g = 0; g < 4; ++g) { denominator += __shfl_sync(0xffffffff, state.l, g * 8 + r); } #pragma unroll for (int d = 0; d < DP; ++d) { float value = 0.0f; #pragma unroll for (int g = 0; g < 4; ++g) { value += __shfl_sync(0xffffffff, state.acc[d], g * 8 + r); } state.acc[d] = value / denominator; } if (group == 0) { uint4* out_ptr = reinterpret_cast( out + static_cast(query) * D + r * DP); #pragma unroll for (int chunk = 0; chunk < DP / 8; ++chunk) { const int d = chunk * 8; uint4 raw; raw.x = (static_cast(__bfloat16_as_ushort(__float2bfloat16_rn(state.acc[d + 1]))) << 16) | __bfloat16_as_ushort(__float2bfloat16_rn(state.acc[d + 0])); raw.y = (static_cast(__bfloat16_as_ushort(__float2bfloat16_rn(state.acc[d + 3]))) << 16) | __bfloat16_as_ushort(__float2bfloat16_rn(state.acc[d + 2])); raw.z = (static_cast(__bfloat16_as_ushort(__float2bfloat16_rn(state.acc[d + 5]))) << 16) | __bfloat16_as_ushort(__float2bfloat16_rn(state.acc[d + 4])); raw.w = (static_cast(__bfloat16_as_ushort(__float2bfloat16_rn(state.acc[d + 7]))) << 16) | __bfloat16_as_ushort(__float2bfloat16_rn(state.acc[d + 6])); out_ptr[chunk] = raw; } } } torch::Tensor nsa_forward(torch::Tensor q, torch::Tensor k, torch::Tensor v) { TORCH_CHECK(q.is_cuda() && k.is_cuda() && v.is_cuda(), "inputs must be CUDA tensors"); TORCH_CHECK(q.scalar_type() == at::kBFloat16, "inputs must be bf16"); TORCH_CHECK(q.is_contiguous() && k.is_contiguous() && v.is_contiguous(), "inputs must be contiguous"); const int B = q.size(0); const int H = q.size(1); const int S = q.size(2); const int D = q.size(3); TORCH_CHECK(D == 64 || D == 128, "D must be 64 or 128"); auto selected = torch::empty({B, H, S, TOP_N}, q.options().dtype(torch::kInt32)); auto out = torch::empty_like(q); const int BH = B * H; const cudaStream_t stream = at::cuda::getCurrentCUDAStream(); dim3 select_grid((S + 31) / 32, BH); if (D == 64) { select_blocks_kernel<64><<>>( reinterpret_cast(q.data_ptr()), reinterpret_cast(k.data_ptr()), selected.data_ptr(), S); } else { select_blocks_kernel<128><<>>( reinterpret_cast(q.data_ptr()), reinterpret_cast(k.data_ptr()), selected.data_ptr(), S); } dim3 attend_grid((BH * S + 7) / 8, BH == 0 ? 0 : 1); const int total_queries = BH * S; attend_grid.x = (total_queries + 7) / 8; attend_grid.y = 1; if (D == 64) { sparse_attend_kernel<64><<>>( reinterpret_cast(q.data_ptr()), reinterpret_cast(k.data_ptr()), reinterpret_cast(v.data_ptr()), selected.data_ptr(), reinterpret_cast<__nv_bfloat16*>(out.data_ptr()), S, total_queries); } else { sparse_attend_kernel<128><<>>( reinterpret_cast(q.data_ptr()), reinterpret_cast(k.data_ptr()), reinterpret_cast(v.data_ptr()), selected.data_ptr(), reinterpret_cast<__nv_bfloat16*>(out.data_ptr()), S, total_queries); } return out; } """ _ext = load_inline( name="nsa_sparse_sm120_v1", cpp_sources=_CPP_SOURCE, cuda_sources=_CUDA_SOURCE, functions=["nsa_forward"], extra_cuda_cflags=[ "-O3", "--use_fast_math", "-gencode=arch=compute_120,code=sm_120", ], 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)) def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor: return _ext.nsa_forward(q, k, v)