diff --git a/dockerfile/cuda13.0.dockerfile b/dockerfile/cuda13.0.dockerfile index 520920afa..7ce083336 100644 --- a/dockerfile/cuda13.0.dockerfile +++ b/dockerfile/cuda13.0.dockerfile @@ -135,7 +135,7 @@ RUN cd /tmp && \ make install ENV PATH="${PATH}" \ - LD_LIBRARY_PATH="/usr/local/lib:/usr/local/mpi/lib:${LD_LIBRARY_PATH}" \ + LD_LIBRARY_PATH="/usr/local/lib:/usr/local/mpi/lib:/opt/superbench/lib:${LD_LIBRARY_PATH}" \ SB_HOME=/opt/superbench \ SB_MICRO_PATH=/opt/superbench \ ANSIBLE_DEPRECATION_WARNINGS=FALSE \ diff --git a/dockerfile/cuda13.4.dockerfile b/dockerfile/cuda13.4.dockerfile index 09d85889c..e81e2d713 100644 --- a/dockerfile/cuda13.4.dockerfile +++ b/dockerfile/cuda13.4.dockerfile @@ -64,6 +64,8 @@ FROM nvcr.io/nvidia/pytorch:26.09-py3 # - This machine is aarch64 (ARM). cpu_hpl, Intel MLC, AOCC and AMD BLIS auto-skip on aarch64. # - CUDA 13.4 builds the in-tree CUDA benchmarks, CUTLASS, NVBench, # cuBLASLt and NCCL tests for sm_107. +# - CUTLASS v4.8.1 is installed twice: GB200/GB300 into ${SB_MICRO_PATH}/{bin,lib} +# and Rubin (sm_107a) into ${SB_MICRO_PATH}/cutlass_sm107/{bin,lib}. # - streamOlympus is built with GCC 15 in the stream-olympus-builder stage above. # # Build (from repo root), e.g.: @@ -170,7 +172,7 @@ RUN if [ "$TARGETARCH" = "amd64" ]; then \ # Add the base image's HPC-X 2.51 UCX and ompi to the library path and add mpicc to PATH. ENV MPI_HOME=/opt/hpcx/ompi ENV PATH="/opt/hpcx/ompi/bin:${PATH}" \ - LD_LIBRARY_PATH="/opt/hpcx/ucx/lib:/opt/hpcx/ompi/lib:${LD_LIBRARY_PATH}" \ + LD_LIBRARY_PATH="/opt/hpcx/ucx/lib:/opt/hpcx/ompi/lib:/opt/superbench/lib:${LD_LIBRARY_PATH}" \ SB_HOME=/opt/superbench \ SB_MICRO_PATH=/opt/superbench \ ANSIBLE_DEPRECATION_WARNINGS=FALSE \ diff --git a/docs/user-tutorial/benchmarks/micro-benchmarks.md b/docs/user-tutorial/benchmarks/micro-benchmarks.md index 6ce505657..b4216914f 100644 --- a/docs/user-tutorial/benchmarks/micro-benchmarks.md +++ b/docs/user-tutorial/benchmarks/micro-benchmarks.md @@ -25,26 +25,41 @@ which is defined as the time range from the beginning of the launch API call to #### Introduction Measure the GPU GEMM FLOPS for different float and int data types, with or without Tensor Core (XDLOPS), -performed by NVIDIA [cutlass](https://github.com/NVIDIA/cutlass/tree/ccb697bac77fcc898e9c897b2c90aa5b60ac72fb) +performed by NVIDIA [CUTLASS](https://github.com/NVIDIA/cutlass) or AMD [rocblas-bench](https://github.com/ROCmSoftwarePlatform/rocBLAS/tree/develop/clients/benchmarks). +Available precisions depend on the GPU architecture and the installed CUTLASS build. Vera Rubin (compute capability 10.7) +requires CUDA 13.4 or later and the repository-managed CUTLASS build, including its MXFP8 runtime datatype fix. +The benchmark automatically selects the dedicated `cutlass_sm107` profiler and its matching libraries on Rubin. +Precisions without kernels in the installed CUTLASS kernel list (`share/cutlass/generated_kernels.txt` next to the +profiler's `bin` folder) are skipped with a warning. + +Block-scaled modes (`nvfp4_tc`, `nvfp4_ue5m3_tc`, `mxfp8_tc`, and `mxfp4_tc`) disable CUTLASS verification during throughput +measurement to avoid running a CPU reference GEMM for every selected kernel at the default matrix size. +Run correctness checks separately with small matrices and `--verification-enabled=true` using the matching CUTLASS profiler. + #### Metrics -| Name | Unit | Description | -|------------------------------|----------------|---------------------------------------------------------| -| gemm-flops/fp64_flops | FLOPS (GFLOPS) | GEMM float64 peak FLOPS. | -| gemm-flops/fp32_flops | FLOPS (GFLOPS) | GEMM float32 peak FLOPS. | -| gemm-flops/fp16_flops | FLOPS (GFLOPS) | GEMM float16 peak FLOPS. | -| gemm-flops/fp64_tc_flops | FLOPS (GFLOPS) | GEMM float64 peak FLOPS with NVIDIA Tensor Core. | -| gemm-flops/tf32_tc_flops | FLOPS (GFLOPS) | GEMM tensor-float32 peak FLOPS with NVIDIA Tensor Core. | -| gemm-flops/fp16_tc_flops | FLOPS (GFLOPS) | GEMM float16 peak FLOPS with NVIDIA Tensor Core. | -| gemm-flops/bf16_tc_flops | FLOPS (GFLOPS) | GEMM bfloat16 peak FLOPS with NVIDIA Tensor Core. | -| gemm-flops/int8_tc_iops | IOPS (GIOPS) | GEMM int8 peak IOPS with NVIDIA Tensor Core. | -| gemm-flops/int4_tc_iops | IOPS (GIOPS) | GEMM int4 peak IOPS with NVIDIA Tensor Core. | -| gemm-flops/fp32_xdlops_flops | FLOPS (GFLOPS) | GEMM tensor-float32 peak FLOPS with AMD XDLOPS. | -| gemm-flops/fp16_xdlops_flops | FLOPS (GFLOPS) | GEMM float16 peak FLOPS with AMD XDLOPS. | -| gemm-flops/bf16_xdlops_flops | FLOPS (GFLOPS) | GEMM bfloat16 peak FLOPS with AMD XDLOPS. | -| gemm-flops/int8_xdlops_iops | IOPS (GIOPS) | GEMM int8 peak IOPS with AMD XDLOPS. | +| Name | Unit | Description | +|---------------------------------|----------------|----------------------------------------------------------------------------------| +| gemm-flops/fp64_flops | FLOPS (GFLOPS) | GEMM float64 peak FLOPS. | +| gemm-flops/fp32_flops | FLOPS (GFLOPS) | GEMM float32 peak FLOPS. | +| gemm-flops/fp16_flops | FLOPS (GFLOPS) | GEMM float16 peak FLOPS. | +| gemm-flops/fp64_tc_flops | FLOPS (GFLOPS) | GEMM float64 peak FLOPS with NVIDIA Tensor Core. | +| gemm-flops/tf32_tc_flops | FLOPS (GFLOPS) | GEMM tensor-float32 peak FLOPS with NVIDIA Tensor Core. | +| gemm-flops/fp16_tc_flops | FLOPS (GFLOPS) | GEMM float16 peak FLOPS with NVIDIA Tensor Core. | +| gemm-flops/bf16_tc_flops | FLOPS (GFLOPS) | GEMM bfloat16 peak FLOPS with NVIDIA Tensor Core. | +| gemm-flops/int8_tc_iops | IOPS (GIOPS) | GEMM int8 peak IOPS with NVIDIA Tensor Core. | +| gemm-flops/int4_tc_iops | IOPS (GIOPS) | GEMM int4 peak IOPS with NVIDIA Tensor Core. | +| gemm-flops/fp8_tc_flops | FLOPS (GFLOPS) | GEMM FP8 (E4M3) peak FLOPS with NVIDIA Tensor Core. | +| gemm-flops/nvfp4_tc_flops | FLOPS (GFLOPS) | GEMM NVFP4 (E2M1, UE4M3 scale per 16 values) peak FLOPS with NVIDIA Tensor Core. | +| gemm-flops/nvfp4_ue5m3_tc_flops | FLOPS (GFLOPS) | GEMM NVFP4 (E2M1, UE5M3 scale per 16 values) peak FLOPS with NVIDIA Tensor Core. | +| gemm-flops/mxfp8_tc_flops | FLOPS (GFLOPS) | GEMM MXFP8 (E4M3, E8M0 scale per 32 values) peak FLOPS with NVIDIA Tensor Core. | +| gemm-flops/mxfp4_tc_flops | FLOPS (GFLOPS) | GEMM MXFP4 (E2M1, E8M0 scale per 32 values) peak FLOPS with NVIDIA Tensor Core. | +| gemm-flops/fp32_xdlops_flops | FLOPS (GFLOPS) | GEMM tensor-float32 peak FLOPS with AMD XDLOPS. | +| gemm-flops/fp16_xdlops_flops | FLOPS (GFLOPS) | GEMM float16 peak FLOPS with AMD XDLOPS. | +| gemm-flops/bf16_xdlops_flops | FLOPS (GFLOPS) | GEMM bfloat16 peak FLOPS with AMD XDLOPS. | +| gemm-flops/int8_xdlops_iops | IOPS (GIOPS) | GEMM int8 peak IOPS with AMD XDLOPS. | ### `matmul` diff --git a/superbench/benchmarks/micro_benchmarks/cuda_gemm_flops_performance.py b/superbench/benchmarks/micro_benchmarks/cuda_gemm_flops_performance.py index 14c8111f7..d73fa1861 100644 --- a/superbench/benchmarks/micro_benchmarks/cuda_gemm_flops_performance.py +++ b/superbench/benchmarks/micro_benchmarks/cuda_gemm_flops_performance.py @@ -3,7 +3,9 @@ """Module of the FLOPs performance benchmarks.""" +import fnmatch import os +import re from superbench.common.utils import logger from superbench.common.utils import device_manager as dm @@ -52,16 +54,71 @@ def __init__(self, name, parameters=''): self.__kernel_map[8.9] = {k: self.__kernel_map[8.0][k] for k in self.__kernel_map[8.0] if 'fp64' not in k} # Skip INT4 for Hopper due to no native CUDA/Tensor Cores self.__kernel_map[9.0] = {k: self.__kernel_map[8.0][k] for k in self.__kernel_map[8.0] if 'int4_tc' not in k} - self.__kernel_map[10.0] = {k: self.__kernel_map[8.0][k] for k in self.__kernel_map[8.0] if 'int4_tc' not in k} - self.__kernel_map[10.3] = {k: self.__kernel_map[8.0][k] for k in self.__kernel_map[8.0] if 'int4_tc' not in k} - self.__kernel_map[10.7] = {k: self.__kernel_map[8.0][k] for k in self.__kernel_map[8.0] if 'int4_tc' not in k} + # FP8 (e4m3) on Hopper SM90a: CUTLASS 3x WGMMA kernels; v3.x names put the MMA shape before "gemm". + self.__kernel_map[9.0]['fp8_tc'] = 'cutlass3x_sm90_tensorop_*gemm_e4m3_e4m3_f32_f32_f32_*' + # Blackwell (SM100/SM103): CUTLASS v4.3.5 (v4.8.0 with CUDA 13.4+) UMMA TensorOp kernels. + # Runtime --kernels patterns select stream_k + 2sm kernels for peak FLOPS. + # TF32/FP16/BF16: 256x256 tiles only (best for 32/64-byte K-tiles). + # INT8/FP8: include 128x256 + 256x256 because their larger K-tile (128) + # changes optimal tile shape; 256x256 non-epi_tma may fail at runtime. + # FP4: all ~49 kernels (small enough). + # Trailing * after stream_k_2sm matches both _2sm and _2sm_epi_tma. + self.__kernel_map[10.0] = { + 'tf32_tc': 'cutlass3x_sm100_tensorop_tf32gemm*256x256x*stream_k_2sm*', + 'bf16_tc': 'cutlass3x_sm100_tensorop_gemm_bf16_bf16_f32_bf16_bf16*256x256x*stream_k_2sm*', + 'fp16_tc': 'cutlass3x_sm100_tensorop_gemm_f16_f16_f32_f16_f16*256x256x*stream_k_2sm*', + 'int8_tc': 'cutlass3x_sm100_tensorop_gemm_s8_s8_s32_s8_s8*256x*stream_k_2sm*', + 'fp8_tc': 'cutlass3x_sm100_tensorop_gemm_e4m3_e4m3_f32_f32_f32*256x*stream_k_2sm*', + } + # SM103a (GB300 "Blackwell Ultra"): + # - Lacks INT8 UMMA (tcgen05.mma.kind::i8); CuTe's config.hpp only + # defines CUTE_ARCH_TCGEN05_S8_MMA_ENABLED for SM100a/SM101a. + # - Adds NVFP4 (block-scaled FP4) via the BlockScaledGemm operation. + # The FP4 Ultra path uses sm103-specific bstensorop kernels with + # ue4m3 scale factor and vs16 block size (NVFP4 spec). + # nvfp4_tc kernels are profiled with --operation=block_scaled_gemm + # (auto-detected from the kernel name prefix in _preprocess). + self.__kernel_map[10.3] = {k: v for k, v in self.__kernel_map[10.0].items() if k != 'int8_tc'} + self.__kernel_map[10.3]['nvfp4_tc'] = \ + 'cutlass3x_sm103_bstensorop_gemm_ue4m3xe2m1_ue4m3xe2m1_f32_void_f32*256x*ultra_2sm*' + # Rubin SM107a: CUTLASS v4.8.0 kernels from the separate cutlass_sm107 install (third_party/cutlass.mk). + # - TF32/FP16/BF16: SM100 generators retargeted to Sm107, selected like SM100. + # - FP8, NVFP4 (UE4M3 or UE5M3 scales, 16-element blocks) and MXFP8/MXFP4 (UE8M0 scales, 32-element + # blocks): native SM107 kernels (B-reuse schedules, no stream-K), N=256 2SM tiles. + # - No INT8: CuTe enables tcgen05 kind::i8 only for SM100a/SM101a/SM110. + self.__kernel_map[10.7] = { + 'tf32_tc': 'cutlass3x_sm107_tensorop_tf32gemm*256x256x*stream_k_2sm*', + 'bf16_tc': 'cutlass3x_sm107_tensorop_gemm_bf16_bf16_f32_bf16_bf16*256x256x*stream_k_2sm*', + 'fp16_tc': 'cutlass3x_sm107_tensorop_gemm_f16_f16_f32_f16_f16*256x256x*stream_k_2sm*', + 'fp8_tc': 'cutlass3x_sm107_tensorop_gemm_f8_f8_f32_f32_f32*x256x128_*breuse_2sm*', + 'nvfp4_tc': + 'cutlass3x_sm107_bstensorop_gemm_ue4m3xe2m1_ue4m3xe2m1_f32_void_f32*x256x256_*o_vs16_*breuse_2sm*', + 'nvfp4_ue5m3_tc': + 'cutlass3x_sm107_bstensorop_gemm_ue5m3xe2m1_ue5m3xe2m1_f32_void_f32*x256x256_*o_vs16_*breuse_2sm*', + 'mxfp8_tc': 'cutlass3x_sm107_bstensorop_gemm_ue8m0xf8_ue8m0xf8_f32_void_f32*x256x128_*breuse_2sm*', + 'mxfp4_tc': + 'cutlass3x_sm107_bstensorop_gemm_ue8m0xe2m1_ue8m0xe2m1_f32_void_f32*x256x256_*o_vs32_*breuse_2sm*', + } + # Compute capabilities whose CUTLASS build lives in its own SB_MICRO_PATH subfolder. + self.__cutlass_subdir = {10.7: 'cutlass_sm107'} + self.__capability = None + # Install prefix of the selected cutlass_profiler, i.e. the parent of its real bin folder. + self.__install_prefix = None + # ',' of CSV rows to parse: legacy SM70/SM80, SM90, SM100, SM103, SM107. + # Block-scaled kernels report OperationKind 'gemm' (substring matching also accepts 'block_scaled_gemm'). self.__parse_logline = [ 'gemm,cutlass_simt_dgemm_128x128_8x2', 'gemm,cutlass_simt_sgemm_128x128_8x2', 'gemm,cutlass_simt_hgemm_256x128_8x2', 'gemm,cutlass_tensorop_d884gemm_128x128_16x3', 'gemm,cutlass_tensorop_tf32_s1688gemm_tf32_256x128_16x3', 'gemm,cutlass_tensorop_bf16_s16816gemm_bf16_256x128_32x3', 'gemm,cutlass_tensorop_h16816gemm_256x128_32x3', 'gemm,cutlass_tensorop_h884gemm_256x128_32x2', 'gemm,cutlass_tensorop_s8_i16832gemm_s8_256x128_64x3', - 'gemm,cutlass_tensorop_s4_i16864gemm_s4_256x128_128x3' + 'gemm,cutlass_tensorop_s4_i16864gemm_s4_256x128_128x3', 'gemm,cutlass3x_sm90_tensorop_', + 'gemm,cutlass3x_sm100_tensorop_tf32gemm_', 'gemm,cutlass3x_sm100_tensorop_gemm_f16_', + 'gemm,cutlass3x_sm100_tensorop_gemm_bf16_', 'gemm,cutlass3x_sm100_tensorop_gemm_s8_', + 'gemm,cutlass3x_sm100_tensorop_gemm_e4m3_e4m3_', 'gemm,cutlass3x_sm103_bstensorop_gemm_ue4m3xe2m1_', + 'gemm,cutlass3x_sm103_bstensorop_gemm_ue4m3xf4_', 'gemm,cutlass3x_sm107_tensorop_tf32gemm_', + 'gemm,cutlass3x_sm107_tensorop_gemm_f16_', 'gemm,cutlass3x_sm107_tensorop_gemm_bf16_', + 'gemm,cutlass3x_sm107_tensorop_gemm_f8_f8_', 'gemm,cutlass3x_sm107_bstensorop_' ] def add_parser_arguments(self): @@ -74,8 +131,8 @@ def _preprocess(self): Return: True if _preprocess() succeed. """ - # Reset kernels according to compute capability. - capability = dm.device_manager.get_device_compute_capability() + # Reset kernels according to the compute capability of the GPU visible to this process. + capability = dm.device_manager.get_visible_device_compute_capability() if capability not in self.__kernel_map: # After preprocess() self._result.return_code can be generated super()._preprocess() @@ -87,24 +144,94 @@ def _preprocess(self): ) return False + self.__capability = capability self._support_precisions = list(self.__kernel_map[capability].keys()) # 'support_precisions' are precise only after getting capability, # and then using super.preprocess() to check if the precision in arguments are supported to run if not super()._preprocess(): return False + if not self.__filter_installed_precisions(): + return False + for p in self._precision_need_to_run: + kernels = self.__kernel_map[capability][p] command = os.path.join(self._args.bin_dir, self._bin_name) command += (' --warmup-iterations=' + str(self._args.num_warmup)) - command += (' --operation=gemm') + # Block-scaled kernels (bstensorop) are only listed under the block_scaled_gemm operation. + operation = 'block_scaled_gemm' if '_bstensorop_' in kernels else 'gemm' + command += (' --operation=' + operation) command += (' --n=' + str(self._args.n)) command += (' --k=' + str(self._args.k)) command += (' --m=' + str(self._args.m)) - command += (' --kernels=' + self.__kernel_map[capability][p]) + command += (' --kernels=' + kernels) + # Runtime-typed FP8 kernels ("f8" elements: gemm_f8_f8, ue8m0xf8) take the A/B type at launch. + if re.search(r'[_x]f8_', kernels): + command += ' --runtime_input_datatype_a=e4m3 --runtime_input_datatype_b=e4m3' + # cutlass_profiler verifies block-scaled kernels only against a host (CPU) reference, which is impractically + # slow at the default problem size, so skip verification for these throughput runs. + if operation == 'block_scaled_gemm': + command += ' --verification-enabled=false' self._commands.append(command) return True + def __filter_installed_precisions(self): + """Skip precisions whose kernels are not in the installed CUTLASS kernel list. + + CUTLASS v3.x and later install the list of generated kernels to /share/cutlass/generated_kernels.txt + (third_party/cutlass.mk). Without that list, e.g. for CUTLASS v2.x, all precisions are kept. + + Return: + True if at least one precision remains to run. + """ + kernel_list = os.path.join(self.__install_prefix, 'share', 'cutlass', 'generated_kernels.txt') + if not os.path.isfile(kernel_list): + return True + with open(kernel_list) as f: + installed = [line.strip() for line in f if line.strip()] + + precisions = list() + for p in self._precision_need_to_run: + # cutlass_profiler matches --kernels patterns anywhere in the kernel name. + pattern = '*' + self.__kernel_map[self.__capability][p] + '*' + if any(fnmatch.fnmatchcase(name, pattern) for name in installed): + precisions.append(p) + else: + logger.warning( + 'No installed CUTLASS kernels - benchmark: {}, precision: {}, kernel list: {}.'.format( + self._name, p, kernel_list + ) + ) + self._precision_need_to_run = precisions + + if len(self._precision_need_to_run) == 0: + self._result.set_return_code(ReturnCode.NO_SUPPORTED_PRECISION) + return False + return True + + def _set_binary_path(self): + """Search cutlass_profiler in the per-architecture CUTLASS install unless --bin_dir is given. + + Return: + True if the binary exists. + """ + subdir = self.__cutlass_subdir.get(self.__capability) + if subdir and self._args.bin_dir is None and os.getenv('SB_MICRO_PATH'): + self._args.bin_dir = os.path.join(os.getenv('SB_MICRO_PATH'), subdir, 'bin') + if not super()._set_binary_path(): + return False + self._args.bin_dir = os.path.abspath(self._args.bin_dir) + self.__install_prefix = os.path.dirname( + os.path.dirname(os.path.realpath(os.path.join(self._args.bin_dir, self._bin_name))) + ) + # cutlass_profiler only runs kernels from its own build's libcutlass*.so, and LD_LIBRARY_PATH outranks RUNPATH, + # so put the lib folder of the selected install ahead of SB_MICRO_PATH/lib. + lib_dir = os.path.join(self.__install_prefix, 'lib') + if os.path.isdir(lib_dir): + os.environ['LD_LIBRARY_PATH'] = lib_dir + os.pathsep + os.getenv('LD_LIBRARY_PATH', '') + return True + def _process_raw_result(self, cmd_idx, raw_output): """Function to parse raw results and save the summarized results. diff --git a/superbench/benchmarks/micro_benchmarks/gemm_flops_performance_base.py b/superbench/benchmarks/micro_benchmarks/gemm_flops_performance_base.py index a1b283b1e..c0eb577d0 100644 --- a/superbench/benchmarks/micro_benchmarks/gemm_flops_performance_base.py +++ b/superbench/benchmarks/micro_benchmarks/gemm_flops_performance_base.py @@ -20,7 +20,8 @@ def __init__(self, name, parameters=''): super().__init__(name, parameters) self._support_precisions = [ - 'fp64', 'fp32', 'fp16', 'fp64_tc', 'tf32_tc', 'bf16_tc', 'fp16_tc', 'int8_tc', 'int4_tc' + 'fp64', 'fp32', 'fp16', 'fp64_tc', 'tf32_tc', 'bf16_tc', 'fp16_tc', 'int8_tc', 'int4_tc', 'fp8_tc', + 'nvfp4_tc', 'nvfp4_ue5m3_tc', 'mxfp8_tc', 'mxfp4_tc' ] self._precision_need_to_run = list() self._metric_map = { @@ -33,6 +34,11 @@ def __init__(self, name, parameters=''): 'fp16_tc': 'fp16_tc_flops', 'int8_tc': 'int8_tc_iops', 'int4_tc': 'int4_tc_iops', + 'fp8_tc': 'fp8_tc_flops', + 'nvfp4_tc': 'nvfp4_tc_flops', + 'nvfp4_ue5m3_tc': 'nvfp4_ue5m3_tc_flops', + 'mxfp8_tc': 'mxfp8_tc_flops', + 'mxfp4_tc': 'mxfp4_tc_flops', 'fp32_xdlops': 'fp32_xdlops_flops', 'fp16_xdlops': 'fp16_xdlops_flops', 'bf16_xdlops': 'bf16_xdlops_flops', diff --git a/superbench/common/utils/device_manager.py b/superbench/common/utils/device_manager.py index cdcf66e9d..6061e4559 100644 --- a/superbench/common/utils/device_manager.py +++ b/superbench/common/utils/device_manager.py @@ -4,6 +4,8 @@ """Device Management Library Utility.""" import numbers +import subprocess +import sys from typing import Optional from superbench.common.utils import logger @@ -23,6 +25,31 @@ _AMDSMI_MICROWATTS_PER_WATT = 1_000_000 _AMDSMI_MICROWATTS_THRESHOLD = 100_000 +# Prints " " of CUDA device 0 using the driver API, which creates no CUDA context. +_CUDA_DEVICE_0_CAPABILITY_SCRIPT = """ +import ctypes +import sys + +cuda = ctypes.CDLL('libcuda.so.1') +cuda.cuInit.argtypes = [ctypes.c_uint] +cuda.cuDeviceGet.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.c_int] +cuda.cuDeviceGetAttribute.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.c_int, ctypes.c_int] +device, major, minor = ctypes.c_int(), ctypes.c_int(), ctypes.c_int() + + +def check(name, ret): + if ret != 0: + sys.exit('{} failed with CUresult {}'.format(name, ret)) + + +check('cuInit', cuda.cuInit(0)) +check('cuDeviceGet', cuda.cuDeviceGet(ctypes.byref(device), 0)) +# CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR = 75, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR = 76 +check('cuDeviceGetAttribute', cuda.cuDeviceGetAttribute(ctypes.byref(major), 75, device)) +check('cuDeviceGetAttribute', cuda.cuDeviceGetAttribute(ctypes.byref(minor), 76, device)) +print(major.value, minor.value) +""" + def _amdsmi_power_to_watts(value): """Convert an amdsmi power value to integer watts. @@ -59,6 +86,14 @@ def get_device_compute_capability(self): """ return None + def get_visible_device_compute_capability(self): + """Get the compute capability of the first device visible to this process. + + Return: + cap (float): the compute capability of device, None means failed to get the data. + """ + return None + def get_device_utilization(self, idx): """Get the utilization of device. @@ -175,6 +210,33 @@ def get_device_compute_capability(self): return None return cap + def get_visible_device_compute_capability(self): + """Get the compute capability of CUDA device 0, which honors CUDA_VISIBLE_DEVICES unlike NVML indices. + + The CUDA driver is queried in a child process so that this process does not initialize CUDA. + + Return: + cap (float): the compute capability of device, None means failed to get the data. + """ + try: + output = subprocess.run( + [sys.executable, '-c', _CUDA_DEVICE_0_CAPABILITY_SCRIPT], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True, + timeout=60, + check=True + ).stdout.split() + major, minor = int(output[0]), int(output[1]) + except subprocess.CalledProcessError as err: + logger.warning('Get visible device compute capability failed: {}'.format(err.stderr.strip())) + return None + except Exception as err: + logger.warning('Get visible device compute capability failed: {}'.format(str(err))) + return None + # Same format as nvmlDeviceGetCudaComputeCapability() in py3nvml. + return major + 0.1 * minor + def get_device_utilization(self, idx): """Get the utilization of device. diff --git a/tests/benchmarks/micro_benchmarks/test_cuda_gemm_flops_performance.py b/tests/benchmarks/micro_benchmarks/test_cuda_gemm_flops_performance.py index 8dfc25fa8..c703d74f9 100644 --- a/tests/benchmarks/micro_benchmarks/test_cuda_gemm_flops_performance.py +++ b/tests/benchmarks/micro_benchmarks/test_cuda_gemm_flops_performance.py @@ -3,6 +3,9 @@ """Tests for gemm-flops benchmark.""" +import fnmatch +import os +import tempfile import unittest from unittest import mock @@ -19,7 +22,9 @@ def setUpClass(cls): """Hook method for setting up class fixture before running tests in the class.""" super().setUpClass() cls.createMockEnvs(cls) - cls.createMockFiles(cls, ['bin/cutlass_profiler']) + cls.createMockFiles( + cls, ['bin/cutlass_profiler', 'cutlass_sm107/bin/cutlass_profiler', 'cutlass_sm107/lib/libcutlass.so'] + ) @decorator.cuda_test def test_flops_performance_cuda(self): @@ -36,7 +41,8 @@ def test_flops_performance_cuda(self): ) ret = benchmark._preprocess() - if dm.device_manager.get_device_compute_capability() not in benchmark._CudaGemmFlopsBenchmark__kernel_map: + if dm.device_manager.get_visible_device_compute_capability( + ) not in benchmark._CudaGemmFlopsBenchmark__kernel_map: assert (ret is False) assert (benchmark.return_code == ReturnCode.MICROBENCHMARK_UNSUPPORTED_ARCHITECTURE) else: @@ -54,7 +60,8 @@ def test_flops_performance_cuda(self): assert (benchmark._args.k == 512) assert (benchmark._args.m == 2048) assert (benchmark._args.precision == ['fp32', 'tf32_tc', 'fp16_tc', 'int8_tc']) - benchmark._CudaGemmFlopsBenchmark__precision_need_to_run = ['fp32', 'tf32_tc', 'fp16_tc', 'int8_tc'] + # Parse the outputs below as these precisions on any GPU architecture. + benchmark._precision_need_to_run = ['fp32', 'tf32_tc', 'fp16_tc', 'int8_tc'] # Check results and metrics. raw_output_fp32 = """ @@ -95,16 +102,345 @@ def test_flops_performance_cuda(self): # Negative case - Add invalid raw output. assert (benchmark._process_raw_result(3, 'Invalid raw output') is False) - def test_flops_performance_cuda_sm107(self): - """Test gemm-flops benchmark selects kernels for compute capability 10.7.""" + @decorator.cuda_test + def test_flops_performance_cuda_sm100(self): + """Test gemm-flops benchmark SM100 (Blackwell) UMMA kernel output parsing.""" + benchmark_name = 'gemm-flops' + (benchmark_class, + predefine_params) = BenchmarkRegistry._BenchmarkRegistry__select_benchmark(benchmark_name, Platform.CUDA) + assert (benchmark_class) + + benchmark = benchmark_class(benchmark_name, parameters='--precision tf32_tc bf16_tc fp16_tc int8_tc') + # Parse args so _args and _result are initialized for _process_raw_result(). + benchmark.add_parser_arguments() + ret, benchmark._args, _ = benchmark.parse_args() + assert ret + from superbench.benchmarks.result import BenchmarkResult + from superbench.benchmarks import BenchmarkType, ReturnCode + benchmark._result = BenchmarkResult(benchmark_name, BenchmarkType.MICRO, ReturnCode.SUCCESS) + benchmark._precision_need_to_run = ['tf32_tc', 'bf16_tc', 'fp16_tc', 'int8_tc'] + + # SM100 UMMA 3x kernel naming: + # cutlass3x_sm100_tensorop_gemm_{dtype_a}_{dtype_b}_{acc}_{c}_{d}_{tile}_{cluster}_{stages}_{layout}_align{al}_{schedule} + raw_output_tf32_tc = """ +CSV Results: + +Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,Runtime,GFLOPs +1,CUTLASS,gemm,cutlass3x_sm100_tensorop_tf32gemm_f32_f32_f32_f32_f32_128x256x32_1x2x1_0_ntn_align4_1sm,passed,success,universal,16384,16384,16384,8.21,1072500 +1,CUTLASS,gemm,cutlass3x_sm100_tensorop_tf32gemm_f32_f32_f32_f32_f32_256x128x32_1x2x1_0_ntn_align4_1sm,passed,success,universal,16384,16384,16384,8.45,1043800 +1,CUTLASS,gemm,cutlass3x_sm100_tensorop_tf32gemm_f32_f32_f32_f32_f32_128x256x32_1x2x1_0_ntn_align4_stream_k_1sm,passed,success,universal,16384,16384,16384,8.10,1086300 +""" + raw_output_bf16_tc = """ +CSV Results: + +Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,Runtime,GFLOPs +1,CUTLASS,gemm,cutlass3x_sm100_tensorop_gemm_bf16_bf16_f32_f32_f32_128x256x64_1x2x1_0_ntn_align8_1sm,passed,success,universal,16384,16384,16384,4.35,2024100 +1,CUTLASS,gemm,cutlass3x_sm100_tensorop_gemm_bf16_bf16_f32_void_f32_128x256x64_1x2x1_0_ntn_align8_1sm,passed,success,universal,16384,16384,16384,4.20,2096300 +""" + raw_output_fp16_tc = """ +CSV Results: + +Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,Runtime,GFLOPs +1,CUTLASS,gemm,cutlass3x_sm100_tensorop_gemm_f16_f16_f16_f16_f16_128x256x64_1x2x1_0_ntn_align8_1sm,passed,success,universal,16384,16384,16384,4.31,2042000 +1,CUTLASS,gemm,cutlass3x_sm100_tensorop_gemm_f16_f16_f32_f32_f32_128x256x64_1x2x1_0_ntn_align8_1sm,passed,success,universal,16384,16384,16384,4.28,2056200 +""" + raw_output_int8_tc = """ +CSV Results: + +Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,Runtime,GFLOPs +1,CUTLASS,gemm,cutlass3x_sm100_tensorop_gemm_s8_s8_s32_s32_s32_128x256x128_1x2x1_0_ntn_align16_1sm,passed,success,universal,16384,16384,16384,2.20,3998400 +1,CUTLASS,gemm,cutlass3x_sm100_tensorop_gemm_s8_s8_s32_void_s32_128x256x128_1x2x1_0_ntn_align16_1sm,passed,success,universal,16384,16384,16384,2.15,4091600 +""" + assert (benchmark._process_raw_result(0, raw_output_tf32_tc)) + assert (benchmark._process_raw_result(1, raw_output_bf16_tc)) + assert (benchmark._process_raw_result(2, raw_output_fp16_tc)) + assert (benchmark._process_raw_result(3, raw_output_int8_tc)) + + assert (benchmark.result['tf32_tc_flops'][0] == 1086300) + assert (benchmark.result['bf16_tc_flops'][0] == 2096300) + assert (benchmark.result['fp16_tc_flops'][0] == 2056200) + assert (benchmark.result['int8_tc_iops'][0] == 4091600) + + @decorator.cuda_test + def test_flops_performance_cuda_fp8(self): + """Test gemm-flops benchmark FP8 (e4m3) kernel output parsing for SM90 and SM100.""" benchmark_name = 'gemm-flops' (benchmark_class, predefine_params) = BenchmarkRegistry._BenchmarkRegistry__select_benchmark(benchmark_name, Platform.CUDA) assert (benchmark_class) - benchmark = benchmark_class(benchmark_name, parameters='--precision fp32 fp16_tc') - assert (10.7 in benchmark._CudaGemmFlopsBenchmark__kernel_map) + benchmark = benchmark_class(benchmark_name, parameters='--precision fp8_tc') + # Parse args so _args and _result are initialized for _process_raw_result(). + benchmark.add_parser_arguments() + ret, benchmark._args, _ = benchmark.parse_args() + assert ret + from superbench.benchmarks.result import BenchmarkResult + from superbench.benchmarks import BenchmarkType, ReturnCode + benchmark._result = BenchmarkResult(benchmark_name, BenchmarkType.MICRO, ReturnCode.SUCCESS) + benchmark._precision_need_to_run = ['fp8_tc', 'fp8_tc'] + + # SM90 Hopper WGMMA 3x kernels from CUTLASS v3.9.2 (MMA shape before "gemm") and v4.3.5. + raw_output_sm90_fp8 = """ +CSV Results: + +Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,Runtime,GFLOPs +1,CUTLASS,gemm,cutlass3x_sm90_tensorop_s64x256x32gemm_e4m3_e4m3_f32_f32_f32_128x256x128_2x1x1_0_tnn_align16_warpspecialized_cooperative_fp8_fastaccum_epi_nosmem,passed,success,universal,16384,16384,16384,3.79,2317200 +1,CUTLASS,gemm,cutlass3x_sm90_tensorop_gemm_e4m3_e4m3_f32_f32_f32_128x256x128_2x1x1_0_tnn_align16_warpspecialized_cooperative_fp8_fastaccum_epi_nosmem,passed,success,universal,16384,16384,16384,3.85,2281500 +""" + pattern = benchmark._CudaGemmFlopsBenchmark__kernel_map[9.0]['fp8_tc'] + names = [line.split(',')[3] for line in raw_output_sm90_fp8.splitlines() if line.startswith('1,')] + assert (names and all(fnmatch.fnmatchcase(name, '*' + pattern + '*') for name in names)) + # SM100 Blackwell UMMA 3x kernel: cutlass3x_sm100_tensorop_gemm_e4m3_{a}_{b}_{acc}_{c}_{d}_{tile}_... + raw_output_sm100_fp8 = """ +CSV Results: + +Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,Runtime,GFLOPs +1,CUTLASS,gemm,cutlass3x_sm100_tensorop_gemm_e4m3_e4m3_f32_bf16_bf16_128x256x64_1x2x1_0_ntn_align16_1sm,passed,success,universal,16384,16384,16384,2.10,5296000 +1,CUTLASS,gemm,cutlass3x_sm100_tensorop_gemm_e4m3_e4m3_f32_f32_f32_128x256x64_1x2x1_0_ntn_align16_1sm,passed,success,universal,16384,16384,16384,2.05,5425400 +""" + assert (benchmark._process_raw_result(0, raw_output_sm90_fp8)) + assert (benchmark._process_raw_result(1, raw_output_sm100_fp8)) + + assert (benchmark.result['fp8_tc_flops'][0] == 2317200) + assert (benchmark.result['fp8_tc_flops'][1] == 5425400) + + @decorator.cuda_test + def test_flops_performance_cuda_nvfp4(self): + """Test gemm-flops benchmark NVFP4 (block-scaled FP4) kernel selection and output parsing for SM103.""" + benchmark_name = 'gemm-flops' + (benchmark_class, + predefine_params) = BenchmarkRegistry._BenchmarkRegistry__select_benchmark(benchmark_name, Platform.CUDA) + assert (benchmark_class) + + benchmark = benchmark_class(benchmark_name, parameters='--precision nvfp4_tc') + benchmark.add_parser_arguments() + ret, benchmark._args, _ = benchmark.parse_args() + assert ret + from superbench.benchmarks.result import BenchmarkResult + from superbench.benchmarks import BenchmarkType, ReturnCode + benchmark._result = BenchmarkResult(benchmark_name, BenchmarkType.MICRO, ReturnCode.SUCCESS) + benchmark._precision_need_to_run = ['nvfp4_tc'] + + # SM103 Blackwell Ultra NVFP4 block-scaled kernel: + # cutlass3x_sm103_bstensorop_gemm_ue4m3xe2m1_ue4m3xe2m1_{acc}_{c}_{d}_{tile}_..._ultra_2sm_* + # cutlass_profiler reports OperationKind "gemm" for them and prints large GFLOPs in exponent notation. + raw_output_sm103_nvfp4 = """ +CSV Results: + +Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,A,B,C,D,alpha,beta,split_k_mode,split_k_slices,batch_count,runtime_input_datatype_a,runtime_input_datatype_b,raster_order,swizzle_size,use_pdl,op_class,accum,cta_m,cta_n,cta_k,cluster_m,cluster_n,cluster_k,cluster_m_fallback,cluster_n_fallback,cluster_k_fallback,stages,warps_m,warps_n,warps_k,inst_m,inst_n,inst_k,min_cc,max_cc,Bytes,Flops,Flops/Byte,Runtime,GB/s,GFLOPs +1,CUTLASS,gemm,cutlass3x_sm103_bstensorop_gemm_ue4m3xe2m1_ue4m3xe2m1_f32_void_f32_256x256x768_2x1x1_0_tnt_align32_o_vs16_ultra_2sm_nopf_epi_nosmem,not_verified,success,universal,16384,16384,16384,fe2m1:row,fe2m1:column,void:row,f32:row,1,0,serial,1,1,invalid,invalid,heuristic,1,false,invalid,f32,256,256,768,2,1,1,2,1,1,4,4,1,1,256,256,128,103,1024,301989888,8796629893120,29128,0.55,511.364,1.59939e+07 +1,CUTLASS,gemm,cutlass3x_sm103_bstensorop_gemm_ue4m3xe2m1_ue4m3xe2m1_f32_void_f32_256x256x768_2x1x1_0_tnt_align32_o_vs16_ultra_2sm_tmapf_epi_nosmem,not_verified,success,universal,16384,16384,16384,fe2m1:row,fe2m1:column,void:row,f32:row,1,0,serial,1,1,invalid,invalid,heuristic,1,false,invalid,f32,256,256,768,2,1,1,2,1,1,4,4,1,1,256,256,128,103,1024,301989888,8796629893120,29128,0.52985,530.811,1.66021e+07 +""" + # The SM10.3 --kernels pattern must select these real CUTLASS v4.3.5 names (matched like '*pattern*'). + pattern = benchmark._CudaGemmFlopsBenchmark__kernel_map[10.3]['nvfp4_tc'] + names = [line.split(',')[3] for line in raw_output_sm103_nvfp4.splitlines() if line.startswith('1,')] + assert (names and all(fnmatch.fnmatchcase(name, '*' + pattern + '*') for name in names)) + + assert (benchmark._process_raw_result(0, raw_output_sm103_nvfp4)) + + assert (benchmark.result['nvfp4_tc_flops'][0] == 16602100) + + def test_flops_performance_cuda_sm107_kernels(self): + """Test gemm-flops benchmark selects native SM107 (Rubin) kernels and parses their output.""" + benchmark_name = 'gemm-flops' + (benchmark_class, + predefine_params) = BenchmarkRegistry._BenchmarkRegistry__select_benchmark(benchmark_name, Platform.CUDA) + assert (benchmark_class) + + precisions = ['tf32_tc', 'bf16_tc', 'fp16_tc', 'fp8_tc', 'nvfp4_tc', 'nvfp4_ue5m3_tc', 'mxfp8_tc', 'mxfp4_tc'] + benchmark = benchmark_class(benchmark_name, parameters='--precision ' + ' '.join(precisions)) + kernel_map = benchmark._CudaGemmFlopsBenchmark__kernel_map[10.7] + assert (sorted(kernel_map) == sorted(precisions)) + # No legacy SM80 (Ampere) selectors on the Rubin performance path. + assert (all(pattern.startswith('cutlass3x_sm107_') for pattern in kernel_map.values())) + + benchmark.add_parser_arguments() + ret, benchmark._args, _ = benchmark.parse_args() + assert ret + from superbench.benchmarks.result import BenchmarkResult + benchmark._result = BenchmarkResult(benchmark_name, BenchmarkType.MICRO, ReturnCode.SUCCESS) + benchmark._precision_need_to_run = precisions + + # Kernel names from CUTLASS v4.8.0 generated for "107a"; the FP8/FP4 ones are native SM107 B-reuse kernels. + raw_output_tf32_tc = """ +CSV Results: + +Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,Runtime,GFLOPs +1,CUTLASS,gemm,cutlass3x_sm107_tensorop_tf32gemm_f32_f32_f32_f32_f32_256x256x32_0x0x1_0_ntn_align4_stream_k_2sm,passed,success,universal,16384,16384,16384,8.0,1100000 +1,CUTLASS,gemm,cutlass3x_sm107_tensorop_tf32gemm_f32_f32_f32_f32_f32_256x256x32_4x4x1_0_tnn_align4_stream_k_2sm,passed,success,universal,16384,16384,16384,8.8,1000000 +""" + raw_output_bf16_tc = """ +CSV Results: + +Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,Runtime,GFLOPs +1,CUTLASS,gemm,cutlass3x_sm107_tensorop_gemm_bf16_bf16_f32_bf16_bf16_256x256x64_0x0x1_0_ntn_align8_stream_k_2sm,passed,success,universal,16384,16384,16384,4.4,2000000 +1,CUTLASS,gemm,cutlass3x_sm107_tensorop_gemm_bf16_bf16_f32_bf16_bf16_256x256x64_4x4x1_0_tnn_align8_stream_k_2sm,passed,success,universal,16384,16384,16384,4.2,2100000 +""" + raw_output_fp16_tc = """ +CSV Results: + +Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,Runtime,GFLOPs +1,CUTLASS,gemm,cutlass3x_sm107_tensorop_gemm_f16_f16_f32_f16_f16_256x256x64_0x0x1_0_ntn_align8_stream_k_2sm,passed,success,universal,16384,16384,16384,4.2,2100000 +1,CUTLASS,gemm,cutlass3x_sm107_tensorop_gemm_f16_f16_f32_f16_f16_256x256x64_4x4x1_0_tnn_align8_stream_k_2sm,passed,success,universal,16384,16384,16384,4.0,2200000 +""" + raw_output_fp8_tc = """ +CSV Results: + +Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,Runtime,GFLOPs +1,CUTLASS,gemm,cutlass3x_sm107_tensorop_gemm_f8_f8_f32_f32_f32_256x256x128_0x0x1_0_ntn_align16_no_breuse_2sm_epi_tma,passed,success,universal,16384,16384,16384,2.2,4000000 +1,CUTLASS,gemm,cutlass3x_sm107_tensorop_gemm_f8_f8_f32_f32_f32_512x256x128_4x4x1_0_tnn_align16_breuse_2sm_epi_tma,passed,success,universal,16384,16384,16384,2.0,4400000 +""" + # Block-scaled outputs use the real cutlass_profiler CSV layout from Rubin: OperationKind is 'gemm'. + raw_output_nvfp4_tc = """ +CSV Results: + +Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,A,B,C,D,alpha,beta,split_k_mode,split_k_slices,batch_count,runtime_input_datatype_a,runtime_input_datatype_b,raster_order,swizzle_size,use_pdl,op_class,accum,cta_m,cta_n,cta_k,cluster_m,cluster_n,cluster_k,cluster_m_fallback,cluster_n_fallback,cluster_k_fallback,stages,warps_m,warps_n,warps_k,inst_m,inst_n,inst_k,min_cc,max_cc,Bytes,Flops,Flops/Byte,Runtime,GB/s,GFLOPs +1,CUTLASS,gemm,cutlass3x_sm107_bstensorop_gemm_ue4m3xe2m1_ue4m3xe2m1_f32_void_f32_256x256x256_0x0x1_0_tnn_align32_o_vs16_no_breuse_2sm_epi_tma,not_verified,success,universal,512,512,512,fe2m1:row,fe2m1:column,void:column,f32:column,1,0,serial,1,1,invalid,invalid,heuristic,1,false,invalid,f32,256,256,256,2,1,1,2,1,1,5,4,1,1,256,256,128,107,1024,294912,268959744,912,0.0057296,47.9367,46942.1 +1,CUTLASS,gemm,cutlass3x_sm107_bstensorop_gemm_ue4m3xe2m1_ue4m3xe2m1_f32_void_f32_512x256x256_4x4x1_0_tnn_align32_o_vs16_breuse_2sm_epi_tma,not_verified,success,universal,512,512,512,fe2m1:row,fe2m1:column,void:column,f32:column,1,0,serial,1,1,invalid,invalid,heuristic,1,false,invalid,f32,512,256,256,4,4,1,2,1,1,4,4,1,1,256,256,128,107,1024,294912,268959744,912,0.0061,45.0259,44091.8 +""" + raw_output_nvfp4_ue5m3_tc = """ +CSV Results: + +Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,A,B,C,D,alpha,beta,split_k_mode,split_k_slices,batch_count,runtime_input_datatype_a,runtime_input_datatype_b,raster_order,swizzle_size,use_pdl,op_class,accum,cta_m,cta_n,cta_k,cluster_m,cluster_n,cluster_k,cluster_m_fallback,cluster_n_fallback,cluster_k_fallback,stages,warps_m,warps_n,warps_k,inst_m,inst_n,inst_k,min_cc,max_cc,Bytes,Flops,Flops/Byte,Runtime,GB/s,GFLOPs +1,CUTLASS,gemm,cutlass3x_sm107_bstensorop_gemm_ue5m3xe2m1_ue5m3xe2m1_f32_void_f32_256x256x256_0x0x1_0_tnn_align32_o_vs16_no_breuse_2sm_epi_tma,not_verified,success,universal,512,512,512,fe2m1:row,fe2m1:column,void:column,f32:column,1,0,serial,1,1,invalid,invalid,heuristic,1,false,invalid,f32,256,256,256,2,1,1,2,1,1,5,4,1,1,256,256,128,107,1024,294912,268959744,912,0.005736,47.8832,46889.8 +1,CUTLASS,gemm,cutlass3x_sm107_bstensorop_gemm_ue5m3xe2m1_ue5m3xe2m1_f32_void_f32_512x256x256_4x4x1_0_tnn_align32_o_vs16_breuse_2sm_epi_tma,not_verified,success,universal,512,512,512,fe2m1:row,fe2m1:column,void:column,f32:column,1,0,serial,1,1,invalid,invalid,heuristic,1,false,invalid,f32,512,256,256,4,4,1,2,1,1,4,4,1,1,256,256,128,107,1024,294912,268959744,912,0.0062,44.2997,43380.6 +""" + raw_output_mxfp8_tc = """ +CSV Results: + +Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,A,B,C,D,alpha,beta,split_k_mode,split_k_slices,batch_count,runtime_input_datatype_a,runtime_input_datatype_b,raster_order,swizzle_size,use_pdl,op_class,accum,cta_m,cta_n,cta_k,cluster_m,cluster_n,cluster_k,cluster_m_fallback,cluster_n_fallback,cluster_k_fallback,stages,warps_m,warps_n,warps_k,inst_m,inst_n,inst_k,min_cc,max_cc,Bytes,Flops,Flops/Byte,Runtime,GB/s,GFLOPs +1,CUTLASS,gemm,cutlass3x_sm107_bstensorop_gemm_ue8m0xf8_ue8m0xf8_f32_void_f32_256x256x128_0x0x1_0_tnn_align16_no_breuse_2sm_epi_tma,not_verified,success,universal,512,512,512,f8:row,f8:column,void:column,f32:column,1,0,serial,1,1,e4m3,e4m3,heuristic,1,false,invalid,f32,256,256,128,2,1,1,2,1,1,6,4,1,1,256,256,64,107,1024,540672,268959744,497,0.0071,70.9211,37881.7 +1,CUTLASS,gemm,cutlass3x_sm107_bstensorop_gemm_ue8m0xf8_ue8m0xf8_f32_void_f32_512x256x128_4x4x1_0_tnn_align16_breuse_2sm_epi_tma,not_verified,success,universal,512,512,512,f8:row,f8:column,void:column,f32:column,1,0,serial,1,1,e4m3,e4m3,heuristic,1,false,invalid,f32,512,256,128,4,4,1,2,1,1,5,4,1,1,256,256,64,107,1024,540672,268959744,497,0.0066,76.2939,40751.5 +""" + raw_output_mxfp4_tc = """ +CSV Results: + +Problem,Provider,OperationKind,Operation,Disposition,Status,gemm_kind,m,n,k,A,B,C,D,alpha,beta,split_k_mode,split_k_slices,batch_count,runtime_input_datatype_a,runtime_input_datatype_b,raster_order,swizzle_size,use_pdl,op_class,accum,cta_m,cta_n,cta_k,cluster_m,cluster_n,cluster_k,cluster_m_fallback,cluster_n_fallback,cluster_k_fallback,stages,warps_m,warps_n,warps_k,inst_m,inst_n,inst_k,min_cc,max_cc,Bytes,Flops,Flops/Byte,Runtime,GB/s,GFLOPs +1,CUTLASS,gemm,cutlass3x_sm107_bstensorop_gemm_ue8m0xe2m1_ue8m0xe2m1_f32_void_f32_256x256x256_0x0x1_0_tnn_align32_o_vs32_no_breuse_2sm_epi_tma,not_verified,success,universal,512,512,512,fe2m1:row,fe2m1:column,void:column,f32:column,1,0,serial,1,1,invalid,invalid,heuristic,1,false,invalid,f32,256,256,256,2,1,1,2,1,1,5,4,1,1,256,256,128,107,1024,278528,268959744,965,0.00568032,45.6663,47349.4 +1,CUTLASS,gemm,cutlass3x_sm107_bstensorop_gemm_ue8m0xe2m1_ue8m0xe2m1_f32_void_f32_512x256x256_4x4x1_0_tnn_align32_o_vs32_breuse_2sm_epi_tma,not_verified,success,universal,512,512,512,fe2m1:row,fe2m1:column,void:column,f32:column,1,0,serial,1,1,invalid,invalid,heuristic,1,false,invalid,f32,512,256,256,4,4,1,2,1,1,4,4,1,1,256,256,128,107,1024,278528,268959744,965,0.006,43.2332,44826.6 +""" + raw_outputs = [ + raw_output_tf32_tc, raw_output_bf16_tc, raw_output_fp16_tc, raw_output_fp8_tc, raw_output_nvfp4_tc, + raw_output_nvfp4_ue5m3_tc, raw_output_mxfp8_tc, raw_output_mxfp4_tc + ] + for idx, raw_output in enumerate(raw_outputs): + # The --kernels pattern must select the real names (matched like '*pattern*'). + pattern = kernel_map[precisions[idx]] + names = [line.split(',')[3] for line in raw_output.splitlines() if line.startswith('1,')] + assert (names and all(fnmatch.fnmatchcase(name, '*' + pattern + '*') for name in names)) + assert (benchmark._process_raw_result(idx, raw_output)) + + assert (benchmark.result['tf32_tc_flops'][0] == 1100000) + assert (benchmark.result['bf16_tc_flops'][0] == 2100000) + assert (benchmark.result['fp16_tc_flops'][0] == 2200000) + assert (benchmark.result['fp8_tc_flops'][0] == 4400000) + assert (benchmark.result['nvfp4_tc_flops'][0] == 46942.1) + assert (benchmark.result['nvfp4_ue5m3_tc_flops'][0] == 46889.8) + assert (benchmark.result['mxfp8_tc_flops'][0] == 40751.5) + assert (benchmark.result['mxfp4_tc_flops'][0] == 47349.4) + + # Retargeted SM100-style kernels, 1SM kernels and other scale types or block sizes are not selected. + unselected = """ +fp8_tc,cutlass3x_sm107_tensorop_gemm_f8_f8_f32_f32_f32_256x256x128_0x0x1_0_ntn_align16_stream_k_2sm +fp8_tc,cutlass3x_sm107_tensorop_gemm_f8_f8_f32_f32_f32_256x256x128_0x0x1_0_ntn_align16_breuse_1sm +nvfp4_tc,cutlass3x_sm107_bstensorop_gemm_ue4m3xe2m1_ue4m3xe2m1_f32_void_f32_256x256x256_0x0x1_0_tnn_align32_o_vs16_2sm +nvfp4_tc,cutlass3x_sm107_bstensorop_gemm_ue4m3xe2m1_ue4m3xe2m1_f32_void_f32_256x256x256_0x0x1_0_tnn_align32_o_vs32_no_breuse_2sm_epi_tma +nvfp4_tc,cutlass3x_sm107_bstensorop_gemm_ue8m0xe2m1_ue8m0xe2m1_f32_void_f32_256x256x256_0x0x1_0_tnn_align32_o_vs32_no_breuse_2sm_epi_tma +nvfp4_ue5m3_tc,cutlass3x_sm107_bstensorop_gemm_ue4m3xe2m1_ue4m3xe2m1_f32_void_f32_256x256x256_0x0x1_0_tnn_align32_o_vs16_no_breuse_2sm_epi_tma +nvfp4_ue5m3_tc,cutlass3x_sm107_bstensorop_gemm_ue5m3xe2m1_ue5m3xe2m1_f32_void_f32_256x256x256_0x0x1_0_tnn_align32_o_vs32_no_breuse_2sm_epi_tma +mxfp8_tc,cutlass3x_sm107_bstensorop_gemm_ue8m0xf8_ue8m0xf8_f32_void_f32_256x256x128_0x0x1_0_tnn_align16_breuse_1sm +mxfp4_tc,cutlass3x_sm107_bstensorop_gemm_ue8m0xe2m1_ue8m0xe2m1_f32_void_f32_256x256x256_0x0x1_0_tnn_align32_o_vs16_no_breuse_2sm_epi_tma +mxfp4_tc,cutlass3x_sm107_bstensorop_gemm_ue8m0xe2m1_ue8m0xe2m1_f32_void_f32_256x256x256_0x0x1_0_tnn_align32_o_vs32_2sm +""" + for line in unselected.split(): + precision, name = line.split(',') + assert (not fnmatch.fnmatchcase(name, '*' + kernel_map[precision] + '*')) + + def test_flops_performance_cuda_sm107_commands(self): + """Test gemm-flops benchmark runs the cutlass_sm107 install on Rubin and skips unsupported precisions.""" + benchmark_name = 'gemm-flops' + (benchmark_class, + predefine_params) = BenchmarkRegistry._BenchmarkRegistry__select_benchmark(benchmark_name, Platform.CUDA) + assert (benchmark_class) + + prefix = os.path.join(self._tmp_dir, 'cutlass_sm107') + with mock.patch.object(dm.device_manager, 'get_visible_device_compute_capability', return_value=10.7): + with mock.patch.dict(os.environ): + benchmark = benchmark_class( + benchmark_name, + parameters='--precision tf32_tc fp8_tc nvfp4_tc nvfp4_ue5m3_tc mxfp8_tc mxfp4_tc int8_tc int4_tc' + ) + assert (benchmark._preprocess() is True) + assert (os.environ['LD_LIBRARY_PATH'].split(os.pathsep)[0] == os.path.join(prefix, 'lib')) + assert (benchmark.return_code == ReturnCode.SUCCESS) + # SM107 has no INT8/INT4 kernels, so they are skipped. + expected = ['tf32_tc', 'fp8_tc', 'nvfp4_tc', 'nvfp4_ue5m3_tc', 'mxfp8_tc', 'mxfp4_tc'] + assert (benchmark._precision_need_to_run == expected) + assert (benchmark._args.bin_dir == os.path.join(prefix, 'bin')) + kernel_map = benchmark._CudaGemmFlopsBenchmark__kernel_map[10.7] + tf32_cmd, fp8_cmd, nvfp4_cmd, nvfp4_ue5m3_cmd, mxfp8_cmd, mxfp4_cmd = benchmark._commands + runtime_e4m3 = ' --runtime_input_datatype_a=e4m3 --runtime_input_datatype_b=e4m3' + no_verification = ' --verification-enabled=false' + assert (tf32_cmd.startswith(os.path.join(prefix, 'bin', 'cutlass_profiler') + ' ')) + assert ('--operation=gemm ' in tf32_cmd and tf32_cmd.endswith(' --kernels=' + kernel_map['tf32_tc'])) + assert ('--operation=gemm ' in fp8_cmd and fp8_cmd.endswith(runtime_e4m3)) + # Dense kernels keep the default verification; block-scaled ones skip the slow host reference check. + assert (all('--verification-enabled' not in cmd for cmd in [tf32_cmd, fp8_cmd])) + for cmd in [nvfp4_cmd, nvfp4_ue5m3_cmd, mxfp4_cmd]: + assert ('--operation=block_scaled_gemm ' in cmd and 'runtime_input_datatype' not in cmd) + assert (cmd.endswith(no_verification)) + # MXFP8 kernels are block-scaled and runtime-typed. + assert ('--operation=block_scaled_gemm ' in mxfp8_cmd) + assert (mxfp8_cmd.endswith(runtime_e4m3 + no_verification)) + + with mock.patch.dict(os.environ): + benchmark = benchmark_class(benchmark_name, parameters='--precision int8_tc') + assert (benchmark._preprocess() is False) + assert (benchmark.return_code == ReturnCode.NO_SUPPORTED_PRECISION) + + # An explicit --bin_dir of the Rubin install also gets its lib folder first in LD_LIBRARY_PATH. + with mock.patch.dict(os.environ): + benchmark = benchmark_class( + benchmark_name, parameters='--precision fp16_tc --bin_dir ' + os.path.join(prefix, 'bin') + ) + assert (benchmark._preprocess() is True) + assert (os.environ['LD_LIBRARY_PATH'].split(os.pathsep)[0] == os.path.join(prefix, 'lib')) + assert (benchmark._args.bin_dir == os.path.join(prefix, 'bin')) + + # An explicit --bin_dir takes precedence over the per-architecture install. + bin_dir = os.path.join(self._tmp_dir, 'bin') + with mock.patch.dict(os.environ): + benchmark = benchmark_class(benchmark_name, parameters='--precision fp16_tc --bin_dir ' + bin_dir) + assert (benchmark._preprocess() is True) + assert (benchmark._args.bin_dir == bin_dir) + + def test_flops_performance_cuda_installed_kernels(self): + """Test gemm-flops benchmark skips precisions without kernels in the installed CUTLASS kernel list.""" + benchmark_name = 'gemm-flops' + (benchmark_class, + predefine_params) = BenchmarkRegistry._BenchmarkRegistry__select_benchmark(benchmark_name, Platform.CUDA) + assert (benchmark_class) + + with tempfile.TemporaryDirectory() as prefix: + bin_dir = os.path.join(prefix, 'bin') + os.makedirs(bin_dir) + profiler = os.path.join(bin_dir, 'cutlass_profiler') + open(profiler, 'w').close() + os.chmod(profiler, 0o755) + # A legacy-only build (e.g. CUDA 11.8) has no Hopper FP8 kernels. + os.makedirs(os.path.join(prefix, 'share', 'cutlass')) + with open(os.path.join(prefix, 'share', 'cutlass', 'generated_kernels.txt'), 'w') as f: + f.write('cutlass_simt_sgemm_128x128_8x2_nn_align1\n') + f.write('cutlass_tensorop_h16816gemm_256x128_32x3_nn_align8\n') + + with mock.patch.object(dm.device_manager, 'get_visible_device_compute_capability', return_value=9.0): + with mock.patch.dict(os.environ): + benchmark = benchmark_class(benchmark_name, parameters='--bin_dir ' + bin_dir) + assert (benchmark._preprocess() is True) + assert (benchmark._precision_need_to_run == ['fp32', 'fp16_tc']) + assert (len(benchmark._commands) == 2) - with mock.patch.object(dm.device_manager, 'get_device_compute_capability', return_value=10.7): - assert (benchmark._preprocess() is True) - assert (benchmark.return_code == ReturnCode.SUCCESS) + with mock.patch.dict(os.environ): + benchmark = benchmark_class(benchmark_name, parameters='--precision fp8_tc --bin_dir ' + bin_dir) + assert (benchmark._preprocess() is False) + assert (benchmark.return_code == ReturnCode.NO_SUPPORTED_PRECISION) diff --git a/tests/common/test_device_manager.py b/tests/common/test_device_manager.py index 96ef66363..aeb5fee7b 100644 --- a/tests/common/test_device_manager.py +++ b/tests/common/test_device_manager.py @@ -188,3 +188,19 @@ def test_amd_device_manager_lifecycle(): bad_rocml.amdsmi_shut_down.side_effect = RuntimeError('rocm gone') with mock.patch(f'{_DM_MODULE}.rocml', bad_rocml, create=True): manager2.__del__() # must not raise + + +def test_nvidia_get_visible_device_compute_capability(): + """The capability of CUDA device 0 comes from a child process; failures return None.""" + class _NvidiaManager(dm.NvidiaDeviceManager): + def __del__(self): + pass + + manager = _NvidiaManager.__new__(_NvidiaManager) + with mock.patch(f'{_DM_MODULE}.subprocess.run') as run: + run.return_value.stdout = '10 7\n' + assert manager.get_visible_device_compute_capability() == 10.7 + assert run.call_args[0][0][1:] == ['-c', dm._CUDA_DEVICE_0_CAPABILITY_SCRIPT] + + run.side_effect = dm.subprocess.CalledProcessError(1, 'python', stderr='cuDeviceGet failed with CUresult 100') + assert manager.get_visible_device_compute_capability() is None diff --git a/third_party/Makefile b/third_party/Makefile index 01516bb12..0001f5ebc 100755 --- a/third_party/Makefile +++ b/third_party/Makefile @@ -38,53 +38,8 @@ sb_micro_path: mkdir -p $(SB_MICRO_PATH)/bin mkdir -p $(SB_MICRO_PATH)/lib -# Build cutlass. -# CUDA >=13.5 uses stable CUTLASS v4.8.1; keep older CUDA release selections below. -cuda_cutlass: -ifeq ($(shell printf '%s\n' "13.5" "$(CUDA_VER)" | sort -V | head -n1),13.5) - $(eval ARCHS := "100;103a;107a") - if [ -d cutlass ]; then rm -rf cutlass; fi - git clone --branch v4.8.1 --depth 1 https://github.com/NVIDIA/cutlass.git && \ - test "$$(git -C cutlass rev-parse HEAD)" = "2c85f497547eb441f0fe80bfb0fb2e6f9add1719" -else ifeq ($(shell echo $(CUDA_VER)">=12.9" | bc -l), 1) - $(eval ARCHS := "100;103") -ifeq ($(shell echo $(CUDA_VER)">=13.4" | bc -l), 1) - $(eval ARCHS := "100;103;107") -endif - if [ -d cutlass ]; then rm -rf cutlass; fi - git clone --branch v4.1.0 --depth 1 https://github.com/NVIDIA/cutlass.git && cd cutlass -else ifeq ($(shell echo $(CUDA_VER)">=12.8" | bc -l), 1) - $(eval ARCHS := "90;100") - if [ -d cutlass ]; then rm -rf cutlass; fi - git clone --branch v3.9.2 --depth 1 https://github.com/NVIDIA/cutlass.git && cd cutlass -else ifeq ($(shell echo $(CUDA_VER)">=11.8" | bc -l), 1) - $(eval ARCHS := "70;75;80;86;89;90") -else - $(eval ARCHS := "70;75;80;86") -endif - -ifneq (,$(wildcard cutlass/CMakeLists.txt)) - cmake -DCMAKE_INSTALL_BINDIR=$(SB_MICRO_PATH)/bin \ - -DCMAKE_INSTALL_LIBDIR=$(SB_MICRO_PATH)/lib \ - -DCMAKE_BUILD_TYPE=Release \ - -DCUTLASS_NVCC_ARCHS=$(ARCHS) \ - -DCUTLASS_ENABLE_EXAMPLES=OFF \ - -DCUTLASS_ENABLE_TESTS=OFF \ - -S ./cutlass \ - -B ./cutlass/build \ - -DCUTLASS_LIBRARY_KERNELS="cutlass_simt_dgemm_128x128_8x2_*,\ -cutlass_simt_sgemm_128x128_8x2_*,\ -cutlass_simt_hgemm_256x128_8x2_*,\ -cutlass_tensorop_h884gemm_256x128_32x2_*,\ -cutlass_tensorop_d884gemm_128x128_16x3_*,\ -cutlass_tensorop_tf32_s1688gemm_tf32_256x128_16x3_*,\ -cutlass_tensorop_bf16_s16816gemm_bf16_256x128_32x3_*,\ -cutlass_tensorop_h16816gemm_256x128_32x3_*,\ -cutlass_tensorop_s8_i16832gemm_s8_256x128_64x3_*,\ -cutlass_tensorop_s4_i16864gemm_s4_256x128_128x3_*" - cmake --build ./cutlass/build -j $(shell nproc --ignore=2) --target install - rm -rf ./cutlass/build -endif +# Build cutlass — configuration lives in cutlass.mk. +include cutlass.mk # Build cuda-samples/Samples/bandwidthTest. # cuda-samples is released together with CUDA, they have the exact same version. Like v10.0, v11.1 and so on. diff --git a/third_party/cutlass.mk b/third_party/cutlass.mk new file mode 100644 index 000000000..0bb4be3c2 --- /dev/null +++ b/third_party/cutlass.mk @@ -0,0 +1,266 @@ +# Copyright (c) Microsoft Corporation - All rights reserved +# Licensed under the MIT License +# +# CUTLASS build configuration for SuperBench. +# +# This sub-makefile is included by the main Makefile and provides the +# cuda_cutlass target. Moving CUTLASS here keeps the growing per-arch +# complexity (kernel filters, generator patches, naming conventions) +# isolated from the rest of the third-party build. +# +# --------------------------------------------------------------------------- +# Kernel naming conventions +# --------------------------------------------------------------------------- +# SM70/80 legacy : cutlass_simt_* / cutlass_tensorop_* (no arch prefix) +# SM90/100+ (3x) : cutlass3x_sm{arch}_tensorop_{core_name}_{dtype}_* +# Note: TF32 kernels use "tf32gemm" (intermediate type before "gemm"), +# e.g. cutlass3x_sm100_tensorop_tf32gemm_f32_f32_* +# "f8"/"f4" element names mark runtime-typed kernels; the profiler takes the +# actual type from --runtime_input_datatype_a/b. +# +# --------------------------------------------------------------------------- +# Shared kernel lists (reusable fragments) +# --------------------------------------------------------------------------- +# SM70–90 legacy SIMT + TensorOp kernels +CUTLASS_KERNELS_LEGACY := \ + cutlass_simt_dgemm_128x128_8x2_*,\ + cutlass_simt_sgemm_128x128_8x2_*,\ + cutlass_simt_hgemm_256x128_8x2_*,\ + cutlass_tensorop_h884gemm_256x128_32x2_*,\ + cutlass_tensorop_d884gemm_128x128_16x3_*,\ + cutlass_tensorop_tf32_s1688gemm_tf32_256x128_16x3_*,\ + cutlass_tensorop_bf16_s16816gemm_bf16_256x128_32x3_*,\ + cutlass_tensorop_h16816gemm_256x128_32x3_*,\ + cutlass_tensorop_s8_i16832gemm_s8_256x128_64x3_*,\ + cutlass_tensorop_s4_i16864gemm_s4_256x128_128x3_* + +# SM90 Hopper FP8 WGMMA kernels (e4m3 in, f32 out); they need the "90a" arch. +# CUTLASS v3.x names put the MMA shape before "gemm" (s64x256x32gemm), v4.x +# names do not, hence the "*" before "gemm". +CUTLASS_KERNELS_SM90 := cutlass3x_sm90_tensorop_*gemm_e4m3_e4m3_f32_f32_f32_* + +# SM100 Blackwell 3x UMMA GEMM kernels +# Optimized for peak-FLOPS benchmarking on GB200/GB300: +# - Only large tiles (128x256, 256x128, 256x256) that are competitive at 16K³ +# - Only the canonical output type per precision (FP32-accum preferred) +# - FP4 kept in full (~49 kernels, small enough) +# - Block-scaled NVFP4 (true FP4 peak) added separately for SM103a (GB300) +# via the BlockScaledGemm operation kind. The FP4 Ultra path uses +# cutlass3x_sm103_bstensorop_gemm_ue4m3x*_ultra_* kernels (ue4m3 scale, +# vs16 = NVFP4 16-element block). They have no f32 C operand, so the +# f32-output variant is named f32_void_f32 (accumulator_C_D). +# - Keeps all cluster/layout/schedule variants per tile so the profiler +# can find the actual peak; runtime --kernels filtering in +# cuda_gemm_flops_performance.py further narrows to ~36/precision. +# On aarch64, each sub-group must stay under ~1000 objects to avoid +# R_AARCH64_PREL32 relocation overflow in per-family shared libraries. +CUTLASS_KERNELS_SM100 := \ + cutlass3x_sm100_tensorop_tf32gemm_f32_f32_f32_f32_f32_*,\ + cutlass3x_sm100_tensorop_gemm_f16_f16_f32_f16_f16_*,\ + cutlass3x_sm100_tensorop_gemm_bf16_bf16_f32_bf16_bf16_*,\ + cutlass3x_sm100_tensorop_gemm_s8_s8_s32_s8_s8_*,\ + cutlass3x_sm100_tensorop_gemm_e4m3_e4m3_f32_f32_f32_*,\ + cutlass3x_sm103_bstensorop_gemm_ue4m3xe2m1_ue4m3xe2m1_f32_void_f32_*ultra_2sm*,\ + cutlass3x_sm103_bstensorop_gemm_ue4m3xf4_ue4m3xf4_f32_void_f32_*ultra_2sm* + +# SM107 Rubin 3x UMMA GEMM kernels (CUTLASS v4.8.1, "107a" build only) +# - TF32/FP16/BF16: CUTLASS has no native SM107 generator; it retargets the +# SM100 generators to Sm107 when a 107 arch is built, so the names match +# the SM100 list with sm107. +# - FP8 and NVFP4: native SM107 kernels (Rubin MMA shapes with B-matrix +# reuse schedules). Only native names contain "breuse" (or "no_breuse"). +# The FP8 ones are runtime-typed (f8_f8). NVFP4 = e2m1 with ue4m3 scale +# and 16-element blocks (vs16). +# - NVFP4 with UE5M3 scales (vs16), MXFP4 (e2m1, ue8m0, vs32) and MXFP8 +# (runtime-typed f8, ue8m0): native 2SM kernels only, to bound build time. +# - No INT8: CuTe enables tcgen05 kind::i8 only for SM100a/SM101a/SM110. +CUTLASS_KERNELS_SM107 := \ + cutlass3x_sm107_tensorop_tf32gemm_f32_f32_f32_f32_f32_*,\ + cutlass3x_sm107_tensorop_gemm_f16_f16_f32_f16_f16_*,\ + cutlass3x_sm107_tensorop_gemm_bf16_bf16_f32_bf16_bf16_*,\ + cutlass3x_sm107_tensorop_gemm_f8_f8_f32_f32_f32_*breuse_*,\ + cutlass3x_sm107_bstensorop_gemm_ue4m3xe2m1_ue4m3xe2m1_f32_void_f32_*_o_vs16_*breuse_*,\ + cutlass3x_sm107_bstensorop_gemm_ue5m3xe2m1_ue5m3xe2m1_f32_void_f32_*_o_vs16_*breuse_2sm*,\ + cutlass3x_sm107_bstensorop_gemm_ue8m0xe2m1_ue8m0xe2m1_f32_void_f32_*_o_vs32_*breuse_2sm*,\ + cutlass3x_sm107_bstensorop_gemm_ue8m0xf8_ue8m0xf8_f32_void_f32_*breuse_2sm* + +# Install prefix of the Rubin build; cuda_gemm_flops_performance.py uses it for CC 10.7. +CUTLASS_SM107_PREFIX = $(SB_MICRO_PATH)/cutlass_sm107 + +# Strip spaces that Make inserts from the line-continuation backslashes. +# Without this, cmake receives "cutlass_simt_dgemm..., cutlass_simt_sgemm..." +# (note the space after each comma) which breaks CUTLASS's kernel filter. +_strip_spaces = $(subst $(space),,$1) +space := $(subst ,, ) + +CUTLASS_MK_DIR := $(dir $(abspath $(lastword $(MAKEFILE_LIST)))) + +# CUTLASS v4.8.0 and v4.8.1 generate SM107 MXFP8 (ue8m0xf8) as runtime-typed +# MXF8F6F4Format kernels, but BlockScaledGemmUniversal3xOperationBase's +# mapping() in tools/library/src/block_scaled_gemm_operation_3x.hpp omitted +# kE4M3/kE5M2 and fell into CUTE_GCC_UNREACHABLE (host SIGSEGV in +# can_implement()). Backport NVIDIA/cutlass commit 555a0474 to map +# kE5M2/kE4M3 and reject unsupported runtime datatypes with kErrorInvalidProblem. +CUTLASS_V481_MXFP8_PATCH = git -C cutlass apply --check $(CUTLASS_MK_DIR)cutlass_v4.8.1_mxfp8.patch && \ + git -C cutlass apply $(CUTLASS_MK_DIR)cutlass_v4.8.1_mxfp8.patch && \ + grep -q "MXF8F6F4Format::E4M3" cutlass/tools/library/src/block_scaled_gemm_operation_3x.hpp && \ + grep -q "is_supported(arguments->runtime_input_datatype_a)" cutlass/tools/library/src/block_scaled_gemm_operation_3x.hpp + +# CUTLASS v4.3.5 generates the GB300 (SM103) FP4 Ultra kernels only for CUDA 13.0+, +# but CUTLASS enables SM103 from CUDA 12.9 and they compile to real UTCOMMA kernels +# with it. Lower only that generator's gate; the grep fails if it no longer applies. +CUTLASS_SM103_ULTRA_PATCH = sed -i "/^def GenerateSM103_TensorOp_fp4_ultra_UMMA_gemm_with_block_scaled/,/return/s/(cuda_version, 13, 0)/(cuda_version, 12, 9)/" cutlass/python/cutlass_library/generator.py && grep -A3 "^def GenerateSM103_TensorOp_fp4_ultra_UMMA_gemm_with_block_scaled" cutlass/python/cutlass_library/generator.py | grep -q "(cuda_version, 12, 9)" + +# $(call cutlass_build,,,,) +# Configures, builds and installs ./cutlass into /{bin,lib}. CUTLASS v3.x+ also installs the +# generated kernel list to /share/cutlass/generated_kernels.txt; cuda_gemm_flops_performance.py +# skips precisions that have no kernel in it. +cutlass_build = cmake -DCMAKE_INSTALL_BINDIR=$(3)/bin \ + -DCMAKE_INSTALL_LIBDIR=$(3)/lib \ + -DCMAKE_INSTALL_INFODIR=$(3)/share \ + -DCMAKE_BUILD_TYPE=Release \ + -DCUTLASS_NVCC_ARCHS=$(1) \ + -DCUTLASS_ENABLE_EXAMPLES=OFF \ + -DCUTLASS_ENABLE_TESTS=OFF \ + -DCUTLASS_BUILD_SHARED_LIBS=ON \ + -DCUTLASS_BUILD_STATIC_LIBS=OFF \ + -DCMAKE_CXX_FLAGS="-fno-asynchronous-unwind-tables -fno-unwind-tables" \ + -DCMAKE_CUDA_FLAGS="-Xcompiler=-fno-asynchronous-unwind-tables -Xcompiler=-fno-unwind-tables" \ + -S ./cutlass \ + -B $(4) \ + "-DCUTLASS_LIBRARY_KERNELS=$(2)" && \ + cmake --build $(4) -j $(NUM_MAKE_JOBS) --target install && \ + rm -rf $(4) + +# --------------------------------------------------------------------------- +# cuda_cutlass target +# --------------------------------------------------------------------------- +# Each CUDA version tier selects: +# CUTLASS_TAG — git tag to clone; must have an entry in CUTLASS_COMMIT_ +# CUTLASS_ARCHS — semicolon-separated NVCC arch list +# CUTLASS_KERNS — comma-separated kernel filter patterns +# CUTLASS_PATCHES — optional post-clone fixups (sed commands, etc.) +# CUTLASS_SM107_KERNS — optional Rubin kernel filter; when set, a second +# "107a" build is installed into $(CUTLASS_SM107_PREFIX) +# +# After the version-specific block, a shared section clones, patches, +# configures, builds, and installs. + +# Expected commit of each CUTLASS tag; the clone fails if a tag has moved. +CUTLASS_COMMIT_v2.4.0 := ccb697bac77fcc898e9c897b2c90aa5b60ac72fb +CUTLASS_COMMIT_v3.9.2 := ad7b2f5e84fcfa124cb02b91d5bd26d238c0459e +CUTLASS_COMMIT_v4.3.5 := 4faf1a1568cf1e4ad8ff71846a13e16f2a6a6f6b +CUTLASS_COMMIT_v4.8.1 := 2c85f497547eb441f0fe80bfb0fb2e6f9add1719 + +.PHONY: cuda_cutlass + +cuda_cutlass: +ifeq ($(shell echo $(CUDA_VER)">=13.4" | bc -l), 1) + # ----------------------------------------------------------------------- + # Blackwell GB200/GB300 + Rubin (SM107a) — CUTLASS v4.8.1, two folders + # ----------------------------------------------------------------------- + # v4.8.0 is the first release with SM107. With any 107 arch in the list, + # it retargets the SM100 generators to SM107 (generator.py + # resolve_sm10x_arch_range), so the SM100 kernels disappear from that build. + # cutlass_profiler only runs kernels from its own libcutlass.so, so one + # clone is built twice into separate folders: + # - "100a;103a" -> $(SB_MICRO_PATH)/{bin,lib} (GB200, GB300) + # - "107a" -> $(CUTLASS_SM107_PREFIX)/{bin,lib} (Rubin) + # v4.8.0 extended the INT8 gate to ['100f', '101f', '103a', '107f']. + # Dropping '103a' keeps SM100a INT8 as in the 12.9 tier; the grep stops + # the build if the patch no longer applies. CUTLASS_V481_MXFP8_PATCH + # fixes the v4.8.1 runtime-typed MXFP8 (ue8m0xf8) SIGSEGV in can_implement(). + $(eval CUTLASS_TAG := v4.8.1) + $(eval CUTLASS_ARCHS := "100a;103a") + $(eval CUTLASS_KERNS := $(call _strip_spaces,$(CUTLASS_KERNELS_SM100))) + $(eval CUTLASS_PATCHES := sed -i "s/arch_family_cc = \['100f', '101f', '103a', '107f'\]/arch_family_cc = ['100f', '101f', '107f']/" cutlass/python/cutlass_library/generator.py && grep -q "arch_family_cc = \['100f', '101f', '107f'\]" cutlass/python/cutlass_library/generator.py && $(CUTLASS_V481_MXFP8_PATCH)) + $(eval CUTLASS_SM107_KERNS := $(call _strip_spaces,$(CUTLASS_KERNELS_SM107))) + +else ifeq ($(shell echo $(CUDA_VER)">=12.9" | bc -l), 1) + # ----------------------------------------------------------------------- + # Blackwell GB200 (SM100a) + GB300 (SM103a) — CUTLASS v4.3.5 + # ----------------------------------------------------------------------- + # Arch tokens must use the "a" suffix; bare "100"/"103" do not trigger + # Blackwell code generation in CUTLASS v4.3.5's generator.py. + # + # SM103a (GB300 "Blackwell Ultra") does NOT support INT8 UMMA + # (tcgen05.mma.kind::i8) — CuTe's config.hpp only defines + # CUTE_ARCH_TCGEN05_S8_MMA_ENABLED for SM100a/SM101a. + # However, CUTLASS's generator.py gates INT8 generation when ANY + # of ['100f','101f','103a'] is in the arch list. Since we build + # with "100a;103a", the gate fires and skips INT8 for ALL archs + # — including SM100a (GB200) which DOES support INT8. + # Fix: remove only '103a' from the gate so INT8 is generated for + # SM100a. The SM103a cubin will compile INT8 with a runtime trap + # (CUTE_INVALID_CONTROL_PATH) but the SM100a cubin will work. + # On a GB300 the profiler will load the SM103a cubin and correctly + # report the kernel as "failed"; cuda_gemm_flops_performance.py + # excludes int8_tc from the SM10.3 kernel map so it is never run. + # CUTLASS_SM103_ULTRA_PATCH lets CUDA 12.9 generate the GB300 NVFP4 kernels. + $(eval CUTLASS_TAG := v4.3.5) + $(eval CUTLASS_ARCHS := "100a;103a") + $(eval CUTLASS_KERNS := $(call _strip_spaces,$(CUTLASS_KERNELS_SM100))) + $(eval CUTLASS_PATCHES := sed -i "s/arch_family_cc = \['100f', '101f', '103a'\]/arch_family_cc = ['100f', '101f']/" cutlass/python/cutlass_library/generator.py && grep -q "arch_family_cc = \['100f', '101f'\]" cutlass/python/cutlass_library/generator.py && $(CUTLASS_SM103_ULTRA_PATCH)) + +else ifeq ($(shell echo $(CUDA_VER)">=12.8" | bc -l), 1) + # ----------------------------------------------------------------------- + # Ampere SM80 + Hopper SM90a + Blackwell SM100a — CUTLASS v4.3.5 + # ----------------------------------------------------------------------- + # SM90 non-FP8 precisions use legacy SM80 kernel names (SIMT + TensorOp) + # which are backward-compatible on Hopper. SM90 FP8 and SM100 use 3x naming. + # v4.3.5 gives the same SM100 names as the 12.9 tier; v3.9.2 puts the MMA + # shape before "gemm" (s128x256x8tf32gemm), which the SM100 filters and + # gemm-flops patterns do not match. The "a" archs are required: plain "90" + # builds the WGMMA kernels as stubs and plain "100" generates no SM100 + # kernels. Without 103a the INT8 gate does not fire, so no patch is needed. + $(eval CUTLASS_TAG := v4.3.5) + $(eval CUTLASS_ARCHS := "80;90a;100a") + $(eval CUTLASS_KERNS := $(call _strip_spaces,$(CUTLASS_KERNELS_LEGACY)),$(CUTLASS_KERNELS_SM90),$(call _strip_spaces,$(CUTLASS_KERNELS_SM100))) + $(eval CUTLASS_PATCHES := @true) + +else ifeq ($(shell echo $(CUDA_VER)">=12.0" | bc -l), 1) + # ----------------------------------------------------------------------- + # Volta through Hopper (SM70–SM90a) — CUTLASS v3.9.2 + # ----------------------------------------------------------------------- + # "90a" is needed for the Hopper FP8 WGMMA kernels (plain "90" builds stubs). + $(eval CUTLASS_TAG := v3.9.2) + $(eval CUTLASS_ARCHS := "70;75;80;86;89;90a") + $(eval CUTLASS_KERNS := $(call _strip_spaces,$(CUTLASS_KERNELS_LEGACY)),$(CUTLASS_KERNELS_SM90)) + $(eval CUTLASS_PATCHES := @true) + +else ifeq ($(shell echo $(CUDA_VER)">=11.8" | bc -l), 1) + # ----------------------------------------------------------------------- + # Volta through Ada (SM70–SM90) — CUTLASS v3.9.2 + # ----------------------------------------------------------------------- + # CUDA 11.8 has no sm_90a, so there are no Hopper FP8 kernels here. + $(eval CUTLASS_TAG := v3.9.2) + $(eval CUTLASS_ARCHS := "70;75;80;86;89;90") + $(eval CUTLASS_KERNS := $(call _strip_spaces,$(CUTLASS_KERNELS_LEGACY))) + $(eval CUTLASS_PATCHES := @true) + +else + # ----------------------------------------------------------------------- + # Volta through Ampere (SM70–SM86) — CUTLASS v2.4.0 + # ----------------------------------------------------------------------- + # v2.4.0 is the third_party/cutlass submodule commit; CUTLASS 3.x needs + # CUDA 11.4+ and CMake 3.19+. + $(eval CUTLASS_TAG := v2.4.0) + $(eval CUTLASS_ARCHS := "70;75;80;86") + $(eval CUTLASS_KERNS := $(call _strip_spaces,$(CUTLASS_KERNELS_LEGACY))) + $(eval CUTLASS_PATCHES := @true) + +endif + # ----------------------------------------------------------------------- + # Shared clone → patch → build → install pipeline + # ----------------------------------------------------------------------- + # With the narrowed kernel filters (Blackwell ~3,800 objects, Rubin ~3,400; + # max ~840 per sub-group), shared per-family libraries stay under the + # R_AARCH64_PREL32 ±2 GB limit on aarch64. Unwind table suppression + # further reduces .eh_frame pressure. + if [ -d cutlass ]; then rm -rf cutlass; fi + git clone --branch $(CUTLASS_TAG) --depth 1 https://github.com/NVIDIA/cutlass.git && \ + test -n "$(CUTLASS_COMMIT_$(CUTLASS_TAG))" && \ + test "$$(git -C cutlass rev-parse HEAD)" = "$(CUTLASS_COMMIT_$(CUTLASS_TAG))" + $(CUTLASS_PATCHES) + $(call cutlass_build,$(CUTLASS_ARCHS),$(CUTLASS_KERNS),$(SB_MICRO_PATH),./cutlass/build) + $(if $(CUTLASS_SM107_KERNS),$(call cutlass_build,"107a",$(CUTLASS_SM107_KERNS),$(CUTLASS_SM107_PREFIX),./cutlass/build_sm107)) diff --git a/third_party/cutlass_v4.8.1_mxfp8.patch b/third_party/cutlass_v4.8.1_mxfp8.patch new file mode 100644 index 000000000..2b8b82041 --- /dev/null +++ b/third_party/cutlass_v4.8.1_mxfp8.patch @@ -0,0 +1,45 @@ +diff --git a/tools/library/src/block_scaled_gemm_operation_3x.hpp b/tools/library/src/block_scaled_gemm_operation_3x.hpp +index a155084..096a09a 100644 +--- a/tools/library/src/block_scaled_gemm_operation_3x.hpp ++++ b/tools/library/src/block_scaled_gemm_operation_3x.hpp +@@ -234,7 +234,11 @@ template + + auto mapping = [](RuntimeDatatype type) { + if constexpr (cute::is_same_v) { +- if (type == RuntimeDatatype::kE3M2) { ++ if (type == RuntimeDatatype::kE5M2) { ++ return cute::UMMA::MXF8F6F4Format::E5M2; ++ } else if (type == RuntimeDatatype::kE4M3) { ++ return cute::UMMA::MXF8F6F4Format::E4M3; ++ } else if (type == RuntimeDatatype::kE3M2) { + return cute::UMMA::MXF8F6F4Format::E3M2; + } else if (type == RuntimeDatatype::kE2M3) { + return cute::UMMA::MXF8F6F4Format::E2M3; +@@ -255,5 +259,27 @@ template + CUTE_GCC_UNREACHABLE; + }; + ++ auto is_supported = [](RuntimeDatatype type) { ++ if constexpr (cute::is_same_v) { ++ return type == RuntimeDatatype::kE5M2 || ++ type == RuntimeDatatype::kE4M3 || ++ type == RuntimeDatatype::kE3M2 || ++ type == RuntimeDatatype::kE2M3 || ++ type == RuntimeDatatype::kE2M1; ++ } ++ else if constexpr (cute::is_same_v) { ++ return type == RuntimeDatatype::kE2M1; ++ } ++ // BlockScaled kernels receive either MXF4Format or MXF8F6F4Format runtime datatype ++ CUTE_GCC_UNREACHABLE; ++ }; ++ ++ // Reject a runtime datatype the kernel cannot represent (including the kStatic default when the ++ // flag is not given) instead of reaching the unreachable path with an undefined format. ++ if (!is_supported(arguments->runtime_input_datatype_a) || ++ !is_supported(arguments->runtime_input_datatype_b)) { ++ return Status::kErrorInvalidProblem; ++ } ++ + operator_args.mainloop.runtime_data_type_a = mapping(arguments->runtime_input_datatype_a); + operator_args.mainloop.runtime_data_type_b = mapping(arguments->runtime_input_datatype_b);