"""W4A16 weight-only quantized GEMM with fused unpack+dequant+GEMM. AWQ/GPTQ-style scheme: x: (M, K) bf16 w_q: (K // 2, N) uint8 -- two int4 weights packed per byte scales: (K // group, N) bf16 zeros: (K // group, N) bf16 out: (M, N) bf16 Uses Triton to fuse unpack, dequant, and GEMM into a single kernel. """ from __future__ import annotations import torch import triton import triton.language as tl from torch import Tensor from torch.nn import Module OP_TYPE = "gemm_w4a16" SUPPORTED_PRECISIONS = ["int4_bf16"] HARDWARE_REQUIRED = ["RTX_PRO_6000", "H100", "B200"] GROUP_SIZE = 128 @triton.jit def _w4a16_gemm_kernel( x_ptr, w_q_ptr, scales_ptr, zeros_ptr, y_ptr, M, N, K, stride_xm, stride_xk, stride_wk, stride_wn, stride_sg, stride_sn, stride_zg, stride_zn, stride_ym, stride_yn, group_size, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, ): """Fused W4A16 GEMM kernel.""" 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_k = tl.arange(0, BLOCK_K) acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) for g_start in range(0, K, BLOCK_K): g_offset = g_start + offs_k g_mask = g_offset < K # Load x: (BLOCK_M, BLOCK_K) x = tl.load( x_ptr + offs_m[:, None] * stride_xm + g_offset[None, :] * stride_xk, mask=(offs_m[:, None] < M) & (g_offset[None, :] < K), other=0.0, ) # Load and unpack w_q k_packed = g_offset // 2 k_is_odd = (g_offset % 2).to(tl.int32) w_q_vals = tl.load( w_q_ptr + k_packed[:, None] * stride_wk + offs_n[None, :] * stride_wn, mask=(g_offset[:, None] < K) & (offs_n[None, :] < N), other=0, ).to(tl.uint8) # Unpack: low nibble for even k, high nibble for odd k w_int4 = tl.where( k_is_odd[:, None] == 1, ((w_q_vals >> 4) & 0xF).to(tl.float32), (w_q_vals & 0xF).to(tl.float32), ) # Load scales and zeros for this group group_id = g_start // group_size scales = tl.load( scales_ptr + group_id * stride_sg + offs_n * stride_sn, mask=offs_n < N, other=0.0, ).to(tl.float32) zeros = tl.load( zeros_ptr + group_id * stride_zg + offs_n * stride_zn, mask=offs_n < N, other=0.0, ).to(tl.float32) # Dequantize: (BLOCK_K, BLOCK_N) w_dequant = ((w_int4 - zeros[None, :]) * scales[None, :]).to(tl.bfloat16) # GEMM acc += tl.dot(x, w_dequant) # Store result tl.store( y_ptr + offs_m[:, None] * stride_ym + offs_n[None, :] * stride_yn, acc.to(tl.bfloat16), mask=(offs_m[:, None] < M) & (offs_n[None, :] < N), ) def w4a16_gemm(x: Tensor, w_q: Tensor, scales: Tensor, zeros: Tensor) -> Tensor: """Compute y = x @ dequant(w_q, scales, zeros).""" M, K = x.shape N = scales.shape[1] group_size = K // scales.shape[0] x = x.contiguous() w_q = w_q.contiguous() scales = scales.contiguous() zeros = zeros.contiguous() y = torch.empty((M, N), dtype=torch.bfloat16, device=x.device) # Use fixed block sizes - tuned for H100 if M == 1: BLOCK_M = 1 # Use smaller BLOCK_N for smaller N to improve occupancy BLOCK_N = 64 if N < 8192 else 128 BLOCK_K = 128 elif M <= 32: BLOCK_M = 32 BLOCK_N = 64 BLOCK_K = 128 elif M <= 128: BLOCK_M = 64 BLOCK_N = 64 BLOCK_K = 128 else: # For M=256, use larger BLOCK_M to better utilize tensor cores # torch.compile's autotuner found BM=128, BN=128, BK=64 to be best BLOCK_M = 128 BLOCK_N = 128 BLOCK_K = 64 grid = (triton.cdiv(M, BLOCK_M), triton.cdiv(N, BLOCK_N)) # Use more warps and stages for larger blocks if BLOCK_M >= 256 or BLOCK_N >= 128: num_warps = 8 num_stages = 4 else: num_warps = 4 num_stages = 2 _w4a16_gemm_kernel[grid]( x, w_q, scales, zeros, y, 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), y.stride(0), y.stride(1), group_size, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N, BLOCK_K=BLOCK_K, num_warps=num_warps, num_stages=num_stages, ) return y class Model(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) w_packed = _pack_int4(w_q) self.register_buffer("w_q", w_packed) self.register_buffer("scales", scales_2d) self.register_buffer("zeros", zeros_2d) def forward(self, x: Tensor) -> Tensor: return w4a16_gemm(x, self.w_q, self.scales, self.zeros) def _pack_int4(w_q: torch.Tensor) -> torch.Tensor: """Pack (K, N) uint8 in [0,15] into (K//2, N) uint8.""" K, N = w_q.shape assert K % 2 == 0 lo = w_q[0::2].to(torch.uint8) & 0xF hi = w_q[1::2].to(torch.uint8) & 0xF return (lo | (hi << 4)).contiguous() 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]