"""Fused W4A16 decode solution for the Kimi-Linear hybrid block. Design (see kernels.py for the actual Triton kernels): 1. Every big projection (KDA q/k/v/g/o, MLA q/kv_a/kv_b/o, MoE gate/up/down) is evaluated with a fused int4 dequant-GEMV that streams the packed weight exactly once -- the int4 bytes are read, dequantized in registers against the per-group scale/zero, and reduced against the activation vector in one pass. The dequantized bf16 matrix is never materialized anywhere. 2. MLA decode never recomputes k_nope/v for the whole growing cache every step (that is what reference.py/baseline.py do, and it is O(context_len) compute per step). Instead it uses matrix absorption: q_nope is projected once through kv_b's nope-half ("qabs"), attention scores + softmax + latent aggregation are fused into one kernel that only reads the compressed cache, and the aggregated latent is projected once through kv_b's v-half ("oabs"). kv_b's weight is streamed O(1) times per step, not O(context_len). 3. The KDA gated-delta-rule state update (decay, delta rule, readout) is one Triton kernel per head instead of ~6 separate elementwise PyTorch ops, so the recurrent state is read and written once instead of several times. 4. Weight buffers that share an input activation (KDA's q/k/v/g, MLA's q_proj/kv_a, MoE's routed+shared experts) are lazily concatenated once (on first `step()`, i.e. during warmup) into single fused buffers so decode issues far fewer kernel launches per token. 5. The MLA latent cache (c_kv, k_rope) is grown with an amortized-doubling buffer instead of reallocating + copying the whole cache every step, so a step's cost stays close to O(1) append instead of O(context_len) copy. Buffer/parameter names mirror reference.py exactly so `load_state_dict` from the reference model's state dict works unmodified. """ from __future__ import annotations import kernels import torch import torch.nn as nn import torch.nn.functional as F import triton # noqa: F401 -- solution.py's actual compute is the @triton.jit kernels in kernels.py EPS = 1.0e-6 GROUP_SIZE = 128 # --------------------------------------------------------------------------- # # quantized weight containers (buffer names/shapes match reference.py exactly # so `sol_model.load_state_dict(ref_model.state_dict(), strict=True)` works) # --------------------------------------------------------------------------- # class QuantLinear(nn.Module): def __init__(self, in_f: int, out_f: int, group: int = GROUP_SIZE): super().__init__() assert in_f % group == 0 and in_f % 2 == 0 self.in_f, self.out_f, self.group = in_f, out_f, group ng = in_f // group self.register_buffer("w_q", torch.zeros(in_f // 2, out_f, dtype=torch.uint8)) self.register_buffer("scales", torch.zeros(ng, out_f, dtype=torch.bfloat16)) self.register_buffer("zeros", torch.zeros(ng, out_f, dtype=torch.bfloat16)) def forward(self, x: torch.Tensor) -> torch.Tensor: y = kernels.qgemv_single(x, self.w_q, self.scales, self.zeros, self.in_f, self.out_f, self.group) return y.to(torch.bfloat16) class QuantExperts(nn.Module): def __init__(self, n: int, in_f: int, out_f: int, group: int = GROUP_SIZE): super().__init__() self.n, self.in_f, self.out_f, self.group = n, in_f, out_f, group ng = in_f // group self.register_buffer("w_q", torch.zeros(n, in_f // 2, out_f, dtype=torch.uint8)) self.register_buffer("scales", torch.zeros(n, ng, out_f, dtype=torch.bfloat16)) self.register_buffer("zeros", torch.zeros(n, ng, out_f, dtype=torch.bfloat16)) # --------------------------------------------------------------------------- # # helpers # --------------------------------------------------------------------------- # def _rmsnorm(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor: return kernels.rmsnorm(x, w, EPS) # --------------------------------------------------------------------------- # # KDA: gated-delta linear attention with fixed-size recurrent state # --------------------------------------------------------------------------- # class KDA(nn.Module): def __init__(self, cfg): super().__init__() self.cfg = cfg H, Dk, d = cfg.kda_heads, cfg.kda_head_dim, cfg.hidden self.q_proj = QuantLinear(d, H * Dk, cfg.group) self.k_proj = QuantLinear(d, H * Dk, cfg.group) self.v_proj = QuantLinear(d, H * Dk, cfg.group) self.g_proj = QuantLinear(d, H * Dk, cfg.group) self.beta_proj = nn.Linear(d, H, bias=False, dtype=cfg.dtype) self.conv_w = nn.Parameter(torch.empty(3, H * Dk, cfg.short_conv, dtype=cfg.dtype)) self.o_proj = QuantLinear(H * Dk, d, cfg.group) self.scale = Dk ** -0.5 self._fused = False def _fuse(self): self.qkvg_wq = torch.cat( [self.q_proj.w_q, self.k_proj.w_q, self.v_proj.w_q, self.g_proj.w_q], dim=1 ).contiguous() self.qkvg_s = torch.cat( [self.q_proj.scales, self.k_proj.scales, self.v_proj.scales, self.g_proj.scales], dim=1 ).contiguous() self.qkvg_z = torch.cat( [self.q_proj.zeros, self.k_proj.zeros, self.v_proj.zeros, self.g_proj.zeros], dim=1 ).contiguous() self._fused = True def step(self, x, st): if not self._fused: self._fuse() cfg = self.cfg H, Dk = cfg.kda_heads, cfg.kda_head_dim Dout = H * Dk qkvg = kernels.qgemv_single(x, self.qkvg_wq, self.qkvg_s, self.qkvg_z, cfg.hidden, 4 * Dout, cfg.group) qkv_raw = qkvg[:3 * Dout].to(torch.bfloat16).view(3, Dout) g_raw = qkvg[3 * Dout:4 * Dout] q, st["cq"] = kernels.short_conv(qkv_raw[0], st["cq"], self.conv_w[0]) k, st["ck"] = kernels.short_conv(qkv_raw[1], st["ck"], self.conv_w[1]) v, st["cv"] = kernels.short_conv(qkv_raw[2], st["cv"], self.conv_w[2]) q = (q.view(H, Dk).float() * self.scale).contiguous() k = k.view(H, Dk).float().contiguous() v = v.view(H, Dk).float().contiguous() g = (-F.softplus(g_raw)).view(H, Dk).contiguous() beta = torch.sigmoid(self.beta_proj(x).float()).contiguous() o, S_new = kernels.kda_recurrence(st["S"], k, v, q, g, beta, Dk) st["S"] = S_new o_bf = o.reshape(Dout).to(torch.bfloat16) return self.o_proj(o_bf) # --------------------------------------------------------------------------- # # MLA: multi-head latent attention with absorbed decode # --------------------------------------------------------------------------- # class MLA(nn.Module): def __init__(self, cfg): super().__init__() self.cfg = cfg H, d = cfg.mla_heads, cfg.hidden self.q_proj = QuantLinear(d, H * (cfg.qk_nope + cfg.qk_rope), cfg.group) self.kv_a = QuantLinear(d, cfg.kv_lora + cfg.qk_rope, cfg.group) self.kv_b = QuantLinear(cfg.kv_lora, H * (cfg.qk_nope + cfg.v_head), cfg.group) self.o_proj = QuantLinear(H * cfg.v_head, d, cfg.group) self.scale = (cfg.qk_nope + cfg.qk_rope) ** -0.5 self._fused = False def _fuse(self): self.qkva_wq = torch.cat([self.q_proj.w_q, self.kv_a.w_q], dim=1).contiguous() self.qkva_s = torch.cat([self.q_proj.scales, self.kv_a.scales], dim=1).contiguous() self.qkva_z = torch.cat([self.q_proj.zeros, self.kv_a.zeros], dim=1).contiguous() self._fused = True def step(self, x, st): if not self._fused: self._fuse() cfg = self.cfg H = cfg.mla_heads pos = st["_len"] Nq = H * (cfg.qk_nope + cfg.qk_rope) Nkva = cfg.kv_lora + cfg.qk_rope out = kernels.qgemv_single(x, self.qkva_wq, self.qkva_s, self.qkva_z, cfg.hidden, Nq + Nkva, cfg.group) q = out[:Nq].view(H, cfg.qk_nope + cfg.qk_rope) # non-contiguous views are fine here: mla_qabs takes explicit strides, # and apply_rope's internal .float() cast already materializes a copy. q_nope = q[:, :cfg.qk_nope] q_rope_raw = q[:, cfg.qk_nope:] c_kv_new = out[Nq:Nq + cfg.kv_lora].to(torch.bfloat16) k_rope_new = out[Nq + cfg.kv_lora:].to(torch.bfloat16) cos, sin = kernels.rope_cossin(pos, cfg.qk_rope, cfg.rope_theta, x.device) q_rope = kernels.apply_rope(q_rope_raw, cos, sin) k_rope_new = kernels.apply_rope(k_rope_new, cos, sin).to(torch.bfloat16) _cache_append(st, "c_kv", c_kv_new, cfg.kv_lora) _cache_append(st, "k_rope", k_rope_new, cfg.qk_rope) st["_len"] += 1 c_kv_view = st["c_kv"][: st["_len"]] k_rope_view = st["k_rope"][: st["_len"]] qabs = kernels.mla_qabs(q_nope, self.kv_b.w_q, self.kv_b.scales, self.kv_b.zeros, H, cfg.qk_nope, cfg.v_head, cfg.kv_lora, cfg.group) ctx_agg = kernels.mla_attend(qabs, q_rope, c_kv_view, k_rope_view, self.scale, cfg.kv_lora, cfg.qk_rope) o = kernels.mla_oabs(ctx_agg, self.kv_b.w_q, self.kv_b.scales, self.kv_b.zeros, H, cfg.qk_nope, cfg.v_head, cfg.kv_lora, cfg.group) o_bf = o.reshape(H * cfg.v_head).to(torch.bfloat16) return self.o_proj(o_bf) def _cache_append(st, key, row, width): """Amortized-growth append: state[key] always exposes an exact-length view (st["_len"] + 1 rows) but the backing buffer over-allocates so most steps are an O(1) write instead of an O(context_len) torch.cat copy.""" buf_key = "_buf_" + key cap_key = "_cap_" + key cur_len = st["_len"] buf = st.get(buf_key) if buf is None: existing = st[key] cap = max(existing.shape[0] * 2, existing.shape[0] + 64) buf = torch.empty((cap, width), dtype=row.dtype, device=row.device) buf[:cur_len] = existing st[buf_key] = buf st[cap_key] = cap elif cur_len >= st[cap_key]: new_cap = st[cap_key] * 2 new_buf = torch.empty((new_cap, width), dtype=buf.dtype, device=buf.device) new_buf[:cur_len] = buf[:cur_len] buf = new_buf st[buf_key] = buf st[cap_key] = new_cap buf[cur_len] = row st[key] = buf[: cur_len + 1] # --------------------------------------------------------------------------- # # MoE: 64-expert top-8 routed + 1 shared, fused batched dequant-GEMV # --------------------------------------------------------------------------- # class MoE(nn.Module): def __init__(self, cfg): super().__init__() self.cfg = cfg d, m, E = cfg.hidden, cfg.moe_inter, cfg.n_experts self.router = nn.Linear(d, E, bias=False, dtype=cfg.dtype) self.gate = QuantExperts(E, d, m, cfg.group) self.up = QuantExperts(E, d, m, cfg.group) self.down = QuantExperts(E, m, d, cfg.group) self.s_gate = QuantExperts(cfg.n_shared, d, m, cfg.group) self.s_up = QuantExperts(cfg.n_shared, d, m, cfg.group) self.s_down = QuantExperts(cfg.n_shared, m, d, cfg.group) self._fused = False def _fuse(self): self.gate_wq = torch.cat([self.gate.w_q, self.s_gate.w_q], dim=0).contiguous() self.gate_s = torch.cat([self.gate.scales, self.s_gate.scales], dim=0).contiguous() self.gate_z = torch.cat([self.gate.zeros, self.s_gate.zeros], dim=0).contiguous() self.up_wq = torch.cat([self.up.w_q, self.s_up.w_q], dim=0).contiguous() self.up_s = torch.cat([self.up.scales, self.s_up.scales], dim=0).contiguous() self.up_z = torch.cat([self.up.zeros, self.s_up.zeros], dim=0).contiguous() self.down_wq = torch.cat([self.down.w_q, self.s_down.w_q], dim=0).contiguous() self.down_s = torch.cat([self.down.scales, self.s_down.scales], dim=0).contiguous() self.down_z = torch.cat([self.down.zeros, self.s_down.zeros], dim=0).contiguous() self._fused = True def step(self, x): if not self._fused: self._fuse() cfg = self.cfg probs = torch.softmax(self.router(x).float(), dim=-1) w, idx = torch.topk(probs, cfg.n_active) w = w / (w.sum() + 1e-9) * cfg.routed_scaling shared_idx = torch.arange(cfg.n_experts, cfg.n_experts + cfg.n_shared, device=x.device, dtype=idx.dtype) idx_all = torch.cat([idx, shared_idx]) weights_all = torch.cat([w, torch.ones(cfg.n_shared, device=x.device, dtype=w.dtype)]) g = kernels.qgemv(x, self.gate_wq, self.gate_s, self.gate_z, idx_all, cfg.hidden, cfg.moe_inter, cfg.group) u = kernels.qgemv(x, self.up_wq, self.up_s, self.up_z, idx_all, cfg.hidden, cfg.moe_inter, cfg.group) h = F.silu(g) * u d = kernels.qgemv(h, self.down_wq, self.down_s, self.down_z, idx_all, cfg.moe_inter, cfg.hidden, cfg.group, x_per_batch=True) out = (weights_all[:, None] * d).sum(0) return out.to(torch.bfloat16) # --------------------------------------------------------------------------- # # Block / Model # --------------------------------------------------------------------------- # class Block(nn.Module): def __init__(self, cfg, kind: str): super().__init__() self.kind = kind self.attn_norm = nn.Parameter(torch.ones(cfg.hidden, dtype=cfg.dtype)) self.moe_norm = nn.Parameter(torch.ones(cfg.hidden, dtype=cfg.dtype)) self.attn = KDA(cfg) if kind == "K" else MLA(cfg) self.moe = MoE(cfg) def step(self, x, st): h = x + self.attn.step(_rmsnorm(x, self.attn_norm), st) return h + self.moe.step(_rmsnorm(h, self.moe_norm)) class Model(nn.Module): def __init__(self, cfg): super().__init__() self.cfg = cfg self.blocks = nn.ModuleList(Block(cfg, k) for k in cfg.pattern) def step(self, hidden, state): for i, blk in enumerate(self.blocks): if blk.kind == "M" and "_len" not in state[i]: state[i]["_len"] = state[i]["c_kv"].shape[0] hidden = blk.step(hidden, state[i]) return hidden, state # ================================================================== # ===== sidecar: kernels.py (22434 bytes, loaded by solution.py) ===== # ================================================================== """Triton kernels for batch-1 W4A16 decode: fused int4 dequant-GEMV plus the MLA matrix-absorption and KDA delta-rule recurrence, so weights stream through as int4 exactly once (never materialized as a full bf16 matrix). Core idea for the GEMV: per output column n, w[k,n] = (nibble[k,n] - zero[g,n]) * scale[g,n] with g = k // group constant within a 128-row group. For a fixed group, sum_k x[k]*w[k,n] = scale[g,n] * (dot(x, nibble[:,n]) - zero[g,n] * sum(x)) so we never need to materialize the dequantized tile before reducing. Packing is 2 int4 values per byte along k (even row -> low nibble, odd row -> high nibble), so each group of 128 rows is read as a (64, BLOCK_N) uint8 tile and split into even/odd contributions. """ from __future__ import annotations import torch import triton import triton.language as tl GROUP = 128 # --------------------------------------------------------------------------- # # Kernel 1: general batched / index-selected fused int4 dequant-GEMV. # y[e, n] = sum_k x[e or 0, k] * dequant(w_q[idx[e], k, n]) # --------------------------------------------------------------------------- # _GEMV_CONFIGS = [ triton.Config({"BLOCK_N": 32, "BLOCK_K": 128, "SPLIT_K": 1}, num_warps=4, num_stages=2), triton.Config({"BLOCK_N": 64, "BLOCK_K": 128, "SPLIT_K": 1}, num_warps=4, num_stages=2), triton.Config({"BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1}, num_warps=4, num_stages=2), triton.Config({"BLOCK_N": 32, "BLOCK_K": 128, "SPLIT_K": 4}, num_warps=4, num_stages=2), triton.Config({"BLOCK_N": 64, "BLOCK_K": 128, "SPLIT_K": 4}, num_warps=4, num_stages=2), triton.Config({"BLOCK_N": 32, "BLOCK_K": 128, "SPLIT_K": 8}, num_warps=4, num_stages=2), triton.Config({"BLOCK_N": 64, "BLOCK_K": 128, "SPLIT_K": 8}, num_warps=4, num_stages=2), triton.Config({"BLOCK_N": 32, "BLOCK_K": 128, "SPLIT_K": 16}, num_warps=4, num_stages=2), triton.Config({"BLOCK_N": 64, "BLOCK_K": 128, "SPLIT_K": 16}, num_warps=4, num_stages=2), triton.Config({"BLOCK_N": 16, "BLOCK_K": 128, "SPLIT_K": 16}, num_warps=2, num_stages=2), triton.Config({"BLOCK_N": 64, "BLOCK_K": 256, "SPLIT_K": 4}, num_warps=8, num_stages=2), triton.Config({"BLOCK_N": 128, "BLOCK_K": 256, "SPLIT_K": 1}, num_warps=8, num_stages=2), ] @triton.autotune(configs=_GEMV_CONFIGS, key=["K", "N"], reset_to_zero=["y_ptr"]) @triton.jit def _qgemv_kernel( x_ptr, stride_xe, stride_xk, wq_ptr, stride_we, stride_wk, stride_wn, scale_ptr, zero_ptr, stride_se, stride_sg, stride_sn, idx_ptr, y_ptr, stride_ye, stride_yn, K, N, GROUP_SZ: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, SPLIT_K: tl.constexpr, ): pid_e = tl.program_id(0) pid_n = tl.program_id(1) pid_k = tl.program_id(2) e_sel = tl.load(idx_ptr + pid_e).to(tl.int64) n_offs = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) n_mask = n_offs < N x_base = x_ptr + pid_e * stride_xe wq_base = wq_ptr + e_sel * stride_we s_base = scale_ptr + e_sel * stride_se z_base = zero_ptr + e_sel * stride_se acc = tl.zeros((BLOCK_N,), dtype=tl.float32) GROUPS_PER_BLOCK: tl.constexpr = BLOCK_K // GROUP_SZ RPG: tl.constexpr = GROUP_SZ // 2 n_kblocks = tl.cdiv(K, BLOCK_K) kblocks_per_split = tl.cdiv(n_kblocks, SPLIT_K) kb_start = pid_k * kblocks_per_split kb_end = tl.minimum(kb_start + kblocks_per_split, n_kblocks) for kb in range(kb_start, kb_end): kblock_start = kb * BLOCK_K for g in tl.static_range(0, GROUPS_PER_BLOCK): k0 = kblock_start + g * GROUP_SZ grp_idx = k0 // GROUP_SZ r_offs = tl.arange(0, RPG) packed_row = k0 // 2 + r_offs k_even = k0 + 2 * r_offs k_odd = k_even + 1 k_even_mask = k_even < K k_odd_mask = k_odd < K x_even = tl.load(x_base + k_even * stride_xk, mask=k_even_mask, other=0.0).to(tl.float32) x_odd = tl.load(x_base + k_odd * stride_xk, mask=k_odd_mask, other=0.0).to(tl.float32) w_ptrs = wq_base + packed_row[:, None] * stride_wk + n_offs[None, :] * stride_wn w_mask = k_even_mask[:, None] & n_mask[None, :] wb = tl.load(w_ptrs, mask=w_mask, other=0) lo = (wb & 0xF).to(tl.float32) hi = ((wb >> 4) & 0xF).to(tl.float32) s = tl.load(s_base + grp_idx * stride_sg + n_offs * stride_sn, mask=n_mask, other=0.0).to(tl.float32) z = tl.load(z_base + grp_idx * stride_sg + n_offs * stride_sn, mask=n_mask, other=0.0).to(tl.float32) xsum = tl.sum(x_even, axis=0) + tl.sum(x_odd, axis=0) dot = tl.sum(x_even[:, None] * lo, axis=0) + tl.sum(x_odd[:, None] * hi, axis=0) acc += s * (dot - z * xsum) y_ptrs = y_ptr + pid_e * stride_ye + n_offs * stride_yn if SPLIT_K == 1: tl.store(y_ptrs, acc, mask=n_mask) else: tl.atomic_add(y_ptrs, acc, mask=n_mask) _ZERO_IDX_CACHE: dict = {} def _zero_idx(device): if device not in _ZERO_IDX_CACHE: _ZERO_IDX_CACHE[device] = torch.zeros(1, dtype=torch.int64, device=device) return _ZERO_IDX_CACHE[device] def qgemv(x, w_q, scales, zeros, idx, K, N, group=GROUP, x_per_batch=False): """x: (K,) broadcast or (Esel,K) if x_per_batch. w_q: (Etot,K//2,N) uint8. scales/zeros: (Etot,K//group,N) bf16. idx: (Esel,) int64. -> (Esel,N) fp32.""" Esel = idx.shape[0] # zero-init: the autotuned config may pick SPLIT_K > 1, which accumulates # into y via atomic_add. y = torch.zeros((Esel, N), dtype=torch.float32, device=x.device) if x_per_batch: stride_xe, stride_xk = x.stride(0), x.stride(1) else: stride_xe, stride_xk = 0, x.stride(0) def grid(meta): return (Esel, triton.cdiv(N, meta["BLOCK_N"]), meta["SPLIT_K"]) _qgemv_kernel[grid]( x, stride_xe, stride_xk, w_q, w_q.stride(0), w_q.stride(1), w_q.stride(2), scales, zeros, scales.stride(0), scales.stride(1), scales.stride(2), idx, y, y.stride(0), y.stride(1), K, N, GROUP_SZ=group, ) return y def qgemv_single(x, w_q, scales, zeros, K, N, group=GROUP): """Single (K,N) matrix, x broadcast. Returns (N,) fp32.""" idx = _zero_idx(x.device) y = qgemv(x, w_q.unsqueeze(0), scales.unsqueeze(0), zeros.unsqueeze(0), idx, K, N, group) return y[0] # --------------------------------------------------------------------------- # # Kernel 2: MLA q-absorption (transposed read of kv_b's nope-half). # qabs[h,k] = sum_j q_nope[h,j] * dequant(kv_b_w)[k, h*head_stride + j] # --------------------------------------------------------------------------- # @triton.jit def _mla_qabs_kernel( qn_ptr, stride_qh, stride_qj, wq_ptr, stride_wr, stride_wn, scale_ptr, zero_ptr, stride_sg, stride_sn, out_ptr, stride_oh, stride_ok, HEAD_STRIDE_N: tl.constexpr, J: tl.constexpr, GROUP_SZ: tl.constexpr, ): h = tl.program_id(0) g = tl.program_id(1) j_offs = tl.arange(0, J) qn = tl.load(qn_ptr + h * stride_qh + j_offs * stride_qj).to(tl.float32) n_base = h * HEAD_STRIDE_N + j_offs s = tl.load(scale_ptr + g * stride_sg + n_base * stride_sn).to(tl.float32) z = tl.load(zero_ptr + g * stride_sg + n_base * stride_sn).to(tl.float32) scaled_q = qn * s zero_contrib = tl.sum(scaled_q * z, axis=0) RPG: tl.constexpr = GROUP_SZ // 2 r_offs = tl.arange(0, RPG) packed_row = g * RPG + r_offs w_ptrs = wq_ptr + packed_row[:, None] * stride_wr + n_base[None, :] * stride_wn wb = tl.load(w_ptrs) lo = (wb & 0xF).to(tl.float32) hi = ((wb >> 4) & 0xF).to(tl.float32) even_out = tl.sum(lo * scaled_q[None, :], axis=1) - zero_contrib odd_out = tl.sum(hi * scaled_q[None, :], axis=1) - zero_contrib k_even = g * GROUP_SZ + 2 * r_offs k_odd = k_even + 1 tl.store(out_ptr + h * stride_oh + k_even * stride_ok, even_out) tl.store(out_ptr + h * stride_oh + k_odd * stride_ok, odd_out) def mla_qabs(q_nope, w_q_kvb, scales_kvb, zeros_kvb, H, qk_nope, v_head, kv_lora, group=GROUP): out = torch.empty((H, kv_lora), dtype=torch.float32, device=q_nope.device) head_stride_n = qk_nope + v_head ng = kv_lora // group grid = (H, ng) _mla_qabs_kernel[grid]( q_nope, q_nope.stride(0), q_nope.stride(1), w_q_kvb, w_q_kvb.stride(0), w_q_kvb.stride(1), scales_kvb, zeros_kvb, scales_kvb.stride(0), scales_kvb.stride(1), out, out.stride(0), out.stride(1), HEAD_STRIDE_N=head_stride_n, J=qk_nope, GROUP_SZ=group, ) return out # --------------------------------------------------------------------------- # # Kernel 3: MLA o-absorption (natural-direction GEMV, per-head x + N-window). # o[h,d] = sum_k ctx_agg[h,k] * dequant(kv_b_w)[k, h*head_stride + v_offset + d] # --------------------------------------------------------------------------- # @triton.jit def _mla_oabs_kernel( ctx_ptr, stride_ch, stride_ck, wq_ptr, stride_wr, stride_wn, scale_ptr, zero_ptr, stride_sg, stride_sn, out_ptr, stride_oh, stride_od, HEAD_STRIDE_N: tl.constexpr, V_OFFSET: tl.constexpr, D: tl.constexpr, GROUP_SZ: tl.constexpr, K: tl.constexpr, ): h = tl.program_id(0) d_offs = tl.arange(0, D) n_offs = h * HEAD_STRIDE_N + V_OFFSET + d_offs acc = tl.zeros((D,), dtype=tl.float32) NG: tl.constexpr = K // GROUP_SZ RPG: tl.constexpr = GROUP_SZ // 2 for g in tl.static_range(0, NG): k0 = g * GROUP_SZ r_offs = tl.arange(0, RPG) packed_row = k0 // 2 + r_offs k_even = k0 + 2 * r_offs k_odd = k_even + 1 x_even = tl.load(ctx_ptr + h * stride_ch + k_even * stride_ck).to(tl.float32) x_odd = tl.load(ctx_ptr + h * stride_ch + k_odd * stride_ck).to(tl.float32) w_ptrs = wq_ptr + packed_row[:, None] * stride_wr + n_offs[None, :] * stride_wn wb = tl.load(w_ptrs) lo = (wb & 0xF).to(tl.float32) hi = ((wb >> 4) & 0xF).to(tl.float32) s = tl.load(scale_ptr + g * stride_sg + n_offs * stride_sn).to(tl.float32) z = tl.load(zero_ptr + g * stride_sg + n_offs * stride_sn).to(tl.float32) xsum = tl.sum(x_even, axis=0) + tl.sum(x_odd, axis=0) dot = tl.sum(x_even[:, None] * lo, axis=0) + tl.sum(x_odd[:, None] * hi, axis=0) acc += s * (dot - z * xsum) tl.store(out_ptr + h * stride_oh + d_offs * stride_od, acc) def mla_oabs(ctx_agg, w_q_kvb, scales_kvb, zeros_kvb, H, qk_nope, v_head, kv_lora, group=GROUP): out = torch.empty((H, v_head), dtype=torch.float32, device=ctx_agg.device) head_stride_n = qk_nope + v_head grid = (H,) _mla_oabs_kernel[grid]( ctx_agg, ctx_agg.stride(0), ctx_agg.stride(1), w_q_kvb, w_q_kvb.stride(0), w_q_kvb.stride(1), scales_kvb, zeros_kvb, scales_kvb.stride(0), scales_kvb.stride(1), out, out.stride(0), out.stride(1), HEAD_STRIDE_N=head_stride_n, V_OFFSET=qk_nope, D=v_head, GROUP_SZ=group, K=kv_lora, ) return out # --------------------------------------------------------------------------- # # Kernel 4: fused attention over the compressed latent cache (online softmax), # split across context chunks so a long cache gets real parallelism instead of # one sequential program per head. # score[l,h] = (qabs[h]·c_kv[l] + q_rope[h]·k_rope[l]) * scale # ctx_agg[h] = sum_l softmax_l(score[l,h]) * c_kv[l] # # Two-level split: grid=(H, N_CHUNKS) with N_CHUNKS FIXED (not scaling with # context length) -- each program online-softmaxes its L/N_CHUNKS-sized chunk # internally in small BLOCK_L sub-tiles (keeps per-program register/shared # footprint small; a naive single big tile per program hits a severe # occupancy/spill cliff). Pass 2 then only ever combines N_CHUNKS partials per # head, so the combine cost stays O(1) in context length instead of growing # with it. # --------------------------------------------------------------------------- # @triton.jit def _mla_attend_pass1_kernel( qabs_ptr, stride_qh, stride_qk, qrope_ptr, stride_rh, stride_rk, ckv_ptr, stride_cl, stride_ck, krope_ptr, stride_kl, stride_kk, m_ptr, stride_mh, stride_ml, l_ptr, stride_lh, stride_ll, acc_ptr, stride_ah, stride_al, stride_ak, L, scale, KV_LORA: tl.constexpr, QK_ROPE: tl.constexpr, BLOCK_L: tl.constexpr, N_CHUNKS: tl.constexpr, ): h = tl.program_id(0) cb = tl.program_id(1) k_offs = tl.arange(0, KV_LORA) r_offs = tl.arange(0, QK_ROPE) qabs_h = tl.load(qabs_ptr + h * stride_qh + k_offs * stride_qk).to(tl.float32) qrope_h = tl.load(qrope_ptr + h * stride_rh + r_offs * stride_rk).to(tl.float32) chunk_size = tl.cdiv(L, N_CHUNKS) chunk_start = cb * chunk_size chunk_end = tl.minimum(chunk_start + chunk_size, L) m_i = float("-inf") l_i = 0.0 acc = tl.zeros((KV_LORA,), dtype=tl.float32) for l0 in range(0, chunk_size, BLOCK_L): l_offs = chunk_start + l0 + tl.arange(0, BLOCK_L) l_mask = l_offs < chunk_end c_tile = tl.load( ckv_ptr + l_offs[:, None] * stride_cl + k_offs[None, :] * stride_ck, mask=l_mask[:, None], other=0.0, ).to(tl.float32) kr_tile = tl.load( krope_ptr + l_offs[:, None] * stride_kl + r_offs[None, :] * stride_kk, mask=l_mask[:, None], other=0.0, ).to(tl.float32) scores = tl.sum(c_tile * qabs_h[None, :], axis=1) + tl.sum(kr_tile * qrope_h[None, :], axis=1) scores = scores * scale scores = tl.where(l_mask, scores, float("-inf")) m_new = tl.maximum(tl.max(scores, axis=0), m_i) # m_i and m_new can both be -inf if neither this tile nor any prior # tile in the chunk had a valid element yet; exp(-inf - -inf) = nan, # so guard explicitly instead of relying on the subtraction. alpha = tl.where(m_i == float("-inf"), 0.0, tl.exp(m_i - m_new)) p = tl.where(l_mask, tl.exp(scores - m_new), 0.0) l_i = l_i * alpha + tl.sum(p, axis=0) acc = acc * alpha + tl.sum(p[:, None] * c_tile, axis=0) m_i = m_new tl.store(m_ptr + h * stride_mh + cb * stride_ml, m_i) tl.store(l_ptr + h * stride_lh + cb * stride_ll, l_i) tl.store(acc_ptr + h * stride_ah + cb * stride_al + k_offs * stride_ak, acc) @triton.jit def _mla_attend_pass2_kernel( m_ptr, stride_mh, stride_ml, l_ptr, stride_lh, stride_ll, acc_ptr, stride_ah, stride_al, stride_ak, out_ptr, stride_oh, stride_ok, KV_LORA: tl.constexpr, N_CHUNKS: tl.constexpr, ): h = tl.program_id(0) c_offs = tl.arange(0, N_CHUNKS) k_offs = tl.arange(0, KV_LORA) m = tl.load(m_ptr + h * stride_mh + c_offs * stride_ml) l_sum = tl.load(l_ptr + h * stride_lh + c_offs * stride_ll) acc = tl.load(acc_ptr + h * stride_ah + c_offs[:, None] * stride_al + k_offs[None, :] * stride_ak) m_global = tl.max(m, axis=0) alpha = tl.exp(m - m_global) l_global = tl.sum(alpha * l_sum, axis=0) acc_global = tl.sum(alpha[:, None] * acc, axis=0) ctx = acc_global / l_global tl.store(out_ptr + h * stride_oh + k_offs * stride_ok, ctx) def mla_attend(qabs, q_rope, c_kv_cache, k_rope_cache, scale, kv_lora, qk_rope, block_l=64, n_chunks=32): H = qabs.shape[0] L = c_kv_cache.shape[0] n_chunks = min(n_chunks, L) m = torch.empty((H, n_chunks), dtype=torch.float32, device=qabs.device) l_sum = torch.empty((H, n_chunks), dtype=torch.float32, device=qabs.device) acc = torch.empty((H, n_chunks, kv_lora), dtype=torch.float32, device=qabs.device) grid = (H, n_chunks) _mla_attend_pass1_kernel[grid]( qabs, qabs.stride(0), qabs.stride(1), q_rope, q_rope.stride(0), q_rope.stride(1), c_kv_cache, c_kv_cache.stride(0), c_kv_cache.stride(1), k_rope_cache, k_rope_cache.stride(0), k_rope_cache.stride(1), m, m.stride(0), m.stride(1), l_sum, l_sum.stride(0), l_sum.stride(1), acc, acc.stride(0), acc.stride(1), acc.stride(2), L, scale, KV_LORA=kv_lora, QK_ROPE=qk_rope, BLOCK_L=block_l, N_CHUNKS=n_chunks, ) out = torch.empty((H, kv_lora), dtype=torch.float32, device=qabs.device) _mla_attend_pass2_kernel[(H,)]( m, m.stride(0), m.stride(1), l_sum, l_sum.stride(0), l_sum.stride(1), acc, acc.stride(0), acc.stride(1), acc.stride(2), out, out.stride(0), out.stride(1), KV_LORA=kv_lora, N_CHUNKS=n_chunks, ) return out # --------------------------------------------------------------------------- # # Kernel 5: fused KDA gated-delta-rule recurrence (one head per program). # --------------------------------------------------------------------------- # @triton.jit def _kda_recurrence_kernel( S_ptr, stride_sh, stride_si, stride_sj, k_ptr, stride_kh, stride_ki, v_ptr, stride_vh, stride_vj, q_ptr, stride_qh, stride_qi, g_ptr, stride_gh, stride_gi, beta_ptr, stride_bh, o_ptr, stride_oh, stride_oj, Sout_ptr, stride_soh, stride_soi, stride_soj, DK: tl.constexpr, ): h = tl.program_id(0) i_offs = tl.arange(0, DK) j_offs = tl.arange(0, DK) S = tl.load(S_ptr + h * stride_sh + i_offs[:, None] * stride_si + j_offs[None, :] * stride_sj).to(tl.float32) k = tl.load(k_ptr + h * stride_kh + i_offs * stride_ki).to(tl.float32) v = tl.load(v_ptr + h * stride_vh + j_offs * stride_vj).to(tl.float32) q = tl.load(q_ptr + h * stride_qh + i_offs * stride_qi).to(tl.float32) g = tl.load(g_ptr + h * stride_gh + i_offs * stride_gi).to(tl.float32) beta = tl.load(beta_ptr + h * stride_bh).to(tl.float32) decay = tl.exp(g) S1 = S * decay[:, None] pred = tl.sum(S1 * k[:, None], axis=0) S2 = S1 + beta * k[:, None] * (v[None, :] - pred[None, :]) o = tl.sum(S2 * q[:, None], axis=0) tl.store(Sout_ptr + h * stride_soh + i_offs[:, None] * stride_soi + j_offs[None, :] * stride_soj, S2) tl.store(o_ptr + h * stride_oh + j_offs * stride_oj, o) def kda_recurrence(S, k, v, q, g, beta, DK): H = S.shape[0] S_out = torch.empty_like(S) o = torch.empty((H, DK), dtype=torch.float32, device=S.device) grid = (H,) _kda_recurrence_kernel[grid]( S, S.stride(0), S.stride(1), S.stride(2), k, k.stride(0), k.stride(1), v, v.stride(0), v.stride(1), q, q.stride(0), q.stride(1), g, g.stride(0), g.stride(1), beta, beta.stride(0), o, o.stride(0), o.stride(1), S_out, S_out.stride(0), S_out.stride(1), S_out.stride(2), DK=DK, ) return o, S_out # --------------------------------------------------------------------------- # # KDA short causal depthwise conv + SiLU, fused into one launch (replaces the # ~6 separate PyTorch ops -- cat, two float casts, mul, sum, silu -- that # batch-1 decode pays full kernel-launch overhead for, three times per block). # --------------------------------------------------------------------------- # @triton.jit def _short_conv_kernel( val_ptr, prev_ptr, stride_pp, stride_pc, w_ptr, stride_wc, stride_wp, out_ptr, newprev_ptr, stride_npp, stride_npc, C, WINDOW: tl.constexpr, BLOCK_C: tl.constexpr, ): pid = tl.program_id(0) c_offs = pid * BLOCK_C + tl.arange(0, BLOCK_C) c_mask = c_offs < C val = tl.load(val_ptr + c_offs, mask=c_mask, other=0.0).to(tl.float32) acc = tl.zeros((BLOCK_C,), dtype=tl.float32) for p in tl.static_range(0, WINDOW - 1): prev_p = tl.load(prev_ptr + p * stride_pp + c_offs * stride_pc, mask=c_mask, other=0.0).to(tl.float32) w_p = tl.load(w_ptr + c_offs * stride_wc + p * stride_wp, mask=c_mask, other=0.0).to(tl.float32) acc += prev_p * w_p if p > 0: tl.store(newprev_ptr + (p - 1) * stride_npp + c_offs * stride_npc, prev_p, mask=c_mask) w_last = tl.load(w_ptr + c_offs * stride_wc + (WINDOW - 1) * stride_wp, mask=c_mask, other=0.0).to(tl.float32) acc += val * w_last tl.store(newprev_ptr + (WINDOW - 2) * stride_npp + c_offs * stride_npc, val, mask=c_mask) sig = 1.0 / (1.0 + tl.exp(-acc)) tl.store(out_ptr + c_offs, acc * sig, mask=c_mask) def short_conv(val, prev, conv_w_slice, block_c=1024): """val: (C,) bf16 new value. prev: (WINDOW-1,C). conv_w_slice: (C,WINDOW). Returns (out (C,) bf16, new_prev (WINDOW-1,C) matching val's dtype).""" C = val.shape[0] window = conv_w_slice.shape[1] out = torch.empty(C, dtype=torch.float32, device=val.device) new_prev = torch.empty_like(prev) grid = (triton.cdiv(C, block_c),) _short_conv_kernel[grid]( val, prev, prev.stride(0), prev.stride(1), conv_w_slice, conv_w_slice.stride(0), conv_w_slice.stride(1), out, new_prev, new_prev.stride(0), new_prev.stride(1), C, WINDOW=window, BLOCK_C=block_c, ) return out.to(val.dtype), new_prev # --------------------------------------------------------------------------- # # RoPE helpers (kept in plain PyTorch -- tiny tensors, not bandwidth-critical). # --------------------------------------------------------------------------- # def rope_cossin(pos, dim, theta, device): inv = 1.0 / (theta ** (torch.arange(0, dim, 2, device=device, dtype=torch.float32) / dim)) ang = pos * inv return torch.cos(ang), torch.sin(ang) def apply_rope(x, cos, sin): xf = x.float() even, odd = xf[..., 0::2], xf[..., 1::2] out = torch.empty_like(xf) out[..., 0::2] = even * cos - odd * sin out[..., 1::2] = odd * cos + even * sin return out # --------------------------------------------------------------------------- # # Fused RMSNorm (single-block kernel; hidden fits in one program). # --------------------------------------------------------------------------- # @triton.jit def _rmsnorm_kernel(x_ptr, w_ptr, out_ptr, N, eps, BLOCK: tl.constexpr): offs = tl.arange(0, BLOCK) mask = offs < N x = tl.load(x_ptr + offs, mask=mask, other=0.0).to(tl.float32) w = tl.load(w_ptr + offs, mask=mask, other=0.0).to(tl.float32) ms = tl.sum(x * x, axis=0) / N inv = 1.0 / tl.sqrt(ms + eps) y = x * inv * w tl.store(out_ptr + offs, y, mask=mask) def rmsnorm(x, w, eps=1e-6): N = x.shape[0] out = torch.empty(N, dtype=torch.bfloat16, device=x.device) block = triton.next_power_of_2(N) _rmsnorm_kernel[(1,)](x, w, out, N, eps, BLOCK=block) return out