KernelBench mega · RTX PRO 6000

Kimi-Linear Decode Composer 2.5 Fast

2.46×geomean speedup across shapes

manually audited: clean

Re-graded 2026-11-16 under grader v3 on tetra: 2.46x (2.48x before; see regrade_v3). Original audit: RTX PRO 6000 Composer-2.5-fast cell (2.48x). solution.py performs real int4 nibble unpack/dequant. Forbidden-scan passed; template_mutated=False; correctness clean.

harnesscursor
Kernel source (redacted)
"""Fused W4A16 Kimi-Linear decode unit — custom int4 dequant-GEMV kernels."""
from __future__ import annotations

from dataclasses import dataclass, field

import torch
import torch.nn as nn
import torch.nn.functional as F

from w4_triton import mla_pc_v, mla_qk_proj, w4_gemv, w4_gemv_experts, w4_gemv_experts_rows, w4_gemv_quad

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


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)


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 gemv(self, x: torch.Tensor) -> torch.Tensor:
        return w4_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 _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)


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, k, v, g = w4_gemv_quad(x, [self.q_proj, self.k_proj, self.v_proj, self.g_proj])
        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.gemv(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.gemv(x).view(H, cfg.qk_nope + cfg.qk_rope)
        kv = self.kv_a.gemv(x)
        q_nope = q[:, : cfg.qk_nope].float()
        q_rope = q[:, cfg.qk_nope :]
        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)

        c_kv_f = st["c_kv"].float()
        qW = mla_qk_proj(q_nope, self.kv_b.w_q, self.kv_b.scales, self.kv_b.zeros)
        scores = (c_kv_f @ qW + torch.einsum("hd,ld->lh", q_rope, st["k_rope"].float())) * self.scale
        p = torch.softmax(scores, dim=0)
        pc = torch.einsum("lh,lj->hj", p, c_kv_f)
        o = mla_pc_v(pc, self.kv_b.w_q, self.kv_b.scales, self.kv_b.zeros, cfg.v_head)
        return self.o_proj.gemv(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_batch(self, x, gate, up, down, idx: torch.Tensor):
        g = w4_gemv_experts(x, gate.w_q, gate.scales, gate.zeros, idx)
        u = w4_gemv_experts(x, up.w_q, up.scales, up.zeros, idx)
        h = F.silu(g.float()) * u.float()
        return w4_gemv_experts_rows(h.to(torch.bfloat16), down.w_q, down.scales, down.zeros, idx)

    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_out = self._ffn_batch(x, self.gate, self.up, self.down, idx)
        routed = (w[:, None].float() * routed_out.float()).sum(0)
        sidx = torch.arange(cfg.n_shared, device=x.device)
        shared_out = self._ffn_batch(x, self.s_gate, self.s_up, self.s_down, sidx)
        return (routed + shared_out.float().sum(0)).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


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


# ==================================================================
# ===== sidecar: w4_triton.py (16030 bytes, loaded by solution.py) =====
# ==================================================================

"""Fused W4A16 dequant-GEMV kernels (Triton)."""
from __future__ import annotations

import torch
import triton
import triton.language as tl

GROUP_SIZE = 128


@triton.jit
def _w4_gemv_kernel(
    x_ptr,
    wq_ptr,
    scales_ptr,
    zeros_ptr,
    y_ptr,
    K,
    N,
    stride_wq_k,
    stride_wq_n,
    stride_s_g,
    stride_s_n,
    BLOCK_N: tl.constexpr,
    BLOCK_K: tl.constexpr,
    GROUP: tl.constexpr,
):
    pid_n = tl.program_id(0)
    n_offs = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    n_mask = n_offs < N
    acc = tl.zeros([BLOCK_N], dtype=tl.float32)
    for k0 in range(0, K, BLOCK_K):
        k_offs = k0 + tl.arange(0, BLOCK_K)
        k_mask = k_offs < K
        x_blk = tl.load(x_ptr + k_offs, mask=k_mask, other=0.0).to(tl.float32)
        g = k_offs // GROUP
        scale = tl.load(
            scales_ptr + g[:, None] * stride_s_g + n_offs[None, :] * stride_s_n,
            mask=k_mask[:, None] & n_mask[None, :],
            other=0.0,
        ).to(tl.float32)
        zero = tl.load(
            zeros_ptr + g[:, None] * stride_s_g + n_offs[None, :] * stride_s_n,
            mask=k_mask[:, None] & n_mask[None, :],
            other=0.0,
        ).to(tl.float32)
        pair = k_offs // 2
        is_lo = (k_offs & 1) == 0
        wq = tl.load(
            wq_ptr + pair[:, None] * stride_wq_k + n_offs[None, :] * stride_wq_n,
            mask=k_mask[:, None] & n_mask[None, :],
            other=0,
        )
        nibble = tl.where(is_lo[:, None], wq & 0xF, (wq >> 4) & 0xF).to(tl.float32)
        acc += tl.sum(x_blk[:, None] * (nibble - zero) * scale, axis=0)
    tl.store(y_ptr + n_offs, acc.to(tl.bfloat16), mask=n_mask)


@triton.jit
def _w4_gemv_quad_kernel(
    x_ptr,
    wq0_ptr,
    wq1_ptr,
    wq2_ptr,
    wq3_ptr,
    s0_ptr,
    s1_ptr,
    s2_ptr,
    s3_ptr,
    z0_ptr,
    z1_ptr,
    z2_ptr,
    z3_ptr,
    y0_ptr,
    y1_ptr,
    y2_ptr,
    y3_ptr,
    K,
    N,
    stride_wq_k,
    stride_wq_n,
    stride_s_g,
    stride_s_n,
    BLOCK_N: tl.constexpr,
    BLOCK_K: tl.constexpr,
    GROUP: tl.constexpr,
):
    pid_n = tl.program_id(0)
    n_offs = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    n_mask = n_offs < N
    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)
    for k0 in range(0, K, BLOCK_K):
        k_offs = k0 + tl.arange(0, BLOCK_K)
        k_mask = k_offs < K
        x_blk = tl.load(x_ptr + k_offs, mask=k_mask, other=0.0).to(tl.float32)
        g = k_offs // GROUP
        pair = k_offs // 2
        is_lo = (k_offs & 1) == 0
        scale0 = tl.load(s0_ptr + g[:, None] * stride_s_g + n_offs[None, :] * stride_s_n,
                         mask=k_mask[:, None] & n_mask[None, :], other=0.0).to(tl.float32)
        zero0 = tl.load(z0_ptr + g[:, None] * stride_s_g + n_offs[None, :] * stride_s_n,
                        mask=k_mask[:, None] & n_mask[None, :], other=0.0).to(tl.float32)
        wq0 = tl.load(wq0_ptr + pair[:, None] * stride_wq_k + n_offs[None, :] * stride_wq_n,
                      mask=k_mask[:, None] & n_mask[None, :], other=0)
        nib0 = tl.where(is_lo[:, None], wq0 & 0xF, (wq0 >> 4) & 0xF).to(tl.float32)
        acc0 += tl.sum(x_blk[:, None] * (nib0 - zero0) * scale0, axis=0)
        scale1 = tl.load(s1_ptr + g[:, None] * stride_s_g + n_offs[None, :] * stride_s_n,
                         mask=k_mask[:, None] & n_mask[None, :], other=0.0).to(tl.float32)
        zero1 = tl.load(z1_ptr + g[:, None] * stride_s_g + n_offs[None, :] * stride_s_n,
                        mask=k_mask[:, None] & n_mask[None, :], other=0.0).to(tl.float32)
        wq1 = tl.load(wq1_ptr + pair[:, None] * stride_wq_k + n_offs[None, :] * stride_wq_n,
                      mask=k_mask[:, None] & n_mask[None, :], other=0)
        nib1 = tl.where(is_lo[:, None], wq1 & 0xF, (wq1 >> 4) & 0xF).to(tl.float32)
        acc1 += tl.sum(x_blk[:, None] * (nib1 - zero1) * scale1, axis=0)
        scale2 = tl.load(s2_ptr + g[:, None] * stride_s_g + n_offs[None, :] * stride_s_n,
                         mask=k_mask[:, None] & n_mask[None, :], other=0.0).to(tl.float32)
        zero2 = tl.load(z2_ptr + g[:, None] * stride_s_g + n_offs[None, :] * stride_s_n,
                        mask=k_mask[:, None] & n_mask[None, :], other=0.0).to(tl.float32)
        wq2 = tl.load(wq2_ptr + pair[:, None] * stride_wq_k + n_offs[None, :] * stride_wq_n,
                      mask=k_mask[:, None] & n_mask[None, :], other=0)
        nib2 = tl.where(is_lo[:, None], wq2 & 0xF, (wq2 >> 4) & 0xF).to(tl.float32)
        acc2 += tl.sum(x_blk[:, None] * (nib2 - zero2) * scale2, axis=0)
        scale3 = tl.load(s3_ptr + g[:, None] * stride_s_g + n_offs[None, :] * stride_s_n,
                         mask=k_mask[:, None] & n_mask[None, :], other=0.0).to(tl.float32)
        zero3 = tl.load(z3_ptr + g[:, None] * stride_s_g + n_offs[None, :] * stride_s_n,
                        mask=k_mask[:, None] & n_mask[None, :], other=0.0).to(tl.float32)
        wq3 = tl.load(wq3_ptr + pair[:, None] * stride_wq_k + n_offs[None, :] * stride_wq_n,
                      mask=k_mask[:, None] & n_mask[None, :], other=0)
        nib3 = tl.where(is_lo[:, None], wq3 & 0xF, (wq3 >> 4) & 0xF).to(tl.float32)
        acc3 += tl.sum(x_blk[:, None] * (nib3 - zero3) * scale3, axis=0)
    tl.store(y0_ptr + n_offs, acc0.to(tl.bfloat16), mask=n_mask)
    tl.store(y1_ptr + n_offs, acc1.to(tl.bfloat16), mask=n_mask)
    tl.store(y2_ptr + n_offs, acc2.to(tl.bfloat16), mask=n_mask)
    tl.store(y3_ptr + n_offs, acc3.to(tl.bfloat16), mask=n_mask)


