KernelBench cuda · RTX PRO 6000
MegaQwen Decode Qwen4 35B-A3B
3.23%geomean peak fraction across shapes
manually audited: clean
Qwen4 35B-A3B (FP8 local vLLM, grok harness, high effort) wrote a 1,003-line hand-written CUDA MegaQwen decode engine scoring 0.0323 geomean (2,602.9 / 2,583.4 / 1,776.4 / 572.0 tok/s at 2k / 8k / 32k / 131k). It launches per-layer raw CUDA kernels with split-KV causal GQA flash attention over the growing KV cache.
harnessgrokthinkinghighagent session8h 36mtotal wall8h 55mcheck30sbenchmark17moutput tokens—regimethroughput
Per-shape vs governing ceilingeach shape graded against whichever binds — bf16 compute or HBM bandwidth
No per-shape benchmark data archived for this run.
Kernel source (redacted)
"""MegaQwen Qwen3-0.6B-geometry decode in hand-written CUDA (SM120 / Blackwell).
One block = RMSNorm -> QKV -> Q/K RMSNorm -> RoPE -> causal GQA attention over
KV cache -> O -> residual -> RMSNorm -> SwiGLU MLP -> residual.
The decode path is a set of small CUDA kernels launched per layer, with
split-KV flash attention for the causal attention over the growing KV cache.
"""
from __future__ import annotations
import math
from pathlib import Path
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
HIDDEN = 1024
INTERMEDIATE = 3072
NUM_Q = 16
NUM_KV = 8
HEAD_DIM = 128
NUM_LAYERS = 4
EPS = 1e-6
_CUDA_SRC = r"""
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <cuda_bf16.h>
#include <ATen/cuda/CUDAContext.h>
#define HD 128
#define HID 1024
#define INTER 3072
#define NQ 16
#define NKV 8
#define REP 2
#define EPSF 1e-6f
using bf16 = __nv_bfloat16;
__device__ __forceinline__ float bf2f(bf16 x) { return __bfloat162float(x); }
__device__ __forceinline__ bf16 f2bf(float x) { return __float2bfloat16(x); }
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
return v;
}
// device-side block-wide reduce over 8 warps (blockDim = 256)
__device__ __forceinline__ float block_sum_256(float v, float* red) {
int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
v = warp_sum(v);
if (lane == 0) red[warp] = v;
__syncthreads();
float tot = 0.f;
#pragma unroll
for (int i = 0; i < 8; i++) tot += red[i];
return tot;
}
__device__ __forceinline__ float row1_sumsq(const bf16* __restrict__ x, float* red) {
float ss = 0.f;
for (int i = threadIdx.x; i < HID; i += 256) {
float v = bf2f(x[i]);
ss += v * v;
}
return block_sum_256(ss, red);
}
__device__ __forceinline__ float rowf32_sumsq(const float* __restrict__ x, float* red) {
float ss = 0.f;
for (int i = threadIdx.x; i < HID; i += 256) {
float v = x[i];
ss += v * v;
}
return block_sum_256(ss, red);
}
// ---------------------------------------------------------------------------
// input mix: h = bf16(0.5*r + 0.5*h) (elementwise, in place on h)
// ---------------------------------------------------------------------------
__global__ void mix_kernel(const bf16* __restrict__ r, bf16* __restrict__ h, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) h[i] = f2bf(0.5f * bf2f(r[i]) + 0.5f * bf2f(h[i]));
}
// ---------------------------------------------------------------------------
// RMSNorm: y[i] = x[i] * rsqrt(mean(x^2)+eps) * w[i] (x,w bf16 in; y fp32 out)
// one block per row (row = 1024). blockDim = 256.
// ---------------------------------------------------------------------------
__global__ void rmsnorm_kernel(const bf16* __restrict__ x,
const bf16* __restrict__ w,
float* __restrict__ y, int n_rows) {
int row = blockIdx.x;
if (row >= n_rows) return;
const bf16* xr = x + (size_t)row * HID;
float* yr = y + (size_t)row * HID;
float ss = 0.f;
for (int i = threadIdx.x; i < HID; i += blockDim.x) {
float v = bf2f(xr[i]);
ss += v * v;
}
ss = warp_sum(ss);
__shared__ float red[8];
int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
if (lane == 0) red[warp] = ss;
__syncthreads();
float tot = 0.f;
for (int i = 0; i < 8; i++) tot += red[i];
float ri = rsqrtf(tot / (float)HID + EPSF);
for (int i = threadIdx.x; i < HID; i += blockDim.x)
yr[i] = bf2f(xr[i]) * ri * bf2f(w[i]);
}
// ---------------------------------------------------------------------------
// RMSNorm fp32-input variant: y[i] = x[i] * rsqrt(mean(x^2)+eps) * w[i]
// (x fp32 in, w bf16, y fp32 out). Used for the post-attention norm where the
// residual stream is kept in fp32 (matching the reference).
// ---------------------------------------------------------------------------
__global__ void rmsnorm_f32_kernel(const float* __restrict__ x,
const bf16* __restrict__ w,
float* __restrict__ y, int n_rows) {
int row = blockIdx.x;
if (row >= n_rows) return;
const float* xr = x + (size_t)row * HID;
float* yr = y + (size_t)row * HID;
float ss = 0.f;
for (int i = threadIdx.x; i < HID; i += blockDim.x) {
float v = xr[i];
ss += v * v;
}
ss = warp_sum(ss);
__shared__ float red[8];
int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
if (lane == 0) red[warp] = ss;
__syncthreads();
float tot = 0.f;
for (int i = 0; i < 8; i++) tot += red[i];
float ri = rsqrtf(tot / (float)HID + EPSF);
for (int i = threadIdx.x; i < HID; i += blockDim.x)
yr[i] = xr[i] * ri * bf2f(w[i]);
}
// ---------------------------------------------------------------------------
// GEMV: y[m] = sum_k W[m,k] * x[k] (W row-major [M,K], x[K], y[M] fp32)
// one warp per output row m. blockDim = 256 (8 warps). grid = ceil(M/8).
// ---------------------------------------------------------------------------
__global__ void gemv_kernel(const bf16* __restrict__ W,
const float* __restrict__ x,
float* __restrict__ y, int M, int K) {
int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
int m = blockIdx.x * 8 + warp;
if (m >= M) return;
const bf16* wrow = W + (size_t)m * K;
float acc = 0.f;
for (int k = lane; k < K; k += 32) acc += bf2f(wrow[k]) * x[k];
acc = warp_sum(acc);
if (lane == 0) y[m] = acc;
}
// ---------------------------------------------------------------------------
// QK norm + RoPE for q and k, write k/v into cache.
// q_in [2048] fp32 (16 heads x128), k_in [1024] (8x128), v_in [1024] (8x128)
// q_norm/k_norm [128] bf16. Writes: q_out[2048] fp32 (normed+roped),
// k_cache[kvh,pos,:], v_cache[kvh,pos,:].
// One block, 512 threads = 16 warps. warp w: q head w (w<16). k/v handled by
// first 8 warps after.
// ---------------------------------------------------------------------------
__global__ void qknorm_rope_kernel(const float* __restrict__ q_in,
const float* __restrict__ k_in,
const float* __restrict__ v_in,
const bf16* __restrict__ q_norm,
const bf16* __restrict__ k_norm,
bf16* __restrict__ k_cache,
bf16* __restrict__ v_cache,
float* __restrict__ q_out,
int pos, int max_seq) {
int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; // 16 warps
__shared__ float rc[64], rs[64];
if (warp == 0) {
for (int j = lane; j < 64; j += 32) {
float inv = 1.0f / powf(10000.0f, (float)j / 64.0f);
float f = (float)pos * inv;
rc[j] = cosf(f);
rs[j] = sinf(f);
}
}
__syncthreads();
// ---- q heads (16) ----
{
int hq = warp; // 0..15
const float* qrow = q_in + hq * 128;
float x[4];
float ss = 0.f;
#pragma unroll
for (int j = 0; j < 4; j++) { x[j] = qrow[lane * 4 + j]; ss += x[j] * x[j]; }
ss = warp_sum(ss);
float ri = rsqrtf(ss / 128.0f + EPSF);
#pragma unroll
for (int j = 0; j < 4; j++) x[j] *= ri * bf2f(q_norm[lane * 4 + j]);
// rope pairs (e, e+64), e in [0,64)
__shared__ float qb[16][128];
#pragma unroll
for (int j = 0; j < 4; j++) qb[warp][lane * 4 + j] = x[j];
__syncwarp();
#pragma unroll
for (int j = 0; j < 4; j++) {
int e = lane * 4 + j;
if (e < 64) {
float a = qb[warp][e], b = qb[warp][e + 64];
qb[warp][e] = a * rc[e] - b * rs[e];
qb[warp][e + 64] = a * rs[e] + b * rc[e];
}
}
__syncwarp();
#pragma unroll
for (int j = 0; j < 4; j++) q_out[hq * 128 + lane * 4 + j] = qb[warp][lane * 4 + j];
}
// ---- k heads (8) ----
if (warp < 8) {
int hk = warp;
const float* krow = k_in + hk * 128;
float x[4];
float ss = 0.f;
#pragma unroll
for (int j = 0; j < 4; j++) { x[j] = krow[lane * 4 + j]; ss += x[j] * x[j]; }
ss = warp_sum(ss);
float ri = rsqrtf(ss / 128.0f + EPSF);
#pragma unroll
for (int j = 0; j < 4; j++) x[j] *= ri * bf2f(k_norm[lane * 4 + j]);
__shared__ float kb[8][128];
#pragma unroll
for (int j = 0; j < 4; j++) kb[warp][lane * 4 + j] = x[j];
__syncwarp();
#pragma unroll
for (int j = 0; j < 4; j++) {
int e = lane * 4 + j;
if (e < 64) {
float a = kb[warp][e], b = kb[warp][e + 64];
kb[warp][e] = a * rc[e] - b * rs[e];
kb[warp][e + 64] = a * rs[e] + b * rc[e];
}
}
__syncwarp();
#pragma unroll
for (int j = 0; j < 4; j++) {
int e = lane * 4 + j;
k_cache[((size_t)hk * max_seq + pos) * HD + e] = f2bf(kb[warp][e]);
}
}
// ---- v heads (8): straight copy to cache ----
if (warp < 8) {
int hk = warp;
#pragma unroll
for (int j = 0; j < 4; j++) {
int e = lane * 4 + j;
v_cache[((size_t)hk * max_seq + pos) * HD + e] = f2bf(v_in[hk * 128 + e]);
}
}
}
// ---------------------------------------------------------------------------
// causal GQA attention (serial reference path, one block). Kept for prefill /
// tiny contexts. q[2048] fp32 (16 heads), k/v cache [8,max_seq,128].
// out[2048] fp32. one block, 512 threads = 16 warps; warp per q head.
// ---------------------------------------------------------------------------
__global__ void attn_kernel(const float* __restrict__ q_in,
const bf16* __restrict__ k_cache,
const bf16* __restrict__ v_cache,
float* __restrict__ out, int pos, int max_seq) {
int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; // 16 warps
int hq = warp;
int kvh = hq / REP;
const bf16* kc = k_cache + (size_t)kvh * max_seq * HD;
const bf16* vc = v_cache + (size_t)kvh * max_seq * HD;
float q[4];
#pragma unroll
for (int j = 0; j < 4; j++) q[j] = q_in[hq * 128 + lane * 4 + j];
float m = -1e30f, l = 0.f;
float acc[4] = {0.f, 0.f, 0.f, 0.f};
for (int p = 0; p <= pos; p++) {
float kv[4];
#pragma unroll
for (int j = 0; j < 4; j++) kv[j] = bf2f(kc[(size_t)p * HD + lane * 4 + j]);
float dot = 0.f;
#pragma unroll
for (int j = 0; j < 4; j++) dot += q[j] * kv[j];
dot = warp_sum(dot) * (1.0f / sqrtf(128.0f));
float m_new = fmaxf(m, dot);
float alpha = expf(m - m_new);
float pe = expf(dot - m_new);
l = l * alpha + pe;
#pragma unroll
for (int j = 0; j < 4; j++) acc[j] *= alpha;
#pragma unroll
for (int j = 0; j < 4; j++)
acc[j] += pe * bf2f(vc[(size_t)p * HD + lane * 4 + j]);
m = m_new;
}
float inv = 1.0f / l;
#pragma unroll
for (int j = 0; j < 4; j++) out[hq * 128 + lane * 4 + j] = acc[j] * inv;
}
// ---------------------------------------------------------------------------
// Split-KV flash attention (flash-decoding). Parallel over KV chunks.
// grid = (n_chunks, 16 q-heads); block = 128 threads (4 warps).
// Each block reduces one chunk of the KV cache for one q head, producing a
// partial (m, l, acc[128]). partials layout:
// pm/hq/chunk (max), pl/hq/chunk (sum), pacc/hq/chunk*128 (fp32 acc).
// q_in[2048] fp32; k/v cache [8,max_seq,128].
// ---------------------------------------------------------------------------
#define CHUNK 512
__global__ void attn_split_kernel(const float* __restrict__ q_in,
const bf16* __restrict__ k_cache,
const bf16* __restrict__ v_cache,
float* __restrict__ pm,
float* __restrict__ pl,
float* __restrict__ pacc,
int pos, int max_seq, int n_chunks) {
int chunk = blockIdx.x;
int hq = blockIdx.y;
int kvh = hq / REP;
int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; // 4 warps
const bf16* kc = k_cache + (size_t)kvh * max_seq * HD;
const bf16* vc = v_cache + (size_t)kvh * max_seq * HD;
int start = chunk * CHUNK;
int end = min(start + CHUNK, pos + 1);
if (start >= pos + 1) {
if (threadIdx.x == 0) { pm[hq * n_chunks + chunk] = -1e30f; pl[hq * n_chunks + chunk] = 0.f; }
return;
}
float q[4];
#pragma unroll
for (int j = 0; j < 4; j++) q[j] = q_in[hq * 128 + lane * 4 + j];
float m = -1e30f, l = 0.f;
float acc[4] = {0.f, 0.f, 0.f, 0.f};
// 4 warps split the chunk: warp w handles positions start+w, start+w+4, ...
// Each warp does its own online softmax over its subsequence, then we
// merge across the 4 warps at the end via shared memory.
float wm = -1e30f, wl = 0.f;
float wacc[4] = {0.f, 0.f, 0.f, 0.f};
for (int p = start + warp; p < end; p += 4) {
float kv[4];
#pragma unroll
for (int j = 0; j < 4; j++) kv[j] = bf2f(kc[(size_t)p * HD + lane * 4 + j]);
float dot = 0.f;
#pragma unroll
for (int j = 0; j < 4; j++) dot += q[j] * kv[j];
dot = warp_sum(dot) * (1.0f / sqrtf(128.0f));
float m_new = fmaxf(wm, dot);
float alpha = expf(wm - m_new);
float pe = expf(dot - m_new);
wl = wl * alpha + pe;
#pragma unroll
for (int j = 0; j < 4; j++) wacc[j] *= alpha;
#pragma unroll
for (int j = 0; j < 4; j++)
wacc[j] += pe * bf2f(vc[(size_t)p * HD + lane * 4 + j]);
wm = m_new;
}
// merge 4 warps: use shared memory [4 warps][128 + 2]
__shared__ float sm[4][130];
#pragma unroll
for (int j = 0; j < 4; j++) { sm[warp][lane * 4 + j] = wacc[j]; }
if (lane == 0) { sm[warp][128] = wm; sm[warp][129] = wl; }
__syncthreads();
// warp 0 merges
if (warp == 0) {
float mm = -1e30f, ll = 0.f;
float a2[4] = {0.f, 0.f, 0.f, 0.f};
for (int w = 0; w < 4; w++) {
float wmw = sm[w][128], wlw = sm[w][129];
float m_new = fmaxf(mm, wmw);
float alpha = expf(mm - m_new);
float beta = expf(wmw - m_new);
ll = ll * alpha + wlw * beta;
#pragma unroll
for (int j = 0; j < 4; j++)
a2[j] = a2[j] * alpha + sm[w][lane * 4 + j] * beta;
mm = m_new;
}
float inv = 1.0f / ll;
(void)inv;
#pragma unroll
for (int j = 0; j < 4; j++)
pacc[((size_t)hq * n_chunks + chunk) * 128 + lane * 4 + j] = a2[j];
if (lane == 0) {
pm[hq * n_chunks + chunk] = mm;
pl[hq * n_chunks + chunk] = ll;
}
}
}
// ---------------------------------------------------------------------------
// combine partial attention outputs across chunks. grid = 16 heads; block =
// 128 threads. out[2048] fp32.
// ---------------------------------------------------------------------------
__global__ void attn_combine_kernel(const float* __restrict__ pm,
const float* __restrict__ pl,
const float* __restrict__ pacc,
float* __restrict__ out,
int n_chunks) {
int hq = blockIdx.x;
int lane = threadIdx.x & 31;
float mm = -1e30f;
for (int c = 0; c < n_chunks; c++) mm = fmaxf(mm, pm[hq * n_chunks + c]);
float ll = 0.f;
for (int c = 0; c < n_chunks; c++)
ll += pl[hq * n_chunks + c] * expf(pm[hq * n_chunks + c] - mm);
float inv = 1.0f / ll;
#pragma unroll
for (int j = 0; j < 4; j++) {
float a = 0.f;
for (int c = 0; c < n_chunks; c++)
a += pacc[((size_t)hq * n_chunks + c) * 128 + lane * 4 + j]
* expf(pm[hq * n_chunks + c] - mm);
out[hq * 128 + lane * 4 + j] = a * inv;
}
}
// ---------------------------------------------------------------------------
// residual add fp32: y = a(fp32) + b(fp32) -> fp32 out (in-place safe)
// ---------------------------------------------------------------------------
__global__ void resid_add_f32_kernel(const float* __restrict__ a,
const float* __restrict__ b,
float* __restrict__ y, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) y[i] = a[i] + b[i];
}
// ---------------------------------------------------------------------------
// residual add: y = bf16(a + b) elementwise
// ---------------------------------------------------------------------------
__global__ void add_residual_kernel(const bf16* __restrict__ a,
const float* __restrict__ b,
bf16* __restrict__ y, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) y[i] = f2bf(bf2f(a[i]) + b[i]);
}
// ---------------------------------------------------------------------------
// cast fp32 -> bf16 elementwise
// ---------------------------------------------------------------------------
__global__ void cast_f32_bf16_kernel(const float* __restrict__ x,
bf16* __restrict__ y, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) y[i] = f2bf(x[i]);
}
// ---------------------------------------------------------------------------
// SwiGLU: h[i] = silu(gate[i]) * up[i] (fp32 in/out, n=3072)
// ---------------------------------------------------------------------------
__global__ void swiglu_kernel(const float* __restrict__ gate,
const float* __restrict__ up,
float* __restrict__ h, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
float g = gate[i];
h[i] = (g / (1.0f + expf(-g))) * up[i];
}
}
// ---------------------------------------------------------------------------
// Split-KV flash attention over the KV cache (flash-decoding partials).
// q_in is already normed+roped (by qknorm_rope). grid = (n_chunks, 8
// kv-heads); blockDim = 256 (8 warps). Each block reduces one KV chunk for
// BOTH q heads that share a kv head into partials (pm, pl, pacc); a separate
// attn_combine kernel merges them (kernel-boundary ordering makes this
// race-free). Reading each KV row once for both q heads halves KV traffic.
// q_in[2048] fp32, k/v cache [8,max_seq,128] bf16.
// ---------------------------------------------------------------------------
__global__ void attn_fused_kernel(const float* __restrict__ q_in,
const bf16* __restrict__ k_cache,
const bf16* __restrict__ v_cache,
float* __restrict__ pm,
float* __restrict__ pl,
float* __restrict__ pacc,
int pos, int max_seq, int n_chunks) {
int chunk = blockIdx.x;
int kvh = blockIdx.y;
int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; // 8 warps
// q is already normed+roped by qknorm_rope; each warp's lane l uses
// q[l*4 .. l*4+3] for its head.
float q0[4], q1[4];
#pragma unroll
for (int j = 0; j < 4; j++) {
q0[j] = q_in[(kvh * REP + 0) * HD + lane * 4 + j];
q1[j] = q_in[(kvh * REP + 1) * HD + lane * 4 + j];
}
const bf16* kc = k_cache + (size_t)kvh * max_seq * HD;
const bf16* vc = v_cache + (size_t)kvh * max_seq * HD;
int start = chunk * CHUNK;
int end = min(start + CHUNK, pos + 1);
if (start >= pos + 1) {
if (threadIdx.x == 0) {
pm[(kvh * REP + 0) * n_chunks + chunk] = -1e30f;
pl[(kvh * REP + 0) * n_chunks + chunk] = 0.f;
pm[(kvh * REP + 1) * n_chunks + chunk] = -1e30f;
pl[(kvh * REP + 1) * n_chunks + chunk] = 0.f;
}
return;
}
float wm0 = -1e30f, wl0 = 0.f;
float wm1 = -1e30f, wl1 = 0.f;
float wacc0[4] = {0.f, 0.f, 0.f, 0.f};
float wacc1[4] = {0.f, 0.f, 0.f, 0.f};
for (int p = start + warp; p < end; p += 8) {
float kv[4];
#pragma unroll
for (int j = 0; j < 4; j++) kv[j] = bf2f(kc[(size_t)p * HD + lane * 4 + j]);
float dot0 = 0.f, dot1 = 0.f;
#pragma unroll
for (int j = 0; j < 4; j++) {
dot0 += q0[j] * kv[j];
dot1 += q1[j] * kv[j];
}
dot0 = warp_sum(dot0) * (1.0f / sqrtf(128.0f));
dot1 = warp_sum(dot1) * (1.0f / sqrtf(128.0f));
float m_new0 = fmaxf(wm0, dot0);
float alpha0 = expf(wm0 - m_new0);
float pe0 = expf(dot0 - m_new0);
wl0 = wl0 * alpha0 + pe0;
#pragma unroll
for (int j = 0; j < 4; j++) wacc0[j] *= alpha0;
float m_new1 = fmaxf(wm1, dot1);
float alpha1 = expf(wm1 - m_new1);
float pe1 = expf(dot1 - m_new1);
wl1 = wl1 * alpha1 + pe1;
#pragma unroll
for (int j = 0; j < 4; j++) wacc1[j] *= alpha1;
float vf[4];
#pragma unroll
for (int j = 0; j < 4; j++) vf[j] = bf2f(vc[(size_t)p * HD + lane * 4 + j]);
#pragma unroll
for (int j = 0; j < 4; j++) {
wacc0[j] += pe0 * vf[j];
wacc1[j] += pe1 * vf[j];
}
wm0 = m_new0;
wm1 = m_new1;
}
__shared__ float sm[2][8][130];
#pragma unroll
for (int j = 0; j < 4; j++) {
sm[0][warp][lane * 4 + j] = wacc0[j];
sm[1][warp][lane * 4 + j] = wacc1[j];
}
if (lane == 0) {
sm[0][warp][128] = wm0;
sm[0][warp][129] = wl0;
sm[1][warp][128] = wm1;
sm[1][warp][129] = wl1;
}
__syncthreads();
// threads 0..127 merge head kvh*REP+0; threads 128..255 merge head
// kvh*REP+1. Each thread owns one output dim d = (t & 127).
int t = threadIdx.x;
int hh = t >> 7; // 0 or 1: which q head
int d = t & 127; // dim within the head
int hq = kvh * REP + hh;
float mm = -1e30f, ll = 0.f, a2 = 0.f;
#pragma unroll
for (int w = 0; w < 8; w++) {
float wmw = sm[hh][w][128], wlw = sm[hh][w][129];
float m_new = fmaxf(mm, wmw);
float alpha = expf(mm - m_new);
float beta = expf(wmw - m_new);
ll = ll * alpha + wlw * beta;
a2 = a2 * alpha + sm[hh][w][d] * beta;
mm = m_new;
}
pacc[((size_t)hq * n_chunks + chunk) * 128 + d] = a2;
if (d == 0) {
pm[hq * n_chunks + chunk] = mm;
pl[hq * n_chunks + chunk] = ll;
}
}
// ---------------------------------------------------------------------------
// Batched QKV GEMV: q_proj[2048,1024], k_proj[1024,1024], v_proj[1024,1024]
// -> q_raw[2048], k_raw[1024], v_raw[1024] (fp32) in one launch.
// blockDim = 128 (4 warps). grid covers 4096 output rows (warp per row).
// ---------------------------------------------------------------------------
__global__ void qkv_gemv_kernel(const bf16* __restrict__ q_proj,
const bf16* __restrict__ k_proj,
const bf16* __restrict__ v_proj,
const float* __restrict__ x,
float* __restrict__ q_raw,
float* __restrict__ k_raw,
float* __restrict__ v_raw) {
int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; // 4 warps
int m0 = blockIdx.x * 4 + warp;
const bf16* wrow;
float* yrow;
if (m0 < 2048) { wrow = q_proj + (size_t)m0 * HID; yrow = q_raw + m0; }
else if (m0 < 3072) { wrow = k_proj + (size_t)(m0 - 2048) * HID; yrow = k_raw + (m0 - 2048); }
else if (m0 < 4096) { wrow = v_proj + (size_t)(m0 - 3072) * HID; yrow = v_raw + (m0 - 3072); }
else return;
float acc = 0.f;
for (int k = lane; k < HID; k += 32) acc += bf2f(wrow[k]) * x[k];
acc = warp_sum(acc);
if (lane == 0) yrow[0] = acc;
}
// ---------------------------------------------------------------------------
// Batched gate+up GEMV: gate_proj[3072,1024], up_proj[3072,1024] ->
// gate[3072], up[3072] (fp32) in one launch. blockDim = 128 (4 warps).
// grid covers 6144 output rows (warp per row).
// ---------------------------------------------------------------------------
__global__ void gu_gemv_kernel(const bf16* __restrict__ gate_proj,
const bf16* __restrict__ up_proj,
const float* __restrict__ x,
float* __restrict__ gate,
float* __restrict__ up) {
int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; // 4 warps
int m0 = blockIdx.x * 4 + warp;
const bf16* wrow;
float* yrow;
if (m0 < 3072) { wrow = gate_proj + (size_t)m0 * HID; yrow = gate + m0; }
else if (m0 < 6144) { wrow = up_proj + (size_t)(m0 - 3072) * HID; yrow = up + (m0 - 3072); }
else return;
float acc = 0.f;
for (int k = lane; k < HID; k += 32) acc += bf2f(wrow[k]) * x[k];
acc = warp_sum(acc);
if (lane == 0) yrow[0] = acc;
}
// ============================== launchers =================================
void launch_mix(torch::Tensor r, torch::Tensor h) {
int n = h.numel();
mix_kernel<<<(n + 255) / 256, 256, 0, at::cuda::getCurrentCUDAStream()>>>(
reinterpret_cast<const bf16*>(r.data_ptr()),
reinterpret_cast<bf16*>(h.data_ptr()), n);
}
void launch_rmsnorm(torch::Tensor x, torch::Tensor w, torch::Tensor y, int64_t rows) {
rmsnorm_kernel<<<(int)rows, 256, 0, at::cuda::getCurrentCUDAStream()>>>(
reinterpret_cast<const bf16*>(x.data_ptr()),
reinterpret_cast<const bf16*>(w.data_ptr()),
y.data_ptr<float>(), (int)rows);
}
void launch_rmsnorm_f32(torch::Tensor x, torch::Tensor w, torch::Tensor y, int64_t rows) {
rmsnorm_f32_kernel<<<(int)rows, 256, 0, at::cuda::getCurrentCUDAStream()>>>(
x.data_ptr<float>(),
reinterpret_cast<const bf16*>(w.data_ptr()),
y.data_ptr<float>(), (int)rows);
}
void launch_gemv(torch::Tensor W, torch::Tensor x, torch::Tensor y) {
int M = W.size(0), K = W.size(1);
int grid = (M + 7) / 8;
gemv_kernel<<<grid, 256, 0, at::cuda::getCurrentCUDAStream()>>>(
reinterpret_cast<const bf16*>(W.data_ptr()),
x.data_ptr<float>(), y.data_ptr<float>(), M, K);
}
void launch_qknorm_rope(torch::Tensor q_in, torch::Tensor k_in, torch::Tensor v_in,
torch::Tensor q_norm, torch::Tensor k_norm,
torch::Tensor k_cache, torch::Tensor v_cache,
torch::Tensor q_out, int64_t pos, int64_t max_seq) {
qknorm_rope_kernel<<<1, 512, 0, at::cuda::getCurrentCUDAStream()>>>(
q_in.data_ptr<float>(), k_in.data_ptr<float>(), v_in.data_ptr<float>(),
reinterpret_cast<const bf16*>(q_norm.data_ptr()),
reinterpret_cast<const bf16*>(k_norm.data_ptr()),
reinterpret_cast<bf16*>(k_cache.data_ptr()),
reinterpret_cast<bf16*>(v_cache.data_ptr()),
q_out.data_ptr<float>(), (int)pos, (int)max_seq);
}
void launch_attn(torch::Tensor q_in, torch::Tensor k_cache, torch::Tensor v_cache,
torch::Tensor out, int64_t pos, int64_t max_seq) {
attn_kernel<<<1, 512, 0, at::cuda::getCurrentCUDAStream()>>>(
q_in.data_ptr<float>(),
reinterpret_cast<const bf16*>(k_cache.data_ptr()),
reinterpret_cast<const bf16*>(v_cache.data_ptr()),
out.data_ptr<float>(), (int)pos, (int)max_seq);
}
void launch_attn_split(torch::Tensor q_in, torch::Tensor k_cache,
torch::Tensor v_cache, torch::Tensor pm, torch::Tensor pl,
torch::Tensor pacc, int64_t pos, int64_t max_seq,
int64_t n_chunks) {
dim3 grid((unsigned)n_chunks, 16);
attn_split_kernel<<<grid, 128, 0, at::cuda::getCurrentCUDAStream()>>>(
q_in.data_ptr<float>(),
reinterpret_cast<const bf16*>(k_cache.data_ptr()),
reinterpret_cast<const bf16*>(v_cache.data_ptr()),
pm.data_ptr<float>(), pl.data_ptr<float>(), pacc.data_ptr<float>(),
(int)pos, (int)max_seq, (int)n_chunks);
}
void launch_attn_combine(torch::Tensor pm, torch::Tensor pl, torch::Tensor pacc,
torch::Tensor out, int64_t n_chunks) {
attn_combine_kernel<<<16, 128, 0, at::cuda::getCurrentCUDAStream()>>>(
pm.data_ptr<float>(), pl.data_ptr<float>(), pacc.data_ptr<float>(),
out.data_ptr<float>(), (int)n_chunks);
}
void launch_add_residual(torch::Tensor a, torch::Tensor b, torch::Tensor y) {
int n = a.numel();
add_residual_kernel<<<(n + 255) / 256, 256, 0, at::cuda::getCurrentCUDAStream()>>>(
reinterpret_cast<const bf16*>(a.data_ptr()),
b.data_ptr<float>(), reinterpret_cast<bf16*>(y.data_ptr()), n);
}
void launch_resid_add_f32(torch::Tensor a, torch::Tensor b, torch::Tensor y) {
int n = a.numel();
resid_add_f32_kernel<<<(n + 255) / 256, 256, 0, at::cuda::getCurrentCUDAStream()>>>(
a.data_ptr<float>(), b.data_ptr<float>(), y.data_ptr<float>(), n);
}
void launch_swiglu(torch::Tensor gate, torch::Tensor up, torch::Tensor h) {
int n = h.numel();
swiglu_kernel<<<(n + 255) / 256, 256, 0, at::cuda::getCurrentCUDAStream()>>>(
gate.data_ptr<float>(), up.data_ptr<float>(), h.data_ptr<float>(), n);
}
void launch_cast(torch::Tensor x, torch::Tensor y) {
int n = x.numel();
cast_f32_bf16_kernel<<<(n + 255) / 256, 256, 0, at::cuda::getCurrentCUDAStream()>>>(
x.data_ptr<float>(), reinterpret_cast<bf16*>(y.data_ptr()), n);
}
void launch_qkv_gemv(torch::Tensor q_proj, torch::Tensor k_proj, torch::Tensor v_proj,
torch::Tensor x, torch::Tensor q_raw, torch::Tensor k_raw,
torch::Tensor v_raw) {
// 4096 output rows, 4 warps per block -> 1024 blocks
qkv_gemv_kernel<<<1024, 128, 0, at::cuda::getCurrentCUDAStream()>>>(
reinterpret_cast<const bf16*>(q_proj.data_ptr()),
reinterpret_cast<const bf16*>(k_proj.data_ptr()),
reinterpret_cast<const bf16*>(v_proj.data_ptr()),
x.data_ptr<float>(), q_raw.data_ptr<float>(), k_raw.data_ptr<float>(),
v_raw.data_ptr<float>());
}
void launch_gu_gemv(torch::Tensor gate_proj, torch::Tensor up_proj, torch::Tensor x,
torch::Tensor gate, torch::Tensor up) {
// 6144 output rows, 4 warps per block -> 1536 blocks
gu_gemv_kernel<<<1536, 128, 0, at::cuda::getCurrentCUDAStream()>>>(
reinterpret_cast<const bf16*>(gate_proj.data_ptr()),
reinterpret_cast<const bf16*>(up_proj.data_ptr()),
x.data_ptr<float>(), gate.data_ptr<float>(), up.data_ptr<float>());
}
void launch_attn_fused(torch::Tensor q_in, torch::Tensor k_cache,
torch::Tensor v_cache, torch::Tensor pm, torch::Tensor pl,
torch::Tensor pacc,
int64_t pos, int64_t max_seq, int64_t n_chunks) {
dim3 grid((unsigned)n_chunks, (unsigned)NKV);
attn_fused_kernel<<<grid, 256, 0, at::cuda::getCurrentCUDAStream()>>>(
q_in.data_ptr<float>(),
reinterpret_cast<const bf16*>(k_cache.data_ptr()),
reinterpret_cast<const bf16*>(v_cache.data_ptr()),
pm.data_ptr<float>(), pl.data_ptr<float>(), pacc.data_ptr<float>(),
(int)pos, (int)max_seq, (int)n_chunks);
}
"""
_CPP_SRC = r"""
#include <torch/extension.h>
void launch_mix(torch::Tensor r, torch::Tensor h);
void launch_rmsnorm(torch::Tensor x, torch::Tensor w, torch::Tensor y, int64_t rows);
void launch_rmsnorm_f32(torch::Tensor x, torch::Tensor w, torch::Tensor y, int64_t rows);
void launch_gemv(torch::Tensor W, torch::Tensor x, torch::Tensor y);
void launch_qknorm_rope(torch::Tensor q_in, torch::Tensor k_in, torch::Tensor v_in,
torch::Tensor q_norm, torch::Tensor k_norm,
torch::Tensor k_cache, torch::Tensor v_cache,
torch::Tensor q_out, int64_t pos, int64_t max_seq);
void launch_attn(torch::Tensor q_in, torch::Tensor k_cache, torch::Tensor v_cache,
torch::Tensor out, int64_t pos, int64_t max_seq);
void launch_attn_split(torch::Tensor q_in, torch::Tensor k_cache,
torch::Tensor v_cache, torch::Tensor pm, torch::Tensor pl,
torch::Tensor pacc, int64_t pos, int64_t max_seq,
int64_t n_chunks);
void launch_attn_combine(torch::Tensor pm, torch::Tensor pl, torch::Tensor pacc,
torch::Tensor out, int64_t n_chunks);
void launch_add_residual(torch::Tensor a, torch::Tensor b, torch::Tensor y);
void launch_resid_add_f32(torch::Tensor a, torch::Tensor b, torch::Tensor y);
void launch_swiglu(torch::Tensor gate, torch::Tensor up, torch::Tensor h);
void launch_cast(torch::Tensor x, torch::Tensor y);
void launch_qkv_gemv(torch::Tensor q_proj, torch::Tensor k_proj, torch::Tensor v_proj,
torch::Tensor x, torch::Tensor q_raw, torch::Tensor k_raw,
torch::Tensor v_raw);
void launch_gu_gemv(torch::Tensor gate_proj, torch::Tensor up_proj, torch::Tensor x,
torch::Tensor gate, torch::Tensor up);
void launch_attn_fused(torch::Tensor q_in, torch::Tensor k_cache,
torch::Tensor v_cache, torch::Tensor pm, torch::Tensor pl,
torch::Tensor pacc,
int64_t pos, int64_t max_seq, int64_t n_chunks);
"""
_ext = None
def _get_ext():
global _ext
if _ext is None:
_ext = load_inline(
name="megaqwen_decode_ext",
cpp_sources=[_CPP_SRC],
cuda_sources=[_CUDA_SRC],
functions=[
"launch_mix", "launch_rmsnorm", "launch_rmsnorm_f32",
"launch_gemv", "launch_qknorm_rope", "launch_attn",
"launch_attn_split", "launch_attn_combine",
"launch_add_residual", "launch_resid_add_f32",
"launch_swiglu", "launch_cast",
"launch_qkv_gemv", "launch_gu_gemv", "launch_attn_fused",
],
extra_cuda_cflags=["-O3", "--use_fast_math", "-arch=sm_120a"],
verbose=False,
)
return _ext
class Block(nn.Module):
def __init__(self):
super().__init__()
H, I, D = HIDDEN, INTERMEDIATE, HEAD_DIM
self.input_ln = nn.Parameter(torch.ones(H, dtype=torch.bfloat16))
self.q_proj = nn.Parameter(torch.empty(NUM_Q * D, H, dtype=torch.bfloat16))
self.k_proj = nn.Parameter(torch.empty(NUM_KV * D, H, dtype=torch.bfloat16))
self.v_proj = nn.Parameter(torch.empty(NUM_KV * D, H, dtype=torch.bfloat16))
self.q_norm = nn.Parameter(torch.ones(D, dtype=torch.bfloat16))
self.k_norm = nn.Parameter(torch.ones(D, dtype=torch.bfloat16))
self.o_proj = nn.Parameter(torch.empty(H, NUM_Q * D, dtype=torch.bfloat16))
self.post_ln = nn.Parameter(torch.ones(H, dtype=torch.bfloat16))
self.gate_proj = nn.Parameter(torch.empty(I, H, dtype=torch.bfloat16))
self.up_proj = nn.Parameter(torch.empty(I, H, dtype=torch.bfloat16))
self.down_proj = nn.Parameter(torch.empty(H, I, dtype=torch.bfloat16))
for p in self.parameters():
if p is self.input_ln or p is self.post_ln or p is self.q_norm or p is self.k_norm:
continue
nn.init.normal_(p, std=0.02)
class Model(nn.Module):
def __init__(self, num_layers: int = NUM_LAYERS, max_seq: int = 131072):
super().__init__()
self.num_layers = num_layers
self.max_seq = max_seq
self.blocks = nn.ModuleList([Block() for _ in range(num_layers)])
def forward(self, x, k_caches, v_caches, position):
raise NotImplementedError("use prefill/decode_steps")
def empty_caches(num_layers, max_seq, device, dtype=torch.bfloat16):
k = [torch.zeros(NUM_KV, max_seq, HEAD_DIM, device=device, dtype=dtype)
for _ in range(num_layers)]
v = [torch.zeros(NUM_KV, max_seq, HEAD_DIM, device=device, dtype=dtype)
for _ in range(num_layers)]
return k, v
def _seeded_hidden(seed, device):
g = torch.Generator(device="cpu")
g.manual_seed(seed)
return torch.randn(HIDDEN, generator=g, dtype=torch.bfloat16).to(device)
def _seeded_randn(seed, n, device):
g = torch.Generator(device="cpu")
g.manual_seed(seed)
return torch.randn(n, generator=g, dtype=torch.bfloat16).to(device)
@torch.no_grad()
def _run_block(ext, block, h_bf16, h_f32, k_cache, v_cache, pos, max_seq, bufs):
"""One block transform. h_bf16: bf16[1024] (input residual, exact fp32
values); h_f32: fp32[1024] (running fp32 residual within the step).
Writes the new fp32 residual into h_f32 in place."""
# rmsnorm (input_ln) on the bf16 residual
ext.launch_rmsnorm(h_bf16, block.input_ln, bufs["hn"], 1)
# qkv projections (fp32), batched into one launch
ext.launch_qkv_gemv(block.q_proj, block.k_proj, block.v_proj,
bufs["hn"], bufs["q_raw"], bufs["k_raw"], bufs["v_raw"])
# q/k norm + rope + write k/v cache row for pos
ext.launch_qknorm_rope(bufs["q_raw"], bufs["k_raw"], bufs["v_raw"],
block.q_norm, block.k_norm, k_cache, v_cache,
bufs["q_normed"], pos, max_seq)
# attention: split-KV flash decoding over the KV cache (q already
# normed+roped by qknorm_rope) + combine across chunks
n_chunks = (pos + 1 + 511) // 512
ext.launch_attn_fused(bufs["q_normed"], k_cache, v_cache, bufs["pm"],
bufs["pl"], bufs["pacc"], pos, max_seq, n_chunks)
ext.launch_attn_combine(bufs["pm"], bufs["pl"], bufs["pacc"], bufs["ao"],
n_chunks)
# o proj
ext.launch_gemv(block.o_proj, bufs["ao"], bufs["ao_proj"]) # 1024
# residual add (fp32): h = h + ao_proj (h_f32 already holds the input
# residual, so this is an in-place fp32 add)
ext.launch_resid_add_f32(h_f32, bufs["ao_proj"], h_f32)
# rmsnorm post (fp32 residual)
ext.launch_rmsnorm_f32(h_f32, block.post_ln, bufs["hn2"], 1)
# gate/up (batched into one launch)
ext.launch_gu_gemv(block.gate_proj, block.up_proj, bufs["hn2"],
bufs["gate"], bufs["up"])
# swiglu
ext.launch_swiglu(bufs["gate"], bufs["up"], bufs["mlp_h"]) # 3072
# down
ext.launch_gemv(block.down_proj, bufs["mlp_h"], bufs["down"]) # 1024
# residual add (fp32): h = h + down
ext.launch_resid_add_f32(h_f32, bufs["down"], h_f32)
def _make_bufs(device):
f = torch.float32
max_chunks = (131072 + 511) // 512 + 1
return {
"hn": torch.empty(HIDDEN, device=device, dtype=f),
"q_raw": torch.empty(NUM_Q * HEAD_DIM, device=device, dtype=f),
"k_raw": torch.empty(NUM_KV * HEAD_DIM, device=device, dtype=f),
"v_raw": torch.empty(NUM_KV * HEAD_DIM, device=device, dtype=f),
"q_normed": torch.empty(NUM_Q * HEAD_DIM, device=device, dtype=f),
"ao": torch.empty(NUM_Q * HEAD_DIM, device=device, dtype=f),
"pm": torch.empty(NUM_Q * max_chunks, device=device, dtype=f),
"pl": torch.empty(NUM_Q * max_chunks, device=device, dtype=f),
"pacc": torch.empty(NUM_Q * max_chunks * HEAD_DIM, device=device, dtype=f),
"ao_proj": torch.empty(HIDDEN, device=device, dtype=f),
"h_f32": torch.empty(HIDDEN, device=device, dtype=f),
"h_bf16": torch.empty(HIDDEN, device=device, dtype=torch.bfloat16),
"hn2": torch.empty(HIDDEN, device=device, dtype=f),
"gate": torch.empty(INTERMEDIATE, device=device, dtype=f),
"up": torch.empty(INTERMEDIATE, device=device, dtype=f),
"mlp_h": torch.empty(INTERMEDIATE, device=device, dtype=f),
"down": torch.empty(HIDDEN, device=device, dtype=f),
}
@torch.no_grad()
def decode_steps(model, hidden, k_caches, v_caches, start_pos, n_steps, seed):
device = hidden.device
ext = _get_ext()
bufs = _make_bufs(device)
g = torch.Generator(device="cpu")
g.manual_seed(seed + 2)
h = hidden
h_f32 = bufs["h_f32"]
for i in range(n_steps):
pos = start_pos + i
x_t = torch.randn(HIDDEN, generator=g, dtype=torch.bfloat16).to(device)
ext.launch_mix(x_t, h)
for j, block in enumerate(model.blocks):
h_f32.copy_(h)
_run_block(ext, block, h, h_f32, k_caches[j], v_caches[j], pos,
model.max_seq, bufs)
ext.launch_cast(h_f32, h)
return h, k_caches, v_caches
@torch.no_grad()
def prefill(model, ctx_len, seed, device=None):
device = device or next(model.parameters()).device
model = model.to(device).eval()
assert ctx_len <= model.max_seq
ext = _get_ext()
bufs = _make_bufs(device)
h = _seeded_hidden(seed, device) # bf16 step boundary
h_f32 = bufs["h_f32"]
k_caches, v_caches = empty_caches(model.num_layers, model.max_seq, device)
g = torch.Generator(device="cpu")
g.manual_seed(seed + 1)
for t in range(ctx_len):
x_t = torch.randn(HIDDEN, generator=g, dtype=torch.bfloat16).to(device)
ext.launch_mix(x_t, h) # h = bf16(0.5 x + 0.5 h)
for i, block in enumerate(model.blocks):
h_f32.copy_(h) # fp32 residual for this block
_run_block(ext, block, h, h_f32, k_caches[i], v_caches[i], t,
model.max_seq, bufs)
ext.launch_cast(h_f32, h) # block output -> bf16 (reference)
return h, k_caches, v_caches
def run(ctx_len, n_decode, seed, model=None, max_seq=None):
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
max_seq = max_seq or max(ctx_len + n_decode, 512)
if model is None:
model = Model(NUM_LAYERS, max_seq)
else:
if getattr(model, "max_seq", 0) < ctx_len + n_decode:
raise ValueError("model.max_seq too small")
model = model.to(device).eval()
h, k_caches, v_caches = prefill(model, ctx_len, seed, device=device)
h, k_caches, v_caches = decode_steps(
model, h, k_caches, v_caches, start_pos=ctx_len, n_steps=n_decode, seed=seed)
return {"last_hidden": h.detach(), "ctx_len": ctx_len, "decode_steps": n_decode}
def get_init_inputs():
return [NUM_LAYERS, 131072]
def get_inputs():
return []20261203_225907_grok_qwen_qwen4-35b-a3b_03_megaqwen_decode