# Copyright (c) 2026 Philip Bartsch (@batteryphil). # Licensed under the Bartsch Personal-Free & 5% Commercial Profit-Share License v1.0 (see LICENSE). """ Exact Fused Triton Decode Kernels for `thinkingmachines/Inkling-2-Mini` ======================================================================= Eliminates the `~43 ms/tok` non-quantized PyTorch/rocBLAS overhead inside `Inkling-2-Mini`'s 48-pass looped decode step while preserving 100% exact mathematical parity with Hugging Face `transformers.models.inkling2_loop.modeling_inkling2_loop`: 1. `short_conv1d_step_res_triton` (176 calls/tok): in-place 4-tap conv state shift + residual / sqrt(5) 2. `dyn_short_conv1d_step_res_triton` ( 16 calls/tok): dynamic + static 4-tap conv state shift + residual / 3 3. `message_gate_triton` ( 96 calls/tok): 2-kernel fused RMSNorm + rank-64 tanh forget/message gate 4. `attn_res_step_triton` (120 calls/tok): 2-kernel fused Block & Message Attention Residuals (zero rocBLAS) 5. `dense_gemv_triton` (112 calls/tok): fast M=1 FP32/BF16 GEMV for TopKRouter, sink_proj, weight_proj 6. `inkling2_decode_attn_triton` ( 48 calls/tok): fused GQA + RelativePositionBias + Per-Head Sink + Ring-Buffer Sliding Window / Full Attention (supports 1K..32K+ context in one single HIP/CUDA Graph with zero per-token KV cache roll!) """ from __future__ import annotations import math from typing import Optional import torch import triton import triton.language as tl @triton.jit def _short_conv1d_step_res_kernel( x_ptr, state_ptr, w_ptr, out_ptr, C, INV_SCALE: tl.constexpr, BLOCK_C: tl.constexpr, ): """In-place 4-tap static depthwise causal conv1d update + residual / sqrt(5) for B=1, T=1.""" pid = tl.program_id(0) c = pid * BLOCK_C + tl.arange(0, BLOCK_C) m = c < C x_f = tl.load(x_ptr + c, mask=m, other=0.0).to(tl.float32) base = c * 4 s0 = tl.load(state_ptr + base + 1, mask=m, other=0.0).to(tl.float32) s1 = tl.load(state_ptr + base + 2, mask=m, other=0.0).to(tl.float32) s2 = tl.load(state_ptr + base + 3, mask=m, other=0.0).to(tl.float32) s3 = x_f tl.store(state_ptr + base + 0, s0.to(state_ptr.dtype.element_ty), mask=m) tl.store(state_ptr + base + 1, s1.to(state_ptr.dtype.element_ty), mask=m) tl.store(state_ptr + base + 2, s2.to(state_ptr.dtype.element_ty), mask=m) tl.store(state_ptr + base + 3, s3.to(state_ptr.dtype.element_ty), mask=m) w0 = tl.load(w_ptr + base + 0, mask=m, other=0.0).to(tl.float32) w1 = tl.load(w_ptr + base + 1, mask=m, other=0.0).to(tl.float32) w2 = tl.load(w_ptr + base + 2, mask=m, other=0.0).to(tl.float32) w3 = tl.load(w_ptr + base + 3, mask=m, other=0.0).to(tl.float32) dot = s0 * w0 + s1 * w1 + s2 * w2 + s3 * w3 out = (dot + x_f) * INV_SCALE tl.store(out_ptr + c, out.to(out_ptr.dtype.element_ty), mask=m) @triton.jit def _dyn_short_conv1d_step_res_kernel( x_ptr, state_ptr, static_w_ptr, # [4, C] row-major: lag 0 = current token, lag 3 = oldest dyn_w_ptr, # [num_heads, 4] row-major out_ptr, C, HEAD_DIM: tl.constexpr, INV_SCALE: tl.constexpr, BLOCK_C: tl.constexpr, ): """In-place 4-tap dynamic+static causal conv1d update + residual / sqrt(9) for B=1, T=1.""" pid = tl.program_id(0) c = pid * BLOCK_C + tl.arange(0, BLOCK_C) m = c < C h = c // HEAD_DIM x_f = tl.load(x_ptr + c, mask=m, other=0.0).to(tl.float32) base = c * 4 s0 = tl.load(state_ptr + base + 1, mask=m, other=0.0).to(tl.float32) # lag 3 (oldest) s1 = tl.load(state_ptr + base + 2, mask=m, other=0.0).to(tl.float32) # lag 2 s2 = tl.load(state_ptr + base + 3, mask=m, other=0.0).to(tl.float32) # lag 1 s3 = x_f # lag 0 (current) tl.store(state_ptr + base + 0, s0.to(state_ptr.dtype.element_ty), mask=m) tl.store(state_ptr + base + 1, s1.to(state_ptr.dtype.element_ty), mask=m) tl.store(state_ptr + base + 2, s2.to(state_ptr.dtype.element_ty), mask=m) tl.store(state_ptr + base + 3, s3.to(state_ptr.dtype.element_ty), mask=m) # static_w[lag, c] + dyn_w[h, lag] where lag 0 multiplies s3 (current) and lag 3 multiplies s0 (oldest) w_lag0 = tl.load(static_w_ptr + 0 * C + c, mask=m, other=0.0).to(tl.float32) + tl.load(dyn_w_ptr + h * 4 + 0, mask=m, other=0.0).to(tl.float32) w_lag1 = tl.load(static_w_ptr + 1 * C + c, mask=m, other=0.0).to(tl.float32) + tl.load(dyn_w_ptr + h * 4 + 1, mask=m, other=0.0).to(tl.float32) w_lag2 = tl.load(static_w_ptr + 2 * C + c, mask=m, other=0.0).to(tl.float32) + tl.load(dyn_w_ptr + h * 4 + 2, mask=m, other=0.0).to(tl.float32) w_lag3 = tl.load(static_w_ptr + 3 * C + c, mask=m, other=0.0).to(tl.float32) + tl.load(dyn_w_ptr + h * 4 + 3, mask=m, other=0.0).to(tl.float32) dot = s3 * w_lag0 + s2 * w_lag1 + s1 * w_lag2 + s0 * w_lag3 out = (dot + x_f) * INV_SCALE tl.store(out_ptr + c, out.to(out_ptr.dtype.element_ty), mask=m) @triton.jit def _dense_gemv_kernel( x_ptr, w_ptr, out_ptr, rows, cols, BLOCK_R: tl.constexpr, BLOCK_K: tl.constexpr, ): """Coalesced FP32/BF16 M=1 GEMV (y = W @ x) bypassing slow rocBLAS small-M Tensile kernels.""" pid = tl.program_id(0) r = pid * BLOCK_R + tl.arange(0, BLOCK_R) r_mask = r < rows r_i64 = r.to(tl.int64) acc = tl.zeros((BLOCK_R,), dtype=tl.float32) k_offs = tl.arange(0, BLOCK_K) for k0 in range(0, cols, BLOCK_K): k = k0 + k_offs k_mask = k < cols xv = tl.load(x_ptr + k, mask=k_mask, other=0.0).to(tl.float32) wv = tl.load(w_ptr + r_i64[:, None] * cols + k[None, :], mask=r_mask[:, None] & k_mask[None, :], other=0.0).to(tl.float32) acc += tl.sum(wv * xv[None, :], axis=1) tl.store(out_ptr + r, acc.to(out_ptr.dtype.element_ty), mask=r_mask) @triton.jit def _msg_gate_stage1_kernel( h_ptr, m_ptr, wdn_ptr, # [R=64, 2*H] bf16/fp32 g_ptr, # [R=64] fp32 R, H, eps, BLOCK_R: tl.constexpr, BLOCK_K: tl.constexpr, ): """Fused RMSNorm(h), RMSNorm(m), and down_proj -> g[64] in fp32 (exact cast parity with wdn.dtype).""" pid = tl.program_id(0) r = pid * BLOCK_R + tl.arange(0, BLOCK_R) r_mask = r < R r_i64 = r.to(tl.int64) k_offs = tl.arange(0, BLOCK_K) ss_h = 0.0 ss_m = 0.0 for k0 in range(0, H, BLOCK_K): k = k0 + k_offs km = k < H hv = tl.load(h_ptr + k, mask=km, other=0.0).to(tl.float32) mv = tl.load(m_ptr + k, mask=km, other=0.0).to(tl.float32) ss_h += tl.sum(hv * hv, axis=0) ss_m += tl.sum(mv * mv, axis=0) inv_h = tl.rsqrt(ss_h / H + eps) inv_m = tl.rsqrt(ss_m / H + eps) acc = tl.zeros((BLOCK_R,), dtype=tl.float32) stride_r = 2 * H for k0 in range(0, H, BLOCK_K): k = k0 + k_offs km = k < H hv = tl.load(h_ptr + k, mask=km, other=0.0).to(tl.float32) mv = tl.load(m_ptr + k, mask=km, other=0.0).to(tl.float32) # Match upstream `gate_hidden_states.to(self.down_proj.weight.dtype)` rounding hn = (hv * inv_h).to(wdn_ptr.dtype.element_ty).to(tl.float32) mn = (mv * inv_m).to(wdn_ptr.dtype.element_ty).to(tl.float32) w0 = tl.load(wdn_ptr + r_i64[:, None] * stride_r + k[None, :], mask=r_mask[:, None] & km[None, :], other=0.0).to(tl.float32) w1 = tl.load(wdn_ptr + r_i64[:, None] * stride_r + (H + k)[None, :], mask=r_mask[:, None] & km[None, :], other=0.0).to(tl.float32) acc += tl.sum(w0 * hn[None, :] + w1 * mn[None, :], axis=1) tl.store(g_ptr + r, acc, mask=r_mask) @triton.jit def _msg_gate_stage2_kernel( h_ptr, m_ptr, g_ptr, # [R=64] fp32 wfg_ptr, # [H, R=64] fp32 wmg_ptr, # [H, R=64] fp32 out_ptr, # [H] fp32 H, R: tl.constexpr, BLOCK_H: tl.constexpr, ): """Fused tanh(w_fg @ g), tanh(w_mg @ g), and (1 - fg) * h + mg * m -> fp32.""" pid = tl.program_id(0) h_idx = pid * BLOCK_H + tl.arange(0, BLOCK_H) hm = h_idx < H h_i64 = h_idx.to(tl.int64) r_offs = tl.arange(0, R) gv = tl.load(g_ptr + r_offs).to(tl.float32) off = h_i64[:, None] * R + r_offs[None, :] wfg = tl.load(wfg_ptr + off, mask=hm[:, None], other=0.0).to(tl.float32) wmg = tl.load(wmg_ptr + off, mask=hm[:, None], other=0.0).to(tl.float32) fg_pre = tl.sum(wfg * gv[None, :], axis=1) mg_pre = tl.sum(wmg * gv[None, :], axis=1) fg = 2.0 * tl.sigmoid(2.0 * fg_pre) - 1.0 mg = 2.0 * tl.sigmoid(2.0 * mg_pre) - 1.0 hv = tl.load(h_ptr + h_idx, mask=hm, other=0.0).to(tl.float32) mv = tl.load(m_ptr + h_idx, mask=hm, other=0.0).to(tl.float32) out = (1.0 - fg) * hv + mg * mv tl.store(out_ptr + h_idx, out, mask=hm) @triton.jit def _attn_res_stage1_kernel( bs_ptr, # [S_prev, H] part_ptr, # [H] q_ptr, # [Q, H] fp32 inv_rms_ptr, # [S] fp32 scores_ptr, # [Q, S] fp32 S_prev, H, Q, Q_PAD: tl.constexpr, BLOCK_K: tl.constexpr, ): """Single-pass AttnRes stage 1: computes inv_rms[s] and (q @ v) * inv_rms / sqrt(H) in ONE pass over H.""" s = tl.program_id(0) is_part = s == S_prev s_i64 = s.to(tl.int64) k_offs = tl.arange(0, BLOCK_K) q_offs = tl.arange(0, Q_PAD) qm = q_offs < Q q_i64 = q_offs.to(tl.int64) ss = 0.0 acc = tl.zeros((Q_PAD,), dtype=tl.float32) for k0 in range(0, H, BLOCK_K): k = k0 + k_offs km = k < H if is_part: v = tl.load(part_ptr + k, mask=km, other=0.0).to(tl.float32) else: v = tl.load(bs_ptr + s_i64 * H + k, mask=km, other=0.0).to(tl.float32) ss += tl.sum(v * v, axis=0) qv = tl.load(q_ptr + q_i64[:, None] * H + k[None, :], mask=qm[:, None] & km[None, :], other=0.0).to(tl.float32) acc += tl.sum(qv * v[None, :], axis=1) inv_r = tl.rsqrt(ss / H + 1.0e-6) tl.store(inv_rms_ptr + s, inv_r) scale = inv_r * tl.rsqrt(tl.cast(H, tl.float32)) S_tot = S_prev + 1 tl.store(scores_ptr + q_i64 * S_tot + s, acc * scale, mask=qm) @triton.jit def _router_topk_kernel( logits_ptr, bias_ptr, out_w_ptr, out_idx_ptr, scale, E: tl.constexpr, TOP_K: tl.constexpr, ): """Single-CTA fused sigmoid + bias + top-K + gather + normalize * scale (4.25x faster than 4 PyTorch kernels).""" offs = tl.arange(0, E) logits = tl.load(logits_ptr + offs).to(tl.float32) bias = tl.load(bias_ptr + offs).to(tl.float32) scores = tl.sigmoid(logits) biased = scores + bias w_sum = 0.0 for k in tl.static_range(0, TOP_K): idx = tl.argmax(biased, axis=0) w_k = tl.sum(tl.where(offs == idx, scores, 0.0), axis=0) w_sum += w_k tl.store(out_idx_ptr + k, idx.to(tl.int64)) tl.store(out_w_ptr + k, w_k) biased = tl.where(offs == idx, -1.0e30, biased) inv_sum = scale / (w_sum + 1.0e-20) k_offs = tl.arange(0, TOP_K) wk_all = tl.load(out_w_ptr + k_offs) * inv_sum tl.store(out_w_ptr + k_offs, wk_all) @triton.jit def _unweighted_rmsnorm_kernel( x_ptr, out_ptr, eps, D: tl.constexpr, ): """Single-kernel unweighted RMSNorm along last dim D (power-of-2; 8x faster than 4-op eager path).""" row = tl.program_id(0).to(tl.int64) d = tl.arange(0, D) xv = tl.load(x_ptr + row * D + d).to(tl.float32) inv_r = tl.rsqrt(tl.sum(xv * xv, axis=0) / D + eps) tl.store(out_ptr + row * D + d, (xv * inv_r).to(out_ptr.dtype.element_ty)) @triton.jit def _attn_res_stage2_kernel( bs_ptr, # [S_prev, H] part_ptr, # [H] inv_rms_ptr, # [S] fp32 scores_ptr, # [Q, S] fp32 out_ptr, # [Q, H] fp32 S_prev, H, Q, Q_PAD: tl.constexpr, S_PAD: tl.constexpr, BLOCK_H: tl.constexpr, ): """Applies exact softmax over S states and accumulates weighted normalized states -> [Q, H] fp32.""" pid = tl.program_id(0) h = pid * BLOCK_H + tl.arange(0, BLOCK_H) hm = h < H h_i64 = h.to(tl.int64) S_tot = S_prev + 1 s_offs = tl.arange(0, S_PAD) s_mask = s_offs < S_tot q_offs = tl.arange(0, Q_PAD) qm = q_offs < Q q_i64 = q_offs.to(tl.int64) # Load scores [Q_PAD, S_PAD] and compute softmax over axis=1 sc = tl.load( scores_ptr + q_i64[:, None] * S_tot + s_offs[None, :], mask=qm[:, None] & s_mask[None, :], other=-1.0e9, ) sc_max = tl.max(sc, axis=1)[:, None] ex = tl.where(s_mask[None, :], tl.exp(sc - sc_max), 0.0) w = ex / tl.sum(ex, axis=1)[:, None] # [Q_PAD, S_PAD] inv_r = tl.load(inv_rms_ptr + s_offs, mask=s_mask, other=0.0) # [S_PAD] w_eff = w * inv_r[None, :] # [Q_PAD, S_PAD] acc = tl.zeros((Q_PAD, BLOCK_H), dtype=tl.float32) for s in range(0, S_tot): if s == S_prev: v = tl.load(part_ptr + h, mask=hm, other=0.0).to(tl.float32) else: v = tl.load(bs_ptr + tl.cast(s, tl.int64) * H + h, mask=hm, other=0.0).to(tl.float32) ws = tl.sum(tl.where(s_offs[None, :] == s, w_eff, 0.0), axis=1) # [Q_PAD] acc += ws[:, None] * v[None, :] tl.store(out_ptr + q_i64[:, None] * H + h_i64[None, :], acc, mask=qm[:, None] & hm[None, :]) @triton.jit def _kv_cache_write_kernel( k_new_ptr, # [H_kv, D] v_new_ptr, # [H_kv, D] k_cache_ptr, # [H_kv, L, D] v_cache_ptr, # [H_kv, L, D] cur_pos_ptr, # [1] int64 L, IS_SLIDING: tl.constexpr, SLIDING_MASK: tl.constexpr, D: tl.constexpr, ): """Writes single-token K/V into StaticCache at `pos` (full) or `pos & (W-1)` (ring-buffer sliding).""" h = tl.program_id(0) d = tl.arange(0, D) pos = tl.load(cur_pos_ptr).to(tl.int64) slot = (pos & SLIDING_MASK) if IS_SLIDING else pos src_off = h.to(tl.int64) * D + d dst_off = (h.to(tl.int64) * L + slot) * D + d tl.store(k_cache_ptr + dst_off, tl.load(k_new_ptr + src_off)) tl.store(v_cache_ptr + dst_off, tl.load(v_new_ptr + src_off)) @triton.jit def _inkling2_decode_attn_kernel( q_ptr, # [H_q, D] bf16 k_cache_ptr, # [H_kv, L, D] bf16 v_cache_ptr, # [H_kv, L, D] bf16 rel_s_ptr, # [H_q, D_REL] bf16 rel_p_ptr, # [D_REL, REL_EXTENT] bf16 sinks_ptr, # [H_q] bf16 cur_pos_ptr, # [1] int64 out_ptr, # [H_q, D] bf16 L, scaling, GQA_GROUPS: tl.constexpr, IS_SLIDING: tl.constexpr, SLIDING_WIN: tl.constexpr, REL_EXTENT: tl.constexpr, D: tl.constexpr, D_REL: tl.constexpr, BLOCK_N: tl.constexpr, ): """ Exact fused GQA + RelativePositionBias + Per-Head Sink + Ring-Buffer Sliding/Full Decode Attention. Zero `repeat_kv`, zero `[H_q, L]` materialization, dynamic loop bound `j0 < n_valid` inside CUDA Graph. """ h = tl.program_id(0) kv_h = h // GQA_GROUPS d = tl.arange(0, D) r_idx = tl.arange(0, D_REL) q = tl.load(q_ptr + h.to(tl.int64) * D + d).to(tl.float32) * scaling rs = tl.load(rel_s_ptr + h.to(tl.int64) * D_REL + r_idx).to(tl.float32) sink = tl.load(sinks_ptr + h).to(tl.float32) cur_pos = tl.load(cur_pos_ptr).to(tl.int32) n_valid = tl.minimum(cur_pos + 1, SLIDING_WIN) if IS_SLIDING else (cur_pos + 1) # Exact attention sink initialization: one extra logit `sink` with zero value vector m_i = sink l_i = 1.0 acc = tl.zeros((D,), dtype=tl.float32) kv_base = kv_h.to(tl.int64) * L * D n_offs = tl.arange(0, BLOCK_N) j0 = 0 while j0 < n_valid: j = j0 + n_offs j_mask = j < n_valid j_i64 = j.to(tl.int64) kv_off = kv_base + j_i64[:, None] * D + d[None, :] k_tile = tl.load(k_cache_ptr + kv_off, mask=j_mask[:, None], other=0.0).to(tl.float32) scores = tl.sum(k_tile * q[None, :], axis=1) if IS_SLIDING: dist = (cur_pos - j) & (SLIDING_WIN - 1) else: dist = cur_pos - j in_rel = j_mask & (dist >= 0) & (dist < REL_EXTENT) dist_safe = tl.where(in_rel, dist, 0).to(tl.int64) rp_off = r_idx[:, None].to(tl.int64) * REL_EXTENT + dist_safe[None, :] rp_tile = tl.load(rel_p_ptr + rp_off, mask=in_rel[None, :], other=0.0).to(tl.float32) bias = tl.sum(rp_tile * rs[:, None], axis=0) scores = scores + tl.where(in_rel, bias, 0.0) scores = tl.where(j_mask, scores, -1.0e9) m_blk = tl.max(scores, axis=0) m_new = tl.maximum(m_i, m_blk) alpha = tl.exp(m_i - m_new) p = tl.where(j_mask, tl.exp(scores - m_new), 0.0) l_i = l_i * alpha + tl.sum(p, axis=0) v_tile = tl.load(v_cache_ptr + kv_off, mask=j_mask[:, None], other=0.0).to(tl.float32) acc = acc * alpha + tl.sum(p[:, None] * v_tile, axis=0) m_i = m_new j0 += BLOCK_N out = acc / l_i tl.store(out_ptr + h.to(tl.int64) * D + d, out.to(out_ptr.dtype.element_ty)) def short_conv1d_step_res_triton( x: torch.Tensor, conv_state: torch.Tensor, weight_2d: torch.Tensor, ) -> torch.Tensor: """Fast Triton 4-tap static short conv update + residual / sqrt(5) for `[1, 1, C]` decode.""" C = x.shape[-1] out = torch.empty_like(x) BLOCK_C = 256 _short_conv1d_step_res_kernel[(triton.cdiv(C, BLOCK_C),)]( x.contiguous(), conv_state, weight_2d.contiguous(), out, C, INV_SCALE=1.0 / math.sqrt(5.0), BLOCK_C=BLOCK_C, num_warps=4, ) return out def dense_gemv_triton(x_1d: torch.Tensor, weight_2d: torch.Tensor, out_dtype: Optional[torch.dtype] = None) -> torch.Tensor: """Fast coalesced M=1 Triton GEMV for small/medium FP32/BF16 linear layers.""" rows, cols = weight_2d.shape dt = out_dtype if out_dtype is not None else x_1d.dtype out = torch.empty((rows,), device=weight_2d.device, dtype=dt) BLOCK_R = 4 if rows <= 128 else 8 _dense_gemv_kernel[(triton.cdiv(rows, BLOCK_R),)]( x_1d.contiguous(), weight_2d.contiguous(), out, rows, cols, BLOCK_R=BLOCK_R, BLOCK_K=256, num_warps=4, ) return out def dyn_short_conv1d_step_res_triton( x: torch.Tensor, dynamic_input: torch.Tensor, conv_state: torch.Tensor, static_weight: torch.Tensor, weight_proj_w: torch.Tensor, num_heads: int, ) -> torch.Tensor: """Fast Triton 4-tap dynamic+static short conv update + residual / 3 for `[1, 1, C]` decode.""" C = x.shape[-1] dyn_w = dense_gemv_triton(dynamic_input.view(-1), weight_proj_w, out_dtype=torch.float32) out = torch.empty_like(x) BLOCK_C = 256 _dyn_short_conv1d_step_res_kernel[(triton.cdiv(C, BLOCK_C),)]( x.contiguous(), conv_state, static_weight.contiguous(), dyn_w, out, C, HEAD_DIM=C // num_heads, INV_SCALE=1.0 / 3.0, BLOCK_C=BLOCK_C, num_warps=4, ) return out def message_gate_triton( h: torch.Tensor, m: torch.Tensor, w_dn: torch.Tensor, w_fg: torch.Tensor, w_mg: torch.Tensor, eps: float, ) -> torch.Tensor: """Exact 2-kernel fused Triton Inkling2LoopMessageGate for `B*T == 1` (returns fp32 `[1, 1, H]`).""" R, two_H = w_dn.shape H = two_H // 2 g = torch.empty((R,), device=h.device, dtype=torch.float32) BLOCK_R = 2 _msg_gate_stage1_kernel[(triton.cdiv(R, BLOCK_R),)]( h.contiguous(), m.contiguous(), w_dn.contiguous(), g, R, H, eps, BLOCK_R=BLOCK_R, BLOCK_K=512, num_warps=2, ) out = torch.empty(h.shape, device=h.device, dtype=torch.float32) BLOCK_H = 32 _msg_gate_stage2_kernel[(triton.cdiv(H, BLOCK_H),)]( h.contiguous(), m.contiguous(), g, w_fg.contiguous(), w_mg.contiguous(), out, H, R=R, BLOCK_H=BLOCK_H, num_warps=4, ) return out def router_topk_triton( logits: torch.Tensor, bias: torch.Tensor, top_k: int, scale: float, ) -> tuple[torch.Tensor, torch.Tensor]: """Single-CTA fused sigmoid + bias + top-K + gather + normalize * scale for `B*T == 1`.""" E = int(bias.shape[-1]) w_out = torch.empty((1, top_k), device=logits.device, dtype=torch.float32) i_out = torch.empty((1, top_k), device=logits.device, dtype=torch.long) _router_topk_kernel[(1,)]( logits.contiguous(), bias.contiguous(), w_out, i_out, float(scale), E=E, TOP_K=int(top_k), num_warps=2, ) return w_out, i_out def unweighted_rmsnorm_triton(x: torch.Tensor, eps: float) -> torch.Tensor: """Single-kernel unweighted RMSNorm along last dim D (power-of-2; 8x faster than eager).""" D = int(x.shape[-1]) x_c = x.contiguous() out = torch.empty_like(x_c) n_rows = x_c.numel() // D _unweighted_rmsnorm_kernel[(n_rows,)](x_c, out, float(eps), D=D, num_warps=2) return out def attn_res_step_triton( block_states: torch.Tensor, partial: torch.Tensor, query: torch.Tensor, ) -> torch.Tensor: """Exact 2-kernel fused Triton Block/Message Attention Residual for `B=1, T=1` -> `[1, 1, Q, H]` fp32.""" S_prev = int(block_states.shape[-2]) H = int(partial.shape[-1]) q_2d = query.view(-1, H).contiguous() Q = int(q_2d.shape[0]) Q_PAD = 1 << (Q - 1).bit_length() S_tot = S_prev + 1 S_PAD = 1 << (S_tot - 1).bit_length() if S_PAD < 2: S_PAD = 2 inv_rms = torch.empty((S_tot,), device=partial.device, dtype=torch.float32) scores = torch.empty((Q, S_tot), device=partial.device, dtype=torch.float32) bs_c = block_states.contiguous() p_c = partial.contiguous() _attn_res_stage1_kernel[(S_tot,)]( bs_c, p_c, q_2d, inv_rms, scores, S_prev, H, Q, Q_PAD=Q_PAD, BLOCK_K=512, num_warps=4, ) out = torch.empty((1, 1, Q, H), device=partial.device, dtype=torch.float32) BLOCK_H = 64 _attn_res_stage2_kernel[(triton.cdiv(H, BLOCK_H),)]( bs_c, p_c, inv_rms, scores, out, S_prev, H, Q, Q_PAD=Q_PAD, S_PAD=S_PAD, BLOCK_H=BLOCK_H, num_warps=2, ) return out def inkling2_decode_attn_triton( q: torch.Tensor, # [1, 24, 1, 128] k_new: torch.Tensor, # [1, 8, 1, 128] v_new: torch.Tensor, # [1, 8, 1, 128] k_cache: torch.Tensor, # [1, 8, L, 128] v_cache: torch.Tensor, # [1, 8, L, 128] rel_states: torch.Tensor, # [1, 1, 24, 16] rel_proj: torch.Tensor, # [16, 1024] sinks: torch.Tensor, # [1, 24, 1, 1] or [24] cur_pos: torch.Tensor, # [1] int64 scaling: float, is_sliding: bool, sliding_window: int = 1024, rel_extent: int = 1024, ) -> torch.Tensor: """Writes single-token K/V into cache and runs exact fused GQA+RelBias+Sink attention -> `[1, 1, 24, 128]`.""" H_q = int(q.shape[1]) H_kv = int(k_cache.shape[1]) L = int(k_cache.shape[2]) D = int(q.shape[-1]) D_rel = int(rel_states.shape[-1]) _kv_cache_write_kernel[(H_kv,)]( k_new.contiguous(), v_new.contiguous(), k_cache, v_cache, cur_pos, L, IS_SLIDING=is_sliding, SLIDING_MASK=sliding_window - 1, D=D, num_warps=2, ) out = torch.empty((1, 1, H_q, D), device=q.device, dtype=q.dtype) _inkling2_decode_attn_kernel[(H_q,)]( q.contiguous(), k_cache, v_cache, rel_states.contiguous(), rel_proj.contiguous(), sinks.contiguous(), cur_pos, out, L, scaling, GQA_GROUPS=H_q // H_kv, IS_SLIDING=is_sliding, SLIDING_WIN=sliding_window, REL_EXTENT=rel_extent, D=D, D_REL=D_rel, BLOCK_N=64, num_warps=4, ) return out