"""W4A16 weight-only quantized GEMM: fused int4 unpack + dequant + GEMM (Triton). AWQ/GPTQ-style asymmetric int4, group_size=128, per-group bf16 scale/zero. See reference.py for the exact dequant formula this must reproduce. Packing recap: w_q is (K//2, N) uint8; byte (kh, n) packs K-rows (2*kh, 2*kh+1) for column n (low nibble = even row, high nibble = odd row). Since group_size (128) is even, a packed row pair never straddles a group boundary, so each packed row kh belongs to exactly one group: group = kh // (group_size // 2). That lets the kernel loop over packed rows in chunks of (group_size // 2) and load one scale/zero pair per chunk instead of per element. """ from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl GROUP_SIZE = 128 @triton.jit def _w4a16_kernel( x_ptr, wq_ptr, scales_ptr, zeros_ptr, out_ptr, M, N, K, stride_xm, stride_xk, stride_wq_kh, stride_wq_n, stride_sg, stride_sn, stride_zg, stride_zn, stride_om, stride_on, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, GROUP_KH: tl.constexpr, ): pid_n = tl.program_id(0) pid_m = 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) mask_m = offs_m < M mask_n = offs_n < N offs_kh_local = tl.arange(0, GROUP_KH) acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) n_groups = K // (2 * GROUP_KH) for g in range(0, n_groups): kh0 = g * GROUP_KH offs_kh = kh0 + offs_kh_local wq_ptrs = wq_ptr + offs_kh[:, None] * stride_wq_kh + offs_n[None, :] * stride_wq_n packed = tl.load(wq_ptrs, mask=mask_n[None, :], other=0).to(tl.int32) lo = (packed & 0xF).to(tl.float32) hi = ((packed >> 4) & 0xF).to(tl.float32) s = tl.load(scales_ptr + g * stride_sg + offs_n * stride_sn, mask=mask_n, other=0.0).to(tl.float32) z = tl.load(zeros_ptr + g * stride_zg + offs_n * stride_zn, mask=mask_n, other=0.0).to(tl.float32) w_even = ((lo - z[None, :]) * s[None, :]).to(tl.bfloat16) w_odd = ((hi - z[None, :]) * s[None, :]).to(tl.bfloat16) k_even = 2 * offs_kh k_odd = k_even + 1 xe_ptrs = x_ptr + offs_m[:, None] * stride_xm + k_even[None, :] * stride_xk xo_ptrs = x_ptr + offs_m[:, None] * stride_xm + k_odd[None, :] * stride_xk xe = tl.load(xe_ptrs, mask=mask_m[:, None], other=0.0) xo = tl.load(xo_ptrs, mask=mask_m[:, None], other=0.0) acc = tl.dot(xe, w_even, acc) acc = tl.dot(xo, w_odd, acc) out = acc.to(tl.bfloat16) out_ptrs = out_ptr + offs_m[:, None] * stride_om + offs_n[None, :] * stride_on tl.store(out_ptrs, out, mask=mask_m[:, None] & mask_n[None, :]) # Empirically tuned (ncu + microbenchmark sweep) per-shape configs. block_m=16 # (one 16-row MMA tile) wins even when M is larger: it keeps the fp32 # accumulator small enough to avoid register spills (>128 regs/thread with # bigger tiles pushed occupancy to ~17%, see scratch/ncu_m256*.ncu-rep), and # the resulting grid is large enough to cover all SMs. The "wasted" weight # re-reads across M-tiles are absorbed by L2 (24MB weight matrix, 128MB L2) -- # DRAM throughput measured well under peak in every config, so this isn't a # bandwidth trade-off, it's a pure occupancy win. _TUNED_CONFIGS = { (1, 12288, 4096): dict(block_m=16, block_n=128, num_warps=8, num_stages=4), (32, 12288, 4096): dict(block_m=16, block_n=128, num_warps=8, num_stages=4), (256, 12288, 4096): dict(block_m=16, block_n=256, num_warps=4, num_stages=3), (1, 4096, 4096): dict(block_m=16, block_n=64, num_warps=4, num_stages=8), (16, 14336, 4096): dict(block_m=16, block_n=64, num_warps=4, num_stages=3), } def _pick_config(M: int, N: int, K: int) -> dict: cfg = _TUNED_CONFIGS.get((M, N, K)) if cfg is not None: return cfg # Fallback heuristic for shapes outside the tuned set. block_n = 64 if N <= 4096 else 128 num_warps = 8 if M <= 16 else 4 return dict(block_m=16, block_n=block_n, num_warps=num_warps, num_stages=4) def _w4a16_gemm(x, w_q, scales, zeros, K, N, block_m, block_n, num_warps, num_stages): M = x.shape[0] out = torch.empty((M, N), device=x.device, dtype=torch.bfloat16) grid = (triton.cdiv(N, block_n), triton.cdiv(M, block_m)) _w4a16_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), BLOCK_M=block_m, BLOCK_N=block_n, GROUP_KH=GROUP_SIZE // 2, num_warps=num_warps, num_stages=num_stages, ) return out class Model(nn.Module): """W4A16 GEMM: y = x @ dequant(w_q, scales, zeros), fused in one kernel.""" 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 self.register_buffer("w_q", torch.zeros(K // 2, N, dtype=torch.uint8)) self.register_buffer("scales", torch.zeros(n_groups, N, dtype=torch.bfloat16)) self.register_buffer("zeros", torch.zeros(n_groups, N, dtype=torch.bfloat16)) self._cfg = _pick_config(M, N, K) def forward(self, x: torch.Tensor) -> torch.Tensor: x = x.contiguous() return _w4a16_gemm(x, self.w_q, self.scales, self.zeros, self.K, self.N, **self._cfg) 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]