"""FP8 e4m3 GEMM with per-channel dequant scale. Genuine fp8 x fp8 tensor-core GEMM via Triton tl.dot (fp8 inputs, fp32 accumulate), followed by multiplication with the per-output-channel weight_scale. """ import torch import torch.nn as nn import triton import triton.language as tl E4M3_MAX = 448.0 @triton.jit def fp8_gemm_splitk_kernel( x_ptr, w_ptr, s_ptr, y_ptr, M: tl.constexpr, N: tl.constexpr, K: tl.constexpr, stride_xm, stride_xk, stride_wn, stride_wk, stride_ym, stride_yn, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, GROUP_M: tl.constexpr, SPLIT_K: tl.constexpr, ): """C[m,n] = sum_k A[m,k] * B[n,k] * scale[n] with split-K.""" pid = tl.program_id(0) pid_k = tl.program_id(1) 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) K_per_split = tl.cdiv(K, SPLIT_K) k_start = pid_k * K_per_split k_end = min(k_start + K_per_split, K) num_blocks = tl.cdiv(k_end - k_start, BLOCK_K) offs_k = tl.arange(0, BLOCK_K) + k_start x_ptrs = x_ptr + (offs_m[:, None] * stride_xm + offs_k[None, :] * stride_xk) w_ptrs = w_ptr + (offs_n[:, None] * stride_wn + offs_k[None, :] * stride_wk) acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) for _ in range(0, num_blocks): x = tl.load(x_ptrs) w = tl.load(w_ptrs) acc = tl.dot(x, tl.trans(w), acc) x_ptrs += BLOCK_K * stride_xk w_ptrs += BLOCK_K * stride_wk # Apply per-channel scale (after partial reduction) scale = tl.load(s_ptr + offs_n, mask=offs_n < N, other=0.0) acc = acc * scale[None, :] y = acc.to(tl.bfloat16) y_ptrs = y_ptr + (offs_m[:, None] * stride_ym + offs_n[None, :] * stride_yn) y_mask = (offs_m[:, None] < M) & (offs_n[None, :] < N) tl.atomic_add(y_ptrs, y, mask=y_mask) @triton.jit def fp8_gemm_kernel( x_ptr, w_ptr, s_ptr, y_ptr, M: tl.constexpr, N: tl.constexpr, K: tl.constexpr, stride_xm, stride_xk, stride_wn, stride_wk, stride_ym, stride_yn, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, GROUP_M: tl.constexpr, ): """C[m,n] = sum_k A[m,k] * B[n,k] * scale[n].""" 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) x_ptrs = x_ptr + (offs_m[:, None] * stride_xm + offs_k[None, :] * stride_xk) w_ptrs = w_ptr + (offs_n[:, None] * stride_wn + offs_k[None, :] * stride_wk) acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) for k in range(0, tl.cdiv(K, BLOCK_K)): x = tl.load(x_ptrs) w = tl.load(w_ptrs) acc = tl.dot(x, tl.trans(w), acc) x_ptrs += BLOCK_K * stride_xk w_ptrs += BLOCK_K * stride_wk # Apply per-channel scale scale = tl.load(s_ptr + offs_n, mask=offs_n < N, other=0.0) acc = acc * scale[None, :] y = acc.to(tl.bfloat16) y_ptrs = y_ptr + (offs_m[:, None] * stride_ym + offs_n[None, :] * stride_yn) y_mask = (offs_m[:, None] < M) & (offs_n[None, :] < N) tl.store(y_ptrs, y, mask=y_mask) def pad_k(t: torch.Tensor, block_k: int) -> torch.Tensor: K = t.shape[-1] pad = (block_k - K % block_k) % block_k if pad == 0: return t return torch.nn.functional.pad(t, (0, pad)) def fp8_gemm(x: torch.Tensor, w: torch.Tensor, scale: torch.Tensor) -> torch.Tensor: M, K = x.shape N, K2 = w.shape assert K == K2 BLOCK_K = 128 # Pad K to multiple of BLOCK_K to avoid predicated slow path if K % BLOCK_K != 0: x = pad_k(x, BLOCK_K) w = pad_k(w, BLOCK_K) K = x.shape[1] y = torch.empty((M, N), device=x.device, dtype=torch.bfloat16) # skinny M: use split-K for parallelism if M <= 64 and N >= 4096 and K >= 4096: BLOCK_M = 32 BLOCK_N = 128 SPLIT_K = 16 y.zero_() grid = ( triton.cdiv(M, BLOCK_M) * triton.cdiv(N, BLOCK_N), SPLIT_K, ) fp8_gemm_splitk_kernel[grid]( x, w, scale, y, M, N, K, x.stride(0), x.stride(1), w.stride(0), w.stride(1), y.stride(0), y.stride(1), BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N, BLOCK_K=BLOCK_K, GROUP_M=1, SPLIT_K=SPLIT_K, num_warps=8, num_stages=3, ) return y # large square/rectangular if M >= 4096 and N >= 4096 and K >= 4096: cfg = {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 128, "GROUP_M": 8} else: cfg = {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 128, "GROUP_M": 8} grid = (triton.cdiv(M, cfg["BLOCK_M"]) * triton.cdiv(N, cfg["BLOCK_N"]),) fp8_gemm_kernel[grid]( x, w, scale, y, M, N, K, x.stride(0), x.stride(1), w.stride(0), w.stride(1), y.stride(0), y.stride(1), BLOCK_M=cfg["BLOCK_M"], BLOCK_N=cfg["BLOCK_N"], BLOCK_K=cfg["BLOCK_K"], GROUP_M=cfg["GROUP_M"], num_warps=8, num_stages=3, ) return y 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)) def forward(self, x: torch.Tensor) -> torch.Tensor: return fp8_gemm(x, self.weight, self.weight_scale) 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]