KernelBench mega · H100

Kimi-Linear Decode GPT-5.5

5.62×geomean speedup across shapes

manually audited: clean

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


@triton.jit
def _w4_gemv_kernel(x, wq, scales, zeros, y, K: tl.constexpr, N: tl.constexpr,
                    BLOCK_N: tl.constexpr):
    pid_n = tl.program_id(0)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    mask_n = offs_n < N
    pair = tl.arange(0, 64)
    acc = tl.zeros((BLOCK_N,), tl.float32)

    for g in tl.range(0, K // 128):
        packed = tl.load(
            wq + (g * 64 + pair)[:, None] * N + offs_n[None, :],
            mask=mask_n[None, :],
            other=0,
        )
        lo = packed & 15
        hi = (packed >> 4) & 15
        xe = tl.load(x + g * 128 + pair * 2).to(tl.float32)
        xo = tl.load(x + g * 128 + pair * 2 + 1).to(tl.float32)
        s = tl.load(scales + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        z = tl.load(zeros + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        vals = ((lo.to(tl.float32) - z[None, :]) * xe[:, None] +
                (hi.to(tl.float32) - z[None, :]) * xo[:, None]) * s[None, :]
        acc += tl.sum(vals, axis=0)

    tl.store(y + offs_n, acc, mask=mask_n)


@triton.jit
def _w4_gemv4_kernel(x,
                     wq0, scales0, zeros0, wq1, scales1, zeros1,
                     wq2, scales2, zeros2, wq3, scales3, zeros3,
                     y0, y1, y2, y3,
                     K: tl.constexpr, N: tl.constexpr, BLOCK_N: tl.constexpr):
    pid_n = tl.program_id(0)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    mask_n = offs_n < N
    pair = tl.arange(0, 64)
    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 g in tl.range(0, K // 128):
        xe = tl.load(x + g * 128 + pair * 2).to(tl.float32)
        xo = tl.load(x + g * 128 + pair * 2 + 1).to(tl.float32)

        packed0 = tl.load(
            wq0 + (g * 64 + pair)[:, None] * N + offs_n[None, :],
            mask=mask_n[None, :],
            other=0,
        )
        lo0 = packed0 & 15
        hi0 = (packed0 >> 4) & 15
        s0 = tl.load(scales0 + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        z0 = tl.load(zeros0 + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        vals0 = ((lo0.to(tl.float32) - z0[None, :]) * xe[:, None] +
                 (hi0.to(tl.float32) - z0[None, :]) * xo[:, None]) * s0[None, :]
        acc0 += tl.sum(vals0, axis=0)

        packed1 = tl.load(
            wq1 + (g * 64 + pair)[:, None] * N + offs_n[None, :],
            mask=mask_n[None, :],
            other=0,
        )
        lo1 = packed1 & 15
        hi1 = (packed1 >> 4) & 15
        s1 = tl.load(scales1 + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        z1 = tl.load(zeros1 + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        vals1 = ((lo1.to(tl.float32) - z1[None, :]) * xe[:, None] +
                 (hi1.to(tl.float32) - z1[None, :]) * xo[:, None]) * s1[None, :]
        acc1 += tl.sum(vals1, axis=0)

        packed2 = tl.load(
            wq2 + (g * 64 + pair)[:, None] * N + offs_n[None, :],
            mask=mask_n[None, :],
            other=0,
        )
        lo2 = packed2 & 15
        hi2 = (packed2 >> 4) & 15
        s2 = tl.load(scales2 + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        z2 = tl.load(zeros2 + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        vals2 = ((lo2.to(tl.float32) - z2[None, :]) * xe[:, None] +
                 (hi2.to(tl.float32) - z2[None, :]) * xo[:, None]) * s2[None, :]
        acc2 += tl.sum(vals2, axis=0)

        packed3 = tl.load(
            wq3 + (g * 64 + pair)[:, None] * N + offs_n[None, :],
            mask=mask_n[None, :],
            other=0,
        )
        lo3 = packed3 & 15
        hi3 = (packed3 >> 4) & 15
        s3 = tl.load(scales3 + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        z3 = tl.load(zeros3 + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        vals3 = ((lo3.to(tl.float32) - z3[None, :]) * xe[:, None] +
                 (hi3.to(tl.float32) - z3[None, :]) * xo[:, None]) * s3[None, :]
        acc3 += tl.sum(vals3, axis=0)

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


@triton.jit
def _w4_expert_same_x_kernel(x, wq, scales, zeros, idx, y,
                             K: tl.constexpr, N: tl.constexpr,
                             BLOCK_N: tl.constexpr):
    pid_e = tl.program_id(0)
    pid_n = tl.program_id(1)
    expert = tl.load(idx + pid_e)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    mask_n = offs_n < N
    pair = tl.arange(0, 64)
    acc = tl.zeros((BLOCK_N,), tl.float32)
    wq_base = expert * (K // 2) * N
    q_base = expert * (K // 128) * N

    for g in tl.range(0, K // 128):
        packed = tl.load(
            wq + wq_base + (g * 64 + pair)[:, None] * N + offs_n[None, :],
            mask=mask_n[None, :],
            other=0,
        )
        lo = packed & 15
        hi = (packed >> 4) & 15
        xe = tl.load(x + g * 128 + pair * 2).to(tl.float32)
        xo = tl.load(x + g * 128 + pair * 2 + 1).to(tl.float32)
        s = tl.load(scales + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        z = tl.load(zeros + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        vals = ((lo.to(tl.float32) - z[None, :]) * xe[:, None] +
                (hi.to(tl.float32) - z[None, :]) * xo[:, None]) * s[None, :]
        acc += tl.sum(vals, axis=0)

    tl.store(y + pid_e * N + offs_n, acc, mask=mask_n)


@triton.jit
def _w4_expert_batch_x_kernel(x, wq, scales, zeros, idx, y,
                              K: tl.constexpr, N: tl.constexpr,
                              BLOCK_N: tl.constexpr):
    pid_e = tl.program_id(0)
    pid_n = tl.program_id(1)
    expert = tl.load(idx + pid_e)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    mask_n = offs_n < N
    pair = tl.arange(0, 64)
    acc = tl.zeros((BLOCK_N,), tl.float32)
    wq_base = expert * (K // 2) * N
    q_base = expert * (K // 128) * N
    x_base = pid_e * K

    for g in tl.range(0, K // 128):
        packed = tl.load(
            wq + wq_base + (g * 64 + pair)[:, None] * N + offs_n[None, :],
            mask=mask_n[None, :],
            other=0,
        )
        lo = packed & 15
        hi = (packed >> 4) & 15
        xe = tl.load(x + x_base + g * 128 + pair * 2).to(tl.float32)
        xo = tl.load(x + x_base + g * 128 + pair * 2 + 1).to(tl.float32)
        s = tl.load(scales + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        z = tl.load(zeros + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        vals = ((lo.to(tl.float32) - z[None, :]) * xe[:, None] +
                (hi.to(tl.float32) - z[None, :]) * xo[:, None]) * s[None, :]
        acc += tl.sum(vals, axis=0)

    tl.store(y + pid_e * N + offs_n, acc, mask=mask_n)


@triton.jit
def _w4_expert_pair_same_x_kernel(x, wq0, scales0, zeros0, wq1, scales1, zeros1,
                                  idx, y, K: tl.constexpr, N: tl.constexpr,
                                  BLOCK_N: tl.constexpr):
    pid_e = tl.program_id(0)
    pid_n = tl.program_id(1)
    expert = tl.load(idx + pid_e)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    mask_n = offs_n < N
    pair = tl.arange(0, 64)
    acc0 = tl.zeros((BLOCK_N,), tl.float32)
    acc1 = tl.zeros((BLOCK_N,), tl.float32)
    wq_base = expert * (K // 2) * N
    q_base = expert * (K // 128) * N

    for g in tl.range(0, K // 128):
        xe = tl.load(x + g * 128 + pair * 2).to(tl.float32)
        xo = tl.load(x + g * 128 + pair * 2 + 1).to(tl.float32)

        packed0 = tl.load(
            wq0 + wq_base + (g * 64 + pair)[:, None] * N + offs_n[None, :],
            mask=mask_n[None, :],
            other=0,
        )
        lo0 = packed0 & 15
        hi0 = (packed0 >> 4) & 15
        s0 = tl.load(scales0 + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        z0 = tl.load(zeros0 + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        vals0 = ((lo0.to(tl.float32) - z0[None, :]) * xe[:, None] +
                 (hi0.to(tl.float32) - z0[None, :]) * xo[:, None]) * s0[None, :]
        acc0 += tl.sum(vals0, axis=0)

        packed1 = tl.load(
            wq1 + wq_base + (g * 64 + pair)[:, None] * N + offs_n[None, :],
            mask=mask_n[None, :],
            other=0,
        )
        lo1 = packed1 & 15
        hi1 = (packed1 >> 4) & 15
        s1 = tl.load(scales1 + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        z1 = tl.load(zeros1 + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        vals1 = ((lo1.to(tl.float32) - z1[None, :]) * xe[:, None] +
                 (hi1.to(tl.float32) - z1[None, :]) * xo[:, None]) * s1[None, :]
        acc1 += tl.sum(vals1, axis=0)

    tl.store(y + pid_e * N + offs_n, (acc0 * tl.sigmoid(acc0)) * acc1, mask=mask_n)


@triton.jit
def _w4_down_sum_kernel(x, wq, scales, zeros, idx, route_w,
                        sx, swq, sscales, szeros, y,
                        K: tl.constexpr, N: tl.constexpr, BLOCK_N: tl.constexpr):
    pid_n = tl.program_id(0)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    mask_n = offs_n < N
    pair = tl.arange(0, 64)
    total = tl.zeros((BLOCK_N,), tl.float32)

    for e in tl.range(0, 8):
        expert = tl.load(idx + e)
        wq_base = expert * (K // 2) * N
        q_base = expert * (K // 128) * N
        x_base = e * K
        acc = tl.zeros((BLOCK_N,), tl.float32)
        for g in tl.range(0, K // 128):
            packed = tl.load(
                wq + wq_base + (g * 64 + pair)[:, None] * N + offs_n[None, :],
                mask=mask_n[None, :],
                other=0,
            )
            lo = packed & 15
            hi = (packed >> 4) & 15
            xe = tl.load(x + x_base + g * 128 + pair * 2).to(tl.float32)
            xo = tl.load(x + x_base + g * 128 + pair * 2 + 1).to(tl.float32)
            s = tl.load(scales + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
            z = tl.load(zeros + q_base + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
            vals = ((lo.to(tl.float32) - z[None, :]) * xe[:, None] +
                    (hi.to(tl.float32) - z[None, :]) * xo[:, None]) * s[None, :]
            acc += tl.sum(vals, axis=0)
        total += tl.load(route_w + e).to(tl.float32) * acc

    acc = tl.zeros((BLOCK_N,), tl.float32)
    for g in tl.range(0, K // 128):
        packed = tl.load(
            swq + (g * 64 + pair)[:, None] * N + offs_n[None, :],
            mask=mask_n[None, :],
            other=0,
        )
        lo = packed & 15
        hi = (packed >> 4) & 15
        xe = tl.load(sx + g * 128 + pair * 2).to(tl.float32)
        xo = tl.load(sx + g * 128 + pair * 2 + 1).to(tl.float32)
        s = tl.load(sscales + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        z = tl.load(szeros + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
        vals = ((lo.to(tl.float32) - z[None, :]) * xe[:, None] +
                (hi.to(tl.float32) - z[None, :]) * xo[:, None]) * s[None, :]
        acc += tl.sum(vals, axis=0)
    total += acc
    tl.store(y + offs_n, total, mask=mask_n)


@triton.jit
def _kvb_score_kernel(q, wq, scales, zeros, y,
                      BLOCK_R: tl.constexpr, BLOCK_C: tl.constexpr):
    pid_h = tl.program_id(0)
    pid_r = tl.program_id(1)
    rows = pid_r * BLOCK_R + tl.arange(0, BLOCK_R)
    cols_l = tl.arange(0, BLOCK_C)
    acc = tl.zeros((BLOCK_R,), tl.float32)
    even = (rows & 1) == 0
    groups = rows // 128
    packed_rows = rows // 2

    for c0 in tl.range(0, 128, BLOCK_C):
        cols = pid_h * 256 + c0 + cols_l
        packed = tl.load(wq + packed_rows[:, None] * 8192 + cols[None, :])
        raw = tl.where(even[:, None], packed & 15, (packed >> 4) & 15)
        s = tl.load(scales + groups[:, None] * 8192 + cols[None, :]).to(tl.float32)
        z = tl.load(zeros + groups[:, None] * 8192 + cols[None, :]).to(tl.float32)
        qq = tl.load(q + pid_h * 128 + c0 + cols_l).to(tl.float32)
        acc += tl.sum((raw.to(tl.float32) - z) * s * qq[None, :], axis=1)

    tl.store(y + pid_h * 512 + rows, acc)


@triton.jit
def _kvb_value_kernel(x, wq, scales, zeros, y, BLOCK_N: tl.constexpr):
    pid_h = tl.program_id(0)
    pid_n = tl.program_id(1)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    pair = tl.arange(0, 64)
    cols = pid_h * 256 + 128 + offs_n
    mask_n = offs_n < 128
    acc = tl.zeros((BLOCK_N,), tl.float32)

    for g in tl.range(0, 4):
        packed = tl.load(
            wq + (g * 64 + pair)[:, None] * 8192 + cols[None, :],
            mask=mask_n[None, :],
            other=0,
        )
        lo = packed & 15
        hi = (packed >> 4) & 15
        xe = tl.load(x + pid_h * 512 + g * 128 + pair * 2).to(tl.float32)
        xo = tl.load(x + pid_h * 512 + g * 128 + pair * 2 + 1).to(tl.float32)
        s = tl.load(scales + g * 8192 + cols, mask=mask_n, other=0.0).to(tl.float32)
        z = tl.load(zeros + g * 8192 + cols, mask=mask_n, other=0.0).to(tl.float32)
        vals = ((lo.to(tl.float32) - z[None, :]) * xe[:, None] +
                (hi.to(tl.float32) - z[None, :]) * xo[:, None]) * s[None, :]
        acc += tl.sum(vals, axis=0)

    tl.store(y + pid_h * 128 + offs_n, acc, mask=mask_n)


@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(tl.where(mask, xv * xv, 0.0), axis=0) / N
    inv = tl.rsqrt(ss + 1.0e-6)
    wv = tl.load(w + offs, mask=mask, other=0.0).to(tl.float32)
    tl.store(y + offs, xv * inv * wv, mask=mask)


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

    q0 = tl.load(cq + offs, mask=mask, other=0.0).to(tl.float32)
    q1 = tl.load(cq + C + offs, mask=mask, other=0.0).to(tl.float32)
    q2 = tl.load(cq + 2 * C + offs, mask=mask, other=0.0).to(tl.float32)
    q3 = tl.load(q + offs, mask=mask, other=0.0).to(tl.float32)
    s = q0 * tl.load(cw + offs * 4 + 0, mask=mask, other=0.0).to(tl.float32)
    s += q1 * tl.load(cw + offs * 4 + 1, mask=mask, other=0.0).to(tl.float32)
    s += q2 * tl.load(cw + offs * 4 + 2, mask=mask, other=0.0).to(tl.float32)
    s += q3 * tl.load(cw + offs * 4 + 3, mask=mask, other=0.0).to(tl.float32)
    tl.store(q + offs, s * tl.sigmoid(s), mask=mask)
    tl.store(cq + offs, q1, mask=mask)
    tl.store(cq + C + offs, q2, mask=mask)
    tl.store(cq + 2 * C + offs, q3, mask=mask)

    k0 = tl.load(ck + offs, mask=mask, other=0.0).to(tl.float32)
    k1 = tl.load(ck + C + offs, mask=mask, other=0.0).to(tl.float32)
    k2 = tl.load(ck + 2 * C + offs, mask=mask, other=0.0).to(tl.float32)
    k3 = tl.load(k + offs, mask=mask, other=0.0).to(tl.float32)
    cw_k = cw + C * 4
    s = k0 * tl.load(cw_k + offs * 4 + 0, mask=mask, other=0.0).to(tl.float32)
    s += k1 * tl.load(cw_k + offs * 4 + 1, mask=mask, other=0.0).to(tl.float32)
    s += k2 * tl.load(cw_k + offs * 4 + 2, mask=mask, other=0.0).to(tl.float32)
    s += k3 * tl.load(cw_k + offs * 4 + 3, mask=mask, other=0.0).to(tl.float32)
    tl.store(k + offs, s * tl.sigmoid(s), mask=mask)
    tl.store(ck + offs, k1, mask=mask)
    tl.store(ck + C + offs, k2, mask=mask)
    tl.store(ck + 2 * C + offs, k3, mask=mask)

    v0 = tl.load(cv + offs, mask=mask, other=0.0).to(tl.float32)
    v1 = tl.load(cv + C + offs, mask=mask, other=0.0).to(tl.float32)
    v2 = tl.load(cv + 2 * C + offs, mask=mask, other=0.0).to(tl.float32)
    v3 = tl.load(v + offs, mask=mask, other=0.0).to(tl.float32)
    cw_v = cw + 2 * C * 4
    s = v0 * tl.load(cw_v + offs * 4 + 0, mask=mask, other=0.0).to(tl.float32)
    s += v1 * tl.load(cw_v + offs * 4 + 1, mask=mask, other=0.0).to(tl.float32)
    s += v2 * tl.load(cw_v + offs * 4 + 2, mask=mask, other=0.0).to(tl.float32)
    s += v3 * tl.load(cw_v + offs * 4 + 3, mask=mask, other=0.0).to(tl.float32)
    tl.store(v + offs, s * tl.sigmoid(s), mask=mask)
    tl.store(cv + offs, v1, mask=mask)
    tl.store(cv + C + offs, v2, mask=mask)
    tl.store(cv + 2 * C + offs, v3, mask=mask)


@triton.jit
def _kda_recur_kernel(q, k, v, g_raw, beta, state_s, out,
                      SCALE: tl.constexpr, BLOCK_V: tl.constexpr):
    pid_h = tl.program_id(0)
    pid_v = tl.program_id(1)
    rows = tl.arange(0, 128)
    cols = pid_v * BLOCK_V + tl.arange(0, BLOCK_V)
    base_h = pid_h * 128
    s_base = pid_h * 128 * 128

    qv = tl.load(q + base_h + rows).to(tl.float32) * SCALE
    kv = tl.load(k + base_h + rows).to(tl.float32)
    decay = tl.sigmoid(-tl.load(g_raw + base_h + rows).to(tl.float32))
    vv = tl.load(v + base_h + cols).to(tl.float32)
    b = tl.load(beta + pid_h).to(tl.float32)

    s_old = tl.load(state_s + s_base + rows[:, None] * 128 + cols[None, :]).to(tl.float32)
    s_decayed = s_old * decay[:, None]
    pred = tl.sum(s_decayed * kv[:, None], axis=0)
    s_new = s_decayed + b * kv[:, None] * (vv[None, :] - pred[None, :])
    ov = tl.sum(s_new * qv[:, None], axis=0)

    tl.store(state_s + s_base + rows[:, None] * 128 + cols[None, :], s_new)
    tl.store(out + base_h + cols, ov)


def _block_n(n: int) -> int:
    return 16 if n <= 1024 else 32


def _qgemv(x: torch.Tensor, mod: "QuantLinear", dtype=torch.bfloat16) -> torch.Tensor:
    y = torch.empty((mod.out_f,), device=x.device, dtype=dtype)
    bn = _block_n(mod.out_f)
    grid = (triton.cdiv(mod.out_f, bn),)
    _w4_gemv_kernel[grid](x, mod.w_q, mod.scales, mod.zeros, y, mod.in_f, mod.out_f, bn,
                          num_warps=4)
    return y


def _qgemv4(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((a.out_f,), device=x.device, dtype=torch.bfloat16)
    y2 = torch.empty((a.out_f,), device=x.device, dtype=torch.bfloat16)
    y3 = torch.empty((a.out_f,), device=x.device, dtype=torch.bfloat16)
    bn = 16
    grid = (triton.cdiv(a.out_f, bn),)
    _w4_gemv4_kernel[grid](
        x,
        a.w_q, a.scales, a.zeros,
        b.w_q, b.scales, b.zeros,
        c.w_q, c.scales, c.zeros,
        d.w_q, d.scales, d.zeros,
        y0, y1, y2, y3,
        a.in_f, a.out_f, bn,
        num_warps=4,
    )
    return y0, y1, y2, y3


def _expert_same_x(x: torch.Tensor, mod: "QuantExperts", idx: torch.Tensor,
                   dtype=torch.float32) -> torch.Tensor:
    eact = idx.numel()
    y = torch.empty((eact, mod.out_f), device=x.device, dtype=dtype)
    bn = _block_n(mod.out_f)
    grid = (eact, triton.cdiv(mod.out_f, bn))
    _w4_expert_same_x_kernel[grid](x, mod.w_q, mod.scales, mod.zeros, idx, y,
                                   mod.in_f, mod.out_f, bn, num_warps=4)
    return y


def _expert_batch_x(x: torch.Tensor, mod: "QuantExperts", idx: torch.Tensor,
                    dtype=torch.float32) -> torch.Tensor:
    eact = idx.numel()
    y = torch.empty((eact, mod.out_f), device=x.device, dtype=dtype)
    bn = _block_n(mod.out_f)
    grid = (eact, triton.cdiv(mod.out_f, bn))
    _w4_expert_batch_x_kernel[grid](x, mod.w_q, mod.scales, mod.zeros, idx, y,
                                    mod.in_f, mod.out_f, bn, num_warps=4)
    return y


def _expert_down_sum(x: torch.Tensor, mod: "QuantExperts", idx: torch.Tensor,
                     route_w: torch.Tensor, sx: torch.Tensor, smod: "QuantExperts"):
    y = torch.empty((mod.out_f,), device=x.device, dtype=torch.bfloat16)
    bn = 16
    grid = (triton.cdiv(mod.out_f, bn),)
    _w4_down_sum_kernel[grid](
        x, mod.w_q, mod.scales, mod.zeros, idx, route_w,
        sx, smod.w_q, smod.scales, smod.zeros, y,
        mod.in_f, mod.out_f, bn, num_warps=4,
    )
    return y


def _expert_pair_same_x(x: torch.Tensor, mod0: "QuantExperts", mod1: "QuantExperts",
                        idx: torch.Tensor, dtype=torch.float32):
    eact = idx.numel()
    y = torch.empty((eact, mod0.out_f), device=x.device, dtype=dtype)
    bn = _block_n(mod0.out_f)
    grid = (eact, triton.cdiv(mod0.out_f, bn))
    _w4_expert_pair_same_x_kernel[grid](
        x, mod0.w_q, mod0.scales, mod0.zeros, mod1.w_q, mod1.scales, mod1.zeros,
        idx, y, mod0.in_f, mod0.out_f, bn, num_warps=4,
    )
    return y


def _rmsnorm(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
    y = torch.empty_like(x)
    _rmsnorm_kernel[(1,)](x, w, y, x.numel(), triton.next_power_of_2(x.numel()), num_warps=8)
    return y


def _kda_conv3(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, st: dict,
               conv_w: torch.Tensor):
    c = q.numel()
    _kda_conv3_kernel[(triton.cdiv(c, 256),)](
        q, k, v, st["cq"], st["ck"], st["cv"], conv_w, c, 256, num_warps=4,
    )
    return q, k, v


def _kda_recur(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, g_raw: torch.Tensor,
               beta: torch.Tensor, state_s: torch.Tensor, scale: float):
    out = torch.empty_like(q)
    _kda_recur_kernel[(32, 8)](q, k, v, g_raw, beta, state_s, out, scale, 16, num_warps=4)
    return out


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 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
        self.register_buffer("w_q", torch.zeros(in_f // 2, out_f, dtype=torch.uint8))
        self.register_buffer("scales", torch.zeros(in_f // group, out_f, dtype=torch.bfloat16))
        self.register_buffer("zeros", torch.zeros(in_f // group, out_f, dtype=torch.bfloat16))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return _qgemv(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
        self.register_buffer("w_q", torch.zeros(n, in_f // 2, out_f, dtype=torch.uint8))
        self.register_buffer("scales", torch.zeros(n, in_f // group, out_f, dtype=torch.bfloat16))
        self.register_buffer("zeros", torch.zeros(n, in_f // group, out_f, dtype=torch.bfloat16))


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_raw = _qgemv4(x, self.q_proj, self.k_proj, self.v_proj, self.g_proj)
        q, k, v = _kda_conv3(q, k, v, st, self.conv_w)
        beta = torch.sigmoid(self.beta_proj(x).float())
        o = _kda_recur(q, k, v, g_raw, beta, st["S"], self.scale)
        return self.o_proj(o)


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
        inv = 1.0 / (cfg.rope_theta ** (torch.arange(0, cfg.qk_rope, 2, dtype=torch.float32) / cfg.qk_rope))
        self.register_buffer("_rope_inv", inv, persistent=False)

    def _kvb_score_vecs(self, q_nope: torch.Tensor) -> torch.Tensor:
        out = torch.empty((self.cfg.mla_heads, self.cfg.kv_lora), device=q_nope.device,
                          dtype=torch.bfloat16)
        _kvb_score_kernel[(self.cfg.mla_heads, triton.cdiv(self.cfg.kv_lora, 16))](
            q_nope, self.kv_b.w_q, self.kv_b.scales, self.kv_b.zeros, out, 16, 32,
            num_warps=4,
        )
        return out

    def _kvb_values(self, x: torch.Tensor) -> torch.Tensor:
        out = torch.empty((self.cfg.mla_heads, self.cfg.v_head), device=x.device,
                          dtype=torch.bfloat16)
        _kvb_value_kernel[(self.cfg.mla_heads, triton.cdiv(self.cfg.v_head, 32))](
            x, self.kv_b.w_q, self.kv_b.scales, self.kv_b.zeros, out, 32,
            num_warps=4,
        )
        return out

    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 :]

        ang = pos * self._rope_inv
        cos, sin = torch.cos(ang), torch.sin(ang)
        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)

        score_vecs = self._kvb_score_vecs(q_nope)
        scores = (score_vecs @ st["c_kv"].t()).float()
        scores = scores + (q_rope @ st["k_rope"].t()).float()
        scores = scores * self.scale
        p = torch.softmax(scores, dim=-1).to(torch.bfloat16)
        latent = (p @ st["c_kv"]).to(torch.bfloat16)
        o = self._kvb_values(latent)
        return self.o_proj(o.reshape(h * cfg.v_head))


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)
        self.register_buffer("_shared_idx", torch.zeros(cfg.n_shared, dtype=torch.long), persistent=False)

    def _run_experts(self, x, idx):
        hidden = _expert_pair_same_x(x, self.gate, self.up, idx)
        return _expert_batch_x(hidden, self.down, idx)

    def _run_shared(self, x):
        idx = self._shared_idx
        hidden = _expert_pair_same_x(x, self.s_gate, self.s_up, idx)
        return _expert_batch_x(hidden, self.s_down, 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).float()
        routed = self._run_experts(x, idx)
        out = (w[:, None] * routed).sum(0)
        out = out + self._run_shared(x).sum(0)
        return out.to(torch.bfloat16)


class Block(nn.Module):
    def __init__(self, cfg: Config, kind: str):
        super().__init__()
        self.kind = kind
        self.attn_norm = nn.Parameter(torch.ones(cfg.hidden, dtype=cfg.dtype))
        self.moe_norm = nn.Parameter(torch.ones(cfg.hidden, dtype=cfg.dtype))
        self.attn = KDA(cfg) if kind == "K" else MLA(cfg)
        self.moe = MoE(cfg)

    def step(self, x, st):
        h = x + self.attn.step(_rmsnorm(x, self.attn_norm), st)
        return h + self.moe.step(_rmsnorm(h, self.moe_norm))


class Model(nn.Module):
    def __init__(self, cfg: Config):
        super().__init__()
        self.cfg = cfg
        self.blocks = nn.ModuleList(Block(cfg, k) for k in cfg.pattern)

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


def init_state(cfg: Config, context_len: int, seed: int) -> list:
    dev = torch.device("cuda:0")
    gen = 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=gen) * 0.05,
                "cq": torch.randn(cfg.short_conv - 1, c, device=dev, generator=gen, dtype=cfg.dtype) * 0.1,
                "ck": torch.randn(cfg.short_conv - 1, c, device=dev, generator=gen, dtype=cfg.dtype) * 0.1,
                "cv": torch.randn(cfg.short_conv - 1, c, device=dev, generator=gen, dtype=cfg.dtype) * 0.1,
            })
        else:
            state.append({
                "c_kv": torch.randn(context_len, cfg.kv_lora, device=dev, generator=gen, dtype=cfg.dtype) * 0.1,
                "k_rope": torch.randn(context_len, cfg.qk_rope, device=dev, generator=gen, dtype=cfg.dtype) * 0.1,
            })
    return state


def init_token(cfg: Config, seed: int) -> torch.Tensor:
    dev = torch.device("cuda:0")
    gen = torch.Generator(device=dev).manual_seed(seed + 1)
    return torch.randn(cfg.hidden, device=dev, generator=gen, dtype=cfg.dtype) * 0.25

20260618_040852_codex_gpt-5.5_02_kimi_linear_decode