"""Self-contained, highly optimized Triton-based Kimi-Linear decode unit with packed GEMV optimization.""" from __future__ import annotations from dataclasses import dataclass, field import torch import torch.nn as nn import torch.nn.functional as F import triton import triton.language as tl OP_TYPE = "kimi_linear_w4a16_decode" HARDWARE_REQUIRED = ["RTX_PRO_6000"] EPS = 1.0e-6 GROUP_SIZE = 128 @dataclass(frozen=True) class Config: hidden: int = 2304 kda_heads: int = 32 kda_head_dim: int = 128 short_conv: int = 4 mla_heads: int = 32 kv_lora: int = 512 qk_nope: int = 128 qk_rope: int = 64 v_head: int = 128 rope_theta: float = 10000.0 n_experts: int = 64 n_active: int = 8 n_shared: int = 1 moe_inter: int = 1024 routed_scaling: float = 2.446 group: int = 128 pattern: tuple = ("K", "K", "K", "M") dtype: torch.dtype = field(default=torch.bfloat16) def build_config(shape: dict) -> Config: return Config(n_experts=int(shape.get("n_experts", 64))) # --------------------------------------------------------------------------- # # Highly Optimized Unified Triton GEMV Kernel for W4A16 # --------------------------------------------------------------------------- # @triton.autotune( configs=[ triton.Config({'BLOCK_N': 128, 'BLOCK_K': 64}, num_warps=4), triton.Config({'BLOCK_N': 256, 'BLOCK_K': 64}, num_warps=4), triton.Config({'BLOCK_N': 128, 'BLOCK_K': 128}, num_warps=4), triton.Config({'BLOCK_N': 64, 'BLOCK_K': 64}, num_warps=2), ], key=['K', 'N'], ) @triton.jit def gemv_w4a16_kernel( x_ptr, w_q_ptr, scales_ptr, zeros_ptr, y_ptr, idx_ptr, K, N, group_size, stride_w_q_e, stride_w_q_k, stride_w_q_n, stride_scales_e, stride_scales_g, stride_scales_n, stride_zeros_e, stride_zeros_g, stride_zeros_n, stride_y_e, stride_y_n, stride_x_e, has_expert_idx: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, ): col_idx = tl.program_id(0) exp_idx = tl.program_id(1) if has_expert_idx: expert_idx = tl.load(idx_ptr + exp_idx) else: expert_idx = exp_idx # Offset pointers for this expert w_q_expert = w_q_ptr + expert_idx * stride_w_q_e scales_expert = scales_ptr + expert_idx * stride_scales_e zeros_expert = zeros_ptr + expert_idx * stride_zeros_e y_expert = y_ptr + exp_idx * stride_y_e x_expert = x_ptr + exp_idx * stride_x_e offs_n = col_idx * BLOCK_N + tl.arange(0, BLOCK_N) mask_n = offs_n < N acc = tl.zeros((BLOCK_N,), dtype=tl.float32) # Loop over K (BLOCK_K is restricted to <= group_size) for k_start in range(0, K, BLOCK_K): # Even/odd row pointers for w_q offs_k_packed = (k_start // 2) + tl.arange(0, BLOCK_K // 2) # Load w_q (packed) w_q_offsets = offs_k_packed[:, None] * stride_w_q_k + offs_n[None, :] * stride_w_q_n w_q_packed = tl.load(w_q_expert + w_q_offsets, mask=(offs_k_packed[:, None] < (K // 2)) & mask_n[None, :], other=0) # Unpack lo (even) and hi (odd) w_even = w_q_packed & 0xF w_odd = (w_q_packed >> 4) & 0xF # Load scales and zeros for this block (since BLOCK_K <= group_size) g_idx = k_start // group_size scales_offsets = g_idx * stride_scales_g + offs_n * stride_scales_n zeros_offsets = g_idx * stride_zeros_g + offs_n * stride_zeros_n s = tl.load(scales_expert + scales_offsets, mask=mask_n, other=0.0).to(tl.float32) z = tl.load(zeros_expert + zeros_offsets, mask=mask_n, other=0.0).to(tl.float32) # Dequantize even and odd weights w_even_fp32 = (w_even.to(tl.float32) - z[None, :]) * s[None, :] w_odd_fp32 = (w_odd.to(tl.float32) - z[None, :]) * s[None, :] # Load x_even and x_odd offs_x_even = k_start + 2 * tl.arange(0, BLOCK_K // 2) offs_x_odd = offs_x_even + 1 x_even = tl.load(x_expert + offs_x_even, mask=offs_x_even < K, other=0.0).to(tl.float32) x_odd = tl.load(x_expert + offs_x_odd, mask=offs_x_odd < K, other=0.0).to(tl.float32) # Multiply and accumulate acc += tl.sum(x_even[:, None] * w_even_fp32, axis=0) acc += tl.sum(x_odd[:, None] * w_odd_fp32, axis=0) tl.store(y_expert + offs_n * stride_y_n, acc.to(tl.bfloat16), mask=mask_n) def gemv_w4a16(x: torch.Tensor, w_q: torch.Tensor, scales: torch.Tensor, zeros: torch.Tensor, idx: torch.Tensor | None = None, out: torch.Tensor | None = None) -> torch.Tensor: # Determine shapes if w_q.ndim == 3: E, K_half, N = w_q.shape K = K_half * 2 num_experts = E if idx is None else idx.numel() has_expert_idx = idx is not None else: K_half, N = w_q.shape K = K_half * 2 num_experts = 1 has_expert_idx = False if out is None: out = torch.empty((num_experts, N), dtype=torch.bfloat16, device=x.device) # Get strides stride_w_q_e = w_q.stride(0) if w_q.ndim == 3 else 0 stride_w_q_k = w_q.stride(1) if w_q.ndim == 3 else w_q.stride(0) stride_w_q_n = w_q.stride(2) if w_q.ndim == 3 else w_q.stride(1) stride_scales_e = scales.stride(0) if scales.ndim == 3 else 0 stride_scales_g = scales.stride(1) if scales.ndim == 3 else scales.stride(0) stride_scales_n = scales.stride(2) if scales.ndim == 3 else scales.stride(1) stride_zeros_e = zeros.stride(0) if zeros.ndim == 3 else 0 stride_zeros_g = zeros.stride(1) if zeros.ndim == 3 else zeros.stride(0) stride_zeros_n = zeros.stride(2) if zeros.ndim == 3 else zeros.stride(1) stride_y_e = out.stride(0) if out.ndim == 2 else 0 stride_y_n = out.stride(1) if out.ndim == 2 else out.stride(0) stride_x_e = x.stride(0) if x.ndim == 2 else 0 idx_ptr = idx if has_expert_idx else x # dummy pointer grid = lambda meta: (triton.cdiv(N, meta['BLOCK_N']), num_experts) gemv_w4a16_kernel[grid]( x, w_q, scales, zeros, out, idx_ptr, K, N, GROUP_SIZE, stride_w_q_e, stride_w_q_k, stride_w_q_n, stride_scales_e, stride_scales_g, stride_scales_n, stride_zeros_e, stride_zeros_g, stride_zeros_n, stride_y_e, stride_y_n, stride_x_e, has_expert_idx=has_expert_idx, ) if w_q.ndim == 2: return out.squeeze(0) return out # --------------------------------------------------------------------------- # # W4A16 Quantization classes # --------------------------------------------------------------------------- # def _pack_int4(w_q: torch.Tensor) -> torch.Tensor: lo = w_q[0::2] & 0xF hi = w_q[1::2] & 0xF return (lo | (hi << 4)).contiguous() def _unpack_int4(w_packed: torch.Tensor, K: int) -> torch.Tensor: out = torch.empty((K, w_packed.shape[1]), dtype=torch.uint8, device=w_packed.device) out[0::2] = w_packed & 0xF out[1::2] = (w_packed >> 4) & 0xF return out def quantize(w_io: torch.Tensor, group: int = GROUP_SIZE): K, N = w_io.shape ng = K // group wg = w_io.view(ng, group, N).float() wmin = wg.min(dim=1, keepdim=True).values wmax = wg.max(dim=1, keepdim=True).values scales = (wmax - wmin).clamp_min(1e-8) / 15.0 zeros = (-wmin / scales).round().clamp(0, 15) w_q = ((wg / scales) + zeros).round().clamp(0, 15).to(torch.uint8).view(K, N) return _pack_int4(w_q), scales.squeeze(1).to(torch.bfloat16), zeros.squeeze(1).to(torch.bfloat16) def dequant(w_q: torch.Tensor, scales: torch.Tensor, zeros: torch.Tensor, K: int, group: int) -> torch.Tensor: wu = _unpack_int4(w_q, K).to(torch.bfloat16) s = scales.repeat_interleave(group, dim=0) z = zeros.repeat_interleave(group, dim=0) return (wu - z) * s 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 init_random(self, gen: torch.Generator, std: float = 0.02) -> None: w = torch.randn(self.in_f, self.out_f, generator=gen) * std wq, s, z = quantize(w, self.group) self.w_q.copy_(wq) self.scales.copy_(s) self.zeros.copy_(z) def weight_bf(self) -> torch.Tensor: return dequant(self.w_q, self.scales, self.zeros, self.in_f, self.group) def forward(self, x: torch.Tensor) -> torch.Tensor: return gemv_w4a16(x, self.w_q, self.scales, self.zeros) 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)) def init_random(self, gen: torch.Generator, std: float = 0.02) -> None: for e in range(self.n): w = torch.randn(self.in_f, self.out_f, generator=gen) * std wq, s, z = quantize(w, self.group) self.w_q[e].copy_(wq) self.scales[e].copy_(s) self.zeros[e].copy_(z) def weight_bf(self, e: int) -> torch.Tensor: return dequant(self.w_q[e], self.scales[e], self.zeros[e], self.in_f, self.group) # --------------------------------------------------------------------------- # # Helpers # --------------------------------------------------------------------------- # def _rmsnorm(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor: xf = x.float() xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + EPS) return (xf * w.float()).to(x.dtype) def _rope_cossin(pos: int, dim: int, theta: float, 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: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: 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.to(x.dtype) # --------------------------------------------------------------------------- # # KDA & MLA Layers # --------------------------------------------------------------------------- # @torch.compile def _kda_update(S, g, beta, k, v, q): S = S * g.exp()[:, :, None] pred = (S * k[:, :, None]).sum(1) S = S + beta[:, None, None] * k[:, :, None] * (v - pred)[:, None, :] o = (S * q[:, :, None]).sum(1) return o, S class KDA(nn.Module): def __init__(self, cfg: Config): 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 def _short_conv(self, val, prev, idx): win = torch.cat([prev, val[None]], dim=0) w = self.conv_w[idx].float().transpose(0, 1) out = (win.float() * w).sum(0) return F.silu(out).to(val.dtype), win[1:] def step(self, x, st): H, Dk = self.cfg.kda_heads, self.cfg.kda_head_dim # Packed GEMV optimization: Run q, k, v, g projections in a single Triton launch if not hasattr(self, "packed_w_q"): self.packed_w_q = torch.stack([ self.q_proj.w_q, self.k_proj.w_q, self.v_proj.w_q, self.g_proj.w_q ], dim=0) self.packed_scales = torch.stack([ self.q_proj.scales, self.k_proj.scales, self.v_proj.scales, self.g_proj.scales ], dim=0) self.packed_zeros = torch.stack([ self.q_proj.zeros, self.k_proj.zeros, self.v_proj.zeros, self.g_proj.zeros ], dim=0) out_projs = gemv_w4a16(x, self.packed_w_q, self.packed_scales, self.packed_zeros) # shape (4, H*Dk) q, k, v, g = out_projs[0], out_projs[1], out_projs[2], out_projs[3] q, st["cq"] = self._short_conv(q, st["cq"], 0) k, st["ck"] = self._short_conv(k, st["ck"], 1) v, st["cv"] = self._short_conv(v, st["cv"], 2) q = q.view(H, Dk).float() * self.scale k = k.view(H, Dk).float() v = v.view(H, Dk).float() g = (-F.softplus(g.float())).view(H, Dk) beta = torch.sigmoid(self.beta_proj(x).float()) # Fused state update o, st["S"] = _kda_update(st["S"], g, beta, k, v, q) return self.o_proj(o.reshape(H * Dk).to(torch.bfloat16)) class MLA(nn.Module): def __init__(self, cfg: Config): 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 def step(self, x, st): cfg = self.cfg H = cfg.mla_heads pos = st["c_kv"].shape[0] q = self.q_proj(x).view(H, cfg.qk_nope + cfg.qk_rope) q_nope = q[:, : cfg.qk_nope].float() q_rope = q[:, cfg.qk_nope :] kv = self.kv_a(x) c_kv = kv[: cfg.kv_lora] k_rope = kv[cfg.kv_lora :] cos, sin = _rope_cossin(pos, cfg.qk_rope, cfg.rope_theta, x.device) q_rope = _apply_rope(q_rope, cos, sin).float() k_rope = _apply_rope(k_rope, cos, sin) st["c_kv"] = torch.cat([st["c_kv"], c_kv[None]], 0) st["k_rope"] = torch.cat([st["k_rope"], k_rope[None]], 0) # ------------------------------------------------------------------- # # MLA Absorb optimization: # Instead of projecting the entire history c_kv (shape context_len x 512) # to kvb (shape context_len x H x (nope+v_head)), we absorb the kv_b # weight directly into q_nope and key-value probabilities! # ------------------------------------------------------------------- # kv_b_bf = self.kv_b.weight_bf().view(cfg.kv_lora, H, cfg.qk_nope + cfg.v_head).float() W_k = kv_b_bf[..., : cfg.qk_nope] # shape (512, H, qk_nope) W_v = kv_b_bf[..., cfg.qk_nope :] # shape (512, H, v_head) # 1. Absorb query: q_abs = sum_d q_nope_h_d * W_k_m_h_d q_abs = torch.einsum("hd,mhd->hm", q_nope, W_k) # shape (H, 512) # 2. Compute attention scores: scores = (torch.einsum("hm,lm->lh", q_abs, st["c_kv"].float()) + torch.einsum("hd,ld->lh", q_rope, st["k_rope"].float())) * self.scale p = torch.softmax(scores, dim=0) # shape (pos, H) in float32 # 3. Absorb value projection: c_kv_weighted = torch.einsum("lh,lm->hm", p, st["c_kv"].float()) # shape (H, 512) o = torch.einsum("hm,mhd->hd", c_kv_weighted, W_v) # shape (H, v_head) return self.o_proj(o.reshape(H * cfg.v_head).to(torch.bfloat16)) # --------------------------------------------------------------------------- # # MoE Layer # --------------------------------------------------------------------------- # class MoE(nn.Module): def __init__(self, cfg: Config): 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) def step(self, x): 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).to(x.dtype) # Packed GEMV optimization for active routed experts: Pack gate & up if not hasattr(self, "packed_gate_up_w_q"): self.packed_gate_up_w_q = torch.stack([self.gate.w_q, self.up.w_q], dim=0) # (2, E, K_half, m) self.packed_gate_up_scales = torch.stack([self.gate.scales, self.up.scales], dim=0) self.packed_gate_up_zeros = torch.stack([self.gate.zeros, self.up.zeros], dim=0) E = cfg.n_experts K_half = self.gate.w_q.shape[1] m = self.gate.w_q.shape[2] # Construct combined expert indices for gate (0 to E-1) and up (E to 2*E-1) idx_combined = torch.cat([idx, idx + E], dim=0) # Run packed gate and up GEMVs in a single launch out_gate_up = gemv_w4a16( x, self.packed_gate_up_w_q.view(2 * E, K_half, m), self.packed_gate_up_scales.view(2 * E, -1, m), self.packed_gate_up_zeros.view(2 * E, -1, m), idx=idx_combined ) # shape (16, m) g_out = out_gate_up[:cfg.n_active] u_out = out_gate_up[cfg.n_active:] hh = F.silu(g_out) * u_out # shape (8, m) # Compute routed down projection routed = gemv_w4a16(hh, self.down.w_q, self.down.scales, self.down.zeros, idx=idx) # shape (8, d) out = (w[:, None] * routed).sum(0) # Packed GEMV optimization for shared expert: Pack s_gate & s_up if not hasattr(self, "packed_s_gate_up_w_q"): self.packed_s_gate_up_w_q = torch.stack([self.s_gate.w_q, self.s_up.w_q], dim=0) # (2, s_E, K_half, m) self.packed_s_gate_up_scales = torch.stack([self.s_gate.scales, self.s_up.scales], dim=0) self.packed_s_gate_up_zeros = torch.stack([self.s_gate.zeros, self.s_up.zeros], dim=0) s_E = cfg.n_shared sidx = torch.arange(s_E, device=x.device) sidx_combined = torch.cat([sidx, sidx + s_E], dim=0) s_K_half = self.s_gate.w_q.shape[1] s_m = self.s_gate.w_q.shape[2] # Run packed s_gate and s_up GEMVs in a single launch out_s_gate_up = gemv_w4a16( x, self.packed_s_gate_up_w_q.view(2 * s_E, s_K_half, s_m), self.packed_s_gate_up_scales.view(2 * s_E, -1, s_m), self.packed_s_gate_up_zeros.view(2 * s_E, -1, s_m), idx=sidx_combined ) # shape (2, s_m) sg_out = out_s_gate_up[:s_E] su_out = out_s_gate_up[s_E:] sh = F.silu(sg_out) * su_out # shape (1, s_m) # Compute shared down projection sd_out = gemv_w4a16(sh, self.s_down.w_q, self.s_down.scales, self.s_down.zeros, idx=sidx) # shape (1, d) out = out + sd_out.sum(0) return out class Block(nn.Module): def __init__(self, cfg: Config, 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: Config): 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): hidden = blk.step(hidden, state[i]) return hidden, state # --------------------------------------------------------------------------- # # State / inputs # --------------------------------------------------------------------------- # def init_state(cfg: Config, context_len: int, seed: int) -> list: dev = torch.device("cuda:0") g = torch.Generator(device=dev).manual_seed(seed) H, Dk = cfg.kda_heads, cfg.kda_head_dim C = H * Dk state = [] for kind in cfg.pattern: if kind == "K": state.append({ "S": torch.randn(H, Dk, Dk, device=dev, generator=g) * 0.05, "cq": torch.randn(cfg.short_conv - 1, C, device=dev, generator=g, dtype=cfg.dtype) * 0.1, "ck": torch.randn(cfg.short_conv - 1, C, device=dev, generator=g, dtype=cfg.dtype) * 0.1, "cv": torch.randn(cfg.short_conv - 1, C, device=dev, generator=g, dtype=cfg.dtype) * 0.1, }) else: state.append({ "c_kv": torch.randn(context_len, cfg.kv_lora, device=dev, generator=g, dtype=cfg.dtype) * 0.1, "k_rope": torch.randn(context_len, cfg.qk_rope, device=dev, generator=g, dtype=cfg.dtype) * 0.1, }) return state def init_token(cfg: Config, seed: int) -> torch.Tensor: dev = torch.device("cuda:0") g = torch.Generator(device=dev).manual_seed(seed + 1) return torch.randn(cfg.hidden, device=dev, generator=g, dtype=cfg.dtype) * 0.25