"""KDA forward (chunk form) with custom Triton kernel. Hybrid implementation: - Batched GEMMs compute A_kk, Aqk, w, u. - A Triton kernel applies the in-chunk Woodbury correction to A. - The inter-chunk recurrence is a Python loop over chunks using batched GEMMs. This avoids calling FLA's existing KDA implementation while still using a real custom kernel for the non-GEMM recurrence step. """ from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl @triton.jit def _recurrent_kernel( qg_ptr, u_ptr, w_ptr, Aqk_ptr, kg_ptr, gscale_ptr, o_ptr, B: tl.constexpr, H: tl.constexpr, N: tl.constexpr, C: tl.constexpr, K: tl.constexpr, V: tl.constexpr, V_TILE: tl.constexpr, BLOCK_K: tl.constexpr, stride_qgb: tl.constexpr, stride_qgh: tl.constexpr, stride_qgn: tl.constexpr, stride_qgc: tl.constexpr, stride_qgk: tl.constexpr, stride_ub: tl.constexpr, stride_uh: tl.constexpr, stride_un: tl.constexpr, stride_uc: tl.constexpr, stride_uv: tl.constexpr, stride_wb: tl.constexpr, stride_wh: tl.constexpr, stride_wn: tl.constexpr, stride_wc: tl.constexpr, stride_wk: tl.constexpr, stride_Aqkb: tl.constexpr, stride_Aqkh: tl.constexpr, stride_Aqkn: tl.constexpr, stride_Aqki: tl.constexpr, stride_Aqkj: tl.constexpr, stride_kgb: tl.constexpr, stride_kgh: tl.constexpr, stride_kgn: tl.constexpr, stride_kgc: tl.constexpr, stride_kgk: tl.constexpr, stride_gsb: tl.constexpr, stride_gsh: tl.constexpr, stride_gsn: tl.constexpr, stride_gsk: tl.constexpr, stride_ob: tl.constexpr, stride_oh: tl.constexpr, stride_on: tl.constexpr, stride_oc: tl.constexpr, stride_ov: tl.constexpr, ): """Inter-chunk recurrence for KDA. One block handles one (batch, head, V-tile) and loops over chunks. State tiles S0/S1 are persistent in shared memory / registers. """ pid_b = tl.program_id(0) pid_h = tl.program_id(1) pid_vtile = tl.program_id(2) v_start = pid_vtile * V_TILE offs_c = tl.arange(0, C) offs_v = tl.arange(0, V_TILE) + v_start offs_k0 = tl.arange(0, BLOCK_K) offs_k1 = tl.arange(0, BLOCK_K) + BLOCK_K # Persistent state for K = 2 * BLOCK_K S0 = tl.zeros((BLOCK_K, V_TILE), dtype=tl.float32) S1 = tl.zeros((BLOCK_K, V_TILE), dtype=tl.float32) for n in range(N): qg_b = qg_ptr + pid_b * stride_qgb + pid_h * stride_qgh + n * stride_qgn u_b = u_ptr + pid_b * stride_ub + pid_h * stride_uh + n * stride_un w_b = w_ptr + pid_b * stride_wb + pid_h * stride_wh + n * stride_wn Aqk_b = Aqk_ptr + pid_b * stride_Aqkb + pid_h * stride_Aqkh + n * stride_Aqkn kg_b = kg_ptr + pid_b * stride_kgb + pid_h * stride_kgh + n * stride_kgn gs_b = gscale_ptr + pid_b * stride_gsb + pid_h * stride_gsh + n * stride_gsn o_b = o_ptr + pid_b * stride_ob + pid_h * stride_oh + n * stride_on u = tl.load(u_b + offs_c[:, None] * stride_uc + offs_v[None, :] * stride_uv) w0 = tl.load(w_b + offs_c[:, None] * stride_wc + offs_k0[None, :] * stride_wk) w1 = tl.load(w_b + offs_c[:, None] * stride_wc + offs_k1[None, :] * stride_wk) v_i = u - tl.dot(w0, S0) - tl.dot(w1, S1) qg0 = tl.load(qg_b + offs_c[:, None] * stride_qgc + offs_k0[None, :] * stride_qgk) qg1 = tl.load(qg_b + offs_c[:, None] * stride_qgc + offs_k1[None, :] * stride_qgk) o = tl.dot(qg0, S0) + tl.dot(qg1, S1) Aqk = tl.load(Aqk_b + offs_c[:, None] * stride_Aqki + offs_c[None, :] * stride_Aqkj) o = o + tl.dot(Aqk, v_i) tl.store(o_b + offs_c[:, None] * stride_oc + offs_v[None, :] * stride_ov, o.to(tl.bfloat16)) gscale0 = tl.load(gs_b + offs_k0 * stride_gsk) gscale1 = tl.load(gs_b + offs_k1 * stride_gsk) S0 = S0 * gscale0[:, None] S1 = S1 * gscale1[:, None] kg0 = tl.load(kg_b + offs_k0[:, None] * stride_kgk + offs_c[None, :] * stride_kgc) kg1 = tl.load(kg_b + offs_k1[:, None] * stride_kgk + offs_c[None, :] * stride_kgc) S0 = S0 + tl.dot(kg0, v_i) S1 = S1 + tl.dot(kg1, v_i) def _recurrent_triton(qg, u, w, Aqk, kg, gscale, o): B, H, N, C, K = qg.shape V = o.shape[-1] V_TILE = 32 BLOCK_K = 64 num_v_tiles = V // V_TILE grid = (B, H, num_v_tiles) _recurrent_kernel[grid]( qg, u, w, Aqk, kg, gscale, o, B=B, H=H, N=N, C=C, K=K, V=V, V_TILE=V_TILE, BLOCK_K=BLOCK_K, stride_qgb=qg.stride(0), stride_qgh=qg.stride(1), stride_qgn=qg.stride(2), stride_qgc=qg.stride(3), stride_qgk=qg.stride(4), stride_ub=u.stride(0), stride_uh=u.stride(1), stride_un=u.stride(2), stride_uc=u.stride(3), stride_uv=u.stride(4), stride_wb=w.stride(0), stride_wh=w.stride(1), stride_wn=w.stride(2), stride_wc=w.stride(3), stride_wk=w.stride(4), stride_Aqkb=Aqk.stride(0), stride_Aqkh=Aqk.stride(1), stride_Aqkn=Aqk.stride(2), stride_Aqki=Aqk.stride(3), stride_Aqkj=Aqk.stride(4), stride_kgb=kg.stride(0), stride_kgh=kg.stride(1), stride_kgn=kg.stride(2), stride_kgc=kg.stride(3), stride_kgk=kg.stride(4), stride_gsb=gscale.stride(0), stride_gsh=gscale.stride(1), stride_gsn=gscale.stride(2), stride_gsk=gscale.stride(3), stride_ob=o.stride(0), stride_oh=o.stride(1), stride_on=o.stride(2), stride_oc=o.stride(3), stride_ov=o.stride(4), num_warps=16, num_stages=1, ) return o @triton.jit def _woodbury_kernel( A_ptr, stride_b: tl.constexpr, stride_h: tl.constexpr, stride_n: tl.constexpr, stride_i: tl.constexpr, stride_j: tl.constexpr, BT: tl.constexpr, ): """Apply the causal Woodbury update to A (B, H, N, BT, BT). For each 64x64 matrix, initial A is strictly lower triangular (diag zero). For i = 1 .. BT-1: A[i, :i] += sum_m A[i, m] * A[m, :i] This is done fully in registers/shared memory for one matrix per block. """ pid_b = tl.program_id(0) pid_h = tl.program_id(1) pid_n = tl.program_id(2) base = ( A_ptr + pid_b * stride_b + pid_h * stride_h + pid_n * stride_n ) offs_i = tl.arange(0, BT) offs_j = tl.arange(0, BT) A = tl.load(base + offs_i[:, None] * stride_i + offs_j[None, :] * stride_j) for i in range(1, BT): row_mask = offs_i == i col_mask = offs_j < i row_i = tl.sum(tl.where(row_mask[:, None], A, 0.0), axis=0) # (BT,) rows_left = tl.where(col_mask[None, :], A, 0.0) # (BT, BT), cols >= i zeroed update = tl.sum(row_i[:, None] * rows_left, axis=0) # (BT,) update_mask = row_mask[:, None] & col_mask[None, :] A = A + tl.where(update_mask, update[None, :], 0.0) tl.store(base + offs_i[:, None] * stride_i + offs_j[None, :] * stride_j, A) def _woodbury(A: torch.Tensor) -> torch.Tensor: """In-place Woodbury update on A (B, H, N, BT, BT).""" B, H, N, BT, _ = A.shape grid = (B, H, N) _woodbury_kernel[grid]( A, A.stride(0), A.stride(1), A.stride(2), A.stride(3), A.stride(4), BT=BT, ) return A def _kda_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 B, T, H, K = q.shape V = 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 # (B, T, H, D) -> (B, H, N, C, D) q = q.view(B, NT, BT, H, K).permute(0, 3, 1, 2, 4).contiguous() k = k.view(B, NT, BT, H, K).permute(0, 3, 1, 2, 4).contiguous() v = v.view(B, NT, BT, H, V).permute(0, 3, 1, 2, 4).contiguous() g = g.view(B, NT, BT, H, K).permute(0, 3, 1, 2, 4).contiguous() beta = beta.view(B, NT, BT, H).permute(0, 3, 1, 2).contiguous() g = g.cumsum(-2) exp_g = g.exp() exp_neg_g = (-g).exp() # ---- Intra-chunk A_kk (causal, diag masked) ---- # A_kk[i, j] = -beta[j] * sum_d k[i,d] * k[j,d] * exp(g[i,d] - g[j,d]) for i > j # = -beta[j] * (k * exp(g)) @ (k * exp(-g)).T k_pos = k * exp_g # (B,H,N,C,K) k_neg = k * exp_neg_g # (B,H,N,C,K) A = torch.matmul(k_pos, k_neg.transpose(-2, -1)) # (B,H,N,C,C) # Apply causal mask (strict lower triangular, diag zero), with row beta scaling # Reference does A = A * beta[..., None] then mask/negate, then Woodbury, # then A = (A + I) * beta[..., None, :]. mask_upper = torch.triu(torch.ones(BT, BT, dtype=torch.bool, device=q.device), diagonal=0) A = A * beta[..., None] A = -A.masked_fill(mask_upper, 0.0) # Woodbury update _woodbury(A) # Final column beta scaling: A = (A + I) * beta[..., None, :] A = (A + torch.eye(BT, dtype=torch.float32, device=q.device)) * beta[..., None, :] # w = A @ (exp(g) * k), u = A @ v w = torch.matmul(A, k_pos) # (B,H,N,C,K) u = torch.matmul(A, v) # (B,H,N,C,V) # ---- Inter-chunk recurrence ---- mask_strict_upper = torch.triu(torch.ones(BT, BT, dtype=torch.bool, device=q.device), diagonal=1) # Precompute Aqk for all chunks: (q * exp(g)) @ (k * exp(-g)).T q_pos = q * exp_g Aqk = torch.matmul(q_pos, k_neg.transpose(-2, -1)) Aqk = Aqk.masked_fill(mask_strict_upper, 0.0) # Precompute per-chunk tensors for the recurrence kernel. qg = q_pos # (B,H,N,C,K) gscale = g[:, :, :, -1].exp() # (B,H,N,K) kg = (g[:, :, :, -1:].exp() * exp_neg_g) * k # (B,H,N,C,K) o = torch.empty(B, H, NT, BT, V, dtype=torch.bfloat16, device=q.device) _recurrent_triton(qg, u, w, Aqk, kg, gscale, o) o = o.permute(0, 2, 3, 1, 4).contiguous().view(B, T, H, V) return o.to(dtype) 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) # Compile the forward pass to fuse elementwise ops and small GEMMs. self.forward = torch.compile(self.forward, mode="max-autotune", dynamic=False) def forward( self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, g: torch.Tensor, beta: torch.Tensor, ) -> torch.Tensor: return _kda_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(): 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]