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))) @triton.jit def _int4_gemv_kernel(x, wq, scales, zeros, y, K: tl.constexpr, N: tl.constexpr, NG: tl.constexpr, BLOCK_N: tl.constexpr): pid_n = tl.program_id(0) offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) mask_n = offs_n < N offs_p = tl.arange(0, 64) acc = tl.zeros((BLOCK_N,), tl.float32) for g in range(0, NG): k0 = g * 128 + offs_p * 2 xe = tl.load(x + k0).to(tl.float32) xo = tl.load(x + k0 + 1).to(tl.float32) packed = tl.load(wq + (g * 64 + offs_p)[:, None] * N + offs_n[None, :], mask=mask_n[None, :], other=0) lo = (packed & 15).to(tl.float32) hi = ((packed >> 4) & 15).to(tl.float32) qx = tl.sum(lo * xe[:, None] + hi * xo[:, None], axis=0) xs = tl.sum(xe + xo, axis=0) s = tl.load(scales + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) z = tl.load(zeros + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) acc += s * (qx - z * xs) tl.store(y + offs_n, acc, mask=mask_n) @triton.jit def _rmsnorm_kernel(x, w, y, N: tl.constexpr, BLOCK: tl.constexpr): offs = tl.arange(0, BLOCK) mask = offs < N xv = tl.load(x + offs, mask=mask, other=0.0).to(tl.float32) wv = tl.load(w + offs, mask=mask, other=0.0).to(tl.float32) ss = tl.sum(xv * xv, axis=0) / N inv = tl.rsqrt(ss + 1.0e-6) tl.store(y + offs, xv * inv * wv, mask=mask) @triton.jit def _short_conv_kernel(val, prev, weight, out, new_prev, C: tl.constexpr, BLOCK: tl.constexpr): pid = tl.program_id(0) offs = pid * BLOCK + tl.arange(0, BLOCK) mask = offs < C p0 = tl.load(prev + offs, mask=mask, other=0.0).to(tl.float32) p1 = tl.load(prev + C + offs, mask=mask, other=0.0).to(tl.float32) p2 = tl.load(prev + 2 * C + offs, mask=mask, other=0.0).to(tl.float32) x = tl.load(val + offs, mask=mask, other=0.0).to(tl.float32) w0 = tl.load(weight + offs * 4, mask=mask, other=0.0).to(tl.float32) w1 = tl.load(weight + offs * 4 + 1, mask=mask, other=0.0).to(tl.float32) w2 = tl.load(weight + offs * 4 + 2, mask=mask, other=0.0).to(tl.float32) w3 = tl.load(weight + offs * 4 + 3, mask=mask, other=0.0).to(tl.float32) y = p0 * w0 + p1 * w1 + p2 * w2 + x * w3 y = y * tl.sigmoid(y) tl.store(out + offs, y, mask=mask) tl.store(new_prev + offs, p1, mask=mask) tl.store(new_prev + C + offs, p2, mask=mask) tl.store(new_prev + 2 * C + offs, x, mask=mask) @triton.jit def _kda_state_kernel(q, k, v, g, beta, S, out, H: tl.constexpr, D: tl.constexpr, BLOCK_DV: tl.constexpr): h = tl.program_id(0) block_v = tl.program_id(1) offs_v = block_v * BLOCK_DV + tl.arange(0, BLOCK_DV) mask_v = offs_v < D base_h = h * D * D base_vec = h * D pred = tl.zeros((BLOCK_DV,), tl.float32) for dk in range(0, D): gg = tl.load(g + base_vec + dk).to(tl.float32) kk = tl.load(k + base_vec + dk).to(tl.float32) s_old = tl.load(S + base_h + dk * D + offs_v, mask=mask_v, other=0.0).to(tl.float32) pred += (s_old * tl.exp(gg)) * kk vv = tl.load(v + base_vec + offs_v, mask=mask_v, other=0.0).to(tl.float32) bb = tl.load(beta + h).to(tl.float32) oacc = tl.zeros((BLOCK_DV,), tl.float32) for dk in range(0, D): gg = tl.load(g + base_vec + dk).to(tl.float32) kk = tl.load(k + base_vec + dk).to(tl.float32) qq = tl.load(q + base_vec + dk).to(tl.float32) s_old = tl.load(S + base_h + dk * D + offs_v, mask=mask_v, other=0.0).to(tl.float32) s_new = s_old * tl.exp(gg) + bb * kk * (vv - pred) tl.store(S + base_h + dk * D + offs_v, s_new, mask=mask_v) oacc += s_new * qq tl.store(out + base_vec + offs_v, oacc, mask=mask_v) @triton.jit def _kda_qkvg_kernel(x, wq0, s0, z0, wq1, s1, z1, wq2, s2, z2, wq3, s3, z3, y, K: tl.constexpr, N: tl.constexpr, NG: tl.constexpr, BLOCK_N: tl.constexpr): pid_n = tl.program_id(0) offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) mask_n = offs_n < N offs_p = tl.arange(0, 64) acc0 = tl.zeros((BLOCK_N,), tl.float32) acc1 = tl.zeros((BLOCK_N,), tl.float32) acc2 = tl.zeros((BLOCK_N,), tl.float32) acc3 = tl.zeros((BLOCK_N,), tl.float32) for g in range(0, NG): k0 = g * 128 + offs_p * 2 xe = tl.load(x + k0).to(tl.float32) xo = tl.load(x + k0 + 1).to(tl.float32) xs = tl.sum(xe + xo, axis=0) w_offs = (g * 64 + offs_p)[:, None] * N + offs_n[None, :] p0 = tl.load(wq0 + w_offs, mask=mask_n[None, :], other=0) lo0 = (p0 & 15).to(tl.float32) hi0 = ((p0 >> 4) & 15).to(tl.float32) qx0 = tl.sum(lo0 * xe[:, None] + hi0 * xo[:, None], axis=0) ss0 = tl.load(s0 + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) zz0 = tl.load(z0 + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) acc0 += ss0 * (qx0 - zz0 * xs) p1 = tl.load(wq1 + w_offs, mask=mask_n[None, :], other=0) lo1 = (p1 & 15).to(tl.float32) hi1 = ((p1 >> 4) & 15).to(tl.float32) qx1 = tl.sum(lo1 * xe[:, None] + hi1 * xo[:, None], axis=0) ss1 = tl.load(s1 + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) zz1 = tl.load(z1 + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) acc1 += ss1 * (qx1 - zz1 * xs) p2 = tl.load(wq2 + w_offs, mask=mask_n[None, :], other=0) lo2 = (p2 & 15).to(tl.float32) hi2 = ((p2 >> 4) & 15).to(tl.float32) qx2 = tl.sum(lo2 * xe[:, None] + hi2 * xo[:, None], axis=0) ss2 = tl.load(s2 + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) zz2 = tl.load(z2 + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) acc2 += ss2 * (qx2 - zz2 * xs) p3 = tl.load(wq3 + w_offs, mask=mask_n[None, :], other=0) lo3 = (p3 & 15).to(tl.float32) hi3 = ((p3 >> 4) & 15).to(tl.float32) qx3 = tl.sum(lo3 * xe[:, None] + hi3 * xo[:, None], axis=0) ss3 = tl.load(s3 + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) zz3 = tl.load(z3 + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) acc3 += ss3 * (qx3 - zz3 * xs) tl.store(y + offs_n, acc0, mask=mask_n) tl.store(y + N + offs_n, acc1, mask=mask_n) tl.store(y + 2 * N + offs_n, acc2, mask=mask_n) tl.store(y + 3 * N + offs_n, acc3, mask=mask_n) @triton.jit def _experts_dual_gemv_kernel(x, idx, wq_a, scales_a, zeros_a, wq_b, scales_b, zeros_b, y_a, y_b, K: tl.constexpr, N: tl.constexpr, NG: tl.constexpr, BLOCK_N: tl.constexpr): pid_e = tl.program_id(0) pid_n = tl.program_id(1) e = tl.load(idx + pid_e) offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) mask_n = offs_n < N offs_p = tl.arange(0, 64) acc_a = tl.zeros((BLOCK_N,), tl.float32) acc_b = tl.zeros((BLOCK_N,), tl.float32) w_base = e * (K // 2) * N q_base = e * NG * N for g in range(0, NG): k0 = g * 128 + offs_p * 2 xe = tl.load(x + k0).to(tl.float32) xo = tl.load(x + k0 + 1).to(tl.float32) xs = tl.sum(xe + xo, axis=0) w_offs = w_base + (g * 64 + offs_p)[:, None] * N + offs_n[None, :] pa = tl.load(wq_a + w_offs, mask=mask_n[None, :], other=0) loa = (pa & 15).to(tl.float32) hia = ((pa >> 4) & 15).to(tl.float32) qxa = tl.sum(loa * xe[:, None] + hia * xo[:, None], axis=0) sa = tl.load(scales_a + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) za = tl.load(zeros_a + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) acc_a += sa * (qxa - za * xs) pb = tl.load(wq_b + w_offs, mask=mask_n[None, :], other=0) lob = (pb & 15).to(tl.float32) hib = ((pb >> 4) & 15).to(tl.float32) qxb = tl.sum(lob * xe[:, None] + hib * xo[:, None], axis=0) sb = tl.load(scales_b + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) zb = tl.load(zeros_b + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) acc_b += sb * (qxb - zb * xs) tl.store(y_a + pid_e * N + offs_n, acc_a, mask=mask_n) tl.store(y_b + pid_e * N + offs_n, acc_b, mask=mask_n) @triton.jit def _experts_down_weighted_kernel(h, coeff, idx, wq, scales, zeros, y, K: tl.constexpr, N: tl.constexpr, NG: tl.constexpr, ESEL: tl.constexpr, ADD: tl.constexpr, BLOCK_N: tl.constexpr): pid_n = tl.program_id(0) offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) mask_n = offs_n < N offs_p = tl.arange(0, 64) acc = tl.zeros((BLOCK_N,), tl.float32) for ep in range(0, ESEL): e = tl.load(idx + ep) c = tl.load(coeff + ep).to(tl.float32) w_base = e * (K // 2) * N q_base = e * NG * N acc_e = tl.zeros((BLOCK_N,), tl.float32) for g in range(0, NG): k0 = g * 128 + offs_p * 2 xe = tl.load(h + ep * K + k0).to(tl.float32) xo = tl.load(h + ep * K + k0 + 1).to(tl.float32) packed = tl.load(wq + w_base + (g * 64 + offs_p)[:, None] * N + offs_n[None, :], mask=mask_n[None, :], other=0) lo = (packed & 15).to(tl.float32) hi = ((packed >> 4) & 15).to(tl.float32) qx = tl.sum(lo * xe[:, None] + hi * xo[:, None], axis=0) xs = tl.sum(xe + xo, axis=0) s = tl.load(scales + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) z = tl.load(zeros + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) acc_e += s * (qx - z * xs) acc += c * acc_e if ADD: acc += tl.load(y + offs_n, mask=mask_n, other=0.0).to(tl.float32) tl.store(y + offs_n, acc, mask=mask_n) @triton.jit def _moe_dual_gemv_kernel(x, idx, wq_a, scales_a, zeros_a, wq_b, scales_b, zeros_b, swq_a, sscales_a, szeros_a, swq_b, sscales_b, szeros_b, y_a, y_b, K: tl.constexpr, N: tl.constexpr, NG: tl.constexpr, ACTIVE: tl.constexpr, SHARED: tl.constexpr, BLOCK_N: tl.constexpr): pid_e = tl.program_id(0) pid_n = tl.program_id(1) is_routed = pid_e < ACTIVE e_r = tl.load(idx + pid_e, mask=is_routed, other=0) e_s = pid_e - ACTIVE offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) mask_n = offs_n < N offs_p = tl.arange(0, 64) acc_a = tl.zeros((BLOCK_N,), tl.float32) acc_b = tl.zeros((BLOCK_N,), tl.float32) w_base_r = e_r * (K // 2) * N q_base_r = e_r * NG * N w_base_s = e_s * (K // 2) * N q_base_s = e_s * NG * N for g in range(0, NG): k0 = g * 128 + offs_p * 2 xe = tl.load(x + k0).to(tl.float32) xo = tl.load(x + k0 + 1).to(tl.float32) xs = tl.sum(xe + xo, axis=0) w_offs_r = w_base_r + (g * 64 + offs_p)[:, None] * N + offs_n[None, :] w_offs_s = w_base_s + (g * 64 + offs_p)[:, None] * N + offs_n[None, :] ptra = tl.where(is_routed, wq_a + w_offs_r, swq_a + w_offs_s) ptrb = tl.where(is_routed, wq_b + w_offs_r, swq_b + w_offs_s) pa = tl.load(ptra, mask=mask_n[None, :], other=0) loa = (pa & 15).to(tl.float32) hia = ((pa >> 4) & 15).to(tl.float32) qxa = tl.sum(loa * xe[:, None] + hia * xo[:, None], axis=0) ptra_s = tl.where(is_routed, scales_a + q_base_r + g * N + offs_n, sscales_a + q_base_s + g * N + offs_n) ptra_z = tl.where(is_routed, zeros_a + q_base_r + g * N + offs_n, szeros_a + q_base_s + g * N + offs_n) sa = tl.load(ptra_s, mask=mask_n, other=0.0).to(tl.float32) za = tl.load(ptra_z, mask=mask_n, other=0.0).to(tl.float32) acc_a += sa * (qxa - za * xs) pb = tl.load(ptrb, mask=mask_n[None, :], other=0) lob = (pb & 15).to(tl.float32) hib = ((pb >> 4) & 15).to(tl.float32) qxb = tl.sum(lob * xe[:, None] + hib * xo[:, None], axis=0) ptrb_s = tl.where(is_routed, scales_b + q_base_r + g * N + offs_n, sscales_b + q_base_s + g * N + offs_n) ptrb_z = tl.where(is_routed, zeros_b + q_base_r + g * N + offs_n, szeros_b + q_base_s + g * N + offs_n) sb = tl.load(ptrb_s, mask=mask_n, other=0.0).to(tl.float32) zb = tl.load(ptrb_z, mask=mask_n, other=0.0).to(tl.float32) acc_b += sb * (qxb - zb * xs) tl.store(y_a + pid_e * N + offs_n, acc_a, mask=mask_n) tl.store(y_b + pid_e * N + offs_n, acc_b, mask=mask_n) @triton.jit def _moe_down_kernel(h, coeff, idx, wq, scales, zeros, swq, sscales, szeros, y, K: tl.constexpr, N: tl.constexpr, NG: tl.constexpr, ACTIVE: tl.constexpr, SHARED: tl.constexpr, BLOCK_N: tl.constexpr): pid_n = tl.program_id(0) offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) mask_n = offs_n < N offs_p = tl.arange(0, 64) acc = tl.zeros((BLOCK_N,), tl.float32) for ep in range(0, ACTIVE + SHARED): if ep < ACTIVE: e = tl.load(idx + ep) c = tl.load(coeff + ep).to(tl.float32) base_w = wq base_s = scales base_z = zeros else: e = tl.full((), ep - ACTIVE, tl.int64) c = 1.0 base_w = swq base_s = sscales base_z = szeros w_base = e * (K // 2) * N q_base = e * NG * N acc_e = tl.zeros((BLOCK_N,), tl.float32) for g in range(0, NG): k0 = g * 128 + offs_p * 2 xe = tl.load(h + ep * K + k0).to(tl.float32) xo = tl.load(h + ep * K + k0 + 1).to(tl.float32) packed = tl.load(base_w + w_base + (g * 64 + offs_p)[:, None] * N + offs_n[None, :], mask=mask_n[None, :], other=0) lo = (packed & 15).to(tl.float32) hi = ((packed >> 4) & 15).to(tl.float32) qx = tl.sum(lo * xe[:, None] + hi * xo[:, None], axis=0) xs = tl.sum(xe + xo, axis=0) s = tl.load(base_s + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) z = tl.load(base_z + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) acc_e += s * (qx - z * xs) acc += c * acc_e tl.store(y + offs_n, acc, mask=mask_n) @triton.jit def _mla_q_abs_kernel(q, wq, scales, zeros, out, H: tl.constexpr, K: tl.constexpr, N: tl.constexpr, BLOCK_K: tl.constexpr): pid_h = tl.program_id(0) pid_k = tl.program_id(1) offs_k = pid_k * BLOCK_K + tl.arange(0, BLOCK_K) offs_j = tl.arange(0, 128) mask_k = offs_k < K out_cols = pid_h * 256 + offs_j qv = tl.load(q + pid_h * 128 + offs_j).to(tl.float32) group = offs_k // 128 packed_row = offs_k // 2 packed = tl.load(wq + packed_row[:, None] * N + out_cols[None, :], mask=mask_k[:, None], other=0) nib = tl.where((offs_k[:, None] & 1) == 0, packed & 15, (packed >> 4) & 15).to(tl.float32) s = tl.load(scales + group[:, None] * N + out_cols[None, :], mask=mask_k[:, None], other=0.0).to(tl.float32) z = tl.load(zeros + group[:, None] * N + out_cols[None, :], mask=mask_k[:, None], other=0.0).to(tl.float32) vals = (nib - z) * s acc = tl.sum(vals * qv[None, :], axis=1) tl.store(out + pid_h * K + offs_k, acc, mask=mask_k) @triton.jit def _mla_v_out_kernel(ctx, wq, scales, zeros, out, H: tl.constexpr, K: tl.constexpr, N: tl.constexpr, BLOCK_N: tl.constexpr): pid_h = tl.program_id(0) pid_n = tl.program_id(1) offs_n0 = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) offs_n = pid_h * 256 + 128 + offs_n0 mask_n = offs_n0 < 128 offs_p = tl.arange(0, 64) acc = tl.zeros((BLOCK_N,), tl.float32) for g in range(0, 4): k0 = g * 128 + offs_p * 2 xe = tl.load(ctx + pid_h * K + k0).to(tl.float32) xo = tl.load(ctx + pid_h * K + k0 + 1).to(tl.float32) packed = tl.load(wq + (g * 64 + offs_p)[:, None] * N + offs_n[None, :], mask=mask_n[None, :], other=0) lo = (packed & 15).to(tl.float32) hi = ((packed >> 4) & 15).to(tl.float32) qx = tl.sum(lo * xe[:, None] + hi * xo[:, None], axis=0) xs = tl.sum(xe + xo, axis=0) s = tl.load(scales + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) z = tl.load(zeros + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32) acc += s * (qx - z * xs) tl.store(out + pid_h * 128 + offs_n0, acc, mask=mask_n) def _ceil_div(a: int, b: int) -> int: return triton.cdiv(a, b) def _fused_rmsnorm(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor: y = torch.empty_like(x) _rmsnorm_kernel[(1,)](x, w, y, x.numel(), BLOCK=4096, num_warps=8) return y def _fused_short_conv(val: torch.Tensor, prev: torch.Tensor, weight: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: out = torch.empty_like(val) new_prev = torch.empty_like(prev) _short_conv_kernel[(_ceil_div(val.numel(), 256),)]( val, prev, weight, out, new_prev, val.numel(), BLOCK=256, num_warps=4, ) return out, new_prev def _fused_kda_state(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, g: torch.Tensor, beta: torch.Tensor, state_s: torch.Tensor) -> torch.Tensor: out = torch.empty((32, 128), device=q.device, dtype=torch.bfloat16) _kda_state_kernel[(32, 4)]( q, k, v, g, beta, state_s, out, 32, 128, BLOCK_DV=32, num_warps=4, ) return out def _fused_gemv(x: torch.Tensor, wq: torch.Tensor, scales: torch.Tensor, zeros: torch.Tensor, in_f: int, out_f: int) -> torch.Tensor: y = torch.empty((out_f,), device=x.device, dtype=torch.bfloat16) _int4_gemv_kernel[(_ceil_div(out_f, 32),)]( x, wq, scales, zeros, y, in_f, out_f, in_f // GROUP_SIZE, BLOCK_N=32, num_warps=4, ) return y def _kda_qkvg(x: torch.Tensor, q, k, v, g) -> torch.Tensor: out_f = q.out_f y = torch.empty((4, out_f), device=x.device, dtype=torch.bfloat16) _kda_qkvg_kernel[(_ceil_div(out_f, 32),)]( x, q.w_q, q.scales, q.zeros, k.w_q, k.scales, k.zeros, v.w_q, v.scales, v.zeros, g.w_q, g.scales, g.zeros, y, q.in_f, out_f, q.in_f // GROUP_SIZE, BLOCK_N=32, num_warps=4, ) return y def _experts_dual_gemv(x: torch.Tensor, idx: torch.Tensor, a, b) -> tuple[torch.Tensor, torch.Tensor]: n = idx.numel() ya = torch.empty((n, a.out_f), device=x.device, dtype=torch.float32) yb = torch.empty((n, b.out_f), device=x.device, dtype=torch.float32) _experts_dual_gemv_kernel[(n, _ceil_div(a.out_f, 32))]( x, idx, a.w_q, a.scales, a.zeros, b.w_q, b.scales, b.zeros, ya, yb, a.in_f, a.out_f, a.in_f // GROUP_SIZE, BLOCK_N=32, num_warps=4, ) return ya, yb def _experts_down(h: torch.Tensor, coeff: torch.Tensor, idx: torch.Tensor, down, out: torch.Tensor, add: bool) -> torch.Tensor: _experts_down_weighted_kernel[(_ceil_div(down.out_f, 32),)]( h, coeff, idx, down.w_q, down.scales, down.zeros, out, down.in_f, down.out_f, down.in_f // GROUP_SIZE, idx.numel(), add, BLOCK_N=32, num_warps=4, ) return out def _moe_dual_gemv(x: torch.Tensor, idx: torch.Tensor, gate, up, s_gate, s_up) -> tuple[torch.Tensor, torch.Tensor]: active = idx.numel() shared = s_gate.n rows = active + shared yg = torch.empty((rows, gate.out_f), device=x.device, dtype=torch.float32) yu = torch.empty((rows, up.out_f), device=x.device, dtype=torch.float32) _moe_dual_gemv_kernel[(rows, _ceil_div(gate.out_f, 32))]( x, idx, gate.w_q, gate.scales, gate.zeros, up.w_q, up.scales, up.zeros, s_gate.w_q, s_gate.scales, s_gate.zeros, s_up.w_q, s_up.scales, s_up.zeros, yg, yu, gate.in_f, gate.out_f, gate.in_f // GROUP_SIZE, active, shared, BLOCK_N=32, num_warps=4, ) return yg, yu def _moe_down(h: torch.Tensor, coeff: torch.Tensor, idx: torch.Tensor, down, s_down) -> torch.Tensor: out = torch.empty((down.out_f,), device=h.device, dtype=torch.float32) active = idx.numel() shared = s_down.n _moe_down_kernel[(_ceil_div(down.out_f, 32),)]( h, coeff, idx, down.w_q, down.scales, down.zeros, s_down.w_q, s_down.scales, s_down.zeros, out, down.in_f, down.out_f, down.in_f // GROUP_SIZE, active, shared, BLOCK_N=32, num_warps=4, ) return out def _mla_q_abs(q_nope: torch.Tensor, kv_b) -> torch.Tensor: out = torch.empty((32, 512), device=q_nope.device, dtype=torch.bfloat16) _mla_q_abs_kernel[(32, _ceil_div(512, 32))]( q_nope, kv_b.w_q, kv_b.scales, kv_b.zeros, out, 32, 512, kv_b.out_f, BLOCK_K=32, num_warps=4, ) return out def _mla_v_out(ctx: torch.Tensor, kv_b) -> torch.Tensor: out = torch.empty((32, 128), device=ctx.device, dtype=torch.bfloat16) _mla_v_out_kernel[(32, _ceil_div(128, 32))]( ctx, kv_b.w_q, kv_b.scales, kv_b.zeros, out, 32, 512, kv_b.out_f, BLOCK_N=32, num_warps=4, ) return out 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 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) 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 forward(self, x: torch.Tensor) -> torch.Tensor: return _fused_gemv(x.contiguous(), self.w_q, self.scales, self.zeros, self.in_f, self.out_f) 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 _rmsnorm(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor: if x.is_cuda: return _fused_rmsnorm(x, w) 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) 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): return _fused_short_conv(val, prev, self.conv_w[idx]) def step(self, x, st): H, Dk = self.cfg.kda_heads, self.cfg.kda_head_dim qkvg = _kda_qkvg(x, self.q_proj, self.k_proj, self.v_proj, self.g_proj) q, k, v, g_raw = qkvg[0], qkvg[1], qkvg[2], qkvg[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_raw.float())).view(H, Dk) beta = torch.sigmoid(self.beta_proj(x).float()) S = st["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) st["S"] = S 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] 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) 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) q_abs = _mla_q_abs(q_nope, self.kv_b) scores = (q_abs @ st["c_kv"].t()).float() scores = scores + (q_rope.float() @ st["k_rope"].float().t()) scores = scores * self.scale p = torch.softmax(scores, dim=-1).to(torch.bfloat16) ctx = p @ st["c_kv"] o = _mla_v_out(ctx.contiguous(), self.kv_b) return self.o_proj(o.reshape(H * cfg.v_head)) 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) self.register_buffer("_shared_idx", torch.arange(cfg.n_shared, dtype=torch.int64), persistent=False) self.register_buffer("_shared_coeff", torch.ones(cfg.n_shared, dtype=torch.float32), persistent=False) 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 g, u = _moe_dual_gemv(x, idx, self.gate, self.up, self.s_gate, self.s_up) h = F.silu(g) * u out = _moe_down(h.contiguous(), w.contiguous(), idx, self.down, self.s_down) return out.to(torch.bfloat16) class Block(nn.Module): def __init__(self, cfg, kind): 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): hidden = blk.step(hidden, state[i]) return hidden, state 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