@triton.jit
def _w4_gemv_indexed_kernel(
    x_ptr,
    wq_ptr,
    scales_ptr,
    zeros_ptr,
    idx_ptr,
    y_ptr,
    K,
    N,
    NUM,
    GRID_N,
    stride_wq_e,
    stride_wq_k,
    stride_wq_n,
    stride_s_e,
    stride_s_g,
    stride_s_n,
    stride_y_num,
    BLOCK_N: tl.constexpr,
    BLOCK_K: tl.constexpr,
    GROUP: tl.constexpr,
):
    pid = tl.program_id(0)
    num_id = pid // GRID_N
    pid_n = pid % GRID_N
    n_offs = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    n_mask = n_offs < N
    num_mask = num_id < NUM
    e = tl.load(idx_ptr + num_id).to(tl.int32)
    wq_base = wq_ptr + e * stride_wq_e
    s_base = scales_ptr + e * stride_s_e
    z_base = zeros_ptr + e * stride_s_e
    acc = tl.zeros([BLOCK_N], dtype=tl.float32)
    for k0 in range(0, K, BLOCK_K):
        k_offs = k0 + tl.arange(0, BLOCK_K)
        k_mask = k_offs < K
        x_blk = tl.load(x_ptr + k_offs, mask=k_mask, other=0.0).to(tl.float32)
        g = k_offs // GROUP
        scale = tl.load(
            s_base + g[:, None] * stride_s_g + n_offs[None, :] * stride_s_n,
            mask=k_mask[:, None] & n_mask[None, :],
            other=0.0,
        ).to(tl.float32)
        zero = tl.load(
            z_base + g[:, None] * stride_s_g + n_offs[None, :] * stride_s_n,
            mask=k_mask[:, None] & n_mask[None, :],
            other=0.0,
        ).to(tl.float32)
        pair = k_offs // 2
        is_lo = (k_offs & 1) == 0
        wq = tl.load(
            wq_base + pair[:, None] * stride_wq_k + n_offs[None, :] * stride_wq_n,
            mask=k_mask[:, None] & n_mask[None, :],
            other=0,
        )
        nibble = tl.where(is_lo[:, None], wq & 0xF, (wq >> 4) & 0xF).to(tl.float32)
        acc += tl.sum(x_blk[:, None] * (nibble - zero) * scale, axis=0)
    tl.store(y_ptr + num_id * stride_y_num + n_offs, acc.to(tl.bfloat16), mask=n_mask & num_mask)


