KernelBench mega · RTX PRO 6000

Kimi-Linear Decode GPT-5.5

cleandid not score

manually audited: clean

B200 codex cell (9.37x). 14 Triton @triton.jit kernels implementing the fused int4 dequant- GEMV and the MLA/MoE megakernel; the flagged `_append_cache` is the legitimate incremental MLA KV-cache append, not output memoization. Forbidden-scan passed; template_mutated=False.

harnesscodex
Kernel source (redacted)
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)))


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)


@triton.jit
def _rmsnorm_kernel(x, w, y, N: tl.constexpr, BLOCK: tl.constexpr):
    offs = tl.arange(0, BLOCK)
    mask = offs < N
    xv = tl.load(x + offs, mask=mask, other=0.0).to(tl.float32)
    ss = tl.sum(xv * xv, axis=0) / N
    r = tl.rsqrt(ss + 1.0e-6)
    wv = tl.load(w + offs, mask=mask, other=0.0).to(tl.float32)
    tl.store(y + offs, xv * r * wv, mask=mask)


@triton.jit
def _router_kernel(x, weight, idx_out, w_out, K: tl.constexpr, N: tl.constexpr,
                   SCALE: tl.constexpr, BLOCK_K: tl.constexpr):
    offs_n = tl.arange(0, 64)
    offs_k = tl.arange(0, BLOCK_K)
    acc = tl.zeros((64,), tl.float32)
    for k0 in range(0, K, BLOCK_K):
        kk = k0 + offs_k
        xv = tl.load(x + kk).to(tl.float32)[None, :]
        wv = tl.load(weight + offs_n[:, None] * K + kk[None, :]).to(tl.float32)
        acc += tl.sum(wv * xv, axis=1)

    vals = acc
    m0, i0 = tl.max(vals, axis=0, return_indices=True)
    vals = tl.where(offs_n == i0, -float("inf"), vals)
    m1, i1 = tl.max(vals, axis=0, return_indices=True)
    vals = tl.where(offs_n == i1, -float("inf"), vals)
    m2, i2 = tl.max(vals, axis=0, return_indices=True)
    vals = tl.where(offs_n == i2, -float("inf"), vals)
    m3, i3 = tl.max(vals, axis=0, return_indices=True)
    vals = tl.where(offs_n == i3, -float("inf"), vals)
    m4, i4 = tl.max(vals, axis=0, return_indices=True)
    vals = tl.where(offs_n == i4, -float("inf"), vals)
    m5, i5 = tl.max(vals, axis=0, return_indices=True)
    vals = tl.where(offs_n == i5, -float("inf"), vals)
    m6, i6 = tl.max(vals, axis=0, return_indices=True)
    vals = tl.where(offs_n == i6, -float("inf"), vals)
    m7, i7 = tl.max(vals, axis=0, return_indices=True)

    e0 = 1.0
    e1 = tl.exp(m1 - m0)
    e2 = tl.exp(m2 - m0)
    e3 = tl.exp(m3 - m0)
    e4 = tl.exp(m4 - m0)
    e5 = tl.exp(m5 - m0)
    e6 = tl.exp(m6 - m0)
    e7 = tl.exp(m7 - m0)
    den = e0 + e1 + e2 + e3 + e4 + e5 + e6 + e7 + 1.0e-9
    s = SCALE / den
    tl.store(idx_out + 0, i0)
    tl.store(idx_out + 1, i1)
    tl.store(idx_out + 2, i2)
    tl.store(idx_out + 3, i3)
    tl.store(idx_out + 4, i4)
    tl.store(idx_out + 5, i5)
    tl.store(idx_out + 6, i6)
    tl.store(idx_out + 7, i7)
    tl.store(w_out + 0, e0 * s)
    tl.store(w_out + 1, e1 * s)
    tl.store(w_out + 2, e2 * s)
    tl.store(w_out + 3, e3 * s)
    tl.store(w_out + 4, e4 * s)
    tl.store(w_out + 5, e5 * s)
    tl.store(w_out + 6, e6 * s)
    tl.store(w_out + 7, e7 * s)


@triton.jit
def _beta_kernel(x, weight, y, K: tl.constexpr, BLOCK_K: tl.constexpr):
    offs_n = tl.arange(0, 32)
    offs_k = tl.arange(0, BLOCK_K)
    acc = tl.zeros((32,), tl.float32)
    for k0 in range(0, K, BLOCK_K):
        kk = k0 + offs_k
        xv = tl.load(x + kk).to(tl.float32)[None, :]
        wv = tl.load(weight + offs_n[:, None] * K + kk[None, :]).to(tl.float32)
        acc += tl.sum(wv * xv, axis=1)
    tl.store(y + offs_n, tl.sigmoid(acc))


