"""Paged-attention decode kernel for RTX PRO 6000 (SM120 Blackwell). Single-query decode with grouped-query attention, split-K (FlashDecoding style): * kernel 1 (split): grid = (batch, kv_head, chunk). Each block streams one contiguous chunk of the KV cache with 16-byte vectorized loads and runs an online softmax over its chunk, writing per-chunk (m, sumexp, o) partials. * kernel 2 (merge): grid = (batch, kv_head). Combines the per-chunk partials into the final bf16 output. Each KV head is read exactly once (GQA: `group_size` query heads share it). """ import math import torch import torch.nn as nn from torch.utils.cpp_extension import load_inline OP_TYPE = "attention" SUPPORTED_PRECISIONS = ["bf16"] HARDWARE_REQUIRED = ["RTX_PRO_6000", "H100", "B200"] # --- Shape knobs (overridden by check.py / benchmark.py from shapes.py) ---- BATCH = 8 NUM_HEADS = 32 NUM_KV_HEADS = 8 HEAD_DIM = 128 SEQ_LEN = 1024 PAGE_SIZE = 16 _cuda_src = r""" #include #include #include #include #include #include #include namespace py = pybind11; using bf16 = __nv_bfloat16; __device__ __forceinline__ void load_bf16x4(const bf16* __restrict__ p, float out[4]) { const float2 f = *reinterpret_cast(p); const __nv_bfloat162* pairs = reinterpret_cast(&f); out[0] = __bfloat162float(__low2bfloat16(pairs[0])); out[1] = __bfloat162float(__high2bfloat16(pairs[0])); out[2] = __bfloat162float(__low2bfloat16(pairs[1])); out[3] = __bfloat162float(__high2bfloat16(pairs[1])); } __device__ __forceinline__ void store_bf16x4(bf16* __restrict__ p, const float in[4]) { float2 f; __nv_bfloat162* pairs = reinterpret_cast<__nv_bfloat162*>(&f); pairs[0] = __floats2bfloat162_rn(in[0], in[1]); pairs[1] = __floats2bfloat162_rn(in[2], in[3]); *reinterpret_cast(p) = f; } __device__ __forceinline__ void load_bf16x8(const bf16* __restrict__ p, float out[8]) { const float4 f = *reinterpret_cast(p); const __nv_bfloat162* pairs = reinterpret_cast(&f); #pragma unroll for (int i = 0; i < 4; ++i) { out[2 * i] = __bfloat162float(__low2bfloat16(pairs[i])); out[2 * i + 1] = __bfloat162float(__high2bfloat16(pairs[i])); } } __device__ __forceinline__ void store_bf16x8(bf16* __restrict__ p, const float in[8]) { float4 f; __nv_bfloat162* pairs = reinterpret_cast<__nv_bfloat162*>(&f); #pragma unroll for (int i = 0; i < 4; ++i) { pairs[i] = __floats2bfloat162_rn(in[2 * i], in[2 * i + 1]); } *reinterpret_cast(p) = f; } template __device__ __forceinline__ void load_bf16x(const bf16* __restrict__ p, float* out) { if constexpr (ELTS == 4) load_bf16x4(p, out); else load_bf16x8(p, out); } // Streaming (evict-first) loads: the KV cache is read exactly once, so mark it // evict-first to keep the o_partial buffers resident in L2 for the merge pass. __device__ __forceinline__ void load_bf16x4_cs(const bf16* __restrict__ p, float out[4]) { const float2 f = __ldcs(reinterpret_cast(p)); const __nv_bfloat162* pairs = reinterpret_cast(&f); out[0] = __bfloat162float(__low2bfloat16(pairs[0])); out[1] = __bfloat162float(__high2bfloat16(pairs[0])); out[2] = __bfloat162float(__low2bfloat16(pairs[1])); out[3] = __bfloat162float(__high2bfloat16(pairs[1])); } __device__ __forceinline__ void load_bf16x8_cs(const bf16* __restrict__ p, float out[8]) { const float4 f = __ldcs(reinterpret_cast(p)); const __nv_bfloat162* pairs = reinterpret_cast(&f); #pragma unroll for (int i = 0; i < 4; ++i) { out[2 * i] = __bfloat162float(__low2bfloat16(pairs[i])); out[2 * i + 1] = __bfloat162float(__high2bfloat16(pairs[i])); } } template __device__ __forceinline__ void load_bf16x_cs(const bf16* __restrict__ p, float* out) { if constexpr (ELTS == 4) load_bf16x4_cs(p, out); else load_bf16x8_cs(p, out); } template __device__ __forceinline__ void store_bf16x(bf16* __restrict__ p, const float* in) { if constexpr (ELTS == 4) store_bf16x4(p, in); else store_bf16x8(p, in); } // Sub-warp float reduction over `width` lanes, result broadcast to the segment. __device__ __forceinline__ float warp_reduce_add(float x, unsigned mask, int width, int seg_start) { #pragma unroll for (int off = width / 2; off > 0; off >>= 1) { x += __shfl_down_sync(mask, x, off, width); } return __shfl_sync(mask, x, seg_start); } // --------------------------------------------------------------------------- // Split kernel: one block per (batch, kv_head, chunk). // --------------------------------------------------------------------------- template __global__ void paged_decode_split( const bf16* __restrict__ query, const bf16* __restrict__ kv_cache, const int* __restrict__ block_table, const int* __restrict__ seq_lens, float* __restrict__ m_partial, float* __restrict__ s_partial, bf16* __restrict__ o_partial, int Hkv, int bt_stride, float scale, int C, int chunk_size) { constexpr int VEC_POS = D / ELTS; // vectors per head constexpr int LANES = G * VEC_POS; // lanes per token stream constexpr int GROUPS_PER_WARP = 32 / VEC_POS; const int chunk_id = blockIdx.x; const int c = chunk_id % C; const int kv = (chunk_id / C) % Hkv; const int b = chunk_id / (C * Hkv); const int tid = threadIdx.x; const int g = tid / VEC_POS; // query head within group const int vp = tid % VEC_POS; // vector position in head-dim const int qhead = kv * G + g; const int H = Hkv * G; const int L = seq_lens[b]; const int start = c * chunk_size; int end = start + chunk_size; if (end > L) end = L; float q[ELTS]; load_bf16x(query + ((long)b * H + qhead) * D + vp * ELTS, q); float o[ELTS]; #pragma unroll for (int i = 0; i < ELTS; ++i) o[i] = 0.0f; float m = -INFINITY; float s = 0.0f; const int seg_start = (g % GROUPS_PER_WARP) * VEC_POS; const unsigned segmask = ((1u << VEC_POS) - 1) << seg_start; const long tok_stride = (long)Hkv * (2 * D); if (start < end) { const int p0 = start >> 4; const int p1 = (end - 1) >> 4; for (int p = p0; p <= p1; ++p) { const int block_id = block_table[(long)b * bt_stride + p]; const bf16* page = kv_cache + ((long)block_id * 16 * Hkv + kv) * (2 * D); #pragma unroll for (int sl = 0; sl < 16; ++sl) { const int tok = (p << 4) + sl; const bf16* row = page + (long)sl * tok_stride; float k[ELTS], v[ELTS]; load_bf16x_cs(row + vp * ELTS, k); load_bf16x_cs(row + D + vp * ELTS, v); if (tok >= start && tok < end) { float dot = 0.0f; #pragma unroll for (int i = 0; i < ELTS; ++i) dot += q[i] * k[i]; dot = warp_reduce_add(dot, segmask, VEC_POS, seg_start); const float score = dot * scale; const float m_new = fmaxf(m, score); const float alpha = expf(m - m_new); const float beta = expf(score - m_new); s = s * alpha + beta; #pragma unroll for (int i = 0; i < ELTS; ++i) o[i] = o[i] * alpha + beta * v[i]; m = m_new; } } } } const int head_idx = chunk_id * G + g; if (vp == 0) { m_partial[head_idx] = m; s_partial[head_idx] = s; } bf16* op = o_partial + (long)chunk_id * (G * D) + g * D + vp * ELTS; store_bf16x(op, o); } // --------------------------------------------------------------------------- // Warp-local online-softmax over a warp's strided chunk subset. All LANES lanes // of a warp read the SAME chunk (coalesced); successive chunks are strided by W // so the serial over-chunks loop is parallelized across the block's W warps. // --------------------------------------------------------------------------- template __device__ __forceinline__ void warp_chunk_reduce( const float* m_in, const float* s_in, const bf16* o_in, int base, int c0, int c1, int w, int W, int g, int vp, float& M, float& S, float acc[ELTS]) { M = -INFINITY; S = 0.0f; #pragma unroll for (int i = 0; i < ELTS; ++i) acc[i] = 0.0f; for (int c = c0 + w; c < c1; c += W) { const float mk = m_in[(base + c) * G + g]; if (mk == -INFINITY) continue; // empty chunk (split saw no tokens) const float sk = s_in[(base + c) * G + g]; float ov[ELTS]; load_bf16x(o_in + (long)(base + c) * (G * D) + g * D + vp * ELTS, ov); const float m_new = fmaxf(M, mk); const float alpha = expf(M - m_new); const float beta = expf(mk - m_new); S = S * alpha + sk * beta; #pragma unroll for (int i = 0; i < ELTS; ++i) acc[i] = acc[i] * alpha + ov[i] * beta; M = m_new; } } // --------------------------------------------------------------------------- // Merge kernel: one block per (batch, kv_head). `W` warps cooperatively reduce // the `Cin` chunks of this (b, kv); the W per-warp partials are combined through // shared memory by warp 0. // --------------------------------------------------------------------------- template __global__ void paged_merge( const float* __restrict__ m_partial, const float* __restrict__ s_partial, const bf16* __restrict__ o_partial, bf16* __restrict__ out, int Hkv, int Cin) { constexpr int VEC_POS = D / ELTS; constexpr int LANES = G * VEC_POS; __shared__ float sm_M[W * LANES]; __shared__ float sm_S[W * LANES]; __shared__ float sm_O[W * LANES * ELTS]; const int bx = blockIdx.x; const int b = bx / Hkv; const int kv = bx % Hkv; const int t = threadIdx.x; const int w = t / LANES; const int l = t % LANES; const int g = l / VEC_POS; const int vp = l % VEC_POS; float M, S, acc[ELTS]; warp_chunk_reduce( m_partial, s_partial, o_partial, (b * Hkv + kv) * Cin, 0, Cin, w, W, g, vp, M, S, acc); sm_M[w * LANES + l] = M; sm_S[w * LANES + l] = S; #pragma unroll for (int i = 0; i < ELTS; ++i) sm_O[(w * LANES + l) * ELTS + i] = acc[i]; __syncthreads(); if (w == 0) { float Mg = -INFINITY; #pragma unroll for (int ww = 0; ww < W; ++ww) Mg = fmaxf(Mg, sm_M[ww * LANES + l]); float Sg = 0.0f; float ac[ELTS]; #pragma unroll for (int i = 0; i < ELTS; ++i) ac[i] = 0.0f; if (Mg != -INFINITY) { #pragma unroll for (int ww = 0; ww < W; ++ww) { const float wgt = expf(sm_M[ww * LANES + l] - Mg); Sg += sm_S[ww * LANES + l] * wgt; #pragma unroll for (int i = 0; i < ELTS; ++i) ac[i] += sm_O[(ww * LANES + l) * ELTS + i] * wgt; } } const float inv_S = (Sg > 0.0f) ? (1.0f / Sg) : 0.0f; float of[ELTS]; #pragma unroll for (int i = 0; i < ELTS; ++i) of[i] = ac[i] * inv_S; const int H = Hkv * G; store_bf16x(out + ((long)b * H + (kv * G + g)) * D + vp * ELTS, of); } } // --------------------------------------------------------------------------- // Merge level 1: one block per (batch, kv_head, merge_chunk). Reduces a sub-range // of `CPB` split-chunk partials into a single partial (m, s, o), so the final // merge has far fewer chunks to combine and can be done with more parallelism. // --------------------------------------------------------------------------- template __global__ void paged_merge_partial( const float* __restrict__ m1, const float* __restrict__ s1, const bf16* __restrict__ o1, float* __restrict__ m2, float* __restrict__ s2, bf16* __restrict__ o2, int Hkv, int C, int CPB, int CM) { constexpr int VEC_POS = D / ELTS; constexpr int LANES = G * VEC_POS; __shared__ float sm_M[W * LANES]; __shared__ float sm_S[W * LANES]; __shared__ float sm_O[W * LANES * ELTS]; const int bx = blockIdx.x; const int cm = bx % CM; const int kv = (bx / CM) % Hkv; const int b = bx / (CM * Hkv); const int t = threadIdx.x; const int w = t / LANES; const int l = t % LANES; const int g = l / VEC_POS; const int vp = l % VEC_POS; const int c0 = cm * CPB; int c1 = c0 + CPB; if (c1 > C) c1 = C; float M, S, acc[ELTS]; warp_chunk_reduce(m1, s1, o1, (b * Hkv + kv) * C, c0, c1, w, W, g, vp, M, S, acc); sm_M[w * LANES + l] = M; sm_S[w * LANES + l] = S; #pragma unroll for (int i = 0; i < ELTS; ++i) sm_O[(w * LANES + l) * ELTS + i] = acc[i]; __syncthreads(); if (w == 0) { float Mg = -INFINITY; #pragma unroll for (int ww = 0; ww < W; ++ww) Mg = fmaxf(Mg, sm_M[ww * LANES + l]); float Sg = 0.0f; float ac[ELTS]; #pragma unroll for (int i = 0; i < ELTS; ++i) ac[i] = 0.0f; if (Mg != -INFINITY) { #pragma unroll for (int ww = 0; ww < W; ++ww) { const float wgt = expf(sm_M[ww * LANES + l] - Mg); Sg += sm_S[ww * LANES + l] * wgt; #pragma unroll for (int i = 0; i < ELTS; ++i) ac[i] += sm_O[(ww * LANES + l) * ELTS + i] * wgt; } } const int mb = (b * Hkv + kv) * CM * G + cm * G + g; if (vp == 0) { m2[mb] = Mg; s2[mb] = Sg; } store_bf16x(o2 + (long)((b * Hkv + kv) * CM + cm) * (G * D) + g * D + vp * ELTS, ac); } } template void launch_split( const bf16* q, const bf16* kvc, const int* bt, const int* sl, float* mp, float* sp, bf16* op, int Hkv, int bt_stride, float scale, int C, int chunk_size, int grid, cudaStream_t stream) { constexpr int LANES = G * (D / ELTS); paged_decode_split<<>>( q, kvc, bt, sl, mp, sp, op, Hkv, bt_stride, scale, C, chunk_size); } template void launch_merge( const float* mp, const float* sp, const bf16* op, bf16* o, int Hkv, int C, int grid, cudaStream_t stream) { constexpr int LANES = G * (D / ELTS); paged_merge<<>>(mp, sp, op, o, Hkv, C); } template void launch_merge_partial( const float* m1, const float* s1, const bf16* o1, float* m2, float* s2, bf16* o2, int Hkv, int C, int CPB, int CM, int grid, cudaStream_t stream) { constexpr int LANES = G * (D / ELTS); paged_merge_partial<<>>( m1, s1, o1, m2, s2, o2, Hkv, C, CPB, CM); } void paged_decode_forward( int64_t q_ptr, int64_t kvc_ptr, int64_t bt_ptr, int64_t sl_ptr, int64_t m_ptr, int64_t s_ptr, int64_t o_ptr, int64_t out_ptr, int64_t m2_ptr, int64_t s2_ptr, int64_t o2_ptr, int64_t B, int64_t H, int64_t D, int64_t Hkv, int64_t bt_stride, int64_t C, int64_t chunk_size, int64_t CM, int64_t CPB, int64_t stream) { const bf16* q = reinterpret_cast(q_ptr); const bf16* kvc = reinterpret_cast(kvc_ptr); const int* bt = reinterpret_cast(bt_ptr); const int* sl = reinterpret_cast(sl_ptr); float* mp = reinterpret_cast(m_ptr); float* sp = reinterpret_cast(s_ptr); bf16* op = reinterpret_cast(o_ptr); bf16* o = reinterpret_cast(out_ptr); float* m2p = reinterpret_cast(m2_ptr); float* s2p = reinterpret_cast(s2_ptr); bf16* o2p = reinterpret_cast(o2_ptr); const int G = (int)(H / Hkv); const float scale = 1.0f / sqrtf((float)D); const int grid_split = (int)(B * Hkv * C); const int grid_merge = (int)(B * Hkv); const int grid_mp = (int)(B * Hkv * CM); cudaStream_t s = reinterpret_cast(stream); if (D == 128 && G == 4) { launch_split<128, 4, 8>(q, kvc, bt, sl, mp, sp, op, (int)Hkv, (int)bt_stride, scale, (int)C, (int)chunk_size, grid_split, s); if (CM < C) { launch_merge_partial<128, 4, 8, 8>(mp, sp, op, m2p, s2p, o2p, (int)Hkv, (int)C, (int)CPB, (int)CM, grid_mp, s); launch_merge<128, 4, 8, 8>(m2p, s2p, o2p, o, (int)Hkv, (int)CM, grid_merge, s); } else { launch_merge<128, 4, 8, 8>(mp, sp, op, o, (int)Hkv, (int)C, grid_merge, s); } } else if (D == 128 && G == 8) { launch_split<128, 8, 8>(q, kvc, bt, sl, mp, sp, op, (int)Hkv, (int)bt_stride, scale, (int)C, (int)chunk_size, grid_split, s); if (CM < C) { launch_merge_partial<128, 8, 8, 8>(mp, sp, op, m2p, s2p, o2p, (int)Hkv, (int)C, (int)CPB, (int)CM, grid_mp, s); launch_merge<128, 8, 8, 8>(m2p, s2p, o2p, o, (int)Hkv, (int)CM, grid_merge, s); } else { launch_merge<128, 8, 8, 8>(mp, sp, op, o, (int)Hkv, (int)C, grid_merge, s); } } else if (D == 64 && G == 4) { launch_split<64, 4, 4>(q, kvc, bt, sl, mp, sp, op, (int)Hkv, (int)bt_stride, scale, (int)C, (int)chunk_size, grid_split, s); if (CM < C) { launch_merge_partial<64, 4, 4, 8>(mp, sp, op, m2p, s2p, o2p, (int)Hkv, (int)C, (int)CPB, (int)CM, grid_mp, s); launch_merge<64, 4, 4, 8>(m2p, s2p, o2p, o, (int)Hkv, (int)CM, grid_merge, s); } else { launch_merge<64, 4, 4, 8>(mp, sp, op, o, (int)Hkv, (int)C, grid_merge, s); } } else { throw std::runtime_error("unsupported (head_dim, group_size)"); } } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &paged_decode_forward, "paged attention decode (CUDA)"); } """ _module = None def _get_module(): global _module if _module is None: _module = load_inline( name="paged_decode_ext", cpp_sources="", cuda_sources=_cuda_src, functions=None, extra_cuda_cflags=[ "-O3", "--use_fast_math", "-gencode=arch=compute_120,code=sm_120", ], no_implicit_headers=True, verbose=False, ) return _module class Model(nn.Module): """Single-query paged attention decode (custom CUDA kernel).""" def __init__( self, batch: int, num_heads: int, num_kv_heads: int, head_dim: int, seq_len: int, page_size: int, ): super().__init__() assert num_heads % num_kv_heads == 0, "num_heads must be a multiple of num_kv_heads (GQA)" self.batch = batch self.num_heads = num_heads self.num_kv_heads = num_kv_heads self.head_dim = head_dim self.seq_len = seq_len self.page_size = page_size self.group_size = num_heads // num_kv_heads self.scale = 1.0 / math.sqrt(head_dim) # Split-K chunking: total resident warps = B*H*C/2 (each warp covers two # query heads over VEC_POS=16 vectors). Target ~6144 warps (32/SM) for # D=128; the lighter per-warp work at D=64 needs ~8192 warps to hide # latency. Never let a chunk drop below one page of work. base_h = batch * num_heads # B * H if head_dim == 64: C = int(round(16384.0 / base_h)) else: C = int(round(12288.0 / base_h)) max_C = seq_len // page_size # chunk_size >= page_size self._C = max(1, min(C, max_C)) self._chunk_size = -(-seq_len // self._C) # ceil(seq_len / C) # Two-level merge when the flat merge would be latency-bound (few kv # blocks) but many chunks. Level-1 reduces CPB chunks into one partial so # the final merge only sees <= 8 partials. base_kv = batch * num_kv_heads if self._C > 8 and base_kv <= 64: self._CM = min(self._C, 8) self._CPB = (self._C + self._CM - 1) // self._CM else: self._CM = self._C self._CPB = 1 self.register_buffer("_dummy", torch.zeros(1, dtype=torch.bfloat16), persistent=False) self._m = None self._s = None self._o = None self._m2 = None self._s2 = None self._o2 = None def _partials(self, query, nchunks, nchunks2): G = self.group_size D = self.head_dim if self._m is None or self._m.numel() != nchunks * G: dev = query.device self._m = torch.empty(nchunks * G, dtype=torch.float32, device=dev) self._s = torch.empty(nchunks * G, dtype=torch.float32, device=dev) self._o = torch.empty(nchunks * G * D, dtype=torch.bfloat16, device=dev) self._m2 = torch.empty(nchunks2 * G, dtype=torch.float32, device=dev) self._s2 = torch.empty(nchunks2 * G, dtype=torch.float32, device=dev) self._o2 = torch.empty(nchunks2 * G * D, dtype=torch.bfloat16, device=dev) return self._m, self._s, self._o, self._m2, self._s2, self._o2 def forward( self, query: torch.Tensor, kv_cache: torch.Tensor, block_table: torch.Tensor, seq_lens: torch.Tensor, ) -> torch.Tensor: B, H, D = query.shape Hkv = self.num_kv_heads C = self._C CM = self._CM CPB = self._CPB chunk_size = self._chunk_size nchunks = B * Hkv * C nchunks2 = B * Hkv * CM out = torch.empty(B, H, D, dtype=query.dtype, device=query.device) m_partial, s_partial, o_partial, m2, s2, o2 = self._partials(query, nchunks, nchunks2) stream = torch.cuda.current_stream().cuda_stream _get_module().forward( query.data_ptr(), kv_cache.data_ptr(), block_table.data_ptr(), seq_lens.data_ptr(), m_partial.data_ptr(), s_partial.data_ptr(), o_partial.data_ptr(), out.data_ptr(), m2.data_ptr(), s2.data_ptr(), o2.data_ptr(), B, H, D, Hkv, block_table.stride(0), C, chunk_size, CM, CPB, stream, ) return out def get_inputs(): B = BATCH H = NUM_HEADS Hkv = NUM_KV_HEADS D = HEAD_DIM L = SEQ_LEN P = PAGE_SIZE pages_per_seq = (L + P - 1) // P total_pages = max(B * pages_per_seq + 8, 64) query = torch.randn(B, H, D, dtype=torch.bfloat16) * 0.1 kv_cache = torch.randn(total_pages, P, Hkv, 2 * D, dtype=torch.bfloat16) * 0.1 perm = torch.randperm(total_pages)[: B * pages_per_seq].reshape(B, pages_per_seq).int() block_table = perm.contiguous() seq_lens = torch.full((B,), L, dtype=torch.int32) return [query, kv_cache, block_table, seq_lens] def get_init_inputs(): return [BATCH, NUM_HEADS, NUM_KV_HEADS, HEAD_DIM, SEQ_LEN, PAGE_SIZE]