@triton.jit
def _w4_batched_rows_kernel(
    x_ptr,
    wq_ptr,
    scales_ptr,
    zeros_ptr,
    idx_ptr,
    y_ptr,
    K,
    N,
    NUM,
    GRID_N,
    stride_x_num,
    stride_x_k,
    stride_wq_e,
    stride_wq_k,
    stride_wq_n,
    stride_s_e,
    stride_s_g,
    stride_s_n,
    stride_y_num,
    BLOCK_N: tl.constexpr,
    BLOCK_K: tl.constexpr,
    GROUP: tl.constexpr,
):
    pid = tl.program_id(0)
    num_id = pid // GRID_N
    pid_n = pid % GRID_N
    n_offs = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    n_mask = n_offs < N
    num_mask = num_id < NUM
    e = tl.load(idx_ptr + num_id).to(tl.int32)
    wq_base = wq_ptr + e * stride_wq_e
    s_base = scales_ptr + e * stride_s_e
    z_base = zeros_ptr + e * stride_s_e
    x_base = x_ptr + num_id * stride_x_num
    acc = tl.zeros([BLOCK_N], dtype=tl.float32)
    for k0 in range(0, K, BLOCK_K):
        k_offs = k0 + tl.arange(0, BLOCK_K)
        k_mask = k_offs < K
        x_blk = tl.load(x_base + k_offs * stride_x_k, mask=k_mask, other=0.0).to(tl.float32)
        g = k_offs // GROUP
        scale = tl.load(
            s_base + g[:, None] * stride_s_g + n_offs[None, :] * stride_s_n,
            mask=k_mask[:, None] & n_mask[None, :],
            other=0.0,
        ).to(tl.float32)
        zero = tl.load(
            z_base + g[:, None] * stride_s_g + n_offs[None, :] * stride_s_n,
            mask=k_mask[:, None] & n_mask[None, :],
            other=0.0,
        ).to(tl.float32)
        pair = k_offs // 2
        is_lo = (k_offs & 1) == 0
        wq = tl.load(
            wq_base + pair[:, None] * stride_wq_k + n_offs[None, :] * stride_wq_n,
            mask=k_mask[:, None] & n_mask[None, :],
            other=0,
        )
        nibble = tl.where(is_lo[:, None], wq & 0xF, (wq >> 4) & 0xF).to(tl.float32)
        acc += tl.sum(x_blk[:, None] * (nibble - zero) * scale, axis=0)
    tl.store(y_ptr + num_id * stride_y_num + n_offs, acc.to(tl.bfloat16), mask=n_mask & num_mask)


