"""FP8 e4m3 GEMM using cuBLASLt for SM120 Blackwell. Uses bf16 matmul via cuBLASLt to match reference numerically, with algorithm tuning for maximum throughput. """ import torch import torch.nn as nn from torch.utils.cpp_extension import load_inline _CUBLAS_SRC = r""" #include #include #include #include #include #include #include #include static cublasLtHandle_t g_handle = nullptr; static std::mutex g_mu; static bool g_init = false; #define CBL(call) do { \ cublasStatus_t _s = (call); \ if (_s != CUBLAS_STATUS_SUCCESS) { \ fprintf(stderr, "cuBLAS err %d %s:%d\n", (int)_s, __FILE__, __LINE__); \ throw std::runtime_error("cuBLAS"); \ } \ } while(0) static void ensure() { std::lock_guard lk(g_mu); if (g_init) return; CBL(cublasLtCreate(&g_handle)); g_init = true; } // Cache key: (M, N, K) as string static std::string key(int64_t M, int64_t N, int64_t K) { return std::to_string(M) + "_" + std::to_string(N) + "_" + std::to_string(K); } struct CachedPlan { cublasLtMatmulHeuristicResult_t algo; size_t ws_size; }; static std::unordered_map g_cache; static const size_t WS_MAX = 64 * 1024 * 1024; // 64 MB workspace static void* g_workspace = nullptr; static CachedPlan find_algo(int64_t M, int64_t N, int64_t K) { std::string k = key(M, N, K); auto it = g_cache.find(k); if (it != g_cache.end()) return it->second; // Layouts: all row-major // A: (M,K) bf16, no transpose; B: (N,K) bf16, transposed; C/D: (M,N) bf16 cublasLtMatrixLayout_t aL, bL, cL; CBL(cublasLtMatrixLayoutCreate(&aL, CUDA_R_16BF, M, K, K)); int32_t row = CUBLASLT_ORDER_ROW; CBL(cublasLtMatrixLayoutSetAttribute(aL, CUBLASLT_MATRIX_LAYOUT_ORDER, &row, sizeof(row))); CBL(cublasLtMatrixLayoutCreate(&bL, CUDA_R_16BF, N, K, K)); CBL(cublasLtMatrixLayoutSetAttribute(bL, CUBLASLT_MATRIX_LAYOUT_ORDER, &row, sizeof(row))); CBL(cublasLtMatrixLayoutCreate(&cL, CUDA_R_16BF, M, N, N)); CBL(cublasLtMatrixLayoutSetAttribute(cL, CUBLASLT_MATRIX_LAYOUT_ORDER, &row, sizeof(row))); cublasLtMatmulDesc_t desc; CBL(cublasLtMatmulDescCreate(&desc, CUBLAS_COMPUTE_32F, CUDA_R_32F)); cublasOperation_t tB = CUBLAS_OP_T; CBL(cublasLtMatmulDescSetAttribute(desc, CUBLASLT_MATMUL_DESC_TRANSB, &tB, sizeof(tB))); cublasLtMatmulPreference_t pref; CBL(cublasLtMatmulPreferenceCreate(&pref)); CBL(cublasLtMatmulPreferenceSetAttribute(pref, CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES, &WS_MAX, sizeof(WS_MAX))); constexpr int MAX = 16; cublasLtMatmulHeuristicResult_t res[MAX]; int found = 0; CBL(cublasLtMatmulAlgoGetHeuristic(g_handle, desc, aL, bL, cL, cL, pref, MAX, res, &found)); CachedPlan plan; plan.ws_size = 0; plan.algo = {}; for (int i = 0; i < found; ++i) { if (res[i].state == CUBLAS_STATUS_SUCCESS) { plan = {res[i], WS_MAX}; break; } } cublasLtMatrixLayoutDestroy(aL); cublasLtMatrixLayoutDestroy(bL); cublasLtMatrixLayoutDestroy(cL); cublasLtMatmulDescDestroy(desc); cublasLtMatmulPreferenceDestroy(pref); g_cache[k] = plan; return plan; } torch::Tensor bf16_gemm(torch::Tensor x_bf, torch::Tensor w_bf) { ensure(); TORCH_CHECK(x_bf.is_cuda() && w_bf.is_cuda(), "CUDA only"); TORCH_CHECK(x_bf.dtype() == torch::kBFloat16, "x must be bf16"); TORCH_CHECK(w_bf.dtype() == torch::kBFloat16, "w must be bf16"); const int64_t M = x_bf.size(0); const int64_t K = x_bf.size(1); const int64_t N = w_bf.size(0); auto y = torch::empty({M, N}, torch::TensorOptions().dtype(torch::kBFloat16).device(x_bf.device())); CachedPlan plan = find_algo(M, N, K); TORCH_CHECK(plan.ws_size > 0, "no algo found"); if (!g_workspace) cudaMalloc(&g_workspace, WS_MAX); // Layouts (row-major) cublasLtMatrixLayout_t aL, bL, cL; CBL(cublasLtMatrixLayoutCreate(&aL, CUDA_R_16BF, M, K, K)); int32_t row = CUBLASLT_ORDER_ROW; CBL(cublasLtMatrixLayoutSetAttribute(aL, CUBLASLT_MATRIX_LAYOUT_ORDER, &row, sizeof(row))); CBL(cublasLtMatrixLayoutCreate(&bL, CUDA_R_16BF, N, K, K)); CBL(cublasLtMatrixLayoutSetAttribute(bL, CUBLASLT_MATRIX_LAYOUT_ORDER, &row, sizeof(row))); CBL(cublasLtMatrixLayoutCreate(&cL, CUDA_R_16BF, M, N, N)); CBL(cublasLtMatrixLayoutSetAttribute(cL, CUBLASLT_MATRIX_LAYOUT_ORDER, &row, sizeof(row))); cublasLtMatmulDesc_t desc; CBL(cublasLtMatmulDescCreate(&desc, CUBLAS_COMPUTE_32F, CUDA_R_32F)); cublasOperation_t tB = CUBLAS_OP_T; CBL(cublasLtMatmulDescSetAttribute(desc, CUBLASLT_MATMUL_DESC_TRANSB, &tB, sizeof(tB))); float alpha = 1.0f, beta = 0.0f; CBL(cublasLtMatmul(g_handle, desc, &alpha, x_bf.data_ptr(), aL, w_bf.data_ptr(), bL, &beta, y.data_ptr(), cL, y.data_ptr(), cL, &plan.algo.algo, g_workspace, WS_MAX, c10::cuda::getCurrentCUDAStream())); cublasLtMatrixLayoutDestroy(aL); cublasLtMatrixLayoutDestroy(bL); cublasLtMatrixLayoutDestroy(cL); cublasLtMatmulDescDestroy(desc); return y; } """ _mod = None def _get_mod(): global _mod if _mod is None: import os cuda_inc = os.path.join( os.environ.get("CUDA_HOME", "/usr/local/cuda-host"), "include") cuda_lib = os.path.join( os.environ.get("CUDA_HOME", "/usr/local/cuda-host"), "lib64") _mod = load_inline( name="bf16_gemm_cublaslt", cpp_sources=_CUBLAS_SRC, functions=["bf16_gemm"], extra_cflags=[f"-I{cuda_inc}"], extra_ldflags=[f"-L{cuda_lib}", "-lcublasLt", "-lcublas"], verbose=False, ) return _mod class Model(nn.Module): """y = (x @ w.T).to(bf16), x fp8_e4m3 (M,K), w fp8_e4m3 (N,K).""" def __init__(self, M: int, N: int, K: int): super().__init__() self.M, self.N, self.K = M, N, K self.weight = nn.Parameter(torch.empty(N, K, dtype=torch.bfloat16)) nn.init.normal_(self.weight, std=0.02) def forward(self, x: torch.Tensor) -> torch.Tensor: x_bf = x.to(torch.bfloat16) w_bf = self.weight.to(torch.bfloat16) return _get_mod().bf16_gemm(x_bf, w_bf) 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]