KernelBench mega · RTX PRO 6000
Kimi-Linear Decode Kimi K2.7-Code
2.25×geomean speedup across shapes
manually audited: clean
Re-graded 2026-11-16 under grader v3 on tetra: 2.25x (2.59x before; see regrade_v3). Original audit: RTX PRO 6000 Kimi-k2.7-code cell (2.59x), the only passing Kimi run. Real Triton int4 dequant kernels (2 jit, nibble unpack). Forbidden-scan passed; template_mutated=False; correctness clean.
harnesskimi-claude
Kernel source (redacted)
"""Kimi-Linear W4A16 hybrid decode unit — fused int4 dequant-GEMV.
A from-scratch rewrite of reference.py that keeps the same module/state layout
and numerical recipe, but does every weight-bound projection as a fused
int4-unpack + per-group dequant + GEMV so the weights are streamed at int4
bandwidth and never materialized as bf16.
"""
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)))
# --------------------------------------------------------------------------- #
# Fused int4 GEMV kernel
# --------------------------------------------------------------------------- #
@triton.autotune(
configs=[
triton.Config({"BLOCK_K": 128, "BLOCK_N": 64}, num_warps=4, num_stages=1),
triton.Config({"BLOCK_K": 128, "BLOCK_N": 128}, num_warps=4, num_stages=1),
triton.Config({"BLOCK_K": 128, "BLOCK_N": 256}, num_warps=8, num_stages=1),
triton.Config({"BLOCK_K": 128, "BLOCK_N": 128}, num_warps=8, num_stages=1),
],
key=["K", "N"],
)
@triton.jit
def int4_gemv_kernel(
x_ptr,
w_ptr,
s_ptr,
z_ptr,
y_ptr,
K,
N,
stride_wk,
stride_wn,
stride_sg,
stride_sn,
BLOCK_K: 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
acc = tl.zeros((BLOCK_N,), dtype=tl.float32)
num_blocks = (K + BLOCK_K - 1) // BLOCK_K
for b in tl.range(0, num_blocks):
k0 = b * BLOCK_K
offs_kh = k0 // 2 + tl.arange(0, BLOCK_K // 2)
mask_kh = offs_kh < (K // 2)
w_pack = tl.load(
w_ptr + offs_kh[:, None] * stride_wk + offs_n[None, :] * stride_wn,
mask=mask_kh[:, None] & mask_n[None, :],
other=0,
)
lo = w_pack & 0xF
hi = (w_pack >> 4) & 0xF
w_u = tl.trans(tl.interleave(tl.trans(lo), tl.trans(hi)))
g0 = k0 // 128
scale = tl.load(
s_ptr + g0 * stride_sg + offs_n * stride_sn,
mask=mask_n,
other=0.0,
).to(tl.float32)
zero = tl.load(
z_ptr + g0 * stride_sg + offs_n * stride_sn,
mask=mask_n,
other=0.0,
).to(tl.float32)
w_f = (w_u.to(tl.float32) - zero) * scale
offs_k = k0 + tl.arange(0, BLOCK_K)
mask_k = offs_k < K
x = tl.load(x_ptr + offs_k, mask=mask_k, other=0.0).to(tl.float32)
acc += tl.sum(w_f * x[:, None], axis=0)
tl.store(y_ptr + offs_n, acc.to(tl.bfloat16), mask=mask_n)
def fused_int4_gemv(x: torch.Tensor, w_q: torch.Tensor, scales: torch.Tensor, zeros: torch.Tensor) -> torch.Tensor:
"""M=1 GEMV: x @ W, where W is int4 packed + group-128 asymmetric dequant.
x: [K] bf16 or fp16
w_q: [K//2, N] uint8
scales: [K//128, N] bf16
zeros: [K//128, N] bf16
returns: [N] bf16
"""
assert x.dim() == 1
K, N = w_q.shape[0] * 2, w_q.shape[1]
y = torch.empty(N, dtype=x.dtype, device=x.device)
def grid(meta):
return (triton.cdiv(N, meta["BLOCK_N"]),)
int4_gemv_kernel[grid](
x,
w_q,
scales,
zeros,
y,
K,
N,
w_q.stride(0),
w_q.stride(1),
scales.stride(0),
scales.stride(1),
)
return y
@triton.autotune(
configs=[
triton.Config({"BLOCK_K": 128, "BLOCK_N": 64}, num_warps=4, num_stages=1),
triton.Config({"BLOCK_K": 128, "BLOCK_N": 128}, num_warps=4, num_stages=1),
triton.Config({"BLOCK_K": 128, "BLOCK_N": 256}, num_warps=8, num_stages=1),
triton.Config({"BLOCK_K": 128, "BLOCK_N": 128}, num_warps=8, num_stages=1),
],
key=["K", "N", "E"],
)
@triton.jit
def int4_gemv_batched_kernel(
x_ptr,
w_ptr,
s_ptr,
z_ptr,
idx_ptr,
y_ptr,
K,
N,
E,
stride_xe,
stride_we,
stride_wk,
stride_wn,
stride_se,
stride_sg,
stride_sn,
stride_ye,
stride_yn,
BLOCK_K: tl.constexpr,
BLOCK_N: tl.constexpr,
):
pid_e = tl.program_id(0)
pid_n = tl.program_id(1)
e = tl.load(idx_ptr + pid_e).to(tl.int64)
offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
mask_n = offs_n < N
acc = tl.zeros((BLOCK_N,), dtype=tl.float32)
num_blocks = (K + BLOCK_K - 1) // BLOCK_K
for b in tl.range(0, num_blocks):
k0 = b * BLOCK_K
offs_kh = k0 // 2 + tl.arange(0, BLOCK_K // 2)
mask_kh = offs_kh < (K // 2)
w_pack = tl.load(
w_ptr + e * stride_we + offs_kh[:, None] * stride_wk + offs_n[None, :] * stride_wn,
mask=mask_kh[:, None] & mask_n[None, :],
other=0,
)
lo = w_pack & 0xF
hi = (w_pack >> 4) & 0xF
w_u = tl.trans(tl.interleave(tl.trans(lo), tl.trans(hi)))
g0 = k0 // 128
scale = tl.load(
s_ptr + e * stride_se + g0 * stride_sg + offs_n * stride_sn,
mask=mask_n,
other=0.0,
).to(tl.float32)
zero = tl.load(
z_ptr + e * stride_se + g0 * stride_sg + offs_n * stride_sn,
mask=mask_n,
other=0.0,
).to(tl.float32)
w_f = (w_u.to(tl.float32) - zero) * scale
offs_k = k0 + tl.arange(0, BLOCK_K)
mask_k = offs_k < K
x = tl.load(x_ptr + pid_e * stride_xe + offs_k, mask=mask_k, other=0.0).to(tl.float32)
acc += tl.sum(w_f * x[:, None], axis=0)
tl.store(
y_ptr + pid_e * stride_ye + offs_n * stride_yn,
acc.to(tl.bfloat16),
mask=mask_n,
)
def fused_int4_gemv_batched(
x: torch.Tensor,
w_q: torch.Tensor,
scales: torch.Tensor,
zeros: torch.Tensor,
idx: torch.Tensor,
) -> torch.Tensor:
"""Batched M=1 GEMV: for each selected expert i, compute x[i] @ W[idx[i]].
x: [K] or [E_sel, K] bf16
w_q: [E_total, K//2, N] uint8
scales: [E_total, K//128, N] bf16
zeros: [E_total, K//128, N] bf16
idx: [E_sel] int64 (indices into w_q/scales/zeros)
returns: [E_sel, N] bf16
"""
E = idx.numel()
if x.dim() == 1:
x = x.unsqueeze(0).expand(E, -1).contiguous()
assert x.dim() == 2 and x.shape[0] == E
K = w_q.shape[1] * 2
N = w_q.shape[2]
y = torch.empty((E, N), dtype=x.dtype, device=x.device)
def grid(meta):
return (E, triton.cdiv(N, meta["BLOCK_N"]))
int4_gemv_batched_kernel[grid](
x,
w_q,
scales,
zeros,
idx,
y,
K,
N,
E,
x.stride(0),
w_q.stride(0),
w_q.stride(1),
w_q.stride(2),
scales.stride(0),
scales.stride(1),
scales.stride(2),
y.stride(0),
y.stride(1),
)
return y
# --------------------------------------------------------------------------- #
# Quantization containers (same buffer names as reference.py)
# --------------------------------------------------------------------------- #
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)
def dequant(w_q: torch.Tensor, scales: torch.Tensor, zeros: torch.Tensor, K: int, group: int) -> torch.Tensor:
"""Reference dequant (only used for one-time cache warmup)."""
wu = torch.empty((K, w_q.shape[1]), dtype=torch.uint8, device=w_q.device)
wu[0::2] = w_q & 0xF
wu[1::2] = (w_q >> 4) & 0xF
s = scales.repeat_interleave(group, dim=0)[:K]
z = zeros.repeat_interleave(group, dim=0)[:K]
return (wu.to(torch.bfloat16) - 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 forward(self, x: torch.Tensor) -> torch.Tensor:
return fused_int4_gemv(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 forward(self, e: int, x: torch.Tensor) -> torch.Tensor:
return fused_int4_gemv(x, self.w_q[e], self.scales[e], self.zeros[e])
def forward_batched(self, x: torch.Tensor, idx: torch.Tensor) -> torch.Tensor:
return fused_int4_gemv_batched(x, self.w_q, self.scales, self.zeros, idx)
# --------------------------------------------------------------------------- #
# 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)
# --------------------------------------------------------------------------- #
# Layers
# --------------------------------------------------------------------------- #
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
q = self.q_proj(x)
k = self.k_proj(x)
v = self.v_proj(x)
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(self.g_proj(x).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 _warm_cache(self, st):
"""Project the pre-filled compressed latent cache to k_nope / v once."""
if "k_nope" in st and "v" in st:
return
c_kv = st["c_kv"]
L = c_kv.shape[0]
H = self.cfg.mla_heads
# Materialize kv_b for a single batched matmul at startup only.
W = dequant(self.kv_b.w_q, self.kv_b.scales, self.kv_b.zeros, self.cfg.kv_lora, self.cfg.group)
kvb = (c_kv.float() @ W.float()).view(L, H, self.cfg.qk_nope + self.cfg.v_head)
st["k_nope"] = kvb[..., : self.cfg.qk_nope].to(self.cfg.dtype)
st["v"] = kvb[..., self.cfg.qk_nope :].to(self.cfg.dtype)
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)
self._warm_cache(st)
# Project the new token's latent vector and append to the absorbed caches.
kvb_new = self.kv_b(c_kv).view(H, cfg.qk_nope + cfg.v_head).float()
k_nope_new = kvb_new[..., : cfg.qk_nope].to(cfg.dtype)
v_new = kvb_new[..., cfg.qk_nope :].to(cfg.dtype)
st["c_kv"] = torch.cat([st["c_kv"], c_kv[None]], 0)
st["k_rope"] = torch.cat([st["k_rope"], k_rope[None]], 0)
st["k_nope"] = torch.cat([st["k_nope"], k_nope_new[None]], 0)
st["v"] = torch.cat([st["v"], v_new[None]], 0)
scores = (torch.einsum("hd,lhd->lh", q_nope, st["k_nope"].float())
+ torch.einsum("hd,ld->lh", q_rope, st["k_rope"].float())) * self.scale
p = torch.softmax(scores, dim=0).to(x.dtype)
o = torch.einsum("lh,lhd->hd", p, st["v"])
return self.o_proj(o.reshape(H * cfg.v_head).to(torch.bfloat16))
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
routed_idx = idx.to(torch.int64)
shared_idx = torch.arange(cfg.n_shared, device=x.device, dtype=torch.int64)
gate_routed = self.gate.forward_batched(x, routed_idx)
gate_shared = self.s_gate.forward_batched(x, shared_idx)
gate_outs = torch.cat([gate_routed, gate_shared], dim=0)
up_routed = self.up.forward_batched(x, routed_idx)
up_shared = self.s_up.forward_batched(x, shared_idx)
up_outs = torch.cat([up_routed, up_shared], dim=0)
h = F.silu(gate_outs) * up_outs
down_routed = self.down.forward_batched(h[: cfg.n_active], routed_idx)
down_shared = self.s_down.forward_batched(h[cfg.n_active :], shared_idx)
down_outs = torch.cat([down_routed, down_shared], dim=0)
weights = torch.cat([w, torch.ones(cfg.n_shared, device=x.device, dtype=probs.dtype)])
out = (weights[:, None].float() * down_outs.float()).sum(0)
return out.to(torch.bfloat16)
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)
self.reset_parameters()
def reset_parameters(self):
g = torch.Generator(device="cpu").manual_seed(1234)
for mod in self.modules():
if isinstance(mod, (QuantLinear, QuantExperts)):
mod.init_random(g)
elif isinstance(mod, nn.Linear):
nn.init.normal_(mod.weight, 0.0, 0.02, generator=g)
elif isinstance(mod, KDA):
nn.init.normal_(mod.conv_w, 0.0, 0.1, generator=g)
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
20260618_150545_kimi-claude_kimi-k2.7-code_02_kimi_linear_decode