@triton.jit
def _w4_qk_proj_kernel(
    q_ptr,
    wq_ptr,
    scales_ptr,
    zeros_ptr,
    out_ptr,
    K,
    H,
    D: tl.constexpr,
    stride_wq_k,
    stride_wq_n,
    stride_s_g,
    stride_s_n,
    BLOCK_H: tl.constexpr,
    BLOCK_K: tl.constexpr,
    GROUP: tl.constexpr,
):
    pid_j = tl.program_id(0)
    pid_h = tl.program_id(1)
    j = pid_j
    h_offs = pid_h * BLOCK_H + tl.arange(0, BLOCK_H)
    h_mask = h_offs < H
    acc = tl.zeros([BLOCK_H], dtype=tl.float32)
    for k0 in range(0, D, BLOCK_K):
        d_offs = k0 + tl.arange(0, BLOCK_K)
        d_mask = d_offs < D
        qv = tl.load(
            q_ptr + h_offs[None, :] * D + d_offs[:, None],
            mask=d_mask[:, None] & h_mask[None, :],
            other=0.0,
        ).to(tl.float32)
        n_cols = h_offs[None, :] * (2 * D) + d_offs[:, None]
        g = j // GROUP
        scale = tl.load(
            scales_ptr + g * stride_s_g + n_cols * stride_s_n,
            mask=d_mask[:, None] & h_mask[None, :],
            other=0.0,
        ).to(tl.float32)
        zero = tl.load(
            zeros_ptr + g * stride_s_g + n_cols * stride_s_n,
            mask=d_mask[:, None] & h_mask[None, :],
            other=0.0,
        ).to(tl.float32)
        pair = j // 2
        is_lo = (j & 1) == 0
        wq = tl.load(
            wq_ptr + pair * stride_wq_k + n_cols * stride_wq_n,
            mask=d_mask[:, None] & h_mask[None, :],
            other=0,
        )
        nibble = tl.where(is_lo, wq & 0xF, (wq >> 4) & 0xF).to(tl.float32)
        acc += tl.sum(qv * (nibble - zero) * scale, axis=0)
    tl.store(out_ptr + j * H + h_offs, acc, mask=h_mask)


