KernelBench mega · RTX PRO 6000
Kimi-Linear Decode hy3-preview
wrongdid not score
harnesshy3-claude
Kernel source (redacted)
"""Kimi-Linear W4A16 decode - fused dequant-GEMV.
Optimized implementation with:
1. Fused int4 dequant directly into GEMV (never materialize bf16 weights)
2. Proper 2D handling for MLA kv_b projection (fused dequant matmul)
3. Correct forward pass matching reference.py exactly
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from dataclasses import dataclass, field
from pathlib import Path
import math
# --------------------------------------------------------------------------- #
# Config (must match reference.py exactly)
# --------------------------------------------------------------------------- #
@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)))
# --------------------------------------------------------------------------- #
# Quantization (must match reference.py for weight loading)
# --------------------------------------------------------------------------- #
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 = 128):
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)
# --------------------------------------------------------------------------- #
# Triton fused dequant GEMV kernel
# --------------------------------------------------------------------------- #
import triton
import triton.language as tl
@triton.jit
def fused_gemv_kernel(
x_ptr, w_q_ptr, scales_ptr, zeros_ptr, y_ptr,
K, N, GROUP_SIZE,
BLOCK_N: tl.constexpr,
):
"""Fused int4 dequant GEMV: y[N] = x[K] @ dequant(W[K/2, N])."""
pid = tl.program_id(0)
offs_n = pid * BLOCK_N + tl.arange(0, BLOCK_N)
mask_n = offs_n < N
# Initialize accumulator
acc = tl.zeros((BLOCK_N,), dtype=tl.float32)
K2 = K // 2
for i2 in range(K2):
# Load packed weights for all output elements in this block
w_packed = tl.load(
w_q_ptr + i2 * N + offs_n,
mask=mask_n,
other=0
).to(tl.uint8)
# Unpack
w0_int4 = w_packed & 0xF
w1_int4 = (w_packed >> 4) & 0xF
# Load x values
x0 = tl.load(x_ptr + i2 * 2).to(tl.float32)
x1 = tl.load(x_ptr + i2 * 2 + 1).to(tl.float32)
# Compute group indices
g0 = (i2 * 2) // GROUP_SIZE
g1 = (i2 * 2 + 1) // GROUP_SIZE
# Load scales and zeros
scale0 = tl.load(scales_ptr + g0 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
zero0 = tl.load(zeros_ptr + g0 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
scale1 = tl.load(scales_ptr + g1 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
zero1 = tl.load(zeros_ptr + g1 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
# Dequantize
w0 = (w0_int4.to(tl.float32) - zero0) * scale0
w1 = (w1_int4.to(tl.float32) - zero1) * scale1
# Accumulate
acc += x0 * w0 + x1 * w1
tl.store(y_ptr + offs_n, acc.to(tl.float32), mask=mask_n)
def fused_gemv(x, w_q, scales, zeros):
"""Fused dequant GEMV: y = x @ dequant(W)."""
K, N = x.shape[0], w_q.shape[1]
y = torch.empty(N, dtype=torch.float32, device=x.device)
BLOCK_N = 256
grid = (triton.cdiv(N, BLOCK_N),)
fused_gemv_kernel[grid](
x, w_q, scales, zeros, y,
K, N, 128,
BLOCK_N,
)
return y.to(torch.bfloat16)
# --------------------------------------------------------------------------- #
# Batched fused GEMV (compute multiple GEMVs at once)
# --------------------------------------------------------------------------- #
@triton.jit
def batched_gemv_kernel(
x_ptr,
w_q_ptr0, scales_ptr0, zeros_ptr0, y_ptr0,
w_q_ptr1, scales_ptr1, zeros_ptr1, y_ptr1,
w_q_ptr2, scales_ptr2, zeros_ptr2, y_ptr2,
w_q_ptr3, scales_ptr3, zeros_ptr3, y_ptr3,
K, N, GROUP_SIZE,
BLOCK_N: tl.constexpr,
):
"""Batched fused dequant GEMV: compute 4 GEMVs at once."""
pid = tl.program_id(0)
offs_n = pid * BLOCK_N + tl.arange(0, BLOCK_N)
mask_n = offs_n < N
# Initialize accumulators
acc0 = tl.zeros((BLOCK_N,), dtype=tl.float32)
acc1 = tl.zeros((BLOCK_N,), dtype=tl.float32)
acc2 = tl.zeros((BLOCK_N,), dtype=tl.float32)
acc3 = tl.zeros((BLOCK_N,), dtype=tl.float32)
K2 = K // 2
for i2 in range(K2):
# Load x values
x0 = tl.load(x_ptr + i2 * 2).to(tl.float32)
x1 = tl.load(x_ptr + i2 * 2 + 1).to(tl.float32)
# Load packed weights for all 4 projections
w_packed0 = tl.load(w_q_ptr0 + i2 * N + offs_n, mask=mask_n, other=0).to(tl.uint8)
w_packed1 = tl.load(w_q_ptr1 + i2 * N + offs_n, mask=mask_n, other=0).to(tl.uint8)
w_packed2 = tl.load(w_q_ptr2 + i2 * N + offs_n, mask=mask_n, other=0).to(tl.uint8)
w_packed3 = tl.load(w_q_ptr3 + i2 * N + offs_n, mask=mask_n, other=0).to(tl.uint8)
# Unpack all
w0_int4_0 = w_packed0 & 0xF
w1_int4_0 = (w_packed0 >> 4) & 0xF
w0_int4_1 = w_packed1 & 0xF
w1_int4_1 = (w_packed1 >> 4) & 0xF
w0_int4_2 = w_packed2 & 0xF
w1_int4_2 = (w_packed2 >> 4) & 0xF
w0_int4_3 = w_packed3 & 0xF
w1_int4_3 = (w_packed3 >> 4) & 0xF
# Compute group indices
g0 = (i2 * 2) // GROUP_SIZE
g1 = (i2 * 2 + 1) // GROUP_SIZE
# Load scales and zeros for all 4 projections
scale0_0 = tl.load(scales_ptr0 + g0 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
zero0_0 = tl.load(zeros_ptr0 + g0 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
scale1_0 = tl.load(scales_ptr0 + g1 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
zero1_0 = tl.load(zeros_ptr0 + g1 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
scale0_1 = tl.load(scales_ptr1 + g0 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
zero0_1 = tl.load(zeros_ptr1 + g0 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
scale1_1 = tl.load(scales_ptr1 + g1 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
zero1_1 = tl.load(zeros_ptr1 + g1 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
scale0_2 = tl.load(scales_ptr2 + g0 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
zero0_2 = tl.load(zeros_ptr2 + g0 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
scale1_2 = tl.load(scales_ptr2 + g1 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
zero1_2 = tl.load(zeros_ptr2 + g1 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
scale0_3 = tl.load(scales_ptr3 + g0 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
zero0_3 = tl.load(zeros_ptr3 + g0 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
scale1_3 = tl.load(scales_ptr3 + g1 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
zero1_3 = tl.load(zeros_ptr3 + g1 * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
# Dequantize all
w0_0 = (w0_int4_0.to(tl.float32) - zero0_0) * scale0_0
w1_0 = (w1_int4_0.to(tl.float32) - zero1_0) * scale1_0
w0_1 = (w0_int4_1.to(tl.float32) - zero0_1) * scale0_1
w1_1 = (w1_int4_1.to(tl.float32) - zero1_1) * scale1_1
w0_2 = (w0_int4_2.to(tl.float32) - zero0_2) * scale0_2
w1_2 = (w1_int4_2.to(tl.float32) - zero1_2) * scale1_2
w0_3 = (w0_int4_3.to(tl.float32) - zero0_3) * scale0_3
w1_3 = (w1_int4_3.to(tl.float32) - zero1_3) * scale1_3
# Accumulate all
acc0 += x0 * w0_0 + x1 * w1_0
acc1 += x0 * w0_1 + x1 * w1_1
acc2 += x0 * w0_2 + x1 * w1_2
acc3 += x0 * w0_3 + x1 * w1_3
tl.store(y_ptr0 + offs_n, acc0.to(tl.float32), mask=mask_n)
tl.store(y_ptr1 + offs_n, acc1.to(tl.float32), mask=mask_n)
tl.store(y_ptr2 + offs_n, acc2.to(tl.float32), mask=mask_n)
tl.store(y_ptr3 + offs_n, acc3.to(tl.float32), mask=mask_n)
def batched_gemv_4(x, w_q_list, scales_list, zeros_list):
"""Compute 4 GEMVs at once: y_j = x @ dequant(W_j)."""
K = x.shape[0]
N = w_q_list[0].shape[1]
y_list = [torch.empty(N, dtype=torch.float32, device=x.device) for _ in range(4)]
BLOCK_N = 256
grid = (triton.cdiv(N, BLOCK_N),)
batched_gemv_kernel[grid](
x,
w_q_list[0], scales_list[0], zeros_list[0], y_list[0],
w_q_list[1], scales_list[1], zeros_list[1], y_list[1],
w_q_list[2], scales_list[2], zeros_list[2], y_list[2],
w_q_list[3], scales_list[3], zeros_list[3], y_list[3],
K, N, 128,
BLOCK_N,
)
return [y.to(torch.bfloat16) for y in y_list]
# --------------------------------------------------------------------------- #
# Triton fused dequant GEMM kernel (for 2D case: MLA kv_b projection)
# --------------------------------------------------------------------------- #
@triton.jit
def fused_gemm_kernel(
X_ptr, w_q_ptr, scales_ptr, zeros_ptr, Y_ptr,
M, K, N, GROUP_SIZE,
BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr,
):
"""Fused int4 dequant GEMM: Y[M, N] = X[M, K] @ dequant(W[K/2, N])."""
pid_m = tl.program_id(0)
pid_n = tl.program_id(1)
offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
mask_m = offs_m < M
mask_n = offs_n < N
# Initialize accumulator
acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
K2 = K // 2
for i2 in range(K2):
# Load X tile
x0 = tl.load(X_ptr + offs_m[:, None] * K + i2 * 2, mask=mask_m[:, None], other=0.0).to(tl.float32)
x1 = tl.load(X_ptr + offs_m[:, None] * K + i2 * 2 + 1, mask=mask_m[:, None], other=0.0).to(tl.float32)
# Load packed weights
w_packed = tl.load(
w_q_ptr + i2 * N + offs_n[None, :],
mask=mask_n[None, :],
other=0
).to(tl.uint8)
# Unpack
w0_int4 = w_packed & 0xF
w1_int4 = (w_packed >> 4) & 0xF
# Load scales and zeros
g0 = (i2 * 2) // GROUP_SIZE
g1 = (i2 * 2 + 1) // GROUP_SIZE
scale0 = tl.load(scales_ptr + g0 * N + offs_n[None, :], mask=mask_n[None, :], other=0.0).to(tl.float32)
zero0 = tl.load(zeros_ptr + g0 * N + offs_n[None, :], mask=mask_n[None, :], other=0.0).to(tl.float32)
scale1 = tl.load(scales_ptr + g1 * N + offs_n[None, :], mask=mask_n[None, :], other=0.0).to(tl.float32)
zero1 = tl.load(zeros_ptr + g1 * N + offs_n[None, :], mask=mask_n[None, :], other=0.0).to(tl.float32)
# Dequantize
w0 = (w0_int4.to(tl.float32) - zero0) * scale0
w1 = (w1_int4.to(tl.float32) - zero1) * scale1
# Accumulate
acc += x0 * w0 + x1 * w1
tl.store(Y_ptr + offs_m[:, None] * N + offs_n[None, :], acc.to(tl.float32), mask=mask_m[:, None] & mask_n[None, :])
def fused_gemm(X, w_q, scales, zeros):
"""Fused dequant GEMM: Y = X @ dequant(W)."""
M, K = X.shape
N = w_q.shape[1]
Y = torch.empty((M, N), dtype=torch.float32, device=X.device)
BLOCK_M, BLOCK_N = 32, 128
grid = (triton.cdiv(M, BLOCK_M), triton.cdiv(N, BLOCK_N))
fused_gemm_kernel[grid](
X, w_q, scales, zeros, Y,
M, K, N, 128,
BLOCK_M, BLOCK_N,
)
return Y.to(torch.bfloat16)
# --------------------------------------------------------------------------- #
# Batched fused GEMM (compute multiple GEMMs at once)
# --------------------------------------------------------------------------- #
@triton.jit
def batched_gemm_kernel(
X_ptr,
w_q_ptr0, scales_ptr0, zeros_ptr0, Y_ptr0,
w_q_ptr1, scales_ptr1, zeros_ptr1, Y_ptr1,
M, K, N, GROUP_SIZE,
BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr,
):
"""Batched fused dequant GEMM: compute 2 GEMMs at once."""
pid_m = tl.program_id(0)
pid_n = tl.program_id(1)
offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
mask_m = offs_m < M
mask_n = offs_n < N
# Initialize accumulators
acc0 = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
acc1 = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
K2 = K // 2
for i2 in range(K2):
# Load X tile
x0 = tl.load(X_ptr + offs_m[:, None] * K + i2 * 2, mask=mask_m[:, None], other=0.0).to(tl.float32)
x1 = tl.load(X_ptr + offs_m[:, None] * K + i2 * 2 + 1, mask=mask_m[:, None], other=0.0).to(tl.float32)
# Load packed weights for both projections
w_packed0 = tl.load(w_q_ptr0 + i2 * N + offs_n[None, :], mask=mask_n[None, :], other=0).to(tl.uint8)
w_packed1 = tl.load(w_q_ptr1 + i2 * N + offs_n[None, :], mask=mask_n[None, :], other=0).to(tl.uint8)
# Unpack
w0_int4_0 = w_packed0 & 0xF
w1_int4_0 = (w_packed0 >> 4) & 0xF
w0_int4_1 = w_packed1 & 0xF
w1_int4_1 = (w_packed1 >> 4) & 0xF
# Load scales and zeros
g0 = (i2 * 2) // GROUP_SIZE
g1 = (i2 * 2 + 1) // GROUP_SIZE
scale0_0 = tl.load(scales_ptr0 + g0 * N + offs_n[None, :], mask=mask_n[None, :], other=0.0).to(tl.float32)
zero0_0 = tl.load(zeros_ptr0 + g0 * N + offs_n[None, :], mask=mask_n[None, :], other=0.0).to(tl.float32)
scale1_0 = tl.load(scales_ptr0 + g1 * N + offs_n[None, :], mask=mask_n[None, :], other=0.0).to(tl.float32)
zero1_0 = tl.load(zeros_ptr0 + g1 * N + offs_n[None, :], mask=mask_n[None, :], other=0.0).to(tl.float32)
scale0_1 = tl.load(scales_ptr1 + g0 * N + offs_n[None, :], mask=mask_n[None, :], other=0.0).to(tl.float32)
zero0_1 = tl.load(zeros_ptr1 + g0 * N + offs_n[None, :], mask=mask_n[None, :], other=0.0).to(tl.float32)
scale1_1 = tl.load(scales_ptr1 + g1 * N + offs_n[None, :], mask=mask_n[None, :], other=0.0).to(tl.float32)
zero1_1 = tl.load(zeros_ptr1 + g1 * N + offs_n[None, :], mask=mask_n[None, :], other=0.0).to(tl.float32)
# Dequantize
w0_0 = (w0_int4_0.to(tl.float32) - zero0_0) * scale0_0
w1_0 = (w1_int4_0.to(tl.float32) - zero1_0) * scale1_0
w0_1 = (w0_int4_1.to(tl.float32) - zero0_1) * scale0_1
w1_1 = (w1_int4_1.to(tl.float32) - zero1_1) * scale1_1
# Accumulate
acc0 += x0 * w0_0 + x1 * w1_0
acc1 += x0 * w0_1 + x1 * w1_1
tl.store(Y_ptr0 + offs_m[:, None] * N + offs_n[None, :], acc0.to(tl.float32), mask=mask_m[:, None] & mask_n[None, :])
tl.store(Y_ptr1 + offs_m[:, None] * N + offs_n[None, :], acc1.to(tl.float32), mask=mask_m[:, None] & mask_n[None, :])
def batched_gemm_2(X, w_q_list, scales_list, zeros_list):
"""Compute 2 GEMMs at once: Y_j = X @ dequant(W_j)."""
M, K = X.shape
N = w_q_list[0].shape[1]
Y_list = [torch.empty((M, N), dtype=torch.float32, device=X.device) for _ in range(2)]
BLOCK_M, BLOCK_N = 32, 128
grid = (triton.cdiv(M, BLOCK_M), triton.cdiv(N, BLOCK_N))
batched_gemm_kernel[grid](
X,
w_q_list[0], scales_list[0], zeros_list[0], Y_list[0],
w_q_list[1], scales_list[1], zeros_list[1], Y_list[1],
M, K, N, 128,
BLOCK_M, BLOCK_N,
)
return [Y.to(torch.bfloat16) for Y in Y_list]
# --------------------------------------------------------------------------- #
# Quantized linear layers
# --------------------------------------------------------------------------- #
class QuantLinear(nn.Module):
"""W4A16 linear layer with fused dequant GEMV/GEMM."""
def __init__(self, in_f, out_f, group=128):
super().__init__()
self.in_f = in_f
self.out_f = out_f
self.group = 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):
if x.dim() == 1:
# 1D case: GEMV
return fused_gemv(x, self.w_q, self.scales, self.zeros)
else:
# 2D case: GEMM
return fused_gemm(x, self.w_q, self.scales, self.zeros)
class QuantExperts(nn.Module):
"""Quantized expert weights for MoE."""
def __init__(self, n, in_f, out_f, group=128):
super().__init__()
self.n = n
self.in_f = in_f
self.out_f = out_f
self.group = 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 dequant(self, e):
"""Dequant expert e to bf16 [in_f, out_f]."""
K = self.in_f
N = self.out_f
ng = K // self.group
# Unpack
w_packed = self.w_q[e] # [K/2, N]
w = torch.empty((K, N), dtype=torch.uint8, device=w_packed.device)
w[0::2] = w_packed & 0xF
w[1::2] = (w_packed >> 4) & 0xF
# Dequant
scales = self.scales[e].repeat_interleave(self.group, dim=0) # [K, N]
zeros = self.zeros[e].repeat_interleave(self.group, dim=0) # [K, N]
return (w.to(torch.float32) - zeros.float()) * scales.float()
# --------------------------------------------------------------------------- #
# Helper functions (from reference.py)
# --------------------------------------------------------------------------- #
def _rmsnorm(x, w):
return (x * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + 1e-6) * w.float()).to(x.dtype)
def _rope_cossin(pos, d, theta, device):
freq = 1.0 / (theta ** (torch.arange(0, d, 2, device=device, dtype=torch.float32) / d))
inv = pos * freq
return torch.cos(inv).to(torch.bfloat16), torch.sin(inv).to(torch.bfloat16)
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.to(x.dtype)
# --------------------------------------------------------------------------- #
# KDA layer
# --------------------------------------------------------------------------- #
class KDA(nn.Module):
def __init__(self, cfg, idx):
super().__init__()
self.cfg = cfg
H, Dk = cfg.kda_heads, cfg.kda_head_dim
self.q_proj = QuantLinear(cfg.hidden, H * Dk, cfg.group)
self.k_proj = QuantLinear(cfg.hidden, H * Dk, cfg.group)
self.v_proj = QuantLinear(cfg.hidden, H * Dk, cfg.group)
self.g_proj = QuantLinear(cfg.hidden, H * Dk, cfg.group)
self.beta_proj = nn.Linear(cfg.hidden, 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, cfg.hidden, cfg.group)
self.scale = 1.0 / math.sqrt(Dk)
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
# Batch q, k, v, g projections into one kernel launch
w_q_list = [self.q_proj.w_q, self.k_proj.w_q, self.v_proj.w_q, self.g_proj.w_q]
scales_list = [self.q_proj.scales, self.k_proj.scales, self.v_proj.scales, self.g_proj.scales]
zeros_list = [self.q_proj.zeros, self.k_proj.zeros, self.v_proj.zeros, self.g_proj.zeros]
q, k, v, g = batched_gemv_4(x, w_q_list, scales_list, zeros_list)
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.to(x.dtype)).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))
# --------------------------------------------------------------------------- #
# MLA layer
# --------------------------------------------------------------------------- #
class MLA(nn.Module):
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
H = cfg.mla_heads
self.q_proj = QuantLinear(cfg.hidden, H * (cfg.qk_nope + cfg.qk_rope), cfg.group)
self.kv_a = QuantLinear(cfg.hidden, 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, cfg.hidden, cfg.group)
self.scale = 1.0 / math.sqrt(cfg.qk_nope)
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)
kvb = self.kv_b(st["c_kv"]).view(-1, H, cfg.qk_nope + cfg.v_head).float()
k_nope = kvb[..., :cfg.qk_nope]
v = kvb[..., cfg.qk_nope:]
q_nope_f = q_nope.float()
q_rope_f = q_rope.float()
k_rope_f = st["k_rope"].float()
scores = (torch.einsum("hd,lhd->lh", q_nope_f, k_nope).float()
+ torch.einsum("hd,ld->lh", q_rope_f, k_rope_f).float()) * self.scale
p = torch.softmax(scores, dim=0).to(x.dtype)
o = torch.einsum("lh,lhd->hd", p.float(), v)
return self.o_proj(o.reshape(H * cfg.v_head).to(torch.bfloat16))
# --------------------------------------------------------------------------- #
# MoE layer - FIXED to properly use fused dequant
# --------------------------------------------------------------------------- #
class MoE(nn.Module):
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
self.router = nn.Linear(cfg.hidden, cfg.n_experts, bias=False, dtype=cfg.dtype)
self.gate = QuantExperts(cfg.n_experts, cfg.hidden, cfg.moe_inter, cfg.group)
self.up = QuantExperts(cfg.n_experts, cfg.hidden, cfg.moe_inter, cfg.group)
self.down = QuantExperts(cfg.n_experts, cfg.moe_inter, cfg.hidden, cfg.group)
self.s_gate = QuantExperts(cfg.n_shared, cfg.hidden, cfg.moe_inter, cfg.group)
self.s_up = QuantExperts(cfg.n_shared, cfg.hidden, cfg.moe_inter, cfg.group)
self.s_down = QuantExperts(cfg.n_shared, cfg.moe_inter, cfg.hidden, cfg.group)
def _ffn(self, x, gate, up, down, e):
"""Compute FFN for expert e using dequantized weights."""
# Dequant weights
gw = gate.dequant(e) # [hidden, moe_inter]
uw = up.dequant(e)
dw = down.dequant(e)
# Compute
g = F.silu(x.float() @ gw)
u = x.float() @ uw
h = g * u
return h @ dw
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)
out = x.new_zeros(cfg.hidden, dtype=torch.float32)
for j in range(cfg.n_active):
out = out + w[j] * self._ffn(x, self.gate, self.up, self.down, int(idx[j]))
for s in range(cfg.n_shared):
out = out + self._ffn(x, self.s_gate, self.s_up, self.s_down, s)
return out.to(torch.bfloat16)
# --------------------------------------------------------------------------- #
# Block and Model
# --------------------------------------------------------------------------- #
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, 0) 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
# --------------------------------------------------------------------------- #
# State initialization
# --------------------------------------------------------------------------- #
def init_state(cfg, ctx, seed):
torch.manual_seed(seed)
state = []
for k in cfg.pattern:
st = {}
if k == "K":
st["S"] = torch.randn(cfg.kda_heads, cfg.kda_head_dim, cfg.kda_head_dim, dtype=cfg.dtype)
st["cq"] = torch.randn(cfg.short_conv - 1, cfg.kda_heads * cfg.kda_head_dim, dtype=cfg.dtype)
st["ck"] = torch.randn(cfg.short_conv - 1, cfg.kda_heads * cfg.kda_head_dim, dtype=cfg.dtype)
st["cv"] = torch.randn(cfg.short_conv - 1, cfg.kda_heads * cfg.kda_head_dim, dtype=cfg.dtype)
else:
st["c_kv"] = torch.randn(ctx, cfg.kv_lora, dtype=cfg.dtype)
st["k_rope"] = torch.randn(ctx, cfg.qk_rope, dtype=cfg.dtype)
state.append(st)
return state
def init_token(cfg, seed):
torch.manual_seed(seed + 1)
return torch.randn(cfg.hidden, dtype=cfg.dtype)
if __name__ == "__main__":
cfg = build_config({"n_experts": 64})
m = Model(cfg).cuda().eval()
st = init_state(cfg, 2048, 0)
h = init_token(cfg, 0)
with torch.no_grad():
for _ in range(4):
h, st = m.step(h, st)
torch.cuda.synchronize()
print(f"ok: out {tuple(h.shape)} finite {torch.isfinite(h).all().item()}")
20260707_175932_hy3-claude_tencent_hy3-preview_02_kimi_linear_decode