KernelBench mega · H100

Kimi-Linear Decode Kimi K2.7-Code

wrongdid not score
harnesskimi-claude
Kernel source (redacted)
"""Fused int4-dequant GEMV decode kernel for the Kimi-Linear W4A16 unit.

Key ideas:
- All big linear projections are M=1 GEMVs over int4 weights.  We fuse the
  int4 unpack and per-group (group=128) asymmetric dequant into the GEMV so the
  weights are streamed only as packed uint8.
- KDA q/k/v/g projections are batched into one kernel launch, sharing the
  input x.
- MoE active experts are batched into one kernel launch per gate/up/down
  direction, using expert indices to avoid gathering.
- MLA avoids recomputing c_kv @ kv_b for the whole context every step: we
  materialize and cache k_nope/v ("kvb") across decode steps and only project
  the new token's compressed latent vector each step.
"""
from __future__ import annotations

import math
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)))


# --------------------------------------------------------------------------- #
# Quantization helpers (same format 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 _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


# --------------------------------------------------------------------------- #
# Triton kernels
# --------------------------------------------------------------------------- #
@triton.jit
def _int4_gemv_batched_kernel(
    x_ptr,
    w_ptr,
    s_ptr,
    z_ptr,
    out_ptr,
    K,
    N,
    B,
    stride_xb,
    stride_wb,
    stride_wk,
    stride_wn,
    stride_sb,
    stride_sk,
    stride_sn,
    stride_ob,
    BLOCK_N: tl.constexpr,
    GROUP: tl.constexpr,
):
    """Batched int4-dequant GEMV.

    For each batch item b in [0, B):
        y[b, n] = sum_k x[xbase + b*stride_xb + k] * dequant(w[b, k, n])
    If stride_xb == 0 all batches share the same input vector.
    Weights are contiguous per batch: w shape (B, K//2, N).
    """
    pid_b = tl.program_id(0)
    pid_n = tl.program_id(1)

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

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

    w_base = w_ptr + pid_b * stride_wb
    s_base = s_ptr + pid_b * stride_sb
    z_base = z_ptr + pid_b * stride_sb
    xbase = x_ptr + pid_b * stride_xb

    num_groups = K // GROUP
    for g in tl.range(num_groups):
        gk = g * GROUP
        s = tl.load(s_base + g * stride_sk + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        z = tl.load(z_base + g * stride_sk + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        for k in tl.range(0, GROUP, 2):
            kk = gk + k
            w_packed = tl.load(w_base + (kk // 2) * stride_wk + offs_n, mask=mask_n, other=0)
            w0 = (w_packed & 0x0F).to(tl.float32)
            w1 = ((w_packed >> 4) & 0x0F).to(tl.float32)
            x0 = tl.load(xbase + kk).to(tl.float32)
            x1 = tl.load(xbase + kk + 1).to(tl.float32)
            acc += x0 * (w0 - z) * s + x1 * (w1 - z) * s

    tl.store(out_ptr + pid_b * stride_ob + offs_n, acc.to(tl.bfloat16), mask=mask_n)


@triton.jit
def _int4_gemv_batched_idx_kernel(
    x_ptr,
    idx_ptr,
    w_ptr,
    s_ptr,
    z_ptr,
    out_ptr,
    K,
    N,
    B,
    stride_xb,
    stride_wb,
    stride_wk,
    stride_wn,
    stride_sb,
    stride_sk,
    stride_sn,
    stride_ob,
    BLOCK_N: tl.constexpr,
    GROUP: tl.constexpr,
):
    """Same as above but weights are indexed by expert id.

    w shape (E, K//2, N); idx[b] selects which expert.
    """
    pid_b = tl.program_id(0)
    pid_n = tl.program_id(1)
    e = tl.load(idx_ptr + pid_b)

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

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

    w_base = w_ptr + e * stride_wb
    s_base = s_ptr + e * stride_sb
    z_base = z_ptr + e * stride_sb
    xbase = x_ptr + pid_b * stride_xb

    num_groups = K // GROUP
    for g in tl.range(num_groups):
        gk = g * GROUP
        s = tl.load(s_base + g * stride_sk + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        z = tl.load(z_base + g * stride_sk + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        for k in tl.range(0, GROUP, 2):
            kk = gk + k
            w_packed = tl.load(w_base + (kk // 2) * stride_wk + offs_n, mask=mask_n, other=0)
            w0 = (w_packed & 0x0F).to(tl.float32)
            w1 = ((w_packed >> 4) & 0x0F).to(tl.float32)
            x0 = tl.load(xbase + kk).to(tl.float32)
            x1 = tl.load(xbase + kk + 1).to(tl.float32)
            acc += x0 * (w0 - z) * s + x1 * (w1 - z) * s

    tl.store(out_ptr + pid_b * stride_ob + offs_n, acc.to(tl.bfloat16), mask=mask_n)


@triton.jit
def _int4_gemm_kernel(
    x_ptr,
    w_ptr,
    s_ptr,
    z_ptr,
    out_ptr,
    M,
    N,
    K,
    stride_xm,
    stride_xk,
    stride_wk,
    stride_wn,
    stride_sk,
    stride_sn,
    stride_om,
    stride_on,
    BLOCK_M: tl.constexpr,
    BLOCK_N: tl.constexpr,
    GROUP: tl.constexpr,
):
    """Small int4-dequant GEMM: y[m,n] = sum_k x[m,k] * dequant(w[k,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

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

    num_groups = K // GROUP
    for g in tl.range(num_groups):
        gk = g * GROUP
        s = tl.load(s_ptr + g * stride_sk + offs_n[None, :], mask=mask_n[None, :], other=0.0).to(tl.float32)
        z = tl.load(z_ptr + g * stride_sk + offs_n[None, :], mask=mask_n[None, :], other=0.0).to(tl.float32)
        for k in tl.range(0, GROUP, 2):
            kk = gk + k
            w_packed = tl.load(w_ptr + (kk // 2) * stride_wk + offs_n[None, :], mask=mask_n[None, :], other=0)
            w0 = (w_packed & 0x0F).to(tl.float32)
            w1 = ((w_packed >> 4) & 0x0F).to(tl.float32)
            x0 = tl.load(
                x_ptr + offs_m[:, None] * stride_xm + kk * stride_xk,
                mask=mask_m[:, None],
                other=0.0,
            ).to(tl.float32)
            x1 = tl.load(
                x_ptr + offs_m[:, None] * stride_xm + (kk + 1) * stride_xk,
                mask=mask_m[:, None],
                other=0.0,
            ).to(tl.float32)
            acc += x0 * (w0 - z) * s + x1 * (w1 - z) * s

    tl.store(
        out_ptr + offs_m[:, None] * stride_om + offs_n[None, :] * stride_on,
        acc.to(tl.bfloat16),
        mask=mask_m[:, None] & mask_n[None, :],
    )


# --------------------------------------------------------------------------- #
# Kernel dispatch
# --------------------------------------------------------------------------- #
def _check_dims(in_f: int, out_f: int, group: int):
    assert in_f % group == 0 and in_f % 2 == 0


def int4_gemv(x: torch.Tensor, w_q: torch.Tensor, scales: torch.Tensor, zeros: torch.Tensor) -> torch.Tensor:
    """M=1 int4 GEMV: x[K] @ W[K,N] -> y[N]."""
    K = scales.shape[0] * GROUP_SIZE
    N = scales.shape[1]
    out = torch.empty(N, dtype=torch.bfloat16, device=x.device)
    BLOCK_N = 128
    grid = (1, triton.cdiv(N, BLOCK_N))
    _int4_gemv_batched_kernel[grid](
        x, w_q, scales, zeros, out,
        K, N, 1,
        stride_xb=0,
        stride_wb=0,
        stride_wk=w_q.stride(0),
        stride_wn=w_q.stride(1),
        stride_sb=0,
        stride_sk=scales.stride(0),
        stride_sn=scales.stride(1),
        stride_ob=out.stride(0),
        BLOCK_N=BLOCK_N,
        GROUP=GROUP_SIZE,
    )
    return out


def int4_gemv_batched(
    x: torch.Tensor,
    w_q: torch.Tensor,
    scales: torch.Tensor,
    zeros: torch.Tensor,
    per_input: bool = False,
) -> torch.Tensor:
    """Batched int4 GEMV over contiguous stacked weights.

    w_q shape:    (B, K//2, N)
    scales/zeros: (B, K//128, N)
    x shape:      (K,)            if per_input=False
                  (B, K)          if per_input=True
    out shape:    (B, N)
    """
    B, Khalf, N = w_q.shape
    K = scales.shape[1] * GROUP_SIZE
    out = torch.empty(B, N, dtype=torch.bfloat16, device=x.device)
    stride_xb = x.stride(0) if per_input and x.dim() > 1 else 0
    BLOCK_N = 128
    grid = (B, triton.cdiv(N, BLOCK_N))
    _int4_gemv_batched_kernel[grid](
        x, w_q, scales, zeros, out,
        K, N, B,
        stride_xb=stride_xb,
        stride_wb=w_q.stride(0),
        stride_wk=w_q.stride(1),
        stride_wn=w_q.stride(2),
        stride_sb=scales.stride(0),
        stride_sk=scales.stride(1),
        stride_sn=scales.stride(2),
        stride_ob=out.stride(0),
        BLOCK_N=BLOCK_N,
        GROUP=GROUP_SIZE,
    )
    return out


def int4_gemv_batched_idx(
    x: torch.Tensor,
    idx: torch.Tensor,
    w_q: torch.Tensor,
    scales: torch.Tensor,
    zeros: torch.Tensor,
    per_input: bool = False,
) -> torch.Tensor:
    """Batched int4 GEMV indexed into an expert weight bank.

    w_q shape:    (E, K//2, N)
    scales/zeros: (E, K//128, N)
    idx shape:    (B,) int64
    x shape:      (K,)       if per_input=False
                  (B, K)     if per_input=True
    out shape:    (B, N)
    """
    E, Khalf, N = w_q.shape
    K = scales.shape[1] * GROUP_SIZE
    B = idx.shape[0]
    out = torch.empty(B, N, dtype=torch.bfloat16, device=x.device)
    stride_xb = x.stride(0) if per_input and x.dim() > 1 else 0
    BLOCK_N = 128
    grid = (B, triton.cdiv(N, BLOCK_N))
    _int4_gemv_batched_idx_kernel[grid](
        x, idx, w_q, scales, zeros, out,
        K, N, B,
        stride_xb=stride_xb,
        stride_wb=w_q.stride(0),
        stride_wk=w_q.stride(1),
        stride_wn=w_q.stride(2),
        stride_sb=scales.stride(0),
        stride_sk=scales.stride(1),
        stride_sn=scales.stride(2),
        stride_ob=out.stride(0),
        BLOCK_N=BLOCK_N,
        GROUP=GROUP_SIZE,
    )
    return out


def int4_gemm(x: torch.Tensor, w_q: torch.Tensor, scales: torch.Tensor, zeros: torch.Tensor) -> torch.Tensor:
    """int4 GEMM: x[M,K] @ W[K,N] -> y[M,N]."""
    M, K = x.shape
    N = scales.shape[1]
    out = torch.empty(M, N, dtype=torch.bfloat16, device=x.device)
    BLOCK_M, BLOCK_N = 64, 128
    grid = (triton.cdiv(M, BLOCK_M), triton.cdiv(N, BLOCK_N))
    _int4_gemm_kernel[grid](
        x, w_q, scales, zeros, out,
        M, N, K,
        stride_xm=x.stride(0),
        stride_xk=x.stride(1),
        stride_wk=w_q.stride(0),
        stride_wn=w_q.stride(1),
        stride_sk=scales.stride(0),
        stride_sn=scales.stride(1),
        stride_om=out.stride(0),
        stride_on=out.stride(1),
        BLOCK_M=BLOCK_M,
        BLOCK_N=BLOCK_N,
        GROUP=GROUP_SIZE,
    )
    return out


# --------------------------------------------------------------------------- #
# Modules (identical buffer names to reference.py)
# --------------------------------------------------------------------------- #
class QuantLinear(nn.Module):
    """Hused int4 linear with same buffers as reference QuantLinear."""

    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 int4_gemv(x, self.w_q, self.scales, self.zeros)


class QuantExperts(nn.Module):
    """E independent int4 experts, same buffers as reference QuantExperts."""

    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, idx: torch.Tensor, per_input: bool = False) -> torch.Tensor:
        return int4_gemv_batched_idx(x, idx, self.w_q, self.scales, self.zeros, per_input=per_input)


# --------------------------------------------------------------------------- #
# helpers (same as reference)
# --------------------------------------------------------------------------- #
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

        # Cached stacked q/k/v/g weights (built lazily from state-dict buffers).
        self._qkvg_ready = False
        self.register_buffer("_qkvg_w", None, persistent=False)
        self.register_buffer("_qkvg_s", None, persistent=False)
        self.register_buffer("_qkvg_z", None, persistent=False)

    def _prepare_qkvg(self):
        if self._qkvg_ready:
            return
        projs = (self.q_proj, self.k_proj, self.v_proj, self.g_proj)
        self._qkvg_w = torch.stack([p.w_q for p in projs], dim=0).contiguous()
        self._qkvg_s = torch.stack([p.scales for p in projs], dim=0).contiguous()
        self._qkvg_z = torch.stack([p.zeros for p in projs], dim=0).contiguous()
        self._qkvg_ready = True

    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
        self._prepare_qkvg()
        qkvg = int4_gemv_batched(x, self._qkvg_w, self._qkvg_s, self._qkvg_z, per_input=False)
        q, k, v, g = 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.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].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)

        # Maintain materialized k_nope/v cache across decode steps.
        if "kvb" not in st:
            kvb = int4_gemm(st["c_kv"], self.kv_b.w_q, self.kv_b.scales, self.kv_b.zeros)
            st["kvb"] = kvb.view(-1, H, cfg.qk_nope + cfg.v_head)
        else:
            new_row = int4_gemv(c_kv, self.kv_b.w_q, self.kv_b.scales, self.kv_b.zeros)
            new_row = new_row.view(1, H, cfg.qk_nope + cfg.v_head)
            st["kvb"] = torch.cat([st["kvb"], new_row], 0)

        kvb = st["kvb"].float()
        k_nope = kvb[..., : cfg.qk_nope]
        v = kvb[..., cfg.qk_nope :]

        # [H, L]
        scores = (
            torch.einsum("hd,lhd->hl", q_nope, k_nope)
            + torch.einsum("hd,ld->hl", q_rope, st["k_rope"].float())
        ) * self.scale
        p = torch.softmax(scores, dim=-1)
        o = torch.einsum("hl,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 _ffn_batched(self, x, idx, w_gate, w_up, w_down, weights=None):
        """Batched FFN for idx-selected experts.

        x shape (hidden,).  If weights is not None it is (B,) and the routed
        branch is weighted; otherwise (shared branch) weights are ones.
        """
        B = idx.shape[0]
        gate = self.gate(x, idx, per_input=False)
        up = self.up(x, idx, per_input=False)
        h = F.silu(gate.float()) * up.float()  # (B, m)
        down = self.down(h, idx, per_input=True)  # (B, hidden)
        if weights is None:
            return down.sum(0)
        return (weights[:, None] * down).sum(0)

    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 = self._ffn_batched(x, idx, self.gate, self.up, self.down, weights=w)

        sidx = torch.arange(cfg.n_shared, device=x.device)
        out = out + self._ffn_batched(x, sidx, self.s_gate, self.s_up, self.s_down, weights=None)
        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)):
                # Same init as reference: random normal then quantize.
                w = torch.randn(mod.in_f, mod.out_f, generator=g) * 0.02
                wq, s, z = quantize(w, mod.group)
                mod.w_q.copy_(wq)
                mod.scales.copy_(s)
                mod.zeros.copy_(z)
            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 (same as reference)
# --------------------------------------------------------------------------- #
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_211510_kimi-claude_kimi-k2.7-code_02_kimi_linear_decode