"""W4A16 weight-only quantized GEMM solution using Triton.""" from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl GROUP_SIZE = 128 @triton.autotune( configs=[ triton.Config({'BLOCK_SIZE_M': 16, 'BLOCK_SIZE_N': 128, 'BLOCK_SIZE_K': 64, 'num_warps': 4, 'num_stages': 3}), triton.Config({'BLOCK_SIZE_M': 32, 'BLOCK_SIZE_N': 128, 'BLOCK_SIZE_K': 64, 'num_warps': 4, 'num_stages': 3}), triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 128, 'BLOCK_SIZE_K': 64, 'num_warps': 4, 'num_stages': 3}), triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 128, 'BLOCK_SIZE_K': 128, 'num_warps': 4, 'num_stages': 3}), triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_N': 128, 'BLOCK_SIZE_K': 64, 'num_warps': 8, 'num_stages': 3}), triton.Config({'BLOCK_SIZE_M': 16, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 64, 'num_warps': 4, 'num_stages': 3}), triton.Config({'BLOCK_SIZE_M': 32, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 64, 'num_warps': 4, 'num_stages': 3}), ], key=['M', 'N', 'K'], ) @triton.jit def w4a16_gemm_kernel( # Pointers to matrices a_ptr, b_ptr, scales_ptr, zeros_ptr, c_ptr, # Matrix dimensions M, N, K, # Strides stride_am, stride_ak, stride_bk, stride_bn, stride_scales_g, stride_scales_n, stride_zeros_g, stride_zeros_n, stride_cm, stride_cn, # Meta-parameters BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr, GROUP_SIZE_K: tl.constexpr, ): # Program ID pid_m = tl.program_id(axis=0) pid_n = tl.program_id(axis=1) # Offsets offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M) offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) # Mask for M and N mask_m = offs_m < M mask_n = offs_n < N # Accumulator accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) # Loop over K # BLOCK_SIZE_K must be a power of 2 and <= 128 so it divides GROUP_SIZE_K (128). # offs_k_even and offs_k_odd relative to the block start offs_k_even_rel = tl.arange(0, BLOCK_SIZE_K // 2) * 2 offs_k_odd_rel = tl.arange(0, BLOCK_SIZE_K // 2) * 2 + 1 for k in range(0, K, BLOCK_SIZE_K): # Load A even and odd columns offs_k_even = k + offs_k_even_rel offs_k_odd = k + offs_k_odd_rel a_even = tl.load( a_ptr + offs_m[:, None] * stride_am + offs_k_even[None, :] * stride_ak, mask=(mask_m[:, None]) & (offs_k_even[None, :] < K), other=0.0 ) a_odd = tl.load( a_ptr + offs_m[:, None] * stride_am + offs_k_odd[None, :] * stride_ak, mask=(mask_m[:, None]) & (offs_k_odd[None, :] < K), other=0.0 ) # Load B (packed uint8) # B block size: (BLOCK_SIZE_K // 2, BLOCK_SIZE_N) offs_b_k = (k // 2) + tl.arange(0, BLOCK_SIZE_K // 2) b_tile_packed = tl.load( b_ptr + offs_b_k[:, None] * stride_bk + offs_n[None, :] * stride_bn, mask=(offs_b_k[:, None] < (K // 2)) & (mask_n[None, :]), other=0 ) # Unpack B b_lo = b_tile_packed & 0x0F b_hi = (b_tile_packed >> 4) & 0x0F # Load Scales and Zeros for this K block group_idx = k // GROUP_SIZE_K scale = tl.load(scales_ptr + group_idx * stride_scales_g + offs_n * stride_scales_n, mask=mask_n, other=0.0) zero = tl.load(zeros_ptr + group_idx * stride_zeros_g + offs_n * stride_zeros_n, mask=mask_n, other=0.0) # Dequantize B b_lo_dequant = (b_lo.to(tl.bfloat16) - zero[None, :]) * scale[None, :] b_hi_dequant = (b_hi.to(tl.bfloat16) - zero[None, :]) * scale[None, :] # Perform dot products and accumulate accumulator = tl.dot(a_even, b_lo_dequant.to(tl.bfloat16), acc=accumulator) accumulator = tl.dot(a_odd, b_hi_dequant.to(tl.bfloat16), acc=accumulator) # Store output C c_tile = accumulator.to(tl.bfloat16) c_out_ptr = c_ptr + offs_m[:, None] * stride_cm + offs_n[None, :] * stride_cn tl.store(c_out_ptr, c_tile, mask=mask_m[:, None] & mask_n[None, :]) 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, "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)) # uint8 self.register_buffer("scales", torch.zeros((n_groups, N), dtype=torch.bfloat16)) # bf16 self.register_buffer("zeros", torch.zeros((n_groups, N), dtype=torch.bfloat16)) # bf16 def forward(self, x: torch.Tensor) -> torch.Tensor: M, K = x.shape N = self.N # Output tensor out = torch.empty((M, N), dtype=torch.bfloat16, device=x.device) # Grid function for Triton grid = lambda META: ( triton.cdiv(M, META['BLOCK_SIZE_M']), triton.cdiv(N, META['BLOCK_SIZE_N']) ) # Launch kernel w4a16_gemm_kernel[grid]( x, self.w_q, self.scales, self.zeros, out, M, N, K, x.stride(0), x.stride(1), self.w_q.stride(0), self.w_q.stride(1), self.scales.stride(0), self.scales.stride(1), self.zeros.stride(0), self.zeros.stride(1), out.stride(0), out.stride(1), GROUP_SIZE_K=self.group_size ) return out 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]