"""Fused W4A16 GEMM: unpack int4 weights, apply asymmetric scale/zero, and matmul. Triton implementation using bf16 tensor-core dot products. Each 128-element K group is split into even/odd rows (low/high int4 nibbles). Two consecutive groups are processed per tile so the dot K dimension is 128. """ 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_gemm_kernel( x_ptr, w_ptr, s_ptr, z_ptr, out_ptr, M, N, K, Khalf, n_groups, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, GROUP_SIZE: tl.constexpr, BLOCK_KHALF: tl.constexpr, GROUPS_PER_TILE: tl.constexpr, KH_TILE: tl.constexpr, ): 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) mask_m = offs_m < M mask_n = offs_n < N acc = tl.zeros((BLOCK_M, BLOCK_N), tl.float32) n_tiles = (n_groups + GROUPS_PER_TILE - 1) // GROUPS_PER_TILE for t in range(n_tiles): g0 = t * GROUPS_PER_TILE k0 = g0 * GROUP_SIZE # Load even/odd activations for this tile. The packed weight byte at # Khalf index i holds the even row in the low nibble and the odd row in # the high nibble, corresponding to x[:, k0 + 2*i] and x[:, k0 + 2*i + 1]. i = tl.arange(0, KH_TILE) x_even = tl.load( x_ptr + offs_m[:, None] * K + (k0 + 2 * i[None, :]), mask=mask_m[:, None] & ((k0 + 2 * i[None, :]) < K), other=0.0, ).to(tl.bfloat16) x_odd = tl.load( x_ptr + offs_m[:, None] * K + (k0 + 2 * i[None, :] + 1), mask=mask_m[:, None] & ((k0 + 2 * i[None, :] + 1) < K), other=0.0, ).to(tl.bfloat16) # Load packed weights for KH_TILE packed rows. kh0 = g0 * BLOCK_KHALF w_offs_k = kh0 + tl.arange(0, KH_TILE) w_packed = tl.load( w_ptr + w_offs_k[:, None] * N + offs_n[None, :], mask=(w_offs_k[:, None] < Khalf) & mask_n[None, :], other=0, ) lo = (w_packed & 0xF).to(tl.bfloat16) hi = ((w_packed >> 4) & 0xF).to(tl.bfloat16) # Asymmetric dequant per group. `row_g` selects the right scale/zero for # each 64-row sub-block inside the tile. row_g = (tl.arange(0, KH_TILE)[:, None] // BLOCK_KHALF).to(tl.int32) s = tl.load( s_ptr + (g0 + row_g) * N + offs_n[None, :], mask=(w_offs_k[:, None] < Khalf) & mask_n[None, :], other=0.0, ).to(tl.bfloat16) z = tl.load( z_ptr + (g0 + row_g) * N + offs_n[None, :], mask=(w_offs_k[:, None] < Khalf) & mask_n[None, :], other=0.0, ).to(tl.bfloat16) w0 = (lo - z) * s w1 = (hi - z) * s acc = tl.dot(x_even, w0, acc, allow_tf32=False) acc = tl.dot(x_odd, w1, acc, allow_tf32=False) tl.store( out_ptr + offs_m[:, None] * N + offs_n[None, :], acc.to(tl.bfloat16), mask=mask_m[:, None] & mask_n[None, :], ) def _w4a16_gemm(x, w_q, scales, zeros, group_size): M, K = x.shape Khalf, N = w_q.shape assert Khalf * 2 == K and K % group_size == 0 n_groups = K // group_size out = torch.empty((M, N), dtype=torch.bfloat16, device=x.device) # Tuning: one group per tile (KH_TILE=64) is fastest on this hardware. # Decode-latency shapes use narrower N tiles for more blocks; compute # shapes use 128x32 tiles. groups_per_tile = 1 kh_tile = group_size // 2 if M == 1: block_m = 1 block_n = 64 else: block_m = min(M, 32) block_n = 128 grid = (triton.cdiv(M, block_m), triton.cdiv(N, block_n)) _w4a16_gemm_kernel[grid]( x, w_q, scales, zeros, out, M, N, K, Khalf, n_groups, BLOCK_M=block_m, BLOCK_N=block_n, GROUP_SIZE=group_size, BLOCK_KHALF=group_size // 2, GROUPS_PER_TILE=groups_per_tile, KH_TILE=kh_tile, num_stages=1, ) return out 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 assert K % 2 == 0 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) w_q = ((w_q[0::2] & 0xF) | ((w_q[1::2] & 0xF) << 4)).contiguous() self.register_buffer("w_q", w_q) self.register_buffer("scales", scales.squeeze(1).to(torch.bfloat16)) self.register_buffer("zeros", zeros.squeeze(1).to(torch.bfloat16)) 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) 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]