"""FP8 e4m3 GEMM via Triton TMA persistent kernel (Hopper tensor cores). y = (x @ weight.T) * weight_scale -> bf16 """ import torch import torch.nn as nn import triton import triton.language as tl E4M3_MAX = 448.0 _NUM_SMS = None def _num_sms(): global _NUM_SMS if _NUM_SMS is None: _NUM_SMS = torch.cuda.get_device_properties("cuda").multi_processor_count return _NUM_SMS def _tma_allocator(): def alloc_fn(size: int, alignment: int, stream: int | None): return torch.empty(size, device="cuda", dtype=torch.int8) triton.set_allocator(alloc_fn) @triton.jit def _compute_pid(tile_id, num_pid_in_group, num_pid_m, group_m: tl.constexpr): group_id = tile_id // num_pid_in_group first_pid_m = group_id * group_m group_size_m = min(num_pid_m - first_pid_m, group_m) pid_m = first_pid_m + (tile_id % group_size_m) pid_n = (tile_id % num_pid_in_group) // group_size_m return pid_m, pid_n @triton.jit def _fp8_gemm_tma_persistent_kernel( a_ptr, b_ptr, c_ptr, scale_ptr, M, N, K, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, GROUP_M: tl.constexpr, NUM_SMS: tl.constexpr, ): start_pid = tl.program_id(0) num_pid_m = tl.cdiv(M, BLOCK_M) num_pid_n = tl.cdiv(N, BLOCK_N) k_tiles = tl.cdiv(K, BLOCK_K) num_tiles = num_pid_m * num_pid_n num_pid_in_group = GROUP_M * num_pid_n a_desc = tl.make_tensor_descriptor( a_ptr, shape=[M, K], strides=[K, 1], block_shape=[BLOCK_M, BLOCK_K], ) b_desc = tl.make_tensor_descriptor( b_ptr, shape=[N, K], strides=[K, 1], block_shape=[BLOCK_N, BLOCK_K], ) c_desc = tl.make_tensor_descriptor( c_ptr, shape=[M, N], strides=[N, 1], block_shape=[BLOCK_M, BLOCK_N], ) tile_id_c = start_pid - NUM_SMS for tile_id in tl.range(start_pid, num_tiles, NUM_SMS, flatten=True): pid_m, pid_n = _compute_pid(tile_id, num_pid_in_group, num_pid_m, GROUP_M) offs_am = pid_m * BLOCK_M offs_bn = pid_n * BLOCK_N acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) for ki in range(k_tiles): offs_k = ki * BLOCK_K a = a_desc.load([offs_am, offs_k]) b = b_desc.load([offs_bn, offs_k]) acc = tl.dot(a, b.T, acc) tile_id_c += NUM_SMS pid_m, pid_n = _compute_pid(tile_id_c, num_pid_in_group, num_pid_m, GROUP_M) offs_cm = pid_m * BLOCK_M offs_cn = pid_n * BLOCK_N offs_n = offs_cn + tl.arange(0, BLOCK_N) scale = tl.load(scale_ptr + offs_n, mask=offs_n < N, other=1.0) acc = acc * scale[None, :] c = acc.to(tl.bfloat16) c_desc.store([offs_cm, offs_cn], c) def _pick_config(M: int, N: int, K: int): if M <= 64: return 32, 64, 128, 8, 4, 4 if N >= 12000: return 128, 256, 128, 8, 8, 3 return 128, 256, 128, 8, 8, 3 def fp8_gemm( x: torch.Tensor, weight: torch.Tensor, weight_scale: torch.Tensor, M: int | None = None, K: int | None = None, ) -> torch.Tensor: if M is None: M = x.shape[0] if K is None: K = x.shape[1] N = weight.shape[0] block_m, block_n, block_k, group_m, num_warps, num_stages = _pick_config(M, N, K) out = torch.empty((M, N), device=x.device, dtype=torch.bfloat16) num_tiles = triton.cdiv(M, block_m) * triton.cdiv(N, block_n) num_sms = _num_sms() _tma_allocator() grid = (min(num_sms, num_tiles),) _fp8_gemm_tma_persistent_kernel[grid]( x, weight, out, weight_scale, M, N, K, BLOCK_M=block_m, BLOCK_N=block_n, BLOCK_K=block_k, GROUP_M=group_m, NUM_SMS=min(num_sms, num_tiles), num_warps=num_warps, num_stages=num_stages, ) return out class Model(nn.Module): def __init__(self, M: int, N: int, K: int): super().__init__() self.M, self.N, self.K = M, N, K w = torch.empty(N, K, dtype=torch.bfloat16) nn.init.normal_(w, std=0.02) s = (w.float().abs().amax(dim=1, keepdim=True) / E4M3_MAX).clamp(min=1e-12) w_fp8 = (w.float() / s).to(torch.float8_e4m3fn) self.register_buffer("weight", w_fp8) self.register_buffer("weight_scale", s.squeeze(1).to(torch.float32)) _, _, block_k, _, _, _ = _pick_config(M, N, K) self.padded_k = ((K + block_k - 1) // block_k) * block_k self._w_pad_buf = None def _exec_weight(self) -> torch.Tensor: if self.padded_k == self.K: return self.weight if self._w_pad_buf is None: self._w_pad_buf = torch.zeros( self.N, self.padded_k, dtype=self.weight.dtype, device=self.weight.device ) self._w_pad_buf.zero_() self._w_pad_buf[:, : self.K] = self.weight return self._w_pad_buf def forward(self, x: torch.Tensor) -> torch.Tensor: k = self.padded_k if self.padded_k != self.K: x = torch.nn.functional.pad(x, (0, self.padded_k - self.K)) return fp8_gemm(x, self._exec_weight(), self.weight_scale, self.M, k) M = 4096 N = 4096 K = 4096 def get_inputs(): x = (torch.rand(M, K) * 8 - 4).to(torch.float8_e4m3fn) return [x] def get_init_inputs(): return [M, N, K]