"""Paged attention decode kernel using Triton (GQA-vectorized). Single-query decode with grouped-query attention and fixed-size pages. One Triton block is launched per (batch, kv_head) pair and computes all query heads in that KV head's group with a single batched matmul, so the KV cache is streamed only once. """ import math from typing import List import torch import torch.nn as nn import triton import triton.language as tl OP_TYPE = "attention" SUPPORTED_PRECISIONS = ["bf16"] HARDWARE_REQUIRED = ["RTX_PRO_6000", "H100", "B200"] BATCH = 8 NUM_HEADS = 32 NUM_KV_HEADS = 8 HEAD_DIM = 128 SEQ_LEN = 1024 PAGE_SIZE = 16 @triton.jit def paged_decode_kernel( Q_ptr, KV_ptr, BT_ptr, SL_ptr, O_ptr, stride_qb, stride_qh, stride_qd, stride_knb, stride_kp, stride_kh, stride_kd, stride_btb, stride_btp, stride_ob, stride_oh, stride_od, Hkv, D, P, scale, GROUP: tl.constexpr, BLOCK_D: tl.constexpr, BLOCK_N: tl.constexpr, ): """One block per (batch, kv_head); computes GROUP query heads.""" pid = tl.program_id(0) b = pid // Hkv kv_h = pid % Hkv # Load all query heads in this group (contiguous in the head dim). offs_h = tl.arange(0, GROUP) + kv_h * GROUP q_ptrs = ( Q_ptr + b * stride_qb + offs_h[:, None] * stride_qh + tl.arange(0, BLOCK_D)[None, :] * stride_qd ) q = tl.load(q_ptrs) # (GROUP, BLOCK_D) m = tl.full((GROUP,), -float("inf"), tl.float32) l = tl.zeros((GROUP,), tl.float32) acc = tl.zeros((GROUP, BLOCK_D), tl.float32) seq_len = tl.load(SL_ptr + b) num_pages = tl.cdiv(seq_len, P) for p in range(num_pages): page_idx = tl.load(BT_ptr + b * stride_btb + p * stride_btp).to(tl.int64) base = KV_ptr + page_idx * stride_knb + kv_h * stride_kh offs_n = tl.arange(0, BLOCK_N) offs_d = tl.arange(0, BLOCK_D) k_ptrs = base + offs_n[:, None] * stride_kp + offs_d[None, :] * stride_kd v_ptrs = base + offs_n[:, None] * stride_kp + (D + offs_d)[None, :] * stride_kd k = tl.load(k_ptrs) # (BLOCK_N, BLOCK_D) v = tl.load(v_ptrs) # (BLOCK_N, BLOCK_D) kt = tl.trans(k.to(q.dtype)) # scores for all query heads in the group: (GROUP, BLOCK_N) scores = tl.dot(q, kt) * scale valid_len = seq_len - p * BLOCK_N valid_mask = offs_n < valid_len scores = tl.where(valid_mask[None, :], scores, float("-inf")) # Online softmax update, vectorized over the group. m_new = tl.maximum(m, tl.max(scores, axis=1)) alpha = tl.exp(m - m_new) probs = tl.exp(scores - m_new[:, None]) l = l * alpha + tl.sum(probs, axis=1) acc = acc * alpha[:, None] + tl.dot(probs, v) m = m_new acc = acc / l[:, None] o_ptrs = ( O_ptr + b * stride_ob + offs_h[:, None] * stride_oh + tl.arange(0, BLOCK_D)[None, :] * stride_od ) tl.store(o_ptrs, acc.to(tl.bfloat16)) class Model(nn.Module): 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 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) self.register_buffer("_dummy", torch.zeros(1, dtype=torch.bfloat16), persistent=False) 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 P = self.page_size G = self.group_size out = torch.empty(B, H, D, dtype=query.dtype, device=query.device) grid = (B * Hkv,) BLOCK_D = D BLOCK_N = P paged_decode_kernel[grid]( query, kv_cache, block_table, seq_lens, out, query.stride(0), query.stride(1), query.stride(2), kv_cache.stride(0), kv_cache.stride(1), kv_cache.stride(2), kv_cache.stride(3), block_table.stride(0), block_table.stride(1), out.stride(0), out.stride(1), out.stride(2), Hkv, D, P, self.scale, GROUP=G, BLOCK_D=BLOCK_D, BLOCK_N=BLOCK_N, num_warps=8, num_stages=3, ) 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]