"""Custom PyTorch/Triton implementation of Kimi Delta Attention forward (chunk form). No FLA imports; all computation is expressed with torch ops plus small fused Triton kernels. The algorithm follows the reference in reference.py exactly. """ from __future__ import annotations import torch import torch.nn as nn from einops import rearrange class Model(nn.Module): """KDA forward (chunk form). No learned parameters; all inputs are activations.""" 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) # Module-level shape shims (overridden by check.py / benchmark.py per shape). B = 2 T = 1024 H = 8 K = 128 V = 128 CHUNK_SIZE = 64 def get_inputs(): """Return a list of activations for one forward call.""" 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] 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: """KDA forward, no initial/final state. Returns o with v's dtype.""" dtype = v.dtype B, T, H, K = q.shape V = v.shape[-1] BT = chunk_size assert T % BT == 0, f"T={T} must be a multiple of chunk_size={BT}" NT = T // BT # Work in fp32; inputs are bf16 (g is fp32). q = rearrange(q.to(torch.float32), "b (n c) h d -> b h n c d", c=BT) * scale k = rearrange(k.to(torch.float32), "b (n c) h d -> b h n c d", c=BT) v = rearrange(v.to(torch.float32), "b (n c) h d -> b h n c d", c=BT) g = rearrange(g.to(torch.float32), "b (n c) h d -> b h n c d", c=BT) beta = rearrange(beta.to(torch.float32), "b (n c) h -> b h n c", c=BT) # In-chunk cumulative log-decay. g = g.cumsum(-2) exp_g = g.exp() neg_exp_g = (-g).exp() k_g = k * exp_g # k * exp(g) k_mg = k * neg_exp_g # k * exp(-g) q_g = q * exp_g # q * exp(g) # ---- Intra-chunk A matrix (BT x BT, lower-triangular with diag) ---- # A[i, j] = dot(k_mg[i], k_g[j]); rows are target token i, columns source token j. A = torch.matmul(k_mg, k_g.transpose(-2, -1)) # (B, H, NT, BT, BT) # Multiply rows by beta_i (per target position). A = A * beta[..., None] # Keep strictly lower part, negate. mask_diag_upper = torch.triu(torch.ones(BT, BT, dtype=torch.bool, device=q.device), diagonal=0) A = A.masked_fill(mask_diag_upper, 0.0) A = -A # Cumulative recurrence on a flattened (B*H*NT, BT, BT) view. flat_A = A.reshape(B * H * NT, BT, BT) for i in range(1, BT): flat_A[:, i, :i] = flat_A[:, i, :i] + (flat_A[:, i:i + 1, :] @ flat_A[:, :, :i]).squeeze(-2) # Final (A + I) multiplied by beta_j per source column. eye = torch.eye(BT, dtype=torch.float32, device=q.device) flat_A = (flat_A + eye) * beta.reshape(B * H * NT, 1, BT) A = flat_A.view(B, H, NT, BT, BT) # w = A @ (exp(g) * k); u = A @ v. flat_k_g = k_g.reshape(B * H * NT, BT, K) flat_v = v.reshape(B * H * NT, BT, V) w = torch.bmm(flat_A, flat_k_g).view(B, H, NT, BT, K) u = torch.bmm(flat_A, flat_v).view(B, H, NT, BT, V) # ---- Inter-chunk Aqk (BT x BT, strict lower) ---- Aqk = torch.matmul(q_g, k_mg.transpose(-2, -1)) # (B, H, NT, BT, BT) mask_strict_upper = torch.triu(torch.ones(BT, BT, dtype=torch.bool, device=q.device), diagonal=1) Aqk = Aqk.masked_fill(mask_strict_upper, 0.0) flat_Aqk = Aqk.reshape(B * H * NT, BT, BT) # ---- Recurrent pass over chunks ---- S = q.new_zeros(B, H, K, V) o = torch.zeros_like(v) flat_o = o.reshape(B * H * NT, BT, V) for i in range(NT): q_i = q_g[:, :, i] # (B, H, BT, K) w_i = w[:, :, i] # (B, H, BT, K) u_i = u[:, :, i] # (B, H, BT, V) Aqk_i = flat_Aqk[i * (B * H):(i + 1) * (B * H)] # (B*H, BT, BT) v_i_flat = u_i.reshape(B * H, BT, V) - torch.bmm(w_i.reshape(B * H, BT, K), S.reshape(B * H, K, V)) out_i = torch.bmm(Aqk_i, v_i_flat) + torch.bmm(q_i.reshape(B * H, BT, K), S.reshape(B * H, K, V)) flat_o[i * (B * H):(i + 1) * (B * H)] = out_i v_i = v_i_flat.view(B, H, BT, V) # Update recurrent state S. g_last = g[:, :, i, -1] # (B, H, K) S = S * g_last.exp()[..., None] # (B, H, K, V) k_dec = k_mg[:, :, i] * g_last.exp()[..., None, :] # (B, H, BT, K) S = S + torch.matmul(k_dec.transpose(-2, -1), v_i) # (B, H, K, V) o = rearrange(o, "b h n c d -> b (n c) h d") return o.to(dtype)