KernelBench hard deprecated · RTX PRO 6000
W4A16 GEMM Grok 4.5
manually audited: clean
Genuine hybrid W4A16 kernel: hand-written CUDA split-K GEMV for decode (M=1) — 256 threads/block, K split into 512-wide chunks (8-way for K=4096) with fp32 partials reduced by a second kernel, activations staged in shared memory, fused nibble-unpack + asymmetric dequant + fmaf — and a Triton fused dequant+tl.dot GEMM (22 autotune configs) for M>1. The sidecar scratch/w4a16_cuda.cu was read in full: it computes the real dequant GEMM (no bitsandbytes, no marlin, no F.linear — all forbidden ops absent), plus an unused-at-M=1 multi-row tiled path. No caching/memoization/data_ptr tricks (only compile-once load_inline module handle), no check.py sniffing, all problem files byte-identical, template_mutated=false. Transcript is independent with zero contamination markers. 0.1435 comes almost entirely from the split-K decode insight: 514 GB/s (0.286 peak) on the M=1 N=12288 headline shape under cold-L2 timing.
Per-shape vs governing ceilingeach shape graded against whichever binds — bf16 compute or HBM bandwidth
compute-bound memory-bound · bar + right column = official fraction of the ceiling (the geomean input)
geomean(28.7% · 13.9% · 8.6% · 13.3% · 13.3%) = 14.3%
Kernel source (redacted)
"""Fused W4A16 weight-only quantized GEMM.
CUDA split-K GEMV for decode (M=1); Triton fused dequant+GEMM for prefill (M>1).
Scheme matches reference.py:
x: (M, K) bf16
w_q: (K//2, N) uint8 -- low nibble = even-K, high nibble = odd-K
scales: (K//128, N) bf16
zeros: (K//128, N) bf16
out: (M, N) bf16
w_bf[k,n] = bf16((unpack(w_q)[k,n] - zeros[k//128,n]) * scales[k//128,n])
"""
from __future__ import annotations
from pathlib import Path
import torch
import torch.nn as nn
import triton
import triton.language as tl
from torch.utils.cpp_extension import load_inline
OP_TYPE = "gemm_w4a16"
SUPPORTED_PRECISIONS = ["int4_bf16"]
HARDWARE_REQUIRED = ["RTX_PRO_6000", "H100", "B200"]
GROUP_SIZE = 128
# ---------------------------------------------------------------------------
# CUDA decode (M=1): split-K high-occupancy GEMV
# ---------------------------------------------------------------------------
_CUDA_SRC = (Path(__file__).parent / "w4a16_cuda.cu").read_text()
_CPP_SRC = (
"torch::Tensor w4a16_forward(torch::Tensor x, torch::Tensor w_q, "
"torch::Tensor scales, torch::Tensor zeros);"
)
_mod = None
def _cuda():
global _mod
if _mod is None:
_mod = load_inline(
name="w4a16_gemm_final",
cpp_sources=_CPP_SRC,
cuda_sources=_CUDA_SRC,
functions=["w4a16_forward"],
extra_cuda_cflags=[
"-O3",
"--use_fast_math",
"-lineinfo",
"-gencode=arch=compute_120a,code=sm_120a",
],
verbose=False,
)
return _mod
# ---------------------------------------------------------------------------
# Triton prefill (M>1): fused unpack + dequant + tl.dot
# ---------------------------------------------------------------------------
@triton.autotune(
configs=[
triton.Config({"BLOCK_M": 16, "BLOCK_N": 64, "BLOCK_K": 64}, num_stages=3, num_warps=4),
triton.Config({"BLOCK_M": 16, "BLOCK_N": 128, "BLOCK_K": 64}, num_stages=3, num_warps=4),
triton.Config({"BLOCK_M": 16, "BLOCK_N": 256, "BLOCK_K": 64}, num_stages=2, num_warps=4),
triton.Config({"BLOCK_M": 32, "BLOCK_N": 64, "BLOCK_K": 64}, num_stages=3, num_warps=4),
triton.Config({"BLOCK_M": 32, "BLOCK_N": 128, "BLOCK_K": 64}, num_stages=3, num_warps=4),
triton.Config({"BLOCK_M": 32, "BLOCK_N": 256, "BLOCK_K": 64}, num_stages=2, num_warps=8),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "BLOCK_K": 64}, num_stages=3, num_warps=4),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 64}, num_stages=3, num_warps=4),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 64}, num_stages=2, num_warps=8),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 128}, num_stages=2, num_warps=8),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 64}, num_stages=2, num_warps=4),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 64}, num_stages=2, num_warps=8),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 32}, num_stages=3, num_warps=4),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 32}, num_stages=2, num_warps=8),
triton.Config({"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 64}, num_stages=2, num_warps=8),
triton.Config({"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 32}, num_stages=2, num_warps=8),
triton.Config({"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 64}, num_stages=2, num_warps=8),
triton.Config({"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 32}, num_stages=3, num_warps=8),
triton.Config({"BLOCK_M": 32, "BLOCK_N": 128, "BLOCK_K": 32}, num_stages=4, num_warps=4),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "BLOCK_K": 32}, num_stages=4, num_warps=4),
triton.Config({"BLOCK_M": 16, "BLOCK_N": 128, "BLOCK_K": 128}, num_stages=2, num_warps=4),
triton.Config({"BLOCK_M": 32, "BLOCK_N": 64, "BLOCK_K": 128}, num_stages=2, num_warps=4),
],
key=["M", "N", "K"],
)
@triton.jit
def _w4a16_gemm_kernel(
x_ptr, w_ptr, s_ptr, z_ptr, out_ptr,
M, N, K,
stride_xm, stride_xk,
stride_wk, stride_wn,
stride_sg, stride_sn,
stride_zg, stride_zn,
stride_om, stride_on,
GROUP_SIZE: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
BLOCK_K: tl.constexpr,
):
pid = tl.program_id(0)
num_pid_m = tl.cdiv(M, BLOCK_M)
num_pid_n = tl.cdiv(N, BLOCK_N)
GROUP_M: tl.constexpr = 8
num_pid_in_group = GROUP_M * num_pid_n
group_id = pid // num_pid_in_group
first_pid_m = group_id * GROUP_M
group_size_m = min(num_pid_m - first_pid_m, GROUP_M)
pid_m = first_pid_m + (pid % group_size_m)
pid_n = (pid % num_pid_in_group) // group_size_m
offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
offs_k = tl.arange(0, BLOCK_K)
acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
for kt in range(tl.cdiv(K, BLOCK_K)):
k_base = kt * BLOCK_K
k_offs = k_base + offs_k
x_ptrs = x_ptr + offs_m[:, None] * stride_xm + k_offs[None, :] * stride_xk
x = tl.load(
x_ptrs,
mask=(offs_m[:, None] < M) & (k_offs[None, :] < K),
other=0.0,
)
pk = k_offs // 2
w_ptrs = w_ptr + pk[:, None] * stride_wk + offs_n[None, :] * stride_wn
w_mask = (k_offs[:, None] < K) & (offs_n[None, :] < N)
w_packed = tl.load(w_ptrs, mask=w_mask, other=0)
is_odd = (k_offs % 2)[:, None]
w_i4 = tl.where(is_odd == 0, w_packed & 0xF, (w_packed >> 4) & 0xF).to(tl.float32)
g_offs = k_offs // GROUP_SIZE
s_ptrs = s_ptr + g_offs[:, None] * stride_sg + offs_n[None, :] * stride_sn
z_ptrs = z_ptr + g_offs[:, None] * stride_zg + offs_n[None, :] * stride_zn
scales = tl.load(s_ptrs, mask=w_mask, other=0.0).to(tl.float32)
zeros = tl.load(z_ptrs, mask=w_mask, other=0.0).to(tl.float32)
# bf16-round dequant matches reference numerics under large activations
w_bf = ((w_i4 - zeros) * scales).to(tl.bfloat16)
acc += tl.dot(x, w_bf)
out_ptrs = out_ptr + offs_m[:, None] * stride_om + offs_n[None, :] * stride_on
tl.store(
out_ptrs,
acc.to(tl.bfloat16),
mask=(offs_m[:, None] < M) & (offs_n[None, :] < N),
)
def _triton_gemm(x, w_q, scales, zeros, group_size):
M, K = x.shape
N = w_q.shape[1]
out = torch.empty((M, N), dtype=torch.bfloat16, device=x.device)
grid = lambda meta: (
triton.cdiv(M, meta["BLOCK_M"]) * triton.cdiv(N, meta["BLOCK_N"]),
)
_w4a16_gemm_kernel[grid](
x, w_q, scales, zeros, out,
M, N, K,
x.stride(0), x.stride(1),
w_q.stride(0), w_q.stride(1),
scales.stride(0), scales.stride(1),
zeros.stride(0), zeros.stride(1),
out.stride(0), out.stride(1),
GROUP_SIZE=group_size,
)
return out
def w4a16_gemm(x, w_q, scales, zeros, group_size=GROUP_SIZE):
x = x.contiguous()
w_q = w_q.contiguous()
scales = scales.contiguous()
zeros = zeros.contiguous()
if x.shape[0] == 1:
return _cuda().w4a16_forward(x, w_q, scales, zeros)
return _triton_gemm(x, w_q, scales, zeros, group_size)
class Model(nn.Module):
def __init__(self, M: int, N: int, K: int, group_size: int = GROUP_SIZE):
super().__init__()
assert K % group_size == 0 and K % 2 == 0
self.M, self.N, self.K = M, N, K
self.group_size = group_size
n_groups = K // group_size
self.register_buffer("w_q", torch.zeros(K // 2, N, dtype=torch.uint8))
self.register_buffer("scales", torch.ones(n_groups, N, dtype=torch.bfloat16))
self.register_buffer("zeros", torch.zeros(n_groups, N, dtype=torch.bfloat16))
def forward(self, x: torch.Tensor) -> torch.Tensor:
return w4a16_gemm(x, self.w_q, self.scales, self.zeros, self.group_size)
M, N, K = 1, 12288, 4096
def get_inputs():
return [torch.randn(M, K, dtype=torch.bfloat16)]
def get_init_inputs():
return [M, N, K]
# ==================================================================
# ===== sidecar: w4a16_cuda.cu (11136 bytes, loaded by solution.py) =====
# ==================================================================
// Fused W4A16: high-occupancy GEMV (M=1) + K-tiled multi-row GEMM.
// AWQ asymmetric int4, group=128.
// Packing: w_q[k//2,n] low=even-k, high=odd-k.
#include <cuda_bf16.h>
#include <cuda_runtime.h>
#include <cstdint>
#include <torch/extension.h>
static constexpr int GROUP = 128;
// =============================================================================
// M=1 GEMV: 1 col/thread, 256 thr/block, max occupancy
// =============================================================================
template <int THREADS>
__global__ void __launch_bounds__(THREADS, 4)
w4a16_gemv(
const __nv_bfloat16* __restrict__ x,
const uint8_t* __restrict__ w_q,
const __nv_bfloat16* __restrict__ scales,
const __nv_bfloat16* __restrict__ zeros,
__nv_bfloat16* __restrict__ out,
int N, int K)
{
const int n = blockIdx.x * THREADS + threadIdx.x;
const int tid = threadIdx.x;
extern __shared__ char smem_raw[];
__nv_bfloat16* sx = reinterpret_cast<__nv_bfloat16*>(smem_raw);
for (int k = tid * 2; k < K; k += THREADS * 2) {
if (k + 1 < K) {
*reinterpret_cast<uint32_t*>(sx + k) =
*reinterpret_cast<const uint32_t*>(
reinterpret_cast<const char*>(x) + k * sizeof(__nv_bfloat16));
} else if (k < K) {
sx[k] = x[k];
}
}
__syncthreads();
if (n >= N) return;
float acc = 0.f;
const int n_groups = K / GROUP;
#pragma unroll 1
for (int g = 0; g < n_groups; ++g) {
const float sc = __bfloat162float(__ldg(&scales[(int64_t)g * N + n]));
const float zc = __bfloat162float(__ldg(&zeros[(int64_t)g * N + n]));
const float zs = zc * sc;
const int k0 = g * GROUP;
const int pk0 = k0 >> 1;
#pragma unroll 8
for (int pk = 0; pk < GROUP / 2; ++pk) {
const uint8_t p = __ldg(&w_q[(int64_t)(pk0 + pk) * N + n]);
const float xe = __bfloat162float(sx[k0 + (pk << 1)]);
const float xo = __bfloat162float(sx[k0 + (pk << 1) + 1]);
acc = fmaf(xe, fmaf((float)(p & 0xF), sc, -zs), acc);
acc = fmaf(xo, fmaf((float)(p >> 4), sc, -zs), acc);
}
}
out[n] = __float2bfloat16(acc);
}
// Split-K GEMV: grid (ceil(N/THREADS), split). Each CTA owns a K-chunk.
// Writes partial[sk, n]; host reduces. More CTAs → better latency hiding when N is small.
template <int THREADS, int K_CHUNK>
__global__ void __launch_bounds__(THREADS, 4)
w4a16_gemv_splitk(
const __nv_bfloat16* __restrict__ x,
const uint8_t* __restrict__ w_q,
const __nv_bfloat16* __restrict__ scales,
const __nv_bfloat16* __restrict__ zeros,
float* __restrict__ partial, // [split, N]
int N, int K)
{
const int n = blockIdx.x * THREADS + threadIdx.x;
const int sk = blockIdx.y;
const int tid = threadIdx.x;
const int k_start = sk * K_CHUNK;
const int k_end = min(k_start + K_CHUNK, K);
const int k_len = k_end - k_start;
extern __shared__ char smem_raw[];
__nv_bfloat16* sx = reinterpret_cast<__nv_bfloat16*>(smem_raw);
for (int k = tid; k < k_len; k += THREADS) sx[k] = x[k_start + k];
__syncthreads();
if (n >= N) return;
float acc = 0.f;
const int g0 = k_start / GROUP;
const int g1 = k_end / GROUP;
for (int g = g0; g < g1; ++g) {
const float sc = __bfloat162float(__ldg(&scales[(int64_t)g * N + n]));
const float zc = __bfloat162float(__ldg(&zeros[(int64_t)g * N + n]));
const float zs = zc * sc;
const int k0 = g * GROUP;
const int pk0 = k0 >> 1;
const int lk0 = k0 - k_start;
#pragma unroll 8
for (int pk = 0; pk < GROUP / 2; ++pk) {
const uint8_t p = __ldg(&w_q[(int64_t)(pk0 + pk) * N + n]);
const float xe = __bfloat162float(sx[lk0 + (pk << 1)]);
const float xo = __bfloat162float(sx[lk0 + (pk << 1) + 1]);
acc = fmaf(xe, fmaf((float)(p & 0xF), sc, -zs), acc);
acc = fmaf(xo, fmaf((float)(p >> 4), sc, -zs), acc);
}
}
partial[(int64_t)sk * N + n] = acc;
}
__global__ void reduce_partial_to_bf16(
const float* __restrict__ partial,
__nv_bfloat16* __restrict__ out,
int N, int split)
{
int n = blockIdx.x * blockDim.x + threadIdx.x;
if (n >= N) return;
float s = 0.f;
#pragma unroll 4
for (int sk = 0; sk < split; ++sk) s += partial[(int64_t)sk * N + n];
out[n] = __float2bfloat16(s);
}
// =============================================================================
// Multi-row K-tiled GEMM
// CTA: BM rows x BN cols. Stream K in chunks of BK (multiple of GROUP).
// smem: x tile BM*BK bf16. Weights loaded coalesced and dequantized on the fly,
// reused across BM rows.
// =============================================================================
template <int BM, int BN, int BK, int THREADS>
__global__ void __launch_bounds__(THREADS, 2)
w4a16_gemm_tiled(
const __nv_bfloat16* __restrict__ x, // [M,K]
const uint8_t* __restrict__ w_q, // [K/2,N]
const __nv_bfloat16* __restrict__ scales,
const __nv_bfloat16* __restrict__ zeros,
__nv_bfloat16* __restrict__ out, // [M,N]
int M, int N, int K)
{
static_assert(BK % GROUP == 0, "BK must be multiple of GROUP");
static_assert(BN % 4 == 0, "BN multiple of 4 for vectorization");
const int n0 = blockIdx.x * BN;
const int m0 = blockIdx.y * BM;
if (n0 >= N || m0 >= M) return;
const int tid = threadIdx.x;
const int m_tile = min(BM, M - m0);
const int n_tile = min(BN, N - n0);
// Each thread owns one or more output columns within BN
// THREADS should be == BN for 1-col/thread
const int col = tid; // 0..BN-1
const bool active = (col < n_tile);
extern __shared__ char smem_raw[];
// sx: [BM][BK]
__nv_bfloat16* sx = reinterpret_cast<__nv_bfloat16*>(smem_raw);
float acc[BM];
#pragma unroll
for (int mi = 0; mi < BM; ++mi) acc[mi] = 0.f;
const int n = n0 + col;
for (int k0 = 0; k0 < K; k0 += BK) {
const int bk = min(BK, K - k0);
// Cooperative load of x[m0:m0+m_tile, k0:k0+bk]
for (int mi = 0; mi < m_tile; ++mi) {
const __nv_bfloat16* xrow = x + (int64_t)(m0 + mi) * K + k0;
for (int k = tid; k < bk; k += THREADS) {
sx[mi * BK + k] = xrow[k];
}
}
// zero pad rest of BK for safety
for (int mi = m_tile; mi < BM; ++mi) {
for (int k = tid; k < BK; k += THREADS) sx[mi * BK + k] = __float2bfloat16(0.f);
}
__syncthreads();
if (active) {
// Process this K-tile group-by-group
const int g_start = k0 / GROUP;
const int g_end = (k0 + bk) / GROUP;
for (int g = g_start; g < g_end; ++g) {
const float sc = __bfloat162float(__ldg(&scales[(int64_t)g * N + n]));
const float zc = __bfloat162float(__ldg(&zeros[(int64_t)g * N + n]));
// bf16-round dequant for large-activation correctness
const int gk0 = g * GROUP; // global k
const int lk0 = gk0 - k0; // local k in sx
const int pk0 = gk0 >> 1;
#pragma unroll 4
for (int pk = 0; pk < GROUP / 2; ++pk) {
const uint8_t p = __ldg(&w_q[(int64_t)(pk0 + pk) * N + n]);
const float we = __bfloat162float(__float2bfloat16(((float)(p & 0xF) - zc) * sc));
const float wo = __bfloat162float(__float2bfloat16(((float)(p >> 4) - zc) * sc));
const int le = lk0 + (pk << 1);
#pragma unroll
for (int mi = 0; mi < BM; ++mi) {
if (mi >= m_tile) continue;
float xe = __bfloat162float(sx[mi * BK + le]);
float xo = __bfloat162float(sx[mi * BK + le + 1]);
acc[mi] = fmaf(xe, we, fmaf(xo, wo, acc[mi]));
}
}
}
}
__syncthreads();
}
if (active) {
#pragma unroll
for (int mi = 0; mi < BM; ++mi) {
if (mi >= m_tile) continue;
out[(int64_t)(m0 + mi) * N + n] = __float2bfloat16(acc[mi]);
}
}
}
torch::Tensor w4a16_forward(
torch::Tensor x,
torch::Tensor w_q,
torch::Tensor scales,
torch::Tensor zeros)
{
TORCH_CHECK(x.is_cuda() && w_q.is_cuda());
TORCH_CHECK(x.scalar_type() == torch::kBFloat16);
TORCH_CHECK(w_q.scalar_type() == torch::kByte);
x = x.contiguous();
w_q = w_q.contiguous();
scales = scales.contiguous();
zeros = zeros.contiguous();
const int M = (int)x.size(0);
const int K = (int)x.size(1);
const int N = (int)w_q.size(1);
TORCH_CHECK((int)w_q.size(0) * 2 == K);
TORCH_CHECK(K % GROUP == 0);
auto out = torch::empty({M, N}, x.options());
auto* x_ptr = reinterpret_cast<const __nv_bfloat16*>(x.data_ptr());
auto* w_ptr = w_q.data_ptr<uint8_t>();
auto* s_ptr = reinterpret_cast<const __nv_bfloat16*>(scales.data_ptr());
auto* z_ptr = reinterpret_cast<const __nv_bfloat16*>(zeros.data_ptr());
auto* o_ptr = reinterpret_cast<__nv_bfloat16*>(out.data_ptr());
if (M == 1) {
constexpr int THREADS = 256;
// Always split-K: multiplies CTA count by K/K_CHUNK for HBM latency hiding.
// K_CHUNK=512 → split=8 for K=4096. Measured ~510 GB/s on N=12288 (L2-cold).
constexpr int K_CHUNK = 512;
const int split = K / K_CHUNK;
const int grid_x = (N + THREADS - 1) / THREADS;
auto partial = torch::empty({split, N}, x.options().dtype(torch::kFloat32));
dim3 grid(grid_x, split);
int smem = K_CHUNK * (int)sizeof(__nv_bfloat16);
auto* kern = w4a16_gemv_splitk<THREADS, K_CHUNK>;
cudaFuncSetAttribute(kern, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
kern<<<grid, THREADS, smem>>>(x_ptr, w_ptr, s_ptr, z_ptr,
partial.data_ptr<float>(), N, K);
reduce_partial_to_bf16<<<(N + 255) / 256, 256>>>(
partial.data_ptr<float>(), o_ptr, N, split);
} else if (M <= 64) {
constexpr int BM = 32, BN = 128, BK = 256, THREADS = BN;
dim3 grid((N + BN - 1) / BN, (M + BM - 1) / BM);
int smem = BM * BK * (int)sizeof(__nv_bfloat16); // 16KB
auto* kern = w4a16_gemm_tiled<BM, BN, BK, THREADS>;
cudaFuncSetAttribute(kern, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
kern<<<grid, THREADS, smem>>>(x_ptr, w_ptr, s_ptr, z_ptr, o_ptr, M, N, K);
} else {
// Large M: bigger BM for weight reuse
constexpr int BM = 64, BN = 128, BK = 128, THREADS = BN;
dim3 grid((N + BN - 1) / BN, (M + BM - 1) / BM);
int smem = BM * BK * (int)sizeof(__nv_bfloat16); // 16KB
auto* kern = w4a16_gemm_tiled<BM, BN, BK, THREADS>;
cudaFuncSetAttribute(kern, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);
kern<<<grid, THREADS, smem>>>(x_ptr, w_ptr, s_ptr, z_ptr, o_ptr, M, N, K);
}
return out;
}
20260708_153355_grok_grok-4.5_07_w4a16_gemm