KernelBench mega · RTX PRO 6000

Kimi-Linear Decode Kimi K2.7-Code

bugdid not score

Published row with no score: failure_reason=timeout, correct=false. A solution was written but check.py raised a Triton autotune error ('Conflicting meta-parameters: BLOCK_KQ, BLOCK_N') before any cosine check. Not a hack — a broken/incomplete attempt.

harnesskimi-claude
Kernel source (redacted)
"""Fused int4 dequant-GEMV decode solution for Kimi-Linear W4A16.

Key ideas:
- Triton kernel that streams int4 weights once: unpack two nibbles per byte,
  applies per-group scale/zero dequant, and accumulates y = x @ W on the fly.
- MLA uses the absorb form so the growing latent cache is never materialised
  through kv_b; W_kv_b is split per-head and kept in int4.
- MoE experts are evaluated with the same fused GEMV, one expert at a time.
- All big projections use bf16 accumulation; small layers (router, beta, norms)
  stay eager 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

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 fused int4 dequant-GEMV
# --------------------------------------------------------------------------- #
@triton.autotune(
    configs=[
        triton.Config({"BLOCK_KQ": 64, "BLOCK_N": 64}, num_warps=4, num_stages=2),
        triton.Config({"BLOCK_KQ": 64, "BLOCK_N": 128}, num_warps=4, num_stages=2),
        triton.Config({"BLOCK_KQ": 128, "BLOCK_N": 64}, num_warps=4, num_stages=2),
        triton.Config({"BLOCK_KQ": 128, "BLOCK_N": 128}, num_warps=4, num_stages=2),
        triton.Config({"BLOCK_KQ": 64, "BLOCK_N": 256}, num_warps=8, num_stages=2),
        triton.Config({"BLOCK_KQ": 128, "BLOCK_N": 256}, num_warps=8, num_stages=2),
        triton.Config({"BLOCK_KQ": 64, "BLOCK_N": 512}, num_warps=8, num_stages=2),
    ],
    key=["K", "N"],
)
@triton.jit
def gemv_int4_kernel(
    x_ptr,
    w_ptr,
    s_ptr,
    z_ptr,
    y_ptr,
    K,
    N,
    stride_wk,
    stride_wn,
    stride_sg,
    stride_sn,
    stride_zg,
    stride_zn,
    BLOCK_KQ: tl.constexpr,
    BLOCK_N: tl.constexpr,
    GROUP_SIZE: tl.constexpr,
):
    """y[n] = sum_k x[k] * ((unpack(w_q)[k,n] - zeros[g,n]) * scales[g,n]).

    w_q is packed along K: byte at kq covers input features (2*kq, 2*kq+1).
    g = kq // (GROUP_SIZE // 2).
    """
    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)

    KQ = K // 2
    GRP = GROUP_SIZE // 2
    for kq0 in range(0, KQ, BLOCK_KQ):
        kq = kq0 + tl.arange(0, BLOCK_KQ)
        mask_kq = kq < KQ

        # packed weights [BLOCK_KQ, BLOCK_N]
        w_b = tl.load(
            w_ptr + kq[:, None] * stride_wk + offs_n[None, :] * stride_wn,
            mask=mask_kq[:, None] & mask_n[None, :],
            other=0,
        )
        lo = (w_b & 0xF).to(tl.float32)
        hi = ((w_b >> 4) & 0xF).to(tl.float32)

        # input pair
        k_lo = 2 * kq
        k_hi = 2 * kq + 1
        x_lo = tl.load(x_ptr + k_lo, mask=k_lo < K, other=0.0).to(tl.float32)
        x_hi = tl.load(x_ptr + k_hi, mask=k_hi < K, other=0.0).to(tl.float32)

        # per-group scale / zero (same group for all kq in a 64-byte block)
        g = kq // GRP
        s = tl.load(
            s_ptr + g[:, None] * stride_sg + offs_n[None, :] * stride_sn,
            mask=mask_kq[:, None] & mask_n[None, :],
            other=0.0,
        ).to(tl.float32)
        z = tl.load(
            z_ptr + g[:, None] * stride_zg + offs_n[None, :] * stride_zn,
            mask=mask_kq[:, None] & mask_n[None, :],
            other=0.0,
        ).to(tl.float32)

        # contribution for this kq pair:
        # x_lo*(lo-z)*s + x_hi*(hi-z)*s
        # = s*(x_lo*lo + x_hi*hi) - s*z*(x_lo+x_hi)
        contrib = s * (x_lo[:, None] * lo + x_hi[:, None] * hi)
        contrib = contrib - (s * z) * (x_lo[:, None] + x_hi[:, None])
        acc += tl.sum(contrib, axis=0)

    tl.store(y_ptr + offs_n, acc.to(tl.bfloat16), mask=mask_n)


def gemv_int4(x: torch.Tensor, w_q: torch.Tensor, scales: torch.Tensor, zeros: torch.Tensor,
              group: int = GROUP_SIZE) -> torch.Tensor:
    """Fused int4 GEMV for a single vector: x @ W.

    x: [K] or [1, K] bf16/fp16/fp32
    w_q: [K//2, N] uint8
    scales, zeros: [K//group, N] bf16
    returns: [N] bf16
    """
    if x.dim() == 1:
        pass
    elif x.dim() == 2 and x.shape[0] == 1:
        x = x.squeeze(0)
    else:
        raise ValueError(f"gemv_int4 expects M=1, got x shape {x.shape}")

    K = x.shape[0]
    N = w_q.shape[1]
    assert K % 2 == 0 and K % group == 0
    y = torch.empty(N, dtype=torch.bfloat16, device=x.device)

    # simple heuristic tuning
    if N >= 4096:
        block_n = 512
    elif N >= 1024:
        block_n = 256
    else:
        block_n = 128
    block_kq = 64

    grid = (triton.cdiv(N, block_n),)
    gemv_int4_kernel[grid](
        x, w_q, scales, zeros, y,
        K, N,
        w_q.stride(0), w_q.stride(1),
        scales.stride(0), scales.stride(1),
        zeros.stride(0), zeros.stride(1),
        BLOCK_KQ=block_kq, BLOCK_N=block_n, GROUP_SIZE=group,
    )
    return y


# --------------------------------------------------------------------------- #
# Quantized linear / expert wrappers
# --------------------------------------------------------------------------- #
class QuantLinear(nn.Module):
    """Buffer names match the canonical oracle; forward uses fused int4 GEMV."""

    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:
        return gemv_int4(x, self.w_q, self.scales, self.zeros, self.group)


class QuantExperts(nn.Module):
    """E independent int4 expert weights. forward picks one expert index."""

    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 forward(self, x: torch.Tensor, e: int) -> torch.Tensor:
        return gemv_int4(x, self.w_q[e], self.scales[e], self.zeros[e], 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)


# --------------------------------------------------------------------------- #
# 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 _ensure_absorb(self):
        """Dequant kv_b once and split into per-head bf16 matrices for the absorb form.

        Stored as plain attributes (not registered buffers) so strict state_dict load works.
        W_k[h] is [kv_lora, qk_nope] so q_nope[h] @ W_k[h].T -> [kv_lora].
        W_v[h] is [kv_lora, v_head] so ctx[h] @ W_v[h] -> [v_head].
        """
        if hasattr(self, "_W_k"):
            return
        cfg = self.cfg
        H = cfg.mla_heads
        device = self.kv_b.w_q.device
        # dequant full kv_b (small, ~8 MB bf16) once
        w_b = self.kv_b.w_q
        K, N = w_b.shape
        out = torch.empty((K * 2, N), dtype=torch.uint8, device=device)
        out[0::2] = w_b & 0xF
        out[1::2] = (w_b >> 4) & 0xF
        s = self.kv_b.scales.repeat_interleave(cfg.group, dim=0)
        z = self.kv_b.zeros.repeat_interleave(cfg.group, dim=0)
        w_bf = (out.to(torch.bfloat16) - z) * s  # [kv_lora, H*(qk_nope+v_head)]

        W_k = torch.empty(H, cfg.kv_lora, cfg.qk_nope, dtype=torch.bfloat16, device=device)
        W_v = torch.empty(H, cfg.kv_lora, cfg.v_head, dtype=torch.bfloat16, device=device)
        for h in range(H):
            k_start = h * cfg.qk_nope
            k_end = k_start + cfg.qk_nope
            v_start = H * cfg.qk_nope + h * cfg.v_head
            v_end = v_start + cfg.v_head
            W_k[h] = w_bf[:, k_start:k_end]
            W_v[h] = w_bf[:, v_start:v_end]
        self._W_k = W_k
        self._W_v = W_v

    def step(self, x, st):
        cfg = self.cfg
        H = cfg.mla_heads
        self._ensure_absorb()
        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)

        # absorb form: avoid materialising [L, H, D]
        a_k = torch.stack([q_nope[h] @ self._W_k[h].t().float() for h in range(H)], dim=0)  # [H, kv_lora]
        scores_nope = a_k @ st["c_kv"].T.float()  # [H, L]
        scores_rope = q_rope @ st["k_rope"].T.float()  # [H, L]
        scores = (scores_nope + scores_rope) * self.scale  # [H, L]
        p = torch.softmax(scores, dim=-1)  # [H, L]

        ctx = p @ st["c_kv"].float()  # [H, kv_lora]
        o = torch.stack([ctx[h] @ self._W_v[h].float() for h in range(H)], dim=0)  # [H, v_head]
        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).to(x.dtype)
        out = x.new_zeros(cfg.hidden, dtype=torch.float32)
        for j in range(cfg.n_active):
            h = F.silu(self.gate(x, int(idx[j])).float()) * self.up(x, int(idx[j])).float()
            out = out + w[j] * self.down(h, int(idx[j])).float()
        for s in range(cfg.n_shared):
            h = F.silu(self.s_gate(x, s).float()) * self.s_up(x, s).float()
            out = out + self.s_down(h, s).float()
        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)

    def step(self, hidden, state):
        for i, blk in enumerate(self.blocks):
            hidden = blk.step(hidden, state[i])
        return hidden, state


# --------------------------------------------------------------------------- #
# state / inputs (copied exactly from the oracle)
# --------------------------------------------------------------------------- #
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_211334_kimi-claude_kimi-k2.7-code_02_kimi_linear_decode