"""Fused W4A16 GEMM (AWQ/GPTQ-style asymmetric int4, bf16 activations). The kernel fuses int4 unpacking, per-group dequantization (scale/zero), and bf16 GEMM in one pass. It is implemented in Triton and targets Hopper (SM90). """ from __future__ import annotations 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.jit def w4a16_gemv_kernel( x_ptr, w_ptr, s_ptr, z_ptr, out_ptr, N, K, n_groups, stride_xk, stride_wk, stride_wn, stride_sg, stride_sn, stride_zg, stride_zn, stride_on, BLOCK_N: tl.constexpr, GROUP_SIZE: tl.constexpr, ): """Specialized M == 1 GEMV: y = x @ dequant(w_q, scales, zeros).""" pid_n = tl.program_id(0) offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) offs_kp = tl.arange(0, GROUP_SIZE // 2) mask_n = offs_n < N acc = tl.zeros((BLOCK_N,), dtype=tl.float32) for g in range(n_groups): k_base = g * GROUP_SIZE scale = tl.load( s_ptr + g * stride_sg + offs_n * stride_sn, mask=mask_n, other=0.0, ).to(tl.bfloat16) zero = tl.load( z_ptr + g * stride_zg + offs_n * stride_zn, mask=mask_n, other=0.0, ).to(tl.bfloat16) w_ptrs = ( w_ptr + (k_base // 2 + offs_kp[:, None]) * stride_wk + offs_n[None, :] * stride_wn ) w_packed = tl.load(w_ptrs, mask=mask_n[None, :], other=0) w_lo = (w_packed & 0xF).to(tl.bfloat16) w_hi = ((w_packed >> 4) & 0xF).to(tl.bfloat16) w_lo = (w_lo - zero[None, :]) * scale[None, :] w_hi = (w_hi - zero[None, :]) * scale[None, :] x_even = tl.load(x_ptr + (k_base + 2 * offs_kp) * stride_xk) x_odd = tl.load(x_ptr + (k_base + 2 * offs_kp + 1) * stride_xk) prod = x_even[:, None] * w_lo + x_odd[:, None] * w_hi acc += tl.sum(prod.to(tl.float32), axis=0) tl.store(out_ptr + offs_n, acc.to(tl.bfloat16), mask=mask_n) @triton.jit def w4a16_gemm_kernel( x_ptr, w_ptr, s_ptr, z_ptr, out_ptr, M, N, K, n_groups, stride_xm, stride_xk, stride_wk, stride_wn, stride_sg, stride_sn, stride_zg, stride_zn, stride_om, stride_on, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, GROUP_SIZE: tl.constexpr, ): """Compute y = x @ dequant(w_q, scales, zeros) for one (M, N) tile.""" 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_kp = tl.arange(0, GROUP_SIZE // 2) mask_m = offs_m < M mask_n = offs_n < N acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) for g in range(n_groups): k_base = g * GROUP_SIZE # Per-group scale/zero broadcast over the K tile. scale = tl.load( s_ptr + g * stride_sg + offs_n[None, :] * stride_sn, mask=mask_n[None, :], other=0.0, ).to(tl.bfloat16) zero = tl.load( z_ptr + g * stride_zg + offs_n[None, :] * stride_zn, mask=mask_n[None, :], other=0.0, ).to(tl.bfloat16) # Packed int4 weights: half_k rows, each row holds an even/odd pair. w_ptrs = ( w_ptr + (k_base // 2 + offs_kp[:, None]) * stride_wk + offs_n[None, :] * stride_wn ) w_packed = tl.load(w_ptrs, mask=mask_n[None, :], other=0) w_lo = (w_packed & 0xF).to(tl.bfloat16) w_hi = ((w_packed >> 4) & 0xF).to(tl.bfloat16) w_lo = (w_lo - zero) * scale w_hi = (w_hi - zero) * scale # Even-K rows of x paired with the low nibble weights. x_even_ptrs = ( x_ptr + offs_m[:, None] * stride_xm + (k_base + 2 * offs_kp[None, :]) * stride_xk ) x_even = tl.load(x_even_ptrs, mask=mask_m[:, None], other=0.0) acc += tl.dot(x_even, w_lo) # Odd-K rows of x paired with the high nibble weights. x_odd_ptrs = ( x_ptr + offs_m[:, None] * stride_xm + (k_base + 2 * offs_kp[None, :] + 1) * stride_xk ) x_odd = tl.load(x_odd_ptrs, mask=mask_m[:, None], other=0.0) acc += tl.dot(x_odd, w_hi) out_ptrs = ( out_ptr + offs_m[:, None] * stride_om + offs_n[None, :] * stride_on ) tl.store( out_ptrs, acc.to(tl.bfloat16), mask=mask_m[:, None] & mask_n[None, :], ) def w4a16_gemm(x: torch.Tensor, w_q: torch.Tensor, scales: torch.Tensor, zeros: torch.Tensor, group_size: int = GROUP_SIZE) -> torch.Tensor: M, K = x.shape Kh, N = w_q.shape assert Kh * 2 == K assert K % group_size == 0 n_groups = K // group_size out = torch.empty((M, N), dtype=torch.bfloat16, device=x.device) if M == 1: BLOCK_N = 256 grid = (triton.cdiv(N, BLOCK_N),) w4a16_gemv_kernel[grid]( x, w_q, scales, zeros, out, N, K, n_groups, 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), BLOCK_N=BLOCK_N, GROUP_SIZE=group_size, num_warps=8, ) return out # Choose tile sizes based on the batch dimension. Decode-like shapes use # thin M tiles to expose enough parallelism across N. if M <= 16: BLOCK_M = 16 BLOCK_N = 128 else: BLOCK_M = 32 BLOCK_N = 128 grid = (triton.cdiv(M, BLOCK_M), triton.cdiv(N, BLOCK_N), 1) w4a16_gemm_kernel[grid]( x, w_q, scales, zeros, out, M, N, K, n_groups, 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), BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N, GROUP_SIZE=group_size, num_warps=8, ) return out 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) 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: torch.Tensor) -> torch.Tensor: return w4a16_gemm(x.to(torch.bfloat16), self.w_q, self.scales, self.zeros, self.group_size) def _pack_int4(w_q: torch.Tensor) -> torch.Tensor: 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]