import math 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 _stage1_kernel( query, kv_cache, block_table, seq_lens, partial_m, partial_l, partial_acc, H: tl.constexpr, H_KV: tl.constexpr, D: tl.constexpr, PAGE: tl.constexpr, BT_STRIDE: tl.constexpr, GROUP: tl.constexpr, SCALE: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_D: tl.constexpr, BLOCK_H: tl.constexpr, ): pid_part = tl.program_id(0) pid_kv = tl.program_id(1) pid_b = tl.program_id(2) grid_parts = tl.num_programs(0) grid_b = tl.num_programs(2) offs_h = tl.arange(0, BLOCK_H) offs_d = tl.arange(0, BLOCK_D) offs_n = tl.arange(0, BLOCK_N) h_mask = offs_h < GROUP q_heads = pid_kv * GROUP + offs_h q = tl.load( query + (pid_b * H + q_heads[:, None]) * D + offs_d[None, :], mask=h_mask[:, None] & (offs_d[None, :] < D), other=0.0, ) seq_len = tl.load(seq_lens + pid_b) [REDACTED credential assignment] * BLOCK_N + offs_n n_mask = token < seq_len page_no = token // PAGE page_off = token - page_no * PAGE block_id = tl.load( block_table + pid_b * BT_STRIDE + page_no, mask=n_mask, other=0, ) token_base = ((block_id * PAGE + page_off) * H_KV + pid_kv) * (D * 2) k = tl.load( kv_cache + token_base[None, :] + offs_d[:, None], mask=(offs_d[:, None] < D) & n_mask[None, :], other=0.0, ) scores = tl.dot(q, k) * SCALE scores = tl.where(n_mask[None, :], scores, -float("inf")) m = tl.max(scores, axis=1) part_has_tokens = pid_part * BLOCK_N < seq_len m_safe = tl.where(part_has_tokens, m, 0.0) p = tl.exp(scores - m_safe[:, None]) p = tl.where(n_mask[None, :], p, 0.0) l = tl.sum(p, axis=1) v = tl.load( kv_cache + token_base[:, None] + D + offs_d[None, :], mask=n_mask[:, None] & (offs_d[None, :] < D), other=0.0, ) acc = tl.dot(p.to(tl.bfloat16), v) m_store = tl.where(part_has_tokens, m, -float("inf")) stat_idx = (pid_part * grid_b + pid_b) * H + q_heads tl.store(partial_m + stat_idx, m_store, mask=h_mask) tl.store(partial_l + stat_idx, l, mask=h_mask) acc_idx = ((pid_part * grid_b + pid_b) * H + q_heads[:, None]) * D + offs_d[None, :] tl.store( partial_acc + acc_idx, acc, mask=h_mask[:, None] & (offs_d[None, :] < D), ) @triton.jit def _stage2_kernel( partial_m, partial_l, partial_acc, out, H: tl.constexpr, D: tl.constexpr, NUM_PARTS: tl.constexpr, BLOCK_P: tl.constexpr, BLOCK_D: tl.constexpr, ): pid_h = tl.program_id(0) pid_b = tl.program_id(1) grid_b = tl.num_programs(1) offs_p = tl.arange(0, BLOCK_P) offs_d = tl.arange(0, BLOCK_D) p_mask = offs_p < NUM_PARTS stat_idx = (offs_p * grid_b + pid_b) * H + pid_h m = tl.load(partial_m + stat_idx, mask=p_mask, other=-float("inf")) l = tl.load(partial_l + stat_idx, mask=p_mask, other=0.0) m_final = tl.max(m, axis=0) alpha = tl.exp(m - m_final) denom = tl.sum(alpha * l, axis=0) acc_idx = ((offs_p[:, None] * grid_b + pid_b) * H + pid_h) * D + offs_d[None, :] acc = tl.load( partial_acc + acc_idx, mask=p_mask[:, None] & (offs_d[None, :] < D), other=0.0, ) numer = tl.sum(acc * alpha[:, None], axis=0) result = numer / denom tl.store( out + (pid_b * H + pid_h) * D + offs_d, result, mask=offs_d < D, ) 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.block_n = 32 self.block_h = max(8, triton.next_power_of_2(self.group_size)) self.num_parts = triton.cdiv(seq_len, self.block_n) self.block_p = triton.next_power_of_2(self.num_parts) self.register_buffer("_dummy", torch.zeros(1, dtype=torch.bfloat16), persistent=False) self.register_buffer( "_partial_m", torch.empty((self.num_parts, batch, num_heads), dtype=torch.float32), persistent=False, ) self.register_buffer( "_partial_l", torch.empty((self.num_parts, batch, num_heads), dtype=torch.float32), persistent=False, ) self.register_buffer( "_partial_acc", torch.empty((self.num_parts, batch, num_heads, head_dim), dtype=torch.float32), persistent=False, ) self.register_buffer( "_out", torch.empty((batch, num_heads, head_dim), 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: _stage1_kernel[(self.num_parts, self.num_kv_heads, self.batch)]( query, kv_cache, block_table, seq_lens, self._partial_m, self._partial_l, self._partial_acc, H=self.num_heads, H_KV=self.num_kv_heads, D=self.head_dim, PAGE=self.page_size, BT_STRIDE=block_table.stride(0), GROUP=self.group_size, SCALE=self.scale, BLOCK_N=self.block_n, BLOCK_D=self.head_dim, BLOCK_H=self.block_h, num_warps=4, ) _stage2_kernel[(self.num_heads, self.batch)]( self._partial_m, self._partial_l, self._partial_acc, self._out, H=self.num_heads, D=self.head_dim, NUM_PARTS=self.num_parts, BLOCK_P=self.block_p, BLOCK_D=self.head_dim, num_warps=4, ) return self._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]