KernelBench mega · RTX PRO 6000

Kimi-Linear Decode Gemini 3.5 Flash

cleandid not score

manually audited: clean

H100 Gemini-3.5-flash cell (2.74x). Real Triton fused int4 dequant-GEMV. Forbidden-scan passed; template_mutated=False; correctness clean.

harnessgemini
Kernel source (redacted)
"""Self-contained Kimi-Linear hybrid decode unit solution.

This implementation contains all the necessary weights, layer definitions, and
the Model class. It implements a highly optimized Triton kernel that fuses W4A16
dequantization directly into the GEMV, and implements MLA caching to avoid O(context_len)
recomputation.
"""
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 Dequant GEMV Kernel
# --------------------------------------------------------------------------- #
@triton.jit
def batched_gemv_kernel(
    X_ptr, W_q_ptr, Scales_ptr, Zeros_ptr, Out_ptr, Idx_ptr,
    K, N, Group_Size,
    stride_x_batch, stride_x_k,
    stride_wq_e, stride_wq_k, stride_wq_n,
    stride_scales_e, stride_scales_g, stride_scales_n,
    stride_zeros_e, stride_zeros_g, stride_zeros_n,
    stride_out_batch, stride_out_n,
    HAS_IDX: tl.constexpr,
    BLOCK_N: tl.constexpr,
    BLOCK_K: tl.constexpr,
):
    pid_n = tl.program_id(0)
    pid_batch = tl.program_id(1)

    if HAS_IDX:
        e = tl.load(Idx_ptr + pid_batch)
    else:
        e = pid_batch

    col_offsets = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    mask_n = col_offsets < N

    acc = tl.zeros((BLOCK_N,), dtype=tl.float32)

    # Base pointers for this expert/batch
    x_batch_ptr = X_ptr + pid_batch * stride_x_batch
    wq_e_ptr = W_q_ptr + e * stride_wq_e
    scales_e_ptr = Scales_ptr + e * stride_scales_e
    zeros_e_ptr = Zeros_ptr + e * stride_zeros_e

    for k_start in range(0, K, BLOCK_K):
        # Load x_even and x_odd (cast to float32 explicitly)
        x_even_offsets = k_start + 2 * tl.arange(0, BLOCK_K // 2)
        x_odd_offsets = x_even_offsets + 1

        x_even = tl.load(x_batch_ptr + x_even_offsets * stride_x_k).to(tl.float32)
        x_odd = tl.load(x_batch_ptr + x_odd_offsets * stride_x_k).to(tl.float32)

        # Load w_packed
        packed_k_offsets = (k_start // 2) + tl.arange(0, BLOCK_K // 2)
        w_packed_offsets = packed_k_offsets[:, None] * stride_wq_k + col_offsets[None, :] * stride_wq_n
        w_packed = tl.load(wq_e_ptr + w_packed_offsets, mask=mask_n[None, :], other=0)

        # Unpack
        lo = (w_packed & 0xF).to(tl.float32)
        hi = ((w_packed >> 4) & 0xF).to(tl.float32)

        # Dot products
        dot_even = tl.sum(x_even[:, None] * lo, axis=0)
        dot_odd = tl.sum(x_odd[:, None] * hi, axis=0)

        # Sum of x
        sum_x = tl.sum(x_even) + tl.sum(x_odd)

        # Load scales and zeros
        g = k_start // Group_Size
        scale = tl.load(scales_e_ptr + g * stride_scales_g + col_offsets * stride_scales_n, mask=mask_n, other=0.0).to(tl.float32)
        zero = tl.load(zeros_e_ptr + g * stride_zeros_g + col_offsets * stride_zeros_n, mask=mask_n, other=0.0).to(tl.float32)

        # Accumulate
        acc += scale * (dot_even + dot_odd - zero * sum_x)

    out_batch_ptr = Out_ptr + pid_batch * stride_out_batch
    tl.store(out_batch_ptr + col_offsets * stride_out_n, acc.to(tl.bfloat16), mask=mask_n)


def fused_gemv(
    x: torch.Tensor,
    w_q: torch.Tensor,
    scales: torch.Tensor,
    zeros: torch.Tensor,
    idx: torch.Tensor | None = None,
    group: int = 128,
) -> torch.Tensor:
    is_batched = (w_q.ndim == 3)
    
    if not is_batched:
        # Single QuantLinear
        K = x.shape[-1]
        N = w_q.shape[1]
        out = torch.empty((N,), dtype=torch.bfloat16, device=x.device)
        
        BLOCK_N = 16
        BLOCK_K = 128
        grid = (triton.cdiv(N, BLOCK_N), 1)
        
        batched_gemv_kernel[grid](
            x, w_q, scales, zeros, out, x,
            K, N, group,
            0, x.stride(0) if x.ndim == 1 else x.stride(1),
            0, w_q.stride(0), w_q.stride(1),
            0, scales.stride(0), scales.stride(1),
            0, zeros.stride(0), zeros.stride(1),
            0, out.stride(0),
            HAS_IDX=False,
            BLOCK_N=BLOCK_N,
            BLOCK_K=BLOCK_K,
            num_warps=1,
        )
        return out
    else:
        # Batched QuantExperts
        B = idx.numel() if idx is not None else w_q.shape[0]
        K = x.shape[-1]
        N = w_q.shape[2]
        out = torch.empty((B, N), dtype=torch.bfloat16, device=x.device)
        
        BLOCK_N = 16
        BLOCK_K = 128
        grid = (triton.cdiv(N, BLOCK_N), B)
        
        if x.ndim == 1:
            stride_x_batch = 0
            stride_x_k = x.stride(0)
        else:
            stride_x_batch = x.stride(0)
            stride_x_k = x.stride(1)
            
        batched_gemv_kernel[grid](
            x, w_q, scales, zeros, out, idx,
            K, N, group,
            stride_x_batch, stride_x_k,
            w_q.stride(0), w_q.stride(1), w_q.stride(2),
            scales.stride(0), scales.stride(1), scales.stride(2),
            zeros.stride(0), zeros.stride(1), zeros.stride(2),
            out.stride(0), out.stride(1),
            HAS_IDX=True,
            BLOCK_N=BLOCK_N,
            BLOCK_K=BLOCK_K,
            num_warps=1,
        )
        return out


# --------------------------------------------------------------------------- #
# W4A16 Quantization definitions
# --------------------------------------------------------------------------- #
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 fused_gemv(x, self.w_q, self.scales, self.zeros, None, self.group)


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)


# --------------------------------------------------------------------------- #
# 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 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)

        # Caching MLA KV projections to avoid full O(context_len) GEMM
        if "kvb" not in st:
            w_kv_b = self.kv_b.weight_bf()
            kvb = st["c_kv"] @ w_kv_b
            st["kvb"] = kvb
        else:
            kvb_new = self.kv_b(c_kv)
            st["kvb"] = torch.cat([st["kvb"], kvb_new[None]], 0)
            kvb = st["kvb"]

        kvb = kvb.view(-1, H, cfg.qk_nope + cfg.v_head)
        k_nope = kvb[..., : cfg.qk_nope]
        v = kvb[..., cfg.qk_nope :]
        scores = (torch.einsum("hd,lhd->lh", q_nope, 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, 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).to(x.dtype)
        
        g_val = fused_gemv(x, self.gate.w_q, self.gate.scales, self.gate.zeros, idx, self.gate.group)
        u_val = fused_gemv(x, self.up.w_q, self.up.scales, self.up.zeros, idx, self.up.group)
        hh = F.silu(g_val) * u_val
        routed = fused_gemv(hh, self.down.w_q, self.down.scales, self.down.zeros, idx, self.down.group)
        out = (w[:, None] * routed).sum(0)
        
        sidx = torch.arange(cfg.n_shared, device=x.device)
        sg_val = fused_gemv(x, self.s_gate.w_q, self.s_gate.scales, self.s_gate.zeros, sidx, self.s_gate.group)
        su_val = fused_gemv(x, self.s_up.w_q, self.s_up.scales, self.s_up.zeros, sidx, self.s_up.group)
        sh = F.silu(sg_val) * su_val
        sd_val = fused_gemv(sh, self.s_down.w_q, self.s_down.scales, self.s_down.zeros, sidx, self.s_down.group)
        out = out + sd_val.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


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

20260619_002627_gemini_gemini-3.5-flash_02_kimi_linear_decode