"""Kimi Delta Attention (KDA) forward, chunk form -- custom Triton kernel. Own from-scratch implementation of the chunk-parallel KDA forward (see reference.py for the mathematical spec this must match). Not a call into FLA's kernels. Three-kernel design. The op has an embarrassingly-parallel "intra-chunk" half and a sequential "inter-chunk" recurrence; the recurrence itself is further split into a cheap sequential pass and a fully-parallel one so that as little work as possible sits on the sequential critical path. Kernel 1 ("intra"), grid = (NT, B*H), one program per chunk -- fully parallel, no cross-chunk dependency: 1. In-chunk cumulative log-decay: G = cumsum(g, axis=chunk-time) 2. Build the intra-chunk "delta rule" interaction matrix A_raw[c, i] = sum_d k[c, d] * exp(G[c, d] - G[i, d]) * k[i, d] = (k * exp(G))[c, :] . (k * exp(-G))[i, :] which factorizes into a plain matmul because the decay ratio splits multiplicatively. L is the strictly-lower-triangular, beta-scaled, negated version of A_raw (see reference.py's per-chunk attention math). 3. WY/UT-transform: Tmat = (I - L)^{-1}. L is strictly lower triangular and BT x BT with BT a power of two, hence nilpotent with L^BT = 0, so the finite Neumann series sum_{k=0}^{BT-1} L^k equals the exact inverse and can be computed with log2(BT) doubling steps (repeated squaring): S_2 = I + L, P_2 = L S_{2m} = S_m + S_m @ P_m, P_{2m} = P_m @ P_m This trades the sequential row-by-row forward substitution (BT dependent steps) for log2(BT) dependent *tensor-core matmuls* (6 steps for BT=64) -- shallow, and full tensor-core utilization throughout. 4. w = Tmat @ (exp(G) * k), u = Tmat @ v (the "WY" correction terms), the causal intra-chunk attention weights Aqk[c, j] = sum_d q[c,d] * exp(G[c,d]-G[j,d]) * k[j,d], j <= c and the two ingredients the state recurrence needs -- decayed_k = k * exp(G_last - G) and exp(G_last) -- are all written to scratch so kernels 2a/2b never have to touch q/k/g or redo the cumsum. Kernel 2a ("state"), grid = (VT, B*H), VT-way tiled over the value dim, with a runtime (not unrolled) loop over the NT chunks -- the sequential part. Stripped to only the S -> S critical path (no output computation at all), and snapshots the per-chunk "state at chunk start" S_i to scratch: v' = u - w @ S_i S_{i+1} = S_i * exp(G_last) + decayed_k^T @ v' Kernel 2b ("out"), grid = (NT, VT, B*H) -- fully parallel, no sequential dependency, using the S_i snapshots from kernel 2a: v' = u - w @ S_i o = (q * scale * exp(G)) @ S_i + Aqk @ v' Splitting this way keeps kernel 1 (which does all of the O(BT^3)-ish WY-transform work) and kernel 2b (all of the "use S to produce output" work) fully parallel across hundreds-to-thousands of programs instead of forcing them onto the sequential per-(b,h) critical path, and keeps kernel 2a's register/shared-memory footprint (and hence occupancy) far smaller since it no longer carries the transform's many live intermediates -- or even a cumsum -- alongside the recurrent state. """ from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl OP_TYPE = "linear_attention" SUPPORTED_PRECISIONS = ["bf16"] HARDWARE_REQUIRED = ["RTX_PRO_6000", "H100", "B200"] # --------------------------------------------------------------------------- # Kernel 1: intra-chunk WY-transform (fully parallel over chunks x heads) # --------------------------------------------------------------------------- @triton.jit def _kda_intra_kernel( q_ptr, k_ptr, v_ptr, g_ptr, beta_ptr, w_ptr, u_ptr, aqk_ptr, qg_ptr, dk_ptr, gd_ptr, T, H, scale, K: tl.constexpr, V: tl.constexpr, BT: tl.constexpr, N_DOUBLINGS: tl.constexpr, ): i_t = tl.program_id(0) i_bh = tl.program_id(1) i_b = i_bh // H i_h = i_bh % H NT = T // BT qk_base = (i_b * T * H + i_h) * K v_base = (i_b * T * H + i_h) * V beta_base = i_b * T * H + i_h aqk_base = (i_b * T * H + i_h) * BT gd_base = (i_b * NT + i_t) * H * K + i_h * K d_k = tl.arange(0, K) d_v = tl.arange(0, V) c_ar = tl.arange(0, BT) row = c_ar[:, None] col = c_ar[None, :] strict_lower = row > col causal_incl = row >= col eye = (row == col).to(tl.float32) offs_t = i_t * BT + c_ar q_ptrs = q_ptr + qk_base + offs_t[:, None] * H * K + d_k[None, :] k_ptrs = k_ptr + qk_base + offs_t[:, None] * H * K + d_k[None, :] v_ptrs = v_ptr + v_base + offs_t[:, None] * H * V + d_v[None, :] g_ptrs = g_ptr + qk_base + offs_t[:, None] * H * K + d_k[None, :] beta_ptrs = beta_ptr + beta_base + offs_t * H b_q = tl.load(q_ptrs) b_k = tl.load(k_ptrs) b_g = tl.load(g_ptrs).to(tl.float32) b_beta = tl.load(beta_ptrs).to(tl.float32) b_G = tl.cumsum(b_g, axis=0) eG = tl.exp(b_G) eGinv = 1.0 / eG b_kf = b_k.to(tl.float32) KG = b_kf * eG KGinv = b_kf * eGinv A_raw = tl.dot(KG.to(tl.bfloat16), tl.trans(KGinv.to(tl.bfloat16)), out_dtype=tl.float32) # Aqk only needs eG/KGinv transiently -- compute and store it now so those # two (BT,K) tiles don't have to stay live across the doubling loop below. Qg = (b_q.to(tl.float32) * scale) * eG Qg_bf = Qg.to(tl.bfloat16) Aqk = tl.dot(Qg_bf, tl.trans(KGinv.to(tl.bfloat16)), out_dtype=tl.float32) Aqk = tl.where(causal_incl, Aqk, 0.0) aqk_ptrs = aqk_ptr + aqk_base + offs_t[:, None] * H * BT + c_ar[None, :] tl.store(aqk_ptrs, Aqk.to(tl.bfloat16)) qg_ptrs = qg_ptr + qk_base + offs_t[:, None] * H * K + d_k[None, :] tl.store(qg_ptrs, Qg_bf) # decayed_k = k * exp(g_last - G) and exp(g_last) are the two ingredients # the inter-chunk recurrence needs for the state update; precompute them # here (once per chunk) instead of re-deriving cumsum(g) redundantly in # every value-tile program of the downstream kernels. exp(g_last - G) = # exp(g_last) * exp(-G) = exp(g_last) * eGinv reuses the reciprocal # above instead of a second full (BT,K) transcendental exp call. g_last = tl.sum(b_g, axis=0) gd = tl.exp(g_last) decayed_k_bf = (b_kf * eGinv * gd[None, :]).to(tl.bfloat16) dk_ptrs = dk_ptr + qk_base + offs_t[:, None] * H * K + d_k[None, :] tl.store(dk_ptrs, decayed_k_bf) tl.store(gd_ptr + gd_base + d_k, gd) L = tl.where(strict_lower, -A_raw * b_beta[:, None], 0.0) Pow = L Sacc = eye + L for _ in tl.static_range(N_DOUBLINGS): Pow = tl.dot(Pow.to(tl.bfloat16), Pow.to(tl.bfloat16)) Sacc = Sacc + tl.dot(Sacc.to(tl.bfloat16), Pow.to(tl.bfloat16)) Tmat_bf = (Sacc * b_beta[None, :]).to(tl.bfloat16) w = tl.dot(Tmat_bf, KG.to(tl.bfloat16)) w_ptrs = w_ptr + qk_base + offs_t[:, None] * H * K + d_k[None, :] tl.store(w_ptrs, w.to(tl.bfloat16)) b_v = tl.load(v_ptrs) u = tl.dot(Tmat_bf, b_v) u_ptrs = u_ptr + v_base + offs_t[:, None] * H * V + d_v[None, :] tl.store(u_ptrs, u.to(tl.bfloat16)) # --------------------------------------------------------------------------- # Kernel 2a: propagate the recurrent state S across chunks (sequential, but # stripped to only the work on the S -> S critical path) and snapshot the # per-chunk "state at chunk start" S_i to scratch. Grid = (VT, B*H). # --------------------------------------------------------------------------- @triton.jit def _kda_state_kernel( dk_ptr, gd_ptr, w_ptr, u_ptr, s_ptr, T, H, K: tl.constexpr, V: tl.constexpr, BT: tl.constexpr, BV: tl.constexpr, ): i_v = tl.program_id(0) i_bh = tl.program_id(1) i_b = i_bh // H i_h = i_bh % H VT = V // BV NT = T // BT qk_base = (i_b * T * H + i_h) * K v_base = (i_b * T * H + i_h) * V + i_v * BV gd_base = i_b * NT * H * K + i_h * K s_base = (i_bh * VT + i_v) * NT * K * BV d_k = tl.arange(0, K) d_v = tl.arange(0, BV) c_ar = tl.arange(0, BT) d_kbv = d_k[:, None] * BV + d_v[None, :] S = tl.zeros((K, BV), dtype=tl.float32) # Manually double-buffered: the four small per-chunk loads (dk, gd, w, u) # are independent of S, so the *next* chunk's loads are issued before # this chunk's S-dependent dots -- giving the load latency a full # iteration to be hidden behind the matmuls instead of stalling the # sequential S->S critical path every step. Triton's automatic # num_stages>=2 pipelining does the same thing but budgets shared memory # for the whole loop body (blows the 99KB/block limit here); this hand # version only double-buffers the four cheap loads. dk_cur = tl.load(dk_ptr + qk_base + c_ar[:, None] * H * K + d_k[None, :]) gd_cur = tl.load(gd_ptr + gd_base + d_k) w_cur = tl.load(w_ptr + qk_base + c_ar[:, None] * H * K + d_k[None, :]) u_cur = tl.load(u_ptr + v_base + c_ar[:, None] * H * V + d_v[None, :]) for i_t in range(0, NT): offs_t = i_t * BT + c_ar s_ptrs = s_ptr + s_base + i_t * K * BV + d_kbv tl.store(s_ptrs, S.to(tl.bfloat16)) has_next = i_t + 1 < NT next_offs_t = tl.where(has_next, i_t + 1, i_t) * BT + c_ar dk_nxt = tl.load(dk_ptr + qk_base + next_offs_t[:, None] * H * K + d_k[None, :]) gd_nxt = tl.load(gd_ptr + gd_base + tl.where(has_next, i_t + 1, i_t) * H * K + d_k) w_nxt = tl.load(w_ptr + qk_base + next_offs_t[:, None] * H * K + d_k[None, :]) u_nxt = tl.load(u_ptr + v_base + next_offs_t[:, None] * H * V + d_v[None, :]) v_i_bf = (u_cur.to(tl.float32) - tl.dot(w_cur, S.to(tl.bfloat16))).to(tl.bfloat16) S = S * gd_cur[:, None] + tl.dot(tl.trans(dk_cur), v_i_bf) dk_cur, gd_cur, w_cur, u_cur = dk_nxt, gd_nxt, w_nxt, u_nxt # --------------------------------------------------------------------------- # Kernel 2b: recover o_i from the saved per-chunk state S_i. Fully parallel # over (chunk, value-tile, batch*head) -- no sequential dependency at all. # --------------------------------------------------------------------------- @triton.jit def _kda_out_kernel( qg_ptr, w_ptr, u_ptr, aqk_ptr, s_ptr, o_ptr, T, H, K: tl.constexpr, V: tl.constexpr, BT: tl.constexpr, BV: tl.constexpr, ): i_t = tl.program_id(0) i_v = tl.program_id(1) i_bh = tl.program_id(2) i_b = i_bh // H i_h = i_bh % H VT = V // BV qk_base = (i_b * T * H + i_h) * K v_base = (i_b * T * H + i_h) * V + i_v * BV aqk_base = (i_b * T * H + i_h) * BT NT = T // BT s_base = (i_bh * VT + i_v) * NT * K * BV + i_t * K * BV d_k = tl.arange(0, K) d_v = tl.arange(0, BV) c_ar = tl.arange(0, BT) d_kbv = d_k[:, None] * BV + d_v[None, :] offs_t = i_t * BT + c_ar S_bf = tl.load(s_ptr + s_base + d_kbv) qg_ptrs = qg_ptr + qk_base + offs_t[:, None] * H * K + d_k[None, :] Qg_bf = tl.load(qg_ptrs) w_ptrs = w_ptr + qk_base + offs_t[:, None] * H * K + d_k[None, :] u_ptrs = u_ptr + v_base + offs_t[:, None] * H * V + d_v[None, :] b_w = tl.load(w_ptrs) b_u = tl.load(u_ptrs) v_i_bf = (b_u.to(tl.float32) - tl.dot(b_w, S_bf)).to(tl.bfloat16) aqk_ptrs = aqk_ptr + aqk_base + offs_t[:, None] * H * BT + c_ar[None, :] b_aqk = tl.load(aqk_ptrs) o_i = tl.dot(Qg_bf, S_bf) + tl.dot(b_aqk, v_i_bf) o_ptrs = o_ptr + v_base + offs_t[:, None] * H * V + d_v[None, :] tl.store(o_ptrs, o_i.to(tl.bfloat16)) def _pick_bv(bh: int, V: int, target_blocks: int = 64) -> int: """Pick the value-tile width for kernels 2a/2b. Kernel 2a's sequential loop over chunks means its wall-clock is governed by how many (value-tile, batch*head) programs run concurrently, not by total FLOPs -- so thin-batch shapes (small B*H) want more, narrower V-tiles than wide-batch shapes to keep the SMs similarly occupied. Snaps to a power-of-two divisor of V so the state scratch tiling stays simple. """ vt_desired = max(1, -(-target_blocks // max(bh, 1))) # ceil bv = V while bv // 2 >= 8 and V // bv < vt_desired: bv //= 2 return bv 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: 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}" assert (BT & (BT - 1)) == 0, "chunk_size must be a power of two" q = q.contiguous() k = k.contiguous() v = v.contiguous() g = g.contiguous() beta = beta.contiguous() NT = T // BT n_doublings = BT.bit_length() - 2 # log2(BT) - 1 w = torch.empty(B, T, H, K, dtype=torch.bfloat16, device=q.device) u = torch.empty(B, T, H, V, dtype=torch.bfloat16, device=q.device) aqk = torch.empty(B, T, H, BT, dtype=torch.bfloat16, device=q.device) qg = torch.empty(B, T, H, K, dtype=torch.bfloat16, device=q.device) dk = torch.empty(B, T, H, K, dtype=torch.bfloat16, device=q.device) gd = torch.empty(B, NT, H, K, dtype=torch.float32, device=q.device) o = torch.empty(B, T, H, V, dtype=v.dtype, device=v.device) grid1 = (NT, B * H) _kda_intra_kernel[grid1]( q, k, v, g, beta, w, u, aqk, qg, dk, gd, T, H, scale, K=K, V=V, BT=BT, N_DOUBLINGS=n_doublings, num_warps=8, num_stages=2, ) BV = _pick_bv(B * H, V) VT = V // BV s_scratch = torch.empty(B * H * VT * NT * K * BV, dtype=torch.bfloat16, device=q.device) grid2a = (VT, B * H) _kda_state_kernel[grid2a]( dk, gd, w, u, s_scratch, T, H, K=K, V=V, BT=BT, BV=BV, num_warps=4, num_stages=1, ) grid2b = (NT, VT, B * H) _kda_out_kernel[grid2b]( qg, w, u, aqk, s_scratch, o, T, H, K=K, V=V, BT=BT, BV=BV, num_warps=4, num_stages=1, ) return o 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_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]