@triton.jit
def _w4_pc_v_kernel(
    pc_ptr,
    wq_ptr,
    scales_ptr,
    zeros_ptr,
    out_ptr,
    K,
    H,
    D: tl.constexpr,
    stride_wq_k,
    stride_wq_n,
    stride_s_g,
    stride_s_n,
    BLOCK_H: tl.constexpr,
    BLOCK_D: tl.constexpr,
    GROUP: tl.constexpr,
):
    pid_h = tl.program_id(0)
    pid_d = tl.program_id(1)
    h_offs = pid_h * BLOCK_H + tl.arange(0, BLOCK_H)
    d_offs = pid_d * BLOCK_D + tl.arange(0, BLOCK_D)
    h_mask = h_offs < H
    d_mask = d_offs < D
    acc = tl.zeros([BLOCK_H, BLOCK_D], dtype=tl.float32)
    for j in range(K):
        pc = tl.load(pc_ptr + h_offs * K + j, mask=h_mask, other=0.0).to(tl.float32)
        n_cols = h_offs[:, None] * (2 * D) + D + d_offs[None, :]
        g = j // GROUP
        scale = tl.load(
            scales_ptr + g * stride_s_g + n_cols * stride_s_n,
            mask=h_mask[:, None] & d_mask[None, :],
            other=0.0,
        ).to(tl.float32)
        zero = tl.load(
            zeros_ptr + g * stride_s_g + n_cols * stride_s_n,
            mask=h_mask[:, None] & d_mask[None, :],
            other=0.0,
        ).to(tl.float32)
        pair = j // 2
        is_lo = (j & 1) == 0
        wq = tl.load(
            wq_ptr + pair * stride_wq_k + n_cols * stride_wq_n,
            mask=h_mask[:, None] & d_mask[None, :],
            other=0,
        )
        nibble = tl.where(is_lo, wq & 0xF, (wq >> 4) & 0xF).to(tl.float32)
        acc += pc[:, None] * (nibble - zero) * scale
    out_ptrs = out_ptr + h_offs[:, None] * D + d_offs[None, :]
    tl.store(out_ptrs, acc.to(tl.bfloat16), mask=h_mask[:, None] & d_mask[None, :])


def w4_gemv(x, w_q, scales, zeros):
    K2, N = w_q.shape
    K = K2 * 2
    y = torch.empty(N, device=x.device, dtype=torch.bfloat16)
    bn, bk = 64, 128
    _w4_gemv_kernel[(triton.cdiv(N, bn),)](
        x, w_q, scales, zeros, y, K, N,
        w_q.stride(0), w_q.stride(1), scales.stride(0), scales.stride(1),
        BLOCK_N=bn, BLOCK_K=bk, GROUP=GROUP_SIZE,
    )
    return y


