"""FP8 e4m3 GEMM: Triton tl.dot tensor-core kernel for B200 (SM100). y = (x @ weight.T) * weight_scale -> bf16 x: (M, K) fp8_e4m3, weight: (N, K) fp8_e4m3, weight_scale: (N,) fp32 Real fp8 x fp8 MMA via tl.dot (fp32 accumulate), per-channel scale in epilogue. Optimizations: - tl.dot(..., max_num_imprecise_acc=16) — large SM100 fp8 MMA speedup - K zero-padded to BLOCK_K (predicated K-tails are catastrophic on Triton) - Padded weight cached; invalidated via tensor._version (stress-safe, no sync) - Shape-specific tiles (fat vs decode-skinny) """ from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl E4M3_MAX = 448.0 @triton.jit def _fp8_gemm_kernel( A_ptr, B_ptr, C_ptr, scale_ptr, M, N, K, stride_am, stride_ak, stride_bn, stride_bk, stride_cm, stride_cn, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, GROUP_M: tl.constexpr, IMP: tl.constexpr, ): pid = tl.program_id(0) num_pid_m = tl.cdiv(M, BLOCK_M) num_pid_n = tl.cdiv(N, BLOCK_N) num_pid_in_group = GROUP_M * num_pid_n group_id = pid // 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 + (pid % group_size_m) pid_n = (pid % num_pid_in_group) // group_size_m offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) offs_k = tl.arange(0, BLOCK_K) a_ptrs = A_ptr + offs_m[:, None] * stride_am + offs_k[None, :] * stride_ak b_ptrs = B_ptr + offs_n[:, None] * stride_bn + offs_k[None, :] * stride_bk acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) for _k in range(0, tl.cdiv(K, BLOCK_K)): a = tl.load(a_ptrs, mask=offs_m[:, None] < M, other=0.0) b = tl.load(b_ptrs, mask=offs_n[:, None] < N, other=0.0) acc = tl.dot(a, tl.trans(b), acc, max_num_imprecise_acc=IMP) a_ptrs += BLOCK_K * stride_ak b_ptrs += BLOCK_K * stride_bk scales = tl.load(scale_ptr + offs_n, mask=offs_n < N, other=0.0) acc = acc * scales[None, :] c = acc.to(tl.bfloat16) c_ptrs = C_ptr + offs_m[:, None] * stride_cm + offs_n[None, :] * stride_cn tl.store(c_ptrs, c, mask=(offs_m[:, None] < M) & (offs_n[None, :] < N)) def _pick_config(M: int, N: int, K: int): """(BLOCK_M, BLOCK_N, BLOCK_K, GROUP_M, num_warps, num_stages, IMP).""" if M <= 32: # Decode-style: large BLOCK_K streams the weight matrix return 16, 128, 512, 1, 8, 4, 32 if M <= 128: return 32, 64, 256, 1, 4, 5, 32 # Fat / prefill — most stable high-TFLOPS tile on B200 return 128, 256, 128, 8, 8, 4, 16 class Model(nn.Module): """y = ((x @ w.T) * weight_scale).to(bf16).""" 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)) self._cfg = _pick_config(M, N, K) BK = self._cfg[2] align = max(128, BK) self._Kp = ((K + align - 1) // align) * align self._x_pad = None self._w_pad = None self._w_pad_ver = -1 self._w_pad_ptr = 0 self._out = None def _padded_weight(self) -> torch.Tensor: K, Kp = self.K, self._Kp if K == Kp: w = self.weight return w if w.is_contiguous() else w.contiguous() ver = self.weight._version ptr = self.weight.data_ptr() if ( self._w_pad is None or self._w_pad.shape != (self.N, Kp) or self._w_pad_ver != ver or self._w_pad_ptr != ptr ): if self._w_pad is None or self._w_pad.shape != (self.N, Kp): self._w_pad = torch.zeros( self.N, Kp, device=self.weight.device, dtype=self.weight.dtype ) self._w_pad[:, :K].copy_(self.weight) self._w_pad_ver = ver self._w_pad_ptr = ptr return self._w_pad def _padded_x(self, x: torch.Tensor) -> torch.Tensor: K, Kp = x.shape[1], self._Kp M = x.shape[0] if K == Kp: return x if x.is_contiguous() else x.contiguous() if self._x_pad is None or self._x_pad.shape != (M, Kp): self._x_pad = torch.zeros(M, Kp, device=x.device, dtype=x.dtype) self._x_pad[:, :K].copy_(x) return self._x_pad def forward(self, x: torch.Tensor) -> torch.Tensor: M = x.shape[0] N = self.N Kp = self._Kp BM, BN, BK, GM, warps, stages, imp = self._cfg x_p = self._padded_x(x) w_p = self._padded_weight() scale = self.weight_scale if scale.dtype != torch.float32 or not scale.is_contiguous(): scale = scale.float().contiguous() if self._out is None or self._out.shape != (M, N) or self._out.device != x.device: self._out = torch.empty(M, N, device=x.device, dtype=torch.bfloat16) out = self._out grid = (triton.cdiv(M, BM) * triton.cdiv(N, BN),) _fp8_gemm_kernel[grid]( x_p, w_p, out, scale, M, N, Kp, x_p.stride(0), x_p.stride(1), w_p.stride(0), w_p.stride(1), out.stride(0), out.stride(1), BLOCK_M=BM, BLOCK_N=BN, BLOCK_K=BK, GROUP_M=GM, IMP=imp, num_warps=warps, num_stages=stages, ) return out 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]