"""KDA forward (chunk form) — optimized PyTorch with batch matmuls. Uses efficient batch matrix multiplications for the intra-chunk A matrix (A = k_exp @ k_neg.T with cumulative correction) and the inter-chunk recurrence. All compute runs in fp32 for accuracy with bf16 I/O. """ from __future__ import annotations import torch import torch.nn as nn from einops import rearrange def _kda_forward_pytorch( 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 — batch-matmul formulation (fp32 compute, bf16 output).""" dtype = v.dtype B, T, H, K_dim = q.shape V_dim = v.shape[-1] BT = chunk_size NT = T // BT q, k, v, g, beta = (x.to(torch.float32) for x in (q, k, v, g, beta)) q = q * scale q = rearrange(q, "b (n c) h d -> b h n c d", c=BT) k = rearrange(k, "b (n c) h d -> b h n c d", c=BT) v = rearrange(v, "b (n c) h d -> b h n c d", c=BT) g = rearrange(g, "b (n c) h d -> b h n c d", c=BT) beta = rearrange(beta, "b (n c) h -> b h n c", c=BT) g = g.cumsum(-2) # ---- Intra-chunk: build A = k_exp @ k_neg.T (batch matmul) ---- k_exp = k * g.exp() k_neg = k * (-g).exp() q_exp = q * g.exp() A = torch.matmul(k_exp, k_neg.transpose(-2, -1)) A = A * beta.unsqueeze(-1) A = -A.masked_fill( torch.triu(torch.ones(BT, BT, dtype=torch.bool, device=A.device), diagonal=0), 0.0, ) # Cumulative correction (I - A)^{-1} - I via forward substitution for i in range(1, BT): A_row = A[..., i, :, None] A_left = A[..., :, :i] A[..., i, :i] = A[..., i, :i] + (A_row * A_left).sum(-2) A = (A + torch.eye(BT, dtype=torch.float32, device=A.device)) * beta.unsqueeze(-2) w = torch.matmul(A, k_exp) u = torch.matmul(A, v) # ---- Inter-chunk recurrence ---- S = torch.zeros(B, H, K_dim, V_dim, dtype=torch.float32, device=A.device) o = torch.zeros_like(v) mask_upper = torch.triu(torch.ones(BT, BT, dtype=torch.bool, device=A.device), diagonal=1) for i in range(NT): q_i = q[:, :, i] k_i = k[:, :, i] u_i = u[:, :, i] g_i = g[:, :, i] w_i = w[:, :, i] k_neg_i = k_neg[:, :, i] q_exp_i = q_exp[:, :, i] Aqk = torch.matmul(q_exp_i, k_neg_i.transpose(-2, -1)) Aqk = Aqk.masked_fill(mask_upper, 0.0) v_corrected = u_i - torch.matmul(w_i, S) o_i = torch.matmul(q_exp_i, S) + torch.matmul(Aqk, v_corrected) o[:, :, i] = o_i ge = g_i[:, :, -1].exp() S = S * ge.unsqueeze(-1) gd = (g_i[:, :, -1:] - g_i).exp() S = S + torch.matmul((k_i * gd).transpose(-2, -1), v_corrected) o = rearrange(o, "b h n c d -> b (n c) h d") return o.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, k, v, g, beta): return _kda_forward_pytorch(q, k, v, g, beta, scale=self.scale, chunk_size=self.chunk_size) # Module-level shape shims 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]