@triton.jit
def _gemv_kernel(x, wq, scales, zeros, y, K: tl.constexpr, N: tl.constexpr,
                 BLOCK_N: tl.constexpr, BLOCK_P: tl.constexpr):
    pid_n = tl.program_id(0)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    offs_p = tl.arange(0, BLOCK_P)
    acc = tl.zeros((BLOCK_N,), tl.float32)
    for p0 in range(0, K // 2, BLOCK_P):
        p = p0 + offs_p
        byte = tl.load(wq + p[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0)
        group = p // 64
        s = tl.load(scales + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        z = tl.load(zeros + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        x0 = tl.load(x + 2 * p).to(tl.float32)[:, None]
        x1 = tl.load(x + 2 * p + 1).to(tl.float32)[:, None]
        lo = (byte & 15).to(tl.float32)
        hi = ((byte >> 4) & 15).to(tl.float32)
        acc += tl.sum(((lo - z) * x0 + (hi - z) * x1) * s, axis=0)
    tl.store(y + offs_n, acc, mask=offs_n < N)


@triton.jit
def _gemv4_kernel(x, wq0, sc0, ze0, y0, wq1, sc1, ze1, y1, wq2, sc2, ze2, y2,
                  wq3, sc3, ze3, y3, K: tl.constexpr, N: tl.constexpr,
                  BLOCK_N: tl.constexpr, BLOCK_P: tl.constexpr):
    pid_n = tl.program_id(0)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    offs_p = tl.arange(0, BLOCK_P)
    acc0 = tl.zeros((BLOCK_N,), tl.float32)
    acc1 = tl.zeros((BLOCK_N,), tl.float32)
    acc2 = tl.zeros((BLOCK_N,), tl.float32)
    acc3 = tl.zeros((BLOCK_N,), tl.float32)
    for p0 in range(0, K // 2, BLOCK_P):
        p = p0 + offs_p
        group = p // 64
        x0 = tl.load(x + 2 * p).to(tl.float32)[:, None]
        x1 = tl.load(x + 2 * p + 1).to(tl.float32)[:, None]

        byte = tl.load(wq0 + p[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0)
        s = tl.load(sc0 + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        z = tl.load(ze0 + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        acc0 += tl.sum((((byte & 15).to(tl.float32) - z) * x0 + (((byte >> 4) & 15).to(tl.float32) - z) * x1) * s, axis=0)

        byte = tl.load(wq1 + p[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0)
        s = tl.load(sc1 + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        z = tl.load(ze1 + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        acc1 += tl.sum((((byte & 15).to(tl.float32) - z) * x0 + (((byte >> 4) & 15).to(tl.float32) - z) * x1) * s, axis=0)

        byte = tl.load(wq2 + p[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0)
        s = tl.load(sc2 + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        z = tl.load(ze2 + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        acc2 += tl.sum((((byte & 15).to(tl.float32) - z) * x0 + (((byte >> 4) & 15).to(tl.float32) - z) * x1) * s, axis=0)

        byte = tl.load(wq3 + p[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0)
        s = tl.load(sc3 + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        z = tl.load(ze3 + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        acc3 += tl.sum((((byte & 15).to(tl.float32) - z) * x0 + (((byte >> 4) & 15).to(tl.float32) - z) * x1) * s, axis=0)

    tl.store(y0 + offs_n, acc0, mask=offs_n < N)
    tl.store(y1 + offs_n, acc1, mask=offs_n < N)
    tl.store(y2 + offs_n, acc2, mask=offs_n < N)
    tl.store(y3 + offs_n, acc3, mask=offs_n < N)


@triton.jit
def _expert_gemv2_kernel(x, idx, wq0, sc0, ze0, y0, wq1, sc1, ze1, y1,
                         K: tl.constexpr, N: tl.constexpr, NG: tl.constexpr,
                         BLOCK_N: tl.constexpr, BLOCK_P: tl.constexpr):
    pid_e = tl.program_id(0)
    pid_n = tl.program_id(1)
    e = tl.load(idx + pid_e)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    offs_p = tl.arange(0, BLOCK_P)
    acc0 = tl.zeros((BLOCK_N,), tl.float32)
    acc1 = tl.zeros((BLOCK_N,), tl.float32)
    w_base = e * ((K // 2) * N)
    q_base = e * (NG * N)
    for p0 in range(0, K // 2, BLOCK_P):
        p = p0 + offs_p
        group = p // 64
        x0 = tl.load(x + 2 * p).to(tl.float32)[:, None]
        x1 = tl.load(x + 2 * p + 1).to(tl.float32)[:, None]

        byte = tl.load(wq0 + w_base + p[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0)
        s = tl.load(sc0 + q_base + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        z = tl.load(ze0 + q_base + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        acc0 += tl.sum((((byte & 15).to(tl.float32) - z) * x0 + (((byte >> 4) & 15).to(tl.float32) - z) * x1) * s, axis=0)

        byte = tl.load(wq1 + w_base + p[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0)
        s = tl.load(sc1 + q_base + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        z = tl.load(ze1 + q_base + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        acc1 += tl.sum((((byte & 15).to(tl.float32) - z) * x0 + (((byte >> 4) & 15).to(tl.float32) - z) * x1) * s, axis=0)
    out = pid_e * N + offs_n
    tl.store(y0 + out, acc0, mask=offs_n < N)
    tl.store(y1 + out, acc1, mask=offs_n < N)


@triton.jit
def _short_conv3_kernel(q, k, v, cq, ck, cv, conv_w, C: tl.constexpr, BLOCK: tl.constexpr):
    offs = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
    mask = offs < C

    qv = tl.load(q + offs, mask=mask, other=0.0).to(tl.float32)
    p0 = tl.load(cq + offs, mask=mask, other=0.0).to(tl.float32)
    p1 = tl.load(cq + C + offs, mask=mask, other=0.0).to(tl.float32)
    p2 = tl.load(cq + 2 * C + offs, mask=mask, other=0.0).to(tl.float32)
    w0 = tl.load(conv_w + offs * 4, mask=mask, other=0.0).to(tl.float32)
    w1 = tl.load(conv_w + offs * 4 + 1, mask=mask, other=0.0).to(tl.float32)
    w2 = tl.load(conv_w + offs * 4 + 2, mask=mask, other=0.0).to(tl.float32)
    w3 = tl.load(conv_w + offs * 4 + 3, mask=mask, other=0.0).to(tl.float32)
    out = p0 * w0 + p1 * w1 + p2 * w2 + qv * w3
    tl.store(q + offs, out * tl.sigmoid(out), mask=mask)
    tl.store(cq + offs, p1, mask=mask)
    tl.store(cq + C + offs, p2, mask=mask)
    tl.store(cq + 2 * C + offs, qv, mask=mask)

    kv = tl.load(k + offs, mask=mask, other=0.0).to(tl.float32)
    p0 = tl.load(ck + offs, mask=mask, other=0.0).to(tl.float32)
    p1 = tl.load(ck + C + offs, mask=mask, other=0.0).to(tl.float32)
    p2 = tl.load(ck + 2 * C + offs, mask=mask, other=0.0).to(tl.float32)
    base = C * 4
    w0 = tl.load(conv_w + base + offs * 4, mask=mask, other=0.0).to(tl.float32)
    w1 = tl.load(conv_w + base + offs * 4 + 1, mask=mask, other=0.0).to(tl.float32)
    w2 = tl.load(conv_w + base + offs * 4 + 2, mask=mask, other=0.0).to(tl.float32)
    w3 = tl.load(conv_w + base + offs * 4 + 3, mask=mask, other=0.0).to(tl.float32)
    out = p0 * w0 + p1 * w1 + p2 * w2 + kv * w3
    tl.store(k + offs, out * tl.sigmoid(out), mask=mask)
    tl.store(ck + offs, p1, mask=mask)
    tl.store(ck + C + offs, p2, mask=mask)
    tl.store(ck + 2 * C + offs, kv, mask=mask)

    vv = tl.load(v + offs, mask=mask, other=0.0).to(tl.float32)
    p0 = tl.load(cv + offs, mask=mask, other=0.0).to(tl.float32)
    p1 = tl.load(cv + C + offs, mask=mask, other=0.0).to(tl.float32)
    p2 = tl.load(cv + 2 * C + offs, mask=mask, other=0.0).to(tl.float32)
    base = 2 * C * 4
    w0 = tl.load(conv_w + base + offs * 4, mask=mask, other=0.0).to(tl.float32)
    w1 = tl.load(conv_w + base + offs * 4 + 1, mask=mask, other=0.0).to(tl.float32)
    w2 = tl.load(conv_w + base + offs * 4 + 2, mask=mask, other=0.0).to(tl.float32)
    w3 = tl.load(conv_w + base + offs * 4 + 3, mask=mask, other=0.0).to(tl.float32)
    out = p0 * w0 + p1 * w1 + p2 * w2 + vv * w3
    tl.store(v + offs, out * tl.sigmoid(out), mask=mask)
    tl.store(cv + offs, p1, mask=mask)
    tl.store(cv + C + offs, p2, mask=mask)
    tl.store(cv + 2 * C + offs, vv, mask=mask)


@triton.jit
def _kda_recur_kernel(q, k, v, gp, beta, S, o, D: tl.constexpr,
                      SCALE: tl.constexpr, BLOCK_V: tl.constexpr):
    h = tl.program_id(0)
    pid_v = tl.program_id(1)
    offs_d = tl.arange(0, 128)
    offs_v = pid_v * BLOCK_V + tl.arange(0, BLOCK_V)
    base = h * D
    s_base = h * D * D
    s_offs = s_base + offs_d[:, None] * D + offs_v[None, :]

    qv = tl.load(q + base + offs_d).to(tl.float32) * SCALE
    kv = tl.load(k + base + offs_d).to(tl.float32)
    gv = tl.load(gp + base + offs_d).to(tl.float32)
    decay = tl.sigmoid(-gv)
    vv = tl.load(v + base + offs_v, mask=offs_v < D, other=0.0).to(tl.float32)
    b = tl.load(beta + h).to(tl.float32)

    sold = tl.load(S + s_offs, mask=offs_v[None, :] < D, other=0.0).to(tl.float32)
    sdec = sold * decay[:, None]
    pred = tl.sum(sdec * kv[:, None], axis=0)
    snew = sdec + (b * kv)[:, None] * (vv[None, :] - pred[None, :])
    out = tl.sum(snew * qv[:, None], axis=0)

    tl.store(S + s_offs, snew, mask=offs_v[None, :] < D)
    tl.store(o + base + offs_v, out, mask=offs_v < D)


@triton.jit
def _expert_hidden_kernel(x, idx, wq0, sc0, ze0, wq1, sc1, ze1, y,
                          K: tl.constexpr, N: tl.constexpr, NG: tl.constexpr,
                          BLOCK_N: tl.constexpr, BLOCK_P: tl.constexpr):
    pid_e = tl.program_id(0)
    pid_n = tl.program_id(1)
    e = tl.load(idx + pid_e)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    offs_p = tl.arange(0, BLOCK_P)
    acc0 = tl.zeros((BLOCK_N,), tl.float32)
    acc1 = tl.zeros((BLOCK_N,), tl.float32)
    w_base = e * ((K // 2) * N)
    q_base = e * (NG * N)
    for p0 in range(0, K // 2, BLOCK_P):
        p = p0 + offs_p
        group = p // 64
        x0 = tl.load(x + 2 * p).to(tl.float32)[:, None]
        x1 = tl.load(x + 2 * p + 1).to(tl.float32)[:, None]

        byte = tl.load(wq0 + w_base + p[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0)
        s = tl.load(sc0 + q_base + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        z = tl.load(ze0 + q_base + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        acc0 += tl.sum((((byte & 15).to(tl.float32) - z) * x0 + (((byte >> 4) & 15).to(tl.float32) - z) * x1) * s, axis=0)

        byte = tl.load(wq1 + w_base + p[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0)
        s = tl.load(sc1 + q_base + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        z = tl.load(ze1 + q_base + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        acc1 += tl.sum((((byte & 15).to(tl.float32) - z) * x0 + (((byte >> 4) & 15).to(tl.float32) - z) * x1) * s, axis=0)
    h = (acc0 * tl.sigmoid(acc0)) * acc1
    tl.store(y + pid_e * N + offs_n, h, mask=offs_n < N)


@triton.jit
def _expert_hidden_mix_kernel(x, idx, wq0, sc0, ze0, wq1, sc1, ze1,
                              swq0, ssc0, sze0, swq1, ssc1, sze1, y,
                              K: tl.constexpr, N: tl.constexpr, NG: tl.constexpr,
                              R: tl.constexpr, BLOCK_N: tl.constexpr,
                              BLOCK_P: tl.constexpr):
    pid_e = tl.program_id(0)
    pid_n = tl.program_id(1)
    is_shared = pid_e == R
    e = tl.load(idx + pid_e, mask=pid_e < R, other=0)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    offs_p = tl.arange(0, BLOCK_P)
    acc0 = tl.zeros((BLOCK_N,), tl.float32)
    acc1 = tl.zeros((BLOCK_N,), tl.float32)
    w_base = e * ((K // 2) * N)
    q_base = e * (NG * N)
    for p0 in range(0, K // 2, BLOCK_P):
        p = p0 + offs_p
        group = p // 64
        x0 = tl.load(x + 2 * p).to(tl.float32)[:, None]
        x1 = tl.load(x + 2 * p + 1).to(tl.float32)[:, None]

        ptr = tl.where(is_shared, swq0 + p[:, None] * N + offs_n[None, :],
                       wq0 + w_base + p[:, None] * N + offs_n[None, :])
        sptr = tl.where(is_shared, ssc0 + group[:, None] * N + offs_n[None, :],
                        sc0 + q_base + group[:, None] * N + offs_n[None, :])
        zptr = tl.where(is_shared, sze0 + group[:, None] * N + offs_n[None, :],
                        ze0 + q_base + group[:, None] * N + offs_n[None, :])
        byte = tl.load(ptr, mask=offs_n[None, :] < N, other=0)
        s = tl.load(sptr, mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        z = tl.load(zptr, mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        acc0 += tl.sum((((byte & 15).to(tl.float32) - z) * x0 + (((byte >> 4) & 15).to(tl.float32) - z) * x1) * s, axis=0)

        ptr = tl.where(is_shared, swq1 + p[:, None] * N + offs_n[None, :],
                       wq1 + w_base + p[:, None] * N + offs_n[None, :])
        sptr = tl.where(is_shared, ssc1 + group[:, None] * N + offs_n[None, :],
                        sc1 + q_base + group[:, None] * N + offs_n[None, :])
        zptr = tl.where(is_shared, sze1 + group[:, None] * N + offs_n[None, :],
                        ze1 + q_base + group[:, None] * N + offs_n[None, :])
        byte = tl.load(ptr, mask=offs_n[None, :] < N, other=0)
        s = tl.load(sptr, mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        z = tl.load(zptr, mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
        acc1 += tl.sum((((byte & 15).to(tl.float32) - z) * x0 + (((byte >> 4) & 15).to(tl.float32) - z) * x1) * s, axis=0)
    h = (acc0 * tl.sigmoid(acc0)) * acc1
    tl.store(y + pid_e * N + offs_n, h, mask=offs_n < N)


@triton.jit
def _expert_down_sum_kernel(x, route_w, idx, wq, scales, zeros, y,
                            K: tl.constexpr, N: tl.constexpr, NG: tl.constexpr,
                            ESEL: tl.constexpr, BLOCK_N: tl.constexpr,
                            BLOCK_P: tl.constexpr, ADD: tl.constexpr):
    pid_n = tl.program_id(0)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    offs_p = tl.arange(0, BLOCK_P)
    acc = tl.zeros((BLOCK_N,), tl.float32)
    for jj in range(0, ESEL):
        e = tl.load(idx + jj)
        rw = tl.load(route_w + jj).to(tl.float32)
        w_base = e * ((K // 2) * N)
        q_base = e * (NG * N)
        eacc = tl.zeros((BLOCK_N,), tl.float32)
        for p0 in range(0, K // 2, BLOCK_P):
            p = p0 + offs_p
            group = p // 64
            x0 = tl.load(x + jj * K + 2 * p).to(tl.float32)[:, None]
            x1 = tl.load(x + jj * K + 2 * p + 1).to(tl.float32)[:, None]
            byte = tl.load(wq + w_base + p[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0)
            s = tl.load(scales + q_base + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
            z = tl.load(zeros + q_base + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
            eacc += tl.sum((((byte & 15).to(tl.float32) - z) * x0 + (((byte >> 4) & 15).to(tl.float32) - z) * x1) * s, axis=0)
        acc += rw * eacc
    if ADD:
        acc += tl.load(y + offs_n, mask=offs_n < N, other=0.0).to(tl.float32)
    tl.store(y + offs_n, acc, mask=offs_n < N)


@triton.jit
def _expert_down_mix_kernel(x, route_w, idx, wq, scales, zeros, swq, sscales, szeros, y,
                            K: tl.constexpr, N: tl.constexpr, NG: tl.constexpr,
                            R: tl.constexpr, BLOCK_N: tl.constexpr,
                            BLOCK_P: tl.constexpr):
    pid_n = tl.program_id(0)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    offs_p = tl.arange(0, BLOCK_P)
    acc = tl.zeros((BLOCK_N,), tl.float32)
    for jj in range(0, R + 1):
        eacc = tl.zeros((BLOCK_N,), tl.float32)
        if jj < R:
            e = tl.load(idx + jj)
            rw = tl.load(route_w + jj).to(tl.float32)
            w_base = e * ((K // 2) * N)
            q_base = e * (NG * N)
            for p0 in range(0, K // 2, BLOCK_P):
                p = p0 + offs_p
                group = p // 64
                x0 = tl.load(x + jj * K + 2 * p).to(tl.float32)[:, None]
                x1 = tl.load(x + jj * K + 2 * p + 1).to(tl.float32)[:, None]
                byte = tl.load(wq + w_base + p[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0)
                s = tl.load(scales + q_base + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
                z = tl.load(zeros + q_base + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
                eacc += tl.sum((((byte & 15).to(tl.float32) - z) * x0 + (((byte >> 4) & 15).to(tl.float32) - z) * x1) * s, axis=0)
            acc += rw * eacc
        else:
            for p0 in range(0, K // 2, BLOCK_P):
                p = p0 + offs_p
                group = p // 64
                x0 = tl.load(x + jj * K + 2 * p).to(tl.float32)[:, None]
                x1 = tl.load(x + jj * K + 2 * p + 1).to(tl.float32)[:, None]
                byte = tl.load(swq + p[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0)
                s = tl.load(sscales + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
                z = tl.load(szeros + group[:, None] * N + offs_n[None, :], mask=offs_n[None, :] < N, other=0.0).to(tl.float32)
                eacc += tl.sum((((byte & 15).to(tl.float32) - z) * x0 + (((byte >> 4) & 15).to(tl.float32) - z) * x1) * s, axis=0)
            acc += eacc
    tl.store(y + offs_n, acc, mask=offs_n < N)


@triton.jit
def _mla_alpha_kernel(q, wq, scales, zeros, alpha,
                      H: tl.constexpr, K: tl.constexpr, STRIDE_Q: tl.constexpr,
                      STRIDE_HEAD: tl.constexpr, N_TOTAL: tl.constexpr,
                      BLOCK_R: tl.constexpr, BLOCK_D: tl.constexpr):
    pid_h = tl.program_id(0)
    pid_r = tl.program_id(1)
    offs_r = pid_r * BLOCK_R + tl.arange(0, BLOCK_R)
    offs_d = tl.arange(0, BLOCK_D)
    cols = pid_h * STRIDE_HEAD + offs_d
    byte = tl.load(wq + (offs_r[:, None] // 2) * N_TOTAL + cols[None, :],
                   mask=offs_r[:, None] < K, other=0)
    s = tl.load(scales + (offs_r[:, None] // 128) * N_TOTAL + cols[None, :],
                mask=offs_r[:, None] < K, other=0.0).to(tl.float32)
    z = tl.load(zeros + (offs_r[:, None] // 128) * N_TOTAL + cols[None, :],
                mask=offs_r[:, None] < K, other=0.0).to(tl.float32)
    lo = (byte & 15).to(tl.float32)
    hi = ((byte >> 4) & 15).to(tl.float32)
    use_hi = (offs_r[:, None] & 1) == 1
    w = tl.where(use_hi, hi, lo)
    qv = tl.load(q + pid_h * STRIDE_Q + offs_d).to(tl.float32)[None, :]
    acc = tl.sum((w - z) * s * qv, axis=1)
    tl.store(alpha + pid_h * K + offs_r, acc, mask=offs_r < K)


@triton.jit
def _mla_value_kernel(latent, wq, scales, zeros, out,
                      K: tl.constexpr, N_HEAD: tl.constexpr, STRIDE_HEAD: tl.constexpr,
                      N_TOTAL: tl.constexpr, VALUE_OFF: tl.constexpr,
                      BLOCK_N: tl.constexpr, BLOCK_P: tl.constexpr):
    pid_h = tl.program_id(0)
    pid_n = tl.program_id(1)
    offs_nh = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    cols = pid_h * STRIDE_HEAD + VALUE_OFF + offs_nh
    offs_p = tl.arange(0, BLOCK_P)
    acc = tl.zeros((BLOCK_N,), tl.float32)
    for p0 in range(0, K // 2, BLOCK_P):
        p = p0 + offs_p
        group = p // 64
        x0 = tl.load(latent + pid_h * K + 2 * p).to(tl.float32)[:, None]
        x1 = tl.load(latent + pid_h * K + 2 * p + 1).to(tl.float32)[:, None]
        byte = tl.load(wq + p[:, None] * N_TOTAL + cols[None, :], mask=offs_nh[None, :] < N_HEAD, other=0)
        s = tl.load(scales + group[:, None] * N_TOTAL + cols[None, :], mask=offs_nh[None, :] < N_HEAD, other=0.0).to(tl.float32)
        z = tl.load(zeros + group[:, None] * N_TOTAL + cols[None, :], mask=offs_nh[None, :] < N_HEAD, other=0.0).to(tl.float32)
        acc += tl.sum((((byte & 15).to(tl.float32) - z) * x0 + (((byte >> 4) & 15).to(tl.float32) - z) * x1) * s, axis=0)
    tl.store(out + pid_h * N_HEAD + offs_nh, acc, mask=offs_nh < N_HEAD)


def _lin(x: torch.Tensor, ql: "QuantLinear") -> torch.Tensor:
    y = torch.empty((ql.out_f,), device=x.device, dtype=torch.bfloat16)
    if ql.in_f == 4096:
        block_n, block_p, warps = 8, 512, 8
    elif ql.out_f <= 1024:
        block_n, block_p, warps = 8, 128, 8
    else:
        block_n, block_p, warps = 32, 128, 4
    _gemv_kernel[(triton.cdiv(ql.out_f, block_n),)](
        x, ql.w_q, ql.scales, ql.zeros, y, ql.in_f, ql.out_f,
        BLOCK_N=block_n, BLOCK_P=block_p,
        num_warps=warps,
    )
    return y


def _lin4(x: torch.Tensor, a: "QuantLinear", b: "QuantLinear", c: "QuantLinear",
          d: "QuantLinear"):
    y0 = torch.empty((a.out_f,), device=x.device, dtype=torch.bfloat16)
    y1 = torch.empty_like(y0)
    y2 = torch.empty_like(y0)
    y3 = torch.empty_like(y0)
    _gemv4_kernel[(triton.cdiv(a.out_f, 16),)](
        x, a.w_q, a.scales, a.zeros, y0, b.w_q, b.scales, b.zeros, y1,
        c.w_q, c.scales, c.zeros, y2, d.w_q, d.scales, d.zeros, y3,
        a.in_f, a.out_f, BLOCK_N=16, BLOCK_P=128, num_warps=8,
    )
    return y0, y1, y2, y3


def _fast_rmsnorm(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
    y = torch.empty_like(x)
    _rmsnorm_kernel[(1,)](x, w, y, x.numel(), BLOCK=4096, num_warps=8)
    return y


def _route(x: torch.Tensor, router: nn.Linear, scaling: float):
    idx = torch.empty((8,), device=x.device, dtype=torch.long)
    w = torch.empty((8,), device=x.device, dtype=torch.bfloat16)
    _router_kernel[(1,)](x, router.weight, idx, w, x.numel(), router.out_features, scaling,
                         BLOCK_K=256, num_warps=8)
    return w, idx


def _beta(x: torch.Tensor, proj: nn.Linear) -> torch.Tensor:
    y = torch.empty((32,), device=x.device, dtype=torch.float32)
    _beta_kernel[(1,)](x, proj.weight, y, x.numel(), BLOCK_K=256, num_warps=8)
    return y


class QuantLinear(nn.Module):
    def __init__(self, in_f: int, out_f: int, group: int = GROUP_SIZE):
        super().__init__()
        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 _lin(x, self)


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


class KDA(nn.Module):
    def __init__(self, cfg):
        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, gp = _lin4(x, self.q_proj, self.k_proj, self.v_proj, self.g_proj)
        _short_conv3_kernel[(triton.cdiv(H * Dk, 256),)](
            q, k, v, st["cq"], st["ck"], st["cv"], self.conv_w, H * Dk,
            BLOCK=256, num_warps=4,
        )
        beta = _beta(x, self.beta_proj)
        o = torch.empty((H * Dk,), device=x.device, dtype=torch.bfloat16)
        _kda_recur_kernel[(H, triton.cdiv(Dk, 16))](
            q, k, v, gp, beta, st["S"], o, Dk, self.scale, BLOCK_V=16, num_warps=4,
        )
        return _lin(o, self.o_proj)


class MLA(nn.Module):
    def __init__(self, cfg):
        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 _append_cache(self, st, c_new, k_new, pos):
        cfg = self.cfg
        buf = st.get("_c_buf")
        rbuf = st.get("_r_buf")
        if buf is None or pos >= buf.shape[0]:
            cap = max(pos + 64, max(pos + 1, int((pos + 1) * 1.25)))
            buf = torch.empty((cap, cfg.kv_lora), device=c_new.device, dtype=torch.bfloat16)
            rbuf = torch.empty((cap, cfg.qk_rope), device=c_new.device, dtype=torch.bfloat16)
            if pos:
                buf[:pos].copy_(st["c_kv"])
                rbuf[:pos].copy_(st["k_rope"])
            st["_c_buf"] = buf
            st["_r_buf"] = rbuf
        buf[pos].copy_(c_new)
        rbuf[pos].copy_(k_new)
        st["c_kv"] = buf[: pos + 1]
        st["k_rope"] = rbuf[: pos + 1]

    def step(self, x, st):
        cfg = self.cfg
        H = cfg.mla_heads
        pos = int(st.get("_pos", st["c_kv"].shape[0]))
        q = _lin(x, self.q_proj).view(H, cfg.qk_nope + cfg.qk_rope)
        q_nope = q[:, : cfg.qk_nope]
        q_rope = q[:, cfg.qk_nope :]
        kv = _lin(x, self.kv_a)
        c_new = kv[: cfg.kv_lora]
        k_new = 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_new = _apply_rope(k_new, cos, sin)
        self._append_cache(st, c_new, k_new, pos)
        st["_pos"] = pos + 1

        alpha = torch.empty((H, cfg.kv_lora), device=x.device, dtype=torch.bfloat16)
        _mla_alpha_kernel[(H, triton.cdiv(cfg.kv_lora, 16))](
            q_nope, self.kv_b.w_q, self.kv_b.scales, self.kv_b.zeros, alpha,
            H, cfg.kv_lora, cfg.qk_nope + cfg.qk_rope, cfg.qk_nope + cfg.v_head,
            H * (cfg.qk_nope + cfg.v_head), BLOCK_R=16, BLOCK_D=128,
            num_warps=4,
        )
        scores = alpha @ st["c_kv"].t()
        scores = scores.float()
        scores += q_rope.float() @ st["k_rope"].float().t()
        scores *= self.scale
        p = torch.softmax(scores, dim=-1)
        latent = (p.to(torch.bfloat16) @ st["c_kv"]).to(torch.bfloat16)
        o = torch.empty((H, cfg.v_head), device=x.device, dtype=torch.bfloat16)
        _mla_value_kernel[(H, triton.cdiv(cfg.v_head, 32))](
            latent, self.kv_b.w_q, self.kv_b.scales, self.kv_b.zeros, o,
            cfg.kv_lora, cfg.v_head, cfg.qk_nope + cfg.v_head,
            H * (cfg.qk_nope + cfg.v_head), cfg.qk_nope,
            BLOCK_N=32, BLOCK_P=64, num_warps=4,
        )
        return _lin(o.reshape(H * cfg.v_head), self.o_proj)


class MoE(nn.Module):
    def __init__(self, cfg):
        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)
        self.register_buffer("_shared_idx", torch.zeros(cfg.n_shared, dtype=torch.long), persistent=False)
        self.register_buffer("_shared_w", torch.ones(cfg.n_shared, dtype=torch.bfloat16), persistent=False)

    def _hidden(self, x, idx, gate, up):
        cfg = self.cfg
        y = torch.empty((idx.numel(), cfg.moe_inter), device=x.device, dtype=torch.bfloat16)
        _expert_hidden_kernel[(idx.numel(), triton.cdiv(cfg.moe_inter, 32))](
            x, idx, gate.w_q, gate.scales, gate.zeros, up.w_q, up.scales, up.zeros, y,
            gate.in_f, gate.out_f, gate.in_f // gate.group, BLOCK_N=32, BLOCK_P=128,
            num_warps=4,
        )
        return y

    def _down_sum(self, h, rw, idx, down, out=None, add=False):
        cfg = self.cfg
        if out is None:
            out = torch.empty((cfg.hidden,), device=h.device, dtype=torch.bfloat16)
        _expert_down_sum_kernel[(triton.cdiv(cfg.hidden, 8),)](
            h, rw, idx, down.w_q, down.scales, down.zeros, out,
            down.in_f, down.out_f, down.in_f // down.group, idx.numel(),
            BLOCK_N=8, BLOCK_P=256, ADD=add, num_warps=4,
        )
        return out

    def step(self, x):
        cfg = self.cfg
        w, idx = _route(x, self.router, cfg.routed_scaling)
        h = torch.empty((cfg.n_active + cfg.n_shared, cfg.moe_inter), device=x.device, dtype=torch.bfloat16)
        _expert_hidden_mix_kernel[(cfg.n_active + cfg.n_shared, triton.cdiv(cfg.moe_inter, 32))](
            x, idx, self.gate.w_q, self.gate.scales, self.gate.zeros,
            self.up.w_q, self.up.scales, self.up.zeros,
            self.s_gate.w_q, self.s_gate.scales, self.s_gate.zeros,
            self.s_up.w_q, self.s_up.scales, self.s_up.zeros, h,
            self.gate.in_f, self.gate.out_f, self.gate.in_f // self.gate.group,
            cfg.n_active, BLOCK_N=32, BLOCK_P=128, num_warps=4,
        )
        out = torch.empty((cfg.hidden,), device=x.device, dtype=torch.bfloat16)
        _expert_down_mix_kernel[(triton.cdiv(cfg.hidden, 8),)](
            h, w, idx, self.down.w_q, self.down.scales, self.down.zeros,
            self.s_down.w_q, self.s_down.scales, self.s_down.zeros, out,
            self.down.in_f, self.down.out_f, self.down.in_f // self.down.group,
            cfg.n_active, BLOCK_N=8, BLOCK_P=512, num_warps=4,
        )
        return out


class Block(nn.Module):
    def __init__(self, cfg, kind):
        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(_fast_rmsnorm(x, self.attn_norm), st)
        return h + self.moe.step(_fast_rmsnorm(h, self.moe_norm))


class Model(nn.Module):
    def __init__(self, cfg):
        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

20260618_162338_codex_gpt-5.5_02_kimi_linear_decode