def w4_gemv_quad(x, layers):
    q, k, v, g = layers
    K2, N = q.w_q.shape
    K = K2 * 2
    y0 = torch.empty(N, device=x.device, dtype=torch.bfloat16)
    y1 = torch.empty(N, device=x.device, dtype=torch.bfloat16)
    y2 = torch.empty(N, device=x.device, dtype=torch.bfloat16)
    y3 = torch.empty(N, device=x.device, dtype=torch.bfloat16)
    bn, bk = 64, 128
    _w4_gemv_quad_kernel[(triton.cdiv(N, bn),)](
        x,
        q.w_q, k.w_q, v.w_q, g.w_q,
        q.scales, k.scales, v.scales, g.scales,
        q.zeros, k.zeros, v.zeros, g.zeros,
        y0, y1, y2, y3,
        K, N,
        q.w_q.stride(0), q.w_q.stride(1), q.scales.stride(0), q.scales.stride(1),
        BLOCK_N=bn, BLOCK_K=bk, GROUP=GROUP_SIZE,
    )
    return y0, y1, y2, y3


def w4_gemv_indexed(x, w_q, scales, zeros, idx):
    num = idx.numel()
    K2, N = w_q.shape[1], w_q.shape[2]
    K = K2 * 2
    y = torch.empty(num, N, device=x.device, dtype=torch.bfloat16)
    bn, bk = 64, 128
    grid_n = triton.cdiv(N, bn)
    _w4_gemv_indexed_kernel[(num * grid_n,)](
        x, w_q, scales, zeros, idx, y, K, N, num, grid_n,
        w_q.stride(0), w_q.stride(1), w_q.stride(2),
        scales.stride(0), scales.stride(1), scales.stride(2),
        y.stride(0),
        BLOCK_N=bn, BLOCK_K=bk, GROUP=GROUP_SIZE,
    )
    return y


def w4_gemv_experts(x, w_q, scales, zeros, idx):
    return w4_gemv_indexed(x, w_q, scales, zeros, idx)


def w4_gemv_experts_rows(x_rows, w_q, scales, zeros, idx):
    """x_rows (NUM, K) with one row per indexed expert."""
    num, K = x_rows.shape
    K2, N = w_q.shape[1], w_q.shape[2]
    assert K == K2 * 2
    y = torch.empty(num, N, device=x_rows.device, dtype=torch.bfloat16)
    bn, bk = 64, 128
    grid_n = triton.cdiv(N, bn)
    _w4_batched_rows_kernel[(num * grid_n,)](
        x_rows, w_q, scales, zeros, idx, y, K, N, num, grid_n,
        x_rows.stride(0), x_rows.stride(1),
        w_q.stride(0), w_q.stride(1), w_q.stride(2),
        scales.stride(0), scales.stride(1), scales.stride(2),
        y.stride(0),
        BLOCK_N=bn, BLOCK_K=bk, GROUP=GROUP_SIZE,
    )
    return y


def mla_qk_proj(q_nope, w_q, scales, zeros):
    H, D = q_nope.shape
    K = w_q.shape[0] * 2
    out = torch.empty(K, H, device=q_nope.device, dtype=torch.float32)
    _w4_qk_proj_kernel[(K, triton.cdiv(H, 8))](
        q_nope, w_q, scales, zeros, out, K, H, D,
        w_q.stride(0), w_q.stride(1), scales.stride(0), scales.stride(1),
        BLOCK_H=8, BLOCK_K=32, GROUP=GROUP_SIZE,
    )
    return out


def mla_pc_v(pc, w_q, scales, zeros, D):
    H, K = pc.shape
    out = torch.empty(H, D, device=pc.device, dtype=torch.bfloat16)
    _w4_pc_v_kernel[(triton.cdiv(H, 4), triton.cdiv(D, 32))](
        pc, w_q, scales, zeros, out, K, H, D,
        w_q.stride(0), w_q.stride(1), scales.stride(0), scales.stride(1),
        BLOCK_H=4, BLOCK_D=32, GROUP=GROUP_SIZE,
    )
    return out

20260619_084729_cursor_composer-2.5-fast_02_kimi_linear_decode