KernelBench mega · RTX PRO 6000
Kimi-Linear Decode Kimi K3.1 Pro
wrongdid not score
Kimi K3.1 Pro wrote one cooperative CUDA kernel (188 blocks x 512 threads, 45 grid barriers per step) that runs all four layers and MoEs with in-kernel int4 dequant GEMVs, and passed check.py at about 8.6x in-run. But its absorbed MLA query is wrong: it reads q_nope at h*128+d instead of h*192+d and uses one kv_b scale/zero per head. The checker's random cache hides it.
harnesskimi
Kernel source (redacted)
from __future__ import annotations
import os
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
_CPP_SOURCE = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_bf16.h>
#include <vector>
struct W4 {
const uint8_t* q;
const __nv_bfloat16* s;
const __nv_bfloat16* z;
};
struct QE {
W4 gate, up, down, sgate, sup, sdown;
const __nv_bfloat16* router;
};
struct Params {
const __nv_bfloat16* anorm[4];
const __nv_bfloat16* mnorm[4];
W4 kproj[3][4];
W4 kout[3];
const __nv_bfloat16* beta[3];
const __nv_bfloat16* conv[3];
W4 mq, mkva, mkvb, mo;
QE moe[4];
float* state[3];
__nv_bfloat16* cq[3];
__nv_bfloat16* ck[3];
__nv_bfloat16* cv[3];
const __nv_bfloat16* hidden;
__nv_bfloat16* output;
const __nv_bfloat16* cold;
const __nv_bfloat16* kold;
__nv_bfloat16* cnew;
__nv_bfloat16* knew;
float* ws;
int pos;
int copy_cache;
};
extern "C" int launch_decode(Params p, void* stream);
static W4 get_w4(const std::vector<torch::Tensor>& w, int& i) {
W4 r;
r.q = reinterpret_cast<const uint8_t*>(w[i++].data_ptr());
r.s = reinterpret_cast<const __nv_bfloat16*>(w[i++].data_ptr());
r.z = reinterpret_cast<const __nv_bfloat16*>(w[i++].data_ptr());
return r;
}
void decode(std::vector<torch::Tensor> weights, torch::Tensor hidden,
torch::Tensor output, std::vector<torch::Tensor> kda_state,
torch::Tensor cold, torch::Tensor kold, torch::Tensor cnew,
torch::Tensor knew, torch::Tensor workspace, int64_t pos,
bool copy_cache) {
Params p{};
int i = 0;
for (int b = 0; b < 4; ++b) {
p.anorm[b] = reinterpret_cast<const __nv_bfloat16*>(weights[i++].data_ptr());
p.mnorm[b] = reinterpret_cast<const __nv_bfloat16*>(weights[i++].data_ptr());
if (b < 3) {
for (int j = 0; j < 4; ++j) p.kproj[b][j] = get_w4(weights, i);
p.beta[b] = reinterpret_cast<const __nv_bfloat16*>(weights[i++].data_ptr());
p.conv[b] = reinterpret_cast<const __nv_bfloat16*>(weights[i++].data_ptr());
p.kout[b] = get_w4(weights, i);
} else {
p.mq = get_w4(weights, i);
p.mkva = get_w4(weights, i);
p.mkvb = get_w4(weights, i);
p.mo = get_w4(weights, i);
}
p.moe[b].router = reinterpret_cast<const __nv_bfloat16*>(weights[i++].data_ptr());
p.moe[b].gate = get_w4(weights, i);
p.moe[b].up = get_w4(weights, i);
p.moe[b].down = get_w4(weights, i);
p.moe[b].sgate = get_w4(weights, i);
p.moe[b].sup = get_w4(weights, i);
p.moe[b].sdown = get_w4(weights, i);
}
int j = 0;
for (int b = 0; b < 3; ++b) {
p.state[b] = reinterpret_cast<float*>(kda_state[j++].data_ptr());
p.cq[b] = reinterpret_cast<__nv_bfloat16*>(kda_state[j++].data_ptr());
p.ck[b] = reinterpret_cast<__nv_bfloat16*>(kda_state[j++].data_ptr());
p.cv[b] = reinterpret_cast<__nv_bfloat16*>(kda_state[j++].data_ptr());
}
p.hidden = reinterpret_cast<const __nv_bfloat16*>(hidden.data_ptr());
p.output = reinterpret_cast<__nv_bfloat16*>(output.data_ptr());
p.cold = reinterpret_cast<const __nv_bfloat16*>(cold.data_ptr());
p.kold = reinterpret_cast<const __nv_bfloat16*>(kold.data_ptr());
p.cnew = reinterpret_cast<__nv_bfloat16*>(cnew.data_ptr());
p.knew = reinterpret_cast<__nv_bfloat16*>(knew.data_ptr());
p.ws = reinterpret_cast<float*>(workspace.data_ptr());
p.pos = static_cast<int>(pos);
p.copy_cache = copy_cache ? 1 : 0;
int err = launch_decode(p, reinterpret_cast<void*>(at::cuda::getCurrentCUDAStream().stream()));
TORCH_CHECK(err == 0, "cooperative decode launch failed with CUDA error ", err);
}
"""
_CUDA_SOURCE = r"""
#include <cuda_bf16.h>
#include <cuda_runtime.h>
#include <cooperative_groups.h>
#include <algorithm>
namespace cg = cooperative_groups;
constexpr int D = 2304;
constexpr int H = 32;
constexpr int DK = 128;
constexpr int C = H * DK;
constexpr int M = 1024;
constexpr int SLOTS = 9;
constexpr int THREADS = 512;
// Float workspace offsets. Scores occupy the tail of the allocation.
constexpr int O_RESID = 0;
constexpr int O_XN = O_RESID + D;
constexpr int O_XSUM = O_XN + D;
constexpr int O_PROJ = O_XSUM + 64;
constexpr int O_ATTN_O = O_PROJ + 16384;
constexpr int O_ATTN_OUT = O_ATTN_O + C;
constexpr int O_BETA = O_ATTN_OUT + D;
constexpr int O_LATENT = O_BETA + 64;
constexpr int O_QABS = O_LATENT + H * 512;
constexpr int O_QROPE = O_QABS + H * 512;
constexpr int O_MOE_GU = O_QROPE + 64 * H;
constexpr int O_MOE_H = O_MOE_GU + SLOTS * 2 * M;
constexpr int O_MOE_XSUM = O_MOE_H + SLOTS * M;
constexpr int O_MOE_OUT = O_MOE_XSUM + SLOTS * 8;
constexpr int O_ROUTE = O_MOE_OUT + D;
constexpr int O_SCORES = O_ROUTE + 64;
struct W4 {
const uint8_t* q;
const __nv_bfloat16* s;
const __nv_bfloat16* z;
};
struct QE {
W4 gate;
W4 up;
W4 down;
W4 sgate;
W4 sup;
W4 sdown;
const __nv_bfloat16* router;
};
struct Params {
const __nv_bfloat16* anorm[4];
const __nv_bfloat16* mnorm[4];
W4 kproj[3][4];
W4 kout[3];
const __nv_bfloat16* beta[3];
const __nv_bfloat16* conv[3];
W4 mq;
W4 mkva;
W4 mkvb;
W4 mo;
QE moe[4];
float* state[3];
__nv_bfloat16* cq[3];
__nv_bfloat16* ck[3];
__nv_bfloat16* cv[3];
const __nv_bfloat16* hidden;
__nv_bfloat16* output;
const __nv_bfloat16* cold;
const __nv_bfloat16* kold;
__nv_bfloat16* cnew;
__nv_bfloat16* knew;
float* ws;
int pos;
int copy_cache;
};
__device__ __forceinline__ float bff(__nv_bfloat16 x) {
return __bfloat162float(x);
}
__device__ __forceinline__ float rb(float x) {
return __bfloat162float(__float2bfloat16(x));
}
__device__ __forceinline__ float silu(float x) {
return x / (1.0f + expf(-x));
}
__device__ __forceinline__ float warp_sum(float x) {
#pragma unroll
for (int d = 16; d; d >>= 1) x += __shfl_down_sync(0xffffffff, x, d);
return x;
}
__device__ __forceinline__ float warp_sum_all(float x) {
#pragma unroll
for (int d = 16; d; d >>= 1) x += __shfl_xor_sync(0xffffffff, x, d);
return x;
}
__device__ __forceinline__ float warp_max_all(float x) {
#pragma unroll
for (int d = 16; d; d >>= 1) x = fmaxf(x, __shfl_xor_sync(0xffffffff, x, d));
return x;
}
__device__ __forceinline__ void grid_zero(float* p, int n) {
for (int i = blockIdx.x * THREADS + threadIdx.x; i < n; i += gridDim.x * THREADS)
p[i] = 0.0f;
}
// The input is already bf16-rounded. The group sum lets the inner loop use
// w*x = (q*x) - z*x and apply scale/zero only once per 128 inputs.
__device__ void rmsnorm_block(const float* x, const __nv_bfloat16* w,
float* out, float* xsum, float* shared) {
const int t = threadIdx.x;
const int lane = t & 31;
const int warp = t >> 5;
float ss = 0.0f;
for (int i = t; i < D; i += THREADS) ss += x[i] * x[i];
ss = warp_sum(ss);
if (lane == 0) shared[warp] = ss;
__syncthreads();
if (t == 0) {
float v = 0.0f;
#pragma unroll
for (int j = 0; j < 16; ++j) v += shared[j];
shared[16] = rsqrtf(v * (1.0f / D) + 1.0e-6f);
}
__syncthreads();
const float inv = shared[16];
for (int i = t; i < D; i += THREADS) out[i] = rb(x[i] * inv * bff(w[i]));
__syncthreads();
for (int g = warp; g < D / 128; g += 16) {
float a = 0.0f;
#pragma unroll
for (int j = 0; j < 4; ++j) a += out[g * 128 + lane + 32 * j];
a = warp_sum(a);
if (lane == 0) xsum[g] = a;
}
__syncthreads();
}
__device__ __forceinline__ int split_count(int total_outputs, int groups) {
int target = gridDim.x * THREADS;
int ns = target / total_outputs;
return max(1, min(groups, ns));
}
__device__ __forceinline__ float dequant_chunk(
const W4& w, const float* x, const float* xsum, int n, int N,
int K, int split, int ns) {
const int ng = K / 128;
const int g0 = (ng * split) / ns;
const int g1 = (ng * (split + 1)) / ns;
float acc = 0.0f;
for (int g = g0; g < g1; ++g) {
float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f;
const int p0 = g * 64;
#pragma unroll 4
for (int j = 0; j < 64; j += 4) {
uint8_t v0 = w.q[(p0 + j) * N + n];
uint8_t v1 = w.q[(p0 + j + 1) * N + n];
uint8_t v2 = w.q[(p0 + j + 2) * N + n];
uint8_t v3 = w.q[(p0 + j + 3) * N + n];
a0 = fmaf(x[2 * (p0 + j)], (float)(v0 & 15), a0);
a0 = fmaf(x[2 * (p0 + j) + 1], (float)(v0 >> 4), a0);
a1 = fmaf(x[2 * (p0 + j + 1)], (float)(v1 & 15), a1);
a1 = fmaf(x[2 * (p0 + j + 1) + 1], (float)(v1 >> 4), a1);
a2 = fmaf(x[2 * (p0 + j + 2)], (float)(v2 & 15), a2);
a2 = fmaf(x[2 * (p0 + j + 2) + 1], (float)(v2 >> 4), a2);
a3 = fmaf(x[2 * (p0 + j + 3)], (float)(v3 & 15), a3);
a3 = fmaf(x[2 * (p0 + j + 3) + 1], (float)(v3 >> 4), a3);
}
float a = (a0 + a1) + (a2 + a3);
float scale = bff(w.s[g * N + n]);
float zero = bff(w.z[g * N + n]);
acc = fmaf(scale, a - zero * xsum[g], acc);
}
return acc;
}
__device__ void projection_kda(const Params& p, int b, int ns) {
const int total = 4 * C;
for (int task = blockIdx.x * THREADS + threadIdx.x;
task < total * ns; task += gridDim.x * THREADS) {
int n = task % total;
int split = task / total;
int which = n / C;
int col = n - which * C;
float a = dequant_chunk(p.kproj[b][which], p.ws + O_XN,
p.ws + O_XSUM, col, C, D, split, ns);
atomicAdd(p.ws + O_PROJ + n, a);
}
}
__device__ void projection_mla_q(const Params& p, int ns) {
const int total = H * 192 + 576;
for (int task = blockIdx.x * THREADS + threadIdx.x;
task < total * ns; task += gridDim.x * THREADS) {
int n = task % total;
int split = task / total;
if (n < H * 192) {
float a = dequant_chunk(p.mq, p.ws + O_XN, p.ws + O_XSUM,
n, H * 192, D, split, ns);
atomicAdd(p.ws + O_PROJ + n, a);
} else {
int col = n - H * 192;
float a = dequant_chunk(p.mkva, p.ws + O_XN, p.ws + O_XSUM,
col, 576, D, split, ns);
atomicAdd(p.ws + O_PROJ + n, a);
}
}
}
__device__ void projection_out(const W4& w, const Params& p, int ns) {
for (int task = blockIdx.x * THREADS + threadIdx.x;
task < D * ns; task += gridDim.x * THREADS) {
int n = task % D;
int split = task / D;
float a = dequant_chunk(w, p.ws + O_ATTN_O, p.ws + O_XSUM,
n, D, C, split, ns);
atomicAdd(p.ws + O_ATTN_OUT + n, a);
}
}
__device__ void moe_router_grid(const Params& p, int b, float* shared) {
if (blockIdx.x >= 64) return;
const int e = blockIdx.x;
const int lane = threadIdx.x & 31;
const int warp = threadIdx.x >> 5;
float a = 0.0f;
for (int k = threadIdx.x; k < D; k += THREADS)
a = fmaf(p.ws[O_XN + k], bff(p.moe[b].router[e * D + k]), a);
a = warp_sum(a);
if (lane == 0) shared[warp] = a;
__syncthreads();
if (threadIdx.x == 0) {
float v = 0.0f;
#pragma unroll
for (int j = 0; j < 16; ++j) v += shared[j];
p.ws[O_ROUTE + e] = rb(v);
}
}
__device__ void moe_topk_shared(const Params& p, int* ids, float* weights) {
if (threadIdx.x < 32) {
const int lane = threadIdx.x;
float v0 = p.ws[O_ROUTE + lane];
float v1 = p.ws[O_ROUTE + lane + 32];
float mx = warp_max_all(fmaxf(v0, v1));
for (int j = 0; j < 8; ++j) {
float best = fmaxf(v0, v1);
int bi = v1 > v0 ? lane + 32 : lane;
#pragma unroll
for (int d = 16; d; d >>= 1) {
float ov = __shfl_xor_sync(0xffffffff, best, d);
int oi = __shfl_xor_sync(0xffffffff, bi, d);
if (ov > best || (ov == best && oi < bi)) { best = ov; bi = oi; }
}
if (lane == 0) { ids[j] = bi; weights[j] = best; }
if (lane == (bi & 31)) {
if (bi < 32) v0 = -1.0e30f;
else v1 = -1.0e30f;
}
}
if (lane == 0) {
float wsum = 0.0f;
for (int j = 0; j < 8; ++j) {
float v = expf(weights[j] - mx);
weights[j] = v;
wsum += v;
}
for (int j = 0; j < 8; ++j) weights[j] = weights[j] / (wsum + 1.0e-9f) * 2.446f;
ids[8] = 0;
weights[8] = 1.0f;
}
}
}
__device__ void moe_gu(const Params& p, int b, int ns, const int* ids) {
const int total = SLOTS * 2 * M;
for (int task = blockIdx.x * THREADS + threadIdx.x;
task < total * ns; task += gridDim.x * THREADS) {
int n = task % total;
int split = task / total;
int slot = n / (2 * M);
int r = n - slot * 2 * M;
int which = r / M;
int col = r - which * M;
int e = ids[slot];
W4 w;
if (slot == 8) w = which ? p.moe[b].sup : p.moe[b].sgate;
else w = which ? p.moe[b].up : p.moe[b].gate;
const int64_t qoff = (int64_t)e * (D / 2) * M;
const int64_t soff = (int64_t)e * (D / 128) * M;
w.q += qoff; w.s += soff; w.z += soff;
float a = dequant_chunk(w, p.ws + O_XN, p.ws + O_XSUM,
col, M, D, split, ns);
atomicAdd(p.ws + O_MOE_GU + n, a);
}
}
__device__ void moe_down(const Params& p, int b, int ns, const int* ids, const float* weights) {
const int total = SLOTS * D;
for (int task = blockIdx.x * THREADS + threadIdx.x;
task < total * ns; task += gridDim.x * THREADS) {
int n = task % total;
int split = task / total;
int slot = n / D;
int col = n - slot * D;
int e = ids[slot];
W4 w = slot == 8 ? p.moe[b].sdown : p.moe[b].down;
w.q += (int64_t)e * (M / 2) * D;
w.s += (int64_t)e * (M / 128) * D;
w.z += (int64_t)e * (M / 128) * D;
float a = dequant_chunk(w, p.ws + O_MOE_H + slot * M,
p.ws + O_MOE_XSUM + slot * 8,
col, D, M, split, ns);
atomicAdd(p.ws + O_MOE_OUT + col, a * weights[slot]);
}
}
__global__ void __launch_bounds__(THREADS, 1) decode_kernel(Params p) {
cg::grid_group grid = cg::this_grid();
__shared__ float shared[32];
const int tid = blockIdx.x * THREADS + threadIdx.x;
const int nt = gridDim.x * THREADS;
const int gwarp = tid >> 5;
const int nwarps = nt >> 5;
const int lane = threadIdx.x & 31;
const int warp = threadIdx.x >> 5;
float* ws = p.ws;
for (int b = 0; b < 4; ++b) {
// Residual from the preceding MoE and the attention norm share a phase.
if (blockIdx.x == 0) {
if (b == 0) {
for (int i = threadIdx.x; i < D; i += THREADS)
ws[O_RESID + i] = bff(p.hidden[i]);
} else {
for (int i = threadIdx.x; i < D; i += THREADS)
ws[O_RESID + i] = rb(ws[O_RESID + i] + rb(ws[O_MOE_OUT + i]));
}
__syncthreads();
rmsnorm_block(ws + O_RESID, p.anorm[b], ws + O_XN, ws + O_XSUM, shared);
}
grid_zero(ws + O_PROJ, b == 3 ? H * 192 + 576 : 4 * C);
if (b == 3 && p.copy_cache) {
for (int i = tid; i < p.pos * 512; i += nt) p.cnew[i] = p.cold[i];
for (int i = tid; i < p.pos * 64; i += nt) p.knew[i] = p.kold[i];
}
grid.sync();
if (b < 3) projection_kda(p, b, split_count(4 * C, D / 128));
else projection_mla_q(p, split_count(H * 192 + 576, D / 128));
grid.sync();
if (b < 3) {
// Causal depthwise convolution, window update, decay, and beta.
for (int i = tid; i < 4 * C; i += nt) {
if (i < 3 * C) {
int which = i / C;
int c = i - which * C;
__nv_bfloat16* win = which == 0 ? p.cq[b] : (which == 1 ? p.ck[b] : p.cv[b]);
float v = rb(ws[O_PROJ + i]);
float w0 = bff(p.conv[b][(which * C + c) * 4]);
float w1 = bff(p.conv[b][(which * C + c) * 4 + 1]);
float w2 = bff(p.conv[b][(which * C + c) * 4 + 2]);
float w3 = bff(p.conv[b][(which * C + c) * 4 + 3]);
float x0 = bff(win[c]);
float x1 = bff(win[C + c]);
float x2 = bff(win[2 * C + c]);
float y = ((x0 * w0 + x1 * w1) + (x2 * w2 + v * w3));
win[c] = __float2bfloat16(x1);
win[C + c] = __float2bfloat16(x2);
win[2 * C + c] = __float2bfloat16(v);
ws[O_PROJ + i] = rb(silu(y));
} else {
float g = rb(ws[O_PROJ + i]);
float sp = g > 20.0f ? g : log1pf(expf(g));
ws[O_PROJ + i] = expf(-sp);
}
}
for (int h = gwarp; h < H; h += nwarps) {
float a = 0.0f;
for (int k = lane; k < D; k += 32)
a = fmaf(ws[O_XN + k], bff(p.beta[b][h * D + k]), a);
a = warp_sum_all(a);
ws[O_BETA + h] = 1.0f / (1.0f + expf(-rb(a)));
}
grid_zero(ws + O_XSUM, H);
grid_zero(ws + O_ATTN_OUT, D);
grid.sync();
// One warp owns a recurrent-state column, so prediction, delta
// update, and output reduction need no grid-wide intermediate.
for (int col = gwarp; col < C; col += nwarps) {
int h = col / DK;
int j = col - h * DK;
float pred = 0.0f;
for (int i = lane; i < DK; i += 32) {
int ix = h * DK + i;
int si = ix * DK + j;
float s = p.state[b][si] * ws[O_PROJ + 3 * C + ix];
p.state[b][si] = s;
pred = fmaf(s, ws[O_PROJ + C + ix], pred);
}
pred = warp_sum_all(pred);
float delta = ws[O_BETA + h] * (ws[O_PROJ + 2 * C + h * DK + j] - pred);
float o = 0.0f;
for (int i = lane; i < DK; i += 32) {
int ix = h * DK + i;
int si = ix * DK + j;
float s = fmaf(delta, ws[O_PROJ + C + ix], p.state[b][si]);
p.state[b][si] = s;
o = fmaf(s, ws[O_PROJ + ix] * 0.08838834765f, o);
}
o = warp_sum_all(o);
if (lane == 0) {
float ov = rb(o);
ws[O_ATTN_O + col] = ov;
atomicAdd(ws + O_XSUM + h, ov);
}
}
grid.sync();
projection_out(p.kout[b], p, split_count(D, C / 128));
grid.sync();
} else {
// RoPE and append the current latent/token to the cache.
__shared__ float cs[32];
__shared__ float sn[32];
if (threadIdx.x < 32) {
float inv = exp2f(-13.287712379549449f * (threadIdx.x / 32.0f));
sincosf(p.pos * inv, sn + threadIdx.x, cs + threadIdx.x);
}
__syncthreads();
for (int i = tid; i < H * 128; i += nt) ws[O_PROJ + i] = rb(ws[O_PROJ + i]);
for (int i = tid; i < H * 32; i += nt) {
int h = i / 32;
int r = i - h * 32;
float even = rb(ws[O_PROJ + h * 192 + 128 + 2 * r]);
float odd = rb(ws[O_PROJ + h * 192 + 128 + 2 * r + 1]);
ws[O_QROPE + (2 * r) * H + h] = rb(even * cs[r] - odd * sn[r]);
ws[O_QROPE + (2 * r + 1) * H + h] = rb(odd * cs[r] + even * sn[r]);
}
for (int i = tid; i < 512; i += nt)
p.cnew[p.pos * 512 + i] = __float2bfloat16(ws[O_PROJ + H * 192 + i]);
for (int r = tid; r < 32; r += nt) {
float even = rb(ws[O_PROJ + H * 192 + 512 + 2 * r]);
float odd = rb(ws[O_PROJ + H * 192 + 512 + 2 * r + 1]);
p.knew[p.pos * 64 + 2 * r] = __float2bfloat16(even * cs[r] - odd * sn[r]);
p.knew[p.pos * 64 + 2 * r + 1] = __float2bfloat16(odd * cs[r] + even * sn[r]);
}
grid_zero(ws + O_LATENT, H * 512);
grid_zero(ws + O_ATTN_O, C);
grid_zero(ws + O_ATTN_OUT, D);
grid_zero(ws + O_XSUM, H);
grid.sync();
// q_absorbed[c,h] = sum_d W_kv_b[c,h,d] * q_nope[h,d].
for (int ch = gwarp; ch < 512 * H; ch += nwarps) {
int c = ch / H;
int h = ch - c * H;
float scale = bff(p.mkvb.s[(c / 128) * 8192 + h * 256]);
float zero = bff(p.mkvb.z[(c / 128) * 8192 + h * 256]);
uint8_t packed = 0;
float a = 0.0f;
for (int d = lane; d < 128; d += 32) {
int n = h * 256 + d;
packed = p.mkvb.q[(c / 2) * 8192 + n];
int q = (c & 1) ? (packed >> 4) : (packed & 15);
a = fmaf((q - zero) * scale, ws[O_PROJ + h * 128 + d], a);
}
a = warp_sum_all(a);
if (lane == 0) ws[O_QABS + c * H + h] = a;
}
grid.sync();
const int L = p.pos + 1;
// A warp per token broadcasts each latent to all 32 heads.
for (int l = gwarp; l < L; l += nwarps) {
float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f;
for (int c = 0; c < 512; c += 4) {
a0 = fmaf(bff(p.cnew[l * 512 + c]), ws[O_QABS + c * H + lane], a0);
a1 = fmaf(bff(p.cnew[l * 512 + c + 1]), ws[O_QABS + (c + 1) * H + lane], a1);
a2 = fmaf(bff(p.cnew[l * 512 + c + 2]), ws[O_QABS + (c + 2) * H + lane], a2);
a3 = fmaf(bff(p.cnew[l * 512 + c + 3]), ws[O_QABS + (c + 3) * H + lane], a3);
}
for (int r = 0; r < 64; r += 4) {
a0 = fmaf(bff(p.knew[l * 64 + r]), ws[O_QROPE + r * H + lane], a0);
a1 = fmaf(bff(p.knew[l * 64 + r + 1]), ws[O_QROPE + (r + 1) * H + lane], a1);
a2 = fmaf(bff(p.knew[l * 64 + r + 2]), ws[O_QROPE + (r + 2) * H + lane], a2);
a3 = fmaf(bff(p.knew[l * 64 + r + 3]), ws[O_QROPE + (r + 3) * H + lane], a3);
}
ws[O_SCORES + lane * L + l] = ((a0 + a1) + (a2 + a3)) * 0.07216878365f;
}
grid.sync();
if (blockIdx.x < H) {
const int h = blockIdx.x;
float mx = -1.0e30f;
for (int l = threadIdx.x; l < L; l += THREADS)
mx = fmaxf(mx, ws[O_SCORES + h * L + l]);
mx = warp_max_all(mx);
if (lane == 0) shared[warp] = mx;
__syncthreads();
if (threadIdx.x == 0) {
float v = shared[0];
#pragma unroll
for (int j = 1; j < 16; ++j) v = fmaxf(v, shared[j]);
shared[16] = v;
}
__syncthreads();
mx = shared[16];
float sum = 0.0f;
for (int l = threadIdx.x; l < L; l += THREADS) {
float v = expf(ws[O_SCORES + h * L + l] - mx);
ws[O_SCORES + h * L + l] = v;
sum += v;
}
sum = warp_sum_all(sum);
if (lane == 0) shared[8 + warp] = sum;
__syncthreads();
if (threadIdx.x == 0) {
float v = 0.0f;
#pragma unroll
for (int j = 0; j < 16; ++j) v += shared[8 + j];
shared[17] = 1.0f / v;
}
__syncthreads();
for (int l = threadIdx.x; l < L; l += THREADS)
ws[O_SCORES + h * L + l] *= shared[17];
}
grid.sync();
int lns = max(1, min(L, min(32768, nt / (H * 512))));
for (int task = tid; task < H * 512 * lns; task += nt) {
int n = task % (H * 512);
int split = task / (H * 512);
int h = n / 512;
int c = n - h * 512;
int l0 = (L * split) / lns;
int l1 = (L * (split + 1)) / lns;
float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f;
int l = l0;
for (; l + 3 < l1; l += 4) {
a0 = fmaf(ws[O_SCORES + h * L + l], bff(p.cnew[l * 512 + c]), a0);
a1 = fmaf(ws[O_SCORES + h * L + l + 1], bff(p.cnew[(l + 1) * 512 + c]), a1);
a2 = fmaf(ws[O_SCORES + h * L + l + 2], bff(p.cnew[(l + 2) * 512 + c]), a2);
a3 = fmaf(ws[O_SCORES + h * L + l + 3], bff(p.cnew[(l + 3) * 512 + c]), a3);
}
for (; l < l1; ++l)
a0 = fmaf(ws[O_SCORES + h * L + l], bff(p.cnew[l * 512 + c]), a0);
atomicAdd(ws + O_LATENT + n, (a0 + a1) + (a2 + a3));
}
grid.sync();
// Reconstruct values from the reduced latent, still streaming W4.
int vns = split_count(C, 4);
for (int task = tid; task < C * vns; task += nt) {
int n = task % C;
int split = task / C;
int h = n / 128;
int d = n - h * 128;
int col = h * 256 + 128 + d;
int g0 = (4 * split) / vns;
int g1 = (4 * (split + 1)) / vns;
float a = 0.0f;
for (int g = g0; g < g1; ++g) {
float scale = bff(p.mkvb.s[g * 8192 + col]);
float zero = bff(p.mkvb.z[g * 8192 + col]);
for (int j = 0; j < 64; ++j) {
int kp = g * 64 + j;
uint8_t v = p.mkvb.q[kp * 8192 + col];
a = fmaf(ws[O_LATENT + h * 512 + 2 * kp], ((v & 15) - zero) * scale, a);
a = fmaf(ws[O_LATENT + h * 512 + 2 * kp + 1], ((v >> 4) - zero) * scale, a);
}
}
atomicAdd(ws + O_ATTN_O + n, a);
}
grid.sync();
for (int i = tid; i < C; i += nt) {
float v = rb(ws[O_ATTN_O + i]);
ws[O_ATTN_O + i] = v;
atomicAdd(ws + O_XSUM + i / 128, v);
}
grid.sync();
projection_out(p.mo, p, split_count(D, C / 128));
grid.sync();
}
if (blockIdx.x == 0) {
for (int i = threadIdx.x; i < D; i += THREADS)
ws[O_RESID + i] = rb(ws[O_RESID + i] + rb(ws[O_ATTN_OUT + i]));
__syncthreads();
rmsnorm_block(ws + O_RESID, p.mnorm[b], ws + O_XN, ws + O_XSUM, shared);
}
__shared__ int top_ids[9];
__shared__ float top_weights[9];
grid_zero(ws + O_MOE_GU, SLOTS * 2 * M);
grid_zero(ws + O_MOE_XSUM, SLOTS * 8);
grid.sync();
moe_router_grid(p, b, shared);
grid.sync();
moe_topk_shared(p, top_ids, top_weights);
__syncthreads();
moe_gu(p, b, split_count(SLOTS * 2 * M, D / 128), top_ids);
grid.sync();
for (int i = tid; i < SLOTS * M; i += nt) {
int slot = i / M;
int m = i - slot * M;
float gate = ws[O_MOE_GU + slot * 2 * M + m];
float up = ws[O_MOE_GU + slot * 2 * M + M + m];
float v = silu(gate) * up;
ws[O_MOE_H + i] = v;
atomicAdd(ws + O_MOE_XSUM + slot * 8 + m / 128, v);
}
grid_zero(ws + O_MOE_OUT, D);
grid.sync();
moe_down(p, b, split_count(SLOTS * D, M / 128), top_ids, top_weights);
grid.sync();
}
for (int i = tid; i < D; i += nt)
p.output[i] = __float2bfloat16(ws[O_RESID + i] + rb(ws[O_MOE_OUT + i]));
}
extern "C" int launch_decode(Params p, void* stream) {
static int blocks = []() {
int dev = 0;
cudaGetDevice(&dev);
cudaDeviceProp prop{};
cudaGetDeviceProperties(&prop, dev);
int active = 0;
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&active, decode_kernel, THREADS, 0);
if (active < 1) return 0;
return prop.multiProcessorCount;
}();
if (blocks == 0) return static_cast<int>(cudaErrorInvalidConfiguration);
void* args[] = {&p};
return static_cast<int>(cudaLaunchCooperativeKernel(
reinterpret_cast<void*>(decode_kernel), dim3(blocks), dim3(THREADS),
args, 0, reinterpret_cast<cudaStream_t>(stream)));
}
"""
os.environ.setdefault("TORCH_CUDA_ARCH_LIST", "12.0")
_ext = load_inline(
name="kimi_w4a16_megakernel",
cpp_sources=_CPP_SOURCE,
cuda_sources=_CUDA_SOURCE,
functions=["decode"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
no_implicit_headers=True,
verbose=False,
)
class QuantLinear(nn.Module):
def __init__(self, in_f: int, out_f: int, group: int = 128):
super().__init__()
self.in_f, self.out_f, self.group = in_f, out_f, group
self.register_buffer("w_q", torch.empty(in_f // 2, out_f, dtype=torch.uint8))
self.register_buffer("scales", torch.empty(in_f // group, out_f, dtype=torch.bfloat16))
self.register_buffer("zeros", torch.empty(in_f // group, out_f, dtype=torch.bfloat16))
class QuantExperts(nn.Module):
def __init__(self, n: int, in_f: int, out_f: int, group: int = 128):
super().__init__()
self.n, self.in_f, self.out_f, self.group = n, in_f, out_f, group
self.register_buffer("w_q", torch.empty(n, in_f // 2, out_f, dtype=torch.uint8))
self.register_buffer("scales", torch.empty(n, in_f // group, out_f, dtype=torch.bfloat16))
self.register_buffer("zeros", torch.empty(n, in_f // group, out_f, dtype=torch.bfloat16))
class KDA(nn.Module):
def __init__(self, cfg):
super().__init__()
d, h, dk = cfg.hidden, cfg.kda_heads, cfg.kda_head_dim
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)
class MLA(nn.Module):
def __init__(self, cfg):
super().__init__()
d, h = cfg.hidden, cfg.mla_heads
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)
class MoE(nn.Module):
def __init__(self, cfg):
super().__init__()
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)
class Block(nn.Module):
def __init__(self, cfg, kind):
super().__init__()
self.kind = kind
self.attn_norm = nn.Parameter(torch.empty(cfg.hidden, dtype=cfg.dtype))
self.moe_norm = nn.Parameter(torch.empty(cfg.hidden, dtype=cfg.dtype))
self.attn = KDA(cfg) if kind == "K" else MLA(cfg)
self.moe = MoE(cfg)
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)
self._weights = None
self._workspace = None
def _flatten_weights(self):
flat = []
for block in self.blocks:
flat.extend((block.attn_norm, block.moe_norm))
a = block.attn
if block.kind == "K":
for proj in (a.q_proj, a.k_proj, a.v_proj, a.g_proj):
flat.extend((proj.w_q, proj.scales, proj.zeros))
flat.extend((a.beta_proj.weight, a.conv_w))
flat.extend((a.o_proj.w_q, a.o_proj.scales, a.o_proj.zeros))
else:
for proj in (a.q_proj, a.kv_a, a.kv_b, a.o_proj):
flat.extend((proj.w_q, proj.scales, proj.zeros))
m = block.moe
flat.append(m.router.weight)
for expert in (m.gate, m.up, m.down, m.s_gate, m.s_up, m.s_down):
flat.extend((expert.w_q, expert.scales, expert.zeros))
self._weights = flat
def step(self, hidden, state):
if self._weights is None:
self._flatten_weights()
old_c = state[3]["c_kv"]
old_k = state[3]["k_rope"]
pos = old_c.shape[0]
score_tokens = max(32768, pos + 64)
ws_size = 92424 + 32 * score_tokens
if self._workspace is None or self._workspace.numel() < ws_size:
self._workspace = torch.empty(ws_size, dtype=torch.float32, device=hidden.device)
capacity = old_c.untyped_storage().nbytes() // (512 * old_c.element_size())
if capacity < pos + 1:
capacity = pos + 64
cbase = torch.empty(capacity, 512, dtype=torch.bfloat16, device=hidden.device)
kbase = torch.empty(capacity, 64, dtype=torch.bfloat16, device=hidden.device)
new_c = cbase[:pos + 1]
new_k = kbase[:pos + 1]
copy_cache = True
else:
new_c = old_c.as_strided((pos + 1, 512), (512, 1))
new_k = old_k.as_strided((pos + 1, 64), (64, 1))
copy_cache = False
state[3]["c_kv"] = new_c
state[3]["k_rope"] = new_k
output = torch.empty_like(hidden)
kda_state = []
for b in range(3):
kda_state.extend((state[b]["S"], state[b]["cq"], state[b]["ck"], state[b]["cv"]))
_ext.decode(self._weights, hidden, output, kda_state, old_c, old_k,
new_c, new_k, self._workspace, pos, copy_cache)
return output, state
20261116_012038_kimi_kimi-code_k3.1-pro_02_kimi_linear_decode