"""FP8 e4m3 GEMM for SM120 (RTX PRO 6000 Blackwell). y = (x @ weight.T) * weight_scale, x fp8_e4m3 (M,K), weight fp8_e4m3 (N,K), weight_scale fp32 (N,), output bf16 (M,N). Primary path: CUTLASS 3.x SM120 TMA warp-specialized kernels (see fp8_gemm_sm120.cu) running genuine e4m3 x e4m3 tensor-core MMA with fp32 accumulation; the per-output-channel dequant scale is fused into the epilogue via an EVT (D = s[n] * acc). Compiled with torch.utils.cpp_extension at import (cached in .ext_build). Fallback path (if the extension can't build): Triton kernel doing the same math with tl.dot on fp8 operands (mma.sync...e4m3.e4m3.f32). K not divisible by 16 (e.g. 4127): rows are not 16B aligned, which breaks both TMA and vectorized cp.async loads. Both operands are zero-padded along K to a multiple of 64; zeros contribute nothing to the accumulator. The padded weight is cached keyed on (data_ptr, _version) so it is rebuilt whenever the harness mutates the weight in place. """ import os import torch import torch.nn as nn import triton import triton.language as tl E4M3_MAX = 448.0 _HERE = os.path.dirname(os.path.abspath(__file__)) # ============================================================================ # CUTLASS extension (primary path) # ============================================================================ _CUTLASS_EXT = None def _try_load_cutlass(): global _CUTLASS_EXT if _CUTLASS_EXT is not None: return _CUTLASS_EXT try: from torch.utils.cpp_extension import load src = os.path.join(_HERE, "fp8_gemm_sm120.cu") cutlass_inc = os.path.join(_HERE, "cutlass", "include") if not (os.path.exists(src) and os.path.exists(cutlass_inc)): return None build_dir = os.path.join(_HERE, ".ext_build") os.makedirs(build_dir, exist_ok=True) srcs = [src] + [ os.path.join(_HERE, f"fp8_cfgs_{t}.cu") for t in ("a", "b", "c") ] mod = load( name="fp8_gemm_sm120", sources=srcs, extra_cuda_cflags=[ "-O3", "-std=c++17", "-DNDEBUG", "--generate-code=arch=compute_120a,code=[sm_120a]", "--expt-relaxed-constexpr", "-Xcompiler=-fno-strict-aliasing", ], extra_include_paths=[ cutlass_inc, os.path.join(_HERE, "cutlass", "tools", "util", "include"), ], build_directory=build_dir, verbose=False, ) # Self-test on a tiny problem before trusting it. xt = (torch.randn(64, 64, device="cuda") * 0.3).to(torch.float8_e4m3fn) wt = (torch.randn(64, 64, device="cuda") * 0.3).to(torch.float8_e4m3fn) st = torch.rand(64, device="cuda").float() yt = mod.fp8_gemm(xt, wt, st, 0, 0, 1) ref = (xt.to(torch.bfloat16) @ wt.to(torch.bfloat16).T).float() * st[None, :] if not torch.allclose(yt.float(), ref, atol=0.1, rtol=0.1): return None _CUTLASS_EXT = mod return mod except Exception: return None # ============================================================================ # Triton fallback kernels # ============================================================================ def _gemm_configs(): cfgs = [] for bm, bn, bk, s, w in [ (128, 128, 64, 4, 4), (128, 256, 64, 3, 8), (256, 128, 64, 3, 8), (128, 128, 128, 3, 8), ]: cfgs.append(triton.Config( {"BLOCK_M": bm, "BLOCK_N": bn, "BLOCK_K": bk, "GROUP_M": 8}, num_stages=s, num_warps=w)) return cfgs @triton.autotune(configs=_gemm_configs(), key=["M", "N", "K"]) @triton.jit def _fp8_gemm_kernel( A, B, S, C, M, N, K, stride_am, stride_bn, stride_cm, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, GROUP_M: 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 % num_pid_in_group) % group_size_m) pid_n = (pid % num_pid_in_group) // group_size_m rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) rk = tl.arange(0, BLOCK_K) rm_c = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) rn_c = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) a_ptrs = A + rm_c[:, None] * stride_am + rk[None, :] b_ptrs = B + rn_c[None, :] * stride_bn + rk[:, None] acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) k_full = K // BLOCK_K for _ in range(0, k_full): a = tl.load(a_ptrs) b = tl.load(b_ptrs) acc = tl.dot(a, b, acc) a_ptrs += BLOCK_K b_ptrs += BLOCK_K k_tail = K - k_full * BLOCK_K if k_tail > 0: a = tl.load(a_ptrs, mask=rk[None, :] < k_tail, other=0.0) b = tl.load(b_ptrs, mask=rk[:, None] < k_tail, other=0.0) acc = tl.dot(a, b, acc) s = tl.load(S + rn, mask=rn < N, other=0.0).to(tl.float32) acc = acc * s[None, :] c = acc.to(tl.bfloat16) c_ptrs = C + rm[:, None] * stride_cm + rn[None, :] tl.store(c_ptrs, c, mask=(rm[:, None] < M) & (rn[None, :] < N)) def _splitk_configs(): cfgs = [] for bm, bn, bk, s, w in [ (32, 128, 256, 2, 4), (32, 128, 128, 3, 4), (32, 256, 128, 2, 4), (64, 128, 128, 3, 4), ]: cfgs.append(triton.Config( {"BLOCK_M": bm, "BLOCK_N": bn, "BLOCK_K": bk}, num_stages=s, num_warps=w)) return cfgs @triton.autotune(configs=_splitk_configs(), key=["M", "N", "K", "SPLIT_K"]) @triton.jit def _fp8_gemm_splitk_kernel( A, B, P, M, N, K, stride_am, stride_bn, k_per_split, SPLIT_K, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, ): pid = tl.program_id(0) pid_z = tl.program_id(1) num_pid_n = tl.cdiv(N, BLOCK_N) pid_m = pid // num_pid_n pid_n = pid % num_pid_n k_start = pid_z * k_per_split k_end = tl.minimum(k_start + k_per_split, K) rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) rk = tl.arange(0, BLOCK_K) rm_c = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) rn_c = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) a_ptrs = A + rm_c[:, None] * stride_am + (k_start + rk)[None, :] b_ptrs = B + rn_c[None, :] * stride_bn + (k_start + rk)[:, None] acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) k_len = k_end - k_start k_full = k_len // BLOCK_K for _ in range(0, k_full): a = tl.load(a_ptrs) b = tl.load(b_ptrs) acc = tl.dot(a, b, acc) a_ptrs += BLOCK_K b_ptrs += BLOCK_K k_tail = k_len - k_full * BLOCK_K if k_tail > 0: a = tl.load(a_ptrs, mask=rk[None, :] < k_tail, other=0.0) b = tl.load(b_ptrs, mask=rk[:, None] < k_tail, other=0.0) acc = tl.dot(a, b, acc) p_ptrs = P + pid_z.to(tl.int64) * M * N + rm[:, None] * N + rn[None, :] tl.store(p_ptrs, acc, mask=(rm[:, None] < M) & (rn[None, :] < N)) @triton.jit def _splitk_reduce_kernel( P, S, C, M, N, SPLIT_K: tl.constexpr, BLOCK: tl.constexpr, ): pid = tl.program_id(0) offs = pid * BLOCK + tl.arange(0, BLOCK) total = M * N mask = offs < total acc = tl.zeros((BLOCK,), dtype=tl.float32) total64 = total.to(tl.int64) for z in tl.static_range(SPLIT_K): acc += tl.load(P + z * total64 + offs, mask=mask, other=0.0) n_idx = offs % N s = tl.load(S + n_idx, mask=mask, other=0.0).to(tl.float32) tl.store(C + offs, (acc * s).to(tl.bfloat16), mask=mask) def _triton_gemm(x, w, s, M, N, K): c = torch.empty(M, N, dtype=torch.bfloat16, device=x.device) if M <= 64 and K >= 2048: n_tiles = triton.cdiv(N, 128) split_k = 1 while split_k < 8 and n_tiles * split_k * 2 <= 376 and K // (split_k * 2) >= 1024: split_k *= 2 k_per_split = triton.cdiv(K, split_k * 256) * 256 split_k = triton.cdiv(K, k_per_split) p = torch.empty(split_k, M, N, dtype=torch.float32, device=x.device) grid = lambda meta: ( triton.cdiv(M, meta["BLOCK_M"]) * triton.cdiv(N, meta["BLOCK_N"]), split_k, ) _fp8_gemm_splitk_kernel[grid]( x, w, p, M, N, K, x.stride(0), w.stride(0), k_per_split, split_k, ) BLOCK = 1024 _splitk_reduce_kernel[(triton.cdiv(M * N, BLOCK),)]( p, s, c, M, N, SPLIT_K=split_k, BLOCK=BLOCK, num_warps=8, ) else: grid = lambda meta: ( triton.cdiv(M, meta["BLOCK_M"]) * triton.cdiv(N, meta["BLOCK_N"]), ) _fp8_gemm_kernel[grid]( x, w, s, c, M, N, K, x.stride(0), w.stride(0), c.stride(0), ) return c # ============================================================================ # Host-side driver # ============================================================================ def _pad_k(t: torch.Tensor, K_pad: int) -> torch.Tensor: """Zero-pad a (R, K) fp8 tensor along K to K_pad.""" R, K = t.shape out = torch.empty(R, K_pad, dtype=t.dtype, device=t.device) ob = out.view(torch.uint8) ob[:, K:].zero_() ob[:, :K].copy_(t.view(torch.uint8)) return out class Model(nn.Module): """y = ((x @ w.T) * weight_scale).to(bf16) with a custom fp8 MMA kernel.""" 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) # (N, K) fp8 self.register_buffer("weight_scale", s.squeeze(1).to(torch.float32)) # (N,) self._wpad_cache = None # (key, padded_weight) self._graphs = {} # key -> (CUDAGraph, out tensor) self._key_hits = {} def _padded_weight(self, K_pad: int) -> torch.Tensor: w = self.weight key = (w.data_ptr(), w._version, K_pad) if self._wpad_cache is not None and self._wpad_cache[0] == key: return self._wpad_cache[1] wp = _pad_k(w.contiguous(), K_pad) self._wpad_cache = (key, wp) return wp def _forward_impl(self, x: torch.Tensor) -> torch.Tensor: w = self.weight s = self.weight_scale M, K = x.shape N = w.size(0) if not x.is_contiguous(): x = x.contiguous() if K % 16 != 0: K_eff = ((K + 63) // 64) * 64 x = _pad_k(x, K_eff) w = self._padded_weight(K_eff) else: K_eff = K if not w.is_contiguous(): w = w.contiguous() ext = _try_load_cutlass() if ext is not None: if M <= 64: impl, sw, sp = 11, 0, 1 # pingpong 64x64x256 elif N >= 8192: impl, sw, sp = 3, 8, 1 # coop 128x256x64, wide N else: impl, sw, sp = 3, 1, 1 # coop 128x256x64 ov = os.environ.get("FP8_IMPL_OVERRIDE") if ov: impl, sw, sp = (int(v) for v in ov.split(",")) return ext.fp8_gemm(x, w, s, impl, sw, sp) return _triton_gemm(x, w, s, M, N, K_eff) def forward(self, x: torch.Tensor) -> torch.Tensor: # CUDA-graph repeated identical calls (same input buffer / weights) to # remove launch latency; replays read live memory so in-place updates # to x/weight contents are reflected. Any change of pointer, shape, or # weight version changes the key. if (not x.is_cuda) or torch.cuda.is_current_stream_capturing(): return self._forward_impl(x) w, ws = self.weight, self.weight_scale key = (x.data_ptr(), tuple(x.shape), tuple(x.stride()), w.data_ptr(), w._version, ws.data_ptr(), ws._version) entry = self._graphs.get(key) if entry is not None: g, out = entry g.replay() return out if len(self._key_hits) > 256: self._key_hits.clear() hits = self._key_hits.get(key, 0) + 1 self._key_hits[key] = hits if hits < 3 or len(self._graphs) >= 8: return self._forward_impl(x) try: g = torch.cuda.CUDAGraph() with torch.cuda.graph(g): out = self._forward_impl(x) self._graphs[key] = (g, out) g.replay() return out except Exception: self._graphs.pop(key, None) return self._forward_impl(x) 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] # ================================================================== # ===== sidecar: fp8_gemm_sm120.cu (1897 bytes, loaded by solution.py) ===== # ================================================================== // FP8 e4m3 GEMM for SM120 — binding + dispatch. Kernels in fp8_cfgs_*.cu. #include using RunFn = void (*)(const torch::Tensor&, const torch::Tensor&, const torch::Tensor&, torch::Tensor&, int64_t, int64_t, int64_t, int, int); #define DECL(n) void n(const torch::Tensor&, const torch::Tensor&, \ const torch::Tensor&, torch::Tensor&, int64_t, int64_t, int64_t, int, int); DECL(run_cfg0) DECL(run_cfg1) DECL(run_cfg2) DECL(run_cfg3) DECL(run_cfg4) DECL(run_cfg5) DECL(run_cfg6) DECL(run_cfg7) DECL(run_cfg8) DECL(run_cfg9) DECL(run_cfg10) DECL(run_cfg11) static RunFn kRunners[] = {run_cfg0, run_cfg1, run_cfg2, run_cfg3, run_cfg4, run_cfg5, run_cfg6, run_cfg7, run_cfg8, run_cfg9, run_cfg10, run_cfg11}; torch::Tensor fp8_gemm(torch::Tensor x, torch::Tensor w, torch::Tensor s, int64_t impl, int64_t swizzle, int64_t splits) { TORCH_CHECK(x.is_cuda() && w.is_cuda() && s.is_cuda()); TORCH_CHECK(x.dtype() == torch::kFloat8_e4m3fn && w.dtype() == torch::kFloat8_e4m3fn); TORCH_CHECK(x.is_contiguous() && w.is_contiguous()); int64_t M = x.size(0), K = x.size(1), N = w.size(0); TORCH_CHECK(w.size(1) == K, "K mismatch"); TORCH_CHECK(K % 16 == 0, "K must be divisible by 16 (pad first)"); auto y = torch::empty({M, N}, torch::TensorOptions().dtype(torch::kBFloat16).device(x.device())); int64_t n_impl = int64_t(sizeof(kRunners) / sizeof(kRunners[0])); TORCH_CHECK(impl >= 0 && impl < n_impl, "bad impl"); kRunners[impl](x, w, s, y, M, N, K, int(swizzle), int(splits)); return y; } int64_t num_impls() { return int64_t(sizeof(kRunners) / sizeof(kRunners[0])); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("fp8_gemm", &fp8_gemm, "fp8 gemm sm120 (x, w, s, impl, swizzle, splits)"); m.def("num_impls", &num_impls); }