"""KDA forward (chunk form) - Triton cumsum + batched GPU matmuls.""" from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl from einops import rearrange # --------------------------------------------------------------------------- # Triton chunk-local cumsum (matches FLA layout, natural exp downstream) # --------------------------------------------------------------------------- @triton.jit def _cumsum_chunk_kernel( s_ptr, o_ptr, stride_bt, stride_h, stride_k, T, H, K, BT: tl.constexpr, BK: tl.constexpr, ): i_t, i_bh, i_k = tl.program_id(0), tl.program_id(1), tl.program_id(2) i_b = i_bh // H i_h = i_bh % H base = i_b * T * stride_bt + i_h * stride_h p_s = tl.make_block_ptr( s_ptr + base, (T, K), (stride_bt, stride_k), (i_t * BT, i_k * BK), (BT, BK), (1, 0), ) p_o = tl.make_block_ptr( o_ptr + base, (T, K), (stride_bt, stride_k), (i_t * BT, i_k * BK), (BT, BK), (1, 0), ) b_s = tl.load(p_s, boundary_check=(0, 1)).to(tl.float32) b_o = tl.cumsum(b_s, axis=0) tl.store(p_o, b_o.to(p_o.dtype.element_ty), boundary_check=(0, 1)) def _cumsum_chunk_triton(g: torch.Tensor, chunk_size: int) -> torch.Tensor: B, T, H, K = g.shape out = torch.empty_like(g) NT = T // chunk_size BK = 64 grid = (NT, B * H, triton.cdiv(K, BK)) _cumsum_chunk_kernel[grid]( g, out, g.stride(1), g.stride(2), g.stride(3), T, H, K, BT=chunk_size, BK=BK, num_warps=4, ) return out def _solve_akk_inv(a_pos: torch.Tensor, betaf: torch.Tensor, mask_upper, eye, bt: int): """Forward-substitution inverse for (I + strict_lower(-a_pos)).""" a = -a_pos.masked_fill(mask_upper, 0) for i in range(1, bt): a[:, :, :, i, :i] = a[:, :, :, i, :i] + (a[:, :, :, i, :, None] * a[:, :, :, :, :i]).sum(-2) return (a + eye) * betaf.unsqueeze(-1) def _kda_chunk_forward_impl( qf, kf, vf, gf, betaf, bt: int, mask_upper, mask_strict_upper, eye, ): nt = gf.shape[2] a_pos = torch.empty(qf.shape[0], qf.shape[1], nt, bt, bt, dtype=torch.float32, device=qf.device) aqk = torch.empty_like(a_pos) for n in range(nt): gn, kn, bn = gf[:, :, n], kf[:, :, n], betaf[:, :, n] gdiff = gn.unsqueeze(3) - gn.unsqueeze(2) a_pos[:, :, n] = (kn.unsqueeze(3) * gdiff.exp() * kn.unsqueeze(2)).sum(-1) * bn.unsqueeze(-1) qn = qf[:, :, n] aqk[:, :, n] = (qn.unsqueeze(3) * gdiff.exp() * kn.unsqueeze(2)).sum(-1).masked_fill(mask_strict_upper, 0) a = _solve_akk_inv(a_pos, betaf, mask_upper, eye, bt) w = torch.matmul(a, gf.exp() * kf) u = torch.matmul(a, vf) s = torch.zeros(qf.shape[0], qf.shape[1], qf.shape[-1], vf.shape[-1], dtype=torch.float32, device=qf.device) o = torch.empty(qf.shape[0], qf.shape[1], nt, bt, vf.shape[-1], dtype=torch.float32, device=qf.device) for n in range(nt): qn, gn, kn = qf[:, :, n], gf[:, :, n], kf[:, :, n] wn, un, aqk_n = w[:, :, n], u[:, :, n], aqk[:, :, n] v_new = un - torch.matmul(wn, s) o[:, :, n] = torch.matmul(qn * gn.exp(), s) + torch.matmul(aqk_n, v_new) s = s * gn[:, :, -1].exp().unsqueeze(-1) kg = (gn[:, :, -1:] - gn).exp() * kn s = s + torch.matmul(kg.transpose(-1, -2), v_new) return o def _kda_chunk_forward( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, g: torch.Tensor, beta: torch.Tensor, scale: float, chunk_size: int = 64, ) -> torch.Tensor: dtype = v.dtype bt = chunk_size device = q.device qf = q.to(torch.float32) * scale kf = k.to(torch.float32) vf = v.to(torch.float32) gf = _cumsum_chunk_triton(g, bt) betaf = beta.to(torch.float32) qf = rearrange(qf, "b (n c) h d -> b h n c d", c=bt) kf = rearrange(kf, "b (n c) h d -> b h n c d", c=bt) vf = rearrange(vf, "b (n c) h d -> b h n c d", c=bt) gf = rearrange(gf, "b (n c) h d -> b h n c d", c=bt) betaf = rearrange(betaf, "b (n c) h -> b h n c", c=bt) mask_upper = torch.triu(torch.ones(bt, bt, dtype=torch.bool, device=device), diagonal=0) mask_strict_upper = torch.triu(torch.ones(bt, bt, dtype=torch.bool, device=device), diagonal=1) eye = torch.eye(bt, dtype=torch.float32, device=device) o = _kda_chunk_forward_impl(qf, kf, vf, gf, betaf, bt, mask_upper, mask_strict_upper, eye) return rearrange(o, "b h n c d -> b (n c) h d").to(dtype) class Model(nn.Module): def __init__(self, B: int, T: int, H: int, K: int, V: int, chunk_size: int = 64): super().__init__() self.B, self.T, self.H, self.K, self.V = B, T, H, K, V self.chunk_size = chunk_size self.scale = float(K) ** -0.5 self.register_buffer("_dummy", torch.zeros(1), persistent=False) def forward( self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, g: torch.Tensor, beta: torch.Tensor, ) -> torch.Tensor: return _kda_chunk_forward(q, k, v, g, beta, scale=self.scale, chunk_size=self.chunk_size) B = 2 T = 1024 H = 8 K = 128 V = 128 CHUNK_SIZE = 64 def get_inputs(): torch.manual_seed(0) q = torch.randn(B, T, H, K, dtype=torch.bfloat16) * 0.1 k = torch.randn(B, T, H, K, dtype=torch.bfloat16) * 0.1 v = torch.randn(B, T, H, V, dtype=torch.bfloat16) * 0.1 g = (torch.randn(B, T, H, K, dtype=torch.float32) * 0.1 - 0.05) beta = torch.sigmoid(torch.randn(B, T, H, dtype=torch.bfloat16)) return [q, k, v, g, beta] def get_init_inputs(): return [B, T, H, K, V, CHUNK_SIZE]