"""Fused W4A16 (weight-only int4) GEMM for RTX PRO 6000 (SM120 Blackwell). y[m, n] = sum_k x[m, k] * (unpack(w_q)[k, n] - zeros[k//128, n]) * scales[k//128, n] Two kernels: * Decode (M == 1): a hand-written CUDA GEMV that streams the packed int4 weights at near-bandwidth and uses the "split" trick y[n] = sum_g s[g,n] * ( sum_{k in g} x[k]*w_q[k,n] - z[g,n] * sum_{k in g} x[k] ) so the dequant is applied once per group instead of once per weight. * Prefill (M >= 2): a Triton kernel that fuses nibble unpack + dequant into a bf16 tensor-core GEMM. Because the two nibbles of a byte are even/odd K rows, the activation tile is split into even/odd K columns and two dots are issued (same total MACs, no explicit interleave). """ from __future__ import annotations import os import sys import tempfile from pathlib import Path import torch import torch.nn as nn import triton import triton.language as tl OP_TYPE = "gemm_w4a16" SUPPORTED_PRECISIONS = ["int4_bf16"] HARDWARE_REQUIRED = ["RTX_PRO_6000", "H100", "B200"] GROUP_SIZE = 128 # --------------------------------------------------------------------------- # Triton fused-dequant GEMM (prefill) # --------------------------------------------------------------------------- @triton.jit def _w4a16_kernel( x_ptr, w_ptr, scales_ptr, zeros_ptr, out_ptr, M, N, K, GROUP_SIZE: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, ): # All buffers are contiguous; strides are implied by (M, N, K). pid_m = tl.program_id(0) pid_n = tl.program_id(1) offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) offs_kh = tl.arange(0, BLOCK_K // 2) acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) nmask = offs_n < N for k in range(0, K, BLOCK_K): offs_k = k + tl.arange(0, BLOCK_K) x = tl.load( x_ptr + offs_m[:, None] * K + offs_k[None, :], mask=(offs_m[:, None] < M) & (offs_k[None, :] < K), other=0.0, ) xr = tl.reshape(x, (BLOCK_M, BLOCK_K // 2, 2)) x_even, x_odd = tl.split(xr) g = k // GROUP_SIZE scale = tl.load(scales_ptr + g * N + offs_n, mask=nmask, other=0.0) zero = tl.load(zeros_ptr + g * N + offs_n, mask=nmask, other=0.0) w = tl.load( w_ptr + (k // 2 + offs_kh)[:, None] * N + offs_n[None, :], mask=((k // 2 + offs_kh)[:, None] < K // 2) & nmask[None, :], other=0, ) wi = w.to(tl.int32) lo = wi & 0xF hi = (wi >> 4) & 0xF w_lo = (lo.to(tl.bfloat16) - zero[None, :]) * scale[None, :] w_hi = (hi.to(tl.bfloat16) - zero[None, :]) * scale[None, :] acc += tl.dot(x_even, w_lo) + tl.dot(x_odd, w_hi) out_ptrs = out_ptr + offs_m[:, None] * N + offs_n[None, :] tl.store(out_ptrs, acc.to(tl.bfloat16), mask=(offs_m[:, None] < M) & nmask[None, :]) # --------------------------------------------------------------------------- # CUDA GEMV (decode, M == 1) # --------------------------------------------------------------------------- _GEMV_CUDA = r""" #include #include #include extern "C" { __global__ void w4a16_gemv_kernel( const __nv_bfloat16* __restrict__ x, const uint8_t* __restrict__ w, const __nv_bfloat16* __restrict__ scales, const __nv_bfloat16* __restrict__ zeros, __nv_bfloat16* __restrict__ partials, int K, int N, int G, int hrpb) { const int tid = threadIdx.x; const int nt = blockDim.x; const int col0 = blockIdx.x * (nt * 4) + tid * 4; const int h0 = blockIdx.y * hrpb; const int g = h0 >> 6; float acc0 = 0.f, acc1 = 0.f, acc2 = 0.f, acc3 = 0.f, xsum = 0.f; const uint8_t* wp = w + (size_t)h0 * N + col0; const __nv_bfloat16* xp = x + 2 * h0; #pragma unroll 8 for (int i = 0; i < hrpb; ++i) { uint32_t v = *reinterpret_cast(wp + (size_t)i * N); float xe = __bfloat162float(__ldg(xp + 2*i)); float xo = __bfloat162float(__ldg(xp + 2*i + 1)); uint8_t b0 = (uint8_t)(v & 0xFF), b1 = (uint8_t)((v>>8)&0xFF), b2 = (uint8_t)((v>>16)&0xFF), b3 = (uint8_t)((v>>24)&0xFF); acc0 += xe * (float)(b0 & 0xF) + xo * (float)(b0 >> 4); acc1 += xe * (float)(b1 & 0xF) + xo * (float)(b1 >> 4); acc2 += xe * (float)(b2 & 0xF) + xo * (float)(b2 >> 4); acc3 += xe * (float)(b3 & 0xF) + xo * (float)(b3 >> 4); xsum += xe + xo; } float s0 = __bfloat162float(__ldg(scales + (size_t)g * N + col0)); float s1 = __bfloat162float(__ldg(scales + (size_t)g * N + col0 + 1)); float s2 = __bfloat162float(__ldg(scales + (size_t)g * N + col0 + 2)); float s3 = __bfloat162float(__ldg(scales + (size_t)g * N + col0 + 3)); float z0 = __bfloat162float(__ldg(zeros + (size_t)g * N + col0)); float z1 = __bfloat162float(__ldg(zeros + (size_t)g * N + col0 + 1)); float z2 = __bfloat162float(__ldg(zeros + (size_t)g * N + col0 + 2)); float z3 = __bfloat162float(__ldg(zeros + (size_t)g * N + col0 + 3)); __nv_bfloat16* pp = partials + (size_t)blockIdx.y * N + col0; pp[0] = __float2bfloat16(s0 * (acc0 - z0 * xsum)); pp[1] = __float2bfloat16(s1 * (acc1 - z1 * xsum)); pp[2] = __float2bfloat16(s2 * (acc2 - z2 * xsum)); pp[3] = __float2bfloat16(s3 * (acc3 - z3 * xsum)); } __global__ void reduce_kernel(const __nv_bfloat16* __restrict__ partials, __nv_bfloat16* __restrict__ out, int S, int N) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i >= N) return; float acc = 0.f; for (int s = 0; s < S; ++s) acc += __bfloat162float(partials[(size_t)s * N + i]); out[i] = __float2bfloat16(acc); } void launch(const void* x, const void* w, const void* scales, const void* zeros, void* partials, void* out, int K, int N, int G, int hrpb, int threads, void* stream) { int nb = N / (threads * 4); int S = (G * 64) / hrpb; dim3 grid(nb, S); cudaStream_t st = (cudaStream_t)stream; w4a16_gemv_kernel<<>>( (const __nv_bfloat16*)x, (const uint8_t*)w, (const __nv_bfloat16*)scales, (const __nv_bfloat16*)zeros, (__nv_bfloat16*)partials, K, N, G, hrpb); int rt = 256; reduce_kernel<<<(N + rt - 1)/rt, rt, 0, st>>>((const __nv_bfloat16*)partials, (__nv_bfloat16*)out, S, N); } } """ _GEMV_CPP = r""" #include #include extern "C" void launch(const void* x, const void* w, const void* scales, const void* zeros, void* partials, void* out, int K, int N, int G, int hrpb, int threads, void* stream); void gemv_launch(torch::Tensor x, torch::Tensor w, torch::Tensor scales, torch::Tensor zeros, torch::Tensor partials, torch::Tensor out, int64_t hrpb, int64_t threads) { launch(x.data_ptr(), w.data_ptr(), scales.data_ptr(), zeros.data_ptr(), partials.data_ptr(), out.data_ptr(), (int)x.numel(), (int)w.size(1), (int)scales.size(0), (int)hrpb, (int)threads, (void*)at::cuda::getCurrentCUDAStream()); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("gemv_launch", &gemv_launch); } """ _gemv_mod = None def _get_gemv_module(): global _gemv_mod if _gemv_mod is not None: return _gemv_mod from torch.utils.cpp_extension import load # Compile only for the device's arch (fast build, correct cubin). Force # (do not setdefault) so a pre-set multi-arch TORCH_CUDA_ARCH_LIST cannot # blow the build up into a 6-arch compile. cap = torch.cuda.get_device_capability(0) os.environ["TORCH_CUDA_ARCH_LIST"] = f"{cap[0]}.{cap[1]}" build_dir = Path(__file__).resolve().parent / "_w4a16_build" build_dir.mkdir(exist_ok=True) cu_path = build_dir / "gemv.cu" cpp_path = build_dir / "gemv.cpp" def _write_once(p: Path, content: str) -> None: if not p.exists() or p.read_text() != content: p.write_text(content) _write_once(cu_path, _GEMV_CUDA) _write_once(cpp_path, _GEMV_CPP) _gemv_mod = load( name="w4a16_gemv", sources=[str(cpp_path), str(cu_path)], extra_cuda_cflags=["-O3", "--use_fast_math"], verbose=False, ) return _gemv_mod class Model(nn.Module): """W4A16 GEMM: y = x @ dequant(w_q, scales, zeros).""" def __init__(self, M: int, N: int, K: int, group_size: int = GROUP_SIZE): super().__init__() assert K % group_size == 0, "K must be divisible by group_size" assert K % 2 == 0, "K must be even (int4 packing)" self.M, self.N, self.K = M, N, K self.group_size = group_size n_groups = K // group_size torch.manual_seed(0xC0DE ^ (M * 1315423911 + N * 2654435761 + K)) w_full = torch.randn(K, N, dtype=torch.float32) * 0.02 w_g = w_full.view(n_groups, group_size, N) w_min = w_g.min(dim=1, keepdim=True).values w_max = w_g.max(dim=1, keepdim=True).values scales = (w_max - w_min).clamp_min(1e-8) / 15.0 zeros = (-w_min / scales).round().clamp(0, 15) w_q = ((w_g / scales) + zeros).round().clamp(0, 15).to(torch.uint8) w_q = w_q.view(K, N) scales_2d = scales.squeeze(1).to(torch.bfloat16) zeros_2d = zeros.squeeze(1).to(torch.bfloat16) lo = w_q[0::2].to(torch.uint8) & 0xF hi = w_q[1::2].to(torch.uint8) & 0xF w_packed = (lo | (hi << 4)).contiguous() self.register_buffer("w_q", w_packed) self.register_buffer("scales", scales_2d) self.register_buffer("zeros", zeros_2d) # Decode (M == 1) launch parameters, precomputed once per model. n_groups = K // group_size self._hrpb = 16 if N <= 4096 else 32 self._threads = 128 if N <= 4096 else 256 self._S = (n_groups * 64) // self._hrpb self._gemv_partials = None self._gemv_launch = None self._out = None def _gemv(self, x: torch.Tensor, out: torch.Tensor) -> None: if self._gemv_launch is None: self._gemv_launch = _get_gemv_module().gemv_launch if self._gemv_partials is None or self._gemv_partials.shape[0] != self._S: self._gemv_partials = torch.empty( self._S, self.N, dtype=torch.bfloat16, device=x.device ) self._gemv_launch( x, self.w_q, self.scales, self.zeros, self._gemv_partials, out, self._hrpb, self._threads, ) def forward(self, x: torch.Tensor) -> torch.Tensor: M = x.shape[0] N = self.N if M == 1: out = self._out if out is None: out = torch.empty((1, N), dtype=torch.bfloat16, device=x.device) self._out = out launch = self._gemv_launch if launch is None: launch = _get_gemv_module().gemv_launch self._gemv_launch = launch partials = self._gemv_partials if partials is None: partials = torch.empty(self._S, N, dtype=torch.bfloat16, device=x.device) self._gemv_partials = partials launch(x, self.w_q, self.scales, self.zeros, partials, out, self._hrpb, self._threads) return out K = x.shape[1] out = torch.empty((M, N), dtype=torch.bfloat16, device=x.device) if M <= 16: BM, BN, BK, nw, ns = 16, 64, 128, 4, 4 elif M <= 32: BM, BN, BK, nw, ns = 32, 64, 128, 4, 4 else: BM, BN, BK, nw, ns = 64, 128, 64, 8, 4 grid = (triton.cdiv(M, BM), triton.cdiv(N, BN)) _w4a16_kernel[grid]( x, self.w_q, self.scales, self.zeros, out, M, N, K, GROUP_SIZE=GROUP_SIZE, BLOCK_M=BM, BLOCK_N=BN, BLOCK_K=BK, num_warps=nw, num_stages=ns, ) return out # Bypass nn.Module.__call__'s hook/tracing machinery: the harness calls the # model directly under torch.no_grad(), so a plain forward dispatch is safe # and shaves per-call Python overhead on the decode shapes. __call__ = forward M = 1 N = 12288 K = 4096 def get_inputs(): x = torch.randn(M, K, dtype=torch.bfloat16) return [x] def get_init_inputs(): return [M, N, K]