From 2508e99f62a572303e57d26d63ed279847ac248c Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Thu, 15 Oct 2026 04:09:04 +0000 Subject: [PATCH 01/16] Benchmarks - Add experimental MXFP4 hipBLASLt GEMM Add an opt-in gfx950 MXFP4 path using the ROCm 7.2.4 client contract: E2M1 inputs, 32-element E8M0 blocks, FP32 output, and mandatory CPU verification. Preserve legacy commands and metrics while rejecting invalid throughput and validating the new result contract.\n\nAdd capability, command, parser, failure, and regression coverage. Native client builds, GPU correctness, kernel evidence, and performance baselines remain pending; no production configuration is enabled. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/micro-benchmarks.md | 57 +++++ .../micro_benchmarks/hipblaslt_function.py | 223 +++++++++++++----- .../test_hipblaslt_function.py | 215 ++++++++++++++++- 3 files changed, 430 insertions(+), 65 deletions(-) diff --git a/docs/user-tutorial/benchmarks/micro-benchmarks.md b/docs/user-tutorial/benchmarks/micro-benchmarks.md index 6ce505657..23aa57ab3 100644 --- a/docs/user-tutorial/benchmarks/micro-benchmarks.md +++ b/docs/user-tutorial/benchmarks/micro-benchmarks.md @@ -103,6 +103,55 @@ For quick execution checks, set `num_warmup: 1` and `num_steps: 5` under `parame These shorter runs are useful for diagnosing support and configuration errors, not stable performance measurements. +The ROCm benchmark retains `fp32`, `fp16`, `bf16`, and `fp8` inputs and adds an +**experimental, opt-in `mxfp4`** input. Hardware validation is pending; this is not +a production performance baseline or a claim of MI455X support. The initial path +only allows `gfx950` (MI350X/MI355X/MI350P), TN layout, non-batched GEMM, positive +dimensions with K divisible by 32, and `hpl` or `trig_float` initialization. +Other architectures are explicitly rejected rather than converted to FP16. + +The client contract is based on +[hipBLASLt ROCm 7.2.4 at `b9d7970`](https://github.com/ROCm/hipBLASLt/tree/b9d797017b4d4d7c3692ccc5ac099ff9777ace0f) +(library 1.2.2, with RocRoller enabled). A compatible ROCm PyTorch device and a +`hipblaslt-bench` client with block-scaling options are required. Client option +checks do not prove that an algorithm is available for a particular shape. +The existing ROCm 6.4 image is not upgraded or certified for this mode. + +MXFP4 uses E2M1 A/B inputs, one E8M0 scale per 32 K elements, FP32 computation and +C/D, `alpha=1`, and `beta=0`. Packing, scale-buffer layout, and the decoded-input +CPU reference are supplied by the pinned vendor client, not a second SuperBench +quantization implementation. GPU-event timing excludes CPU reference, +initialization, and packing; no quantization-inclusive latency is reported. +Kernel information and full client output are retained in raw data. + +Example wrapper parameters for an experimental smoke case: + +```text +--in_types mxfp4 --enable_experimental_fp4 --shapes 128,128,128 +--transA T --transB N --initialization hpl --num_warmup 20 --num_steps 50 +``` + +The wrapper always requests CPU verification for MXFP4. The pinned benchmark +reports verification errors without asserting the norm check, so SuperBench +requires a finite relative Frobenius `norm_error < 1e-5` and finite, non-negative +`atol`/`rtol` fields (not `failed`). The norm threshold follows the vendor's FP32 +output check and still requires calibration on real MXFP4 hardware. It checks +kernel error against the decoded quantized inputs, not quantization error against +the original unquantized inputs. + +MXFP4 results must match the requested shape, dtypes, layout and block-scale mode. +Throughput must agree with `2*M*N*K / seconds` within 1% for printed-value rounding. +Missing, malformed, duplicate, non-finite, unsupported or verification-failed +results are errors and do not produce MXFP4 performance metrics. All ROCm input +types now reject non-finite or non-positive throughput; existing valid metric +names, units, commands and default input types remain unchanged. + +Before promoting this mode, run correctness and native-kernel checks on each +claimed GPU/SDK combination, replace synthetic parser fixtures with actual +versioned captures, and repeat a small fixed shape set at least three times. +MI455X needs a separate SDK, format and architecture qualification. No production +configuration or performance gate is enabled by this experimental path. + #### Metrics | Name | Unit | Description | @@ -110,6 +159,14 @@ performance measurements. | cublaslt-gemm/${dtype}\_${batch}\_${m}\_${n}\_${k}_flops | FLOPS (TFLOPS) | TFLOPS of measured GEMM kernel. | | hipblaslt-gemm/${dtype}\_${batch}\_${m}\_${n}\_${k}_flops | FLOPS (TFLOPS) | TFLOPS of measured GEMM kernel. | +MXFP4 additionally reports the following metrics only after validation succeeds: + +| Name | Unit | Description | +|------|------|-------------| +| hipblaslt-gemm/mxfp4\_1\_${m}\_${n}\_${k}_time | time (us) | GEMM-only GPU-event latency. | +| hipblaslt-gemm/mxfp4\_1\_${m}\_${n}\_${k}_norm_error | ratio | Relative Frobenius error against the vendor CPU reference. | +| hipblaslt-gemm/mxfp4\_1\_${m}\_${n}\_${k}_correctness | flag | 1 after the wrapper verification checks pass; failed cases return an error without performance metrics. | + ### `cublas-function` #### Introduction diff --git a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py index 6c708b3c2..338c116a2 100644 --- a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py +++ b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py @@ -3,13 +3,18 @@ """Module of the hipBlasLt GEMM benchmark.""" +import math import os import re +import shlex +from typing import Dict, Tuple -from superbench.common.utils import logger +from superbench.common.utils import LazyImport, logger, run_command from superbench.benchmarks import BenchmarkRegistry, Platform, ReturnCode from superbench.benchmarks.micro_benchmarks import BlasLtBaseBenchmark +torch = LazyImport('torch') + class HipBlasLtBenchmark(BlasLtBaseBenchmark): """The hipBlasLt GEMM benchmark class.""" @@ -23,12 +28,16 @@ def __init__(self, name, parameters=''): super().__init__(name, parameters) self._bin_name = 'hipblaslt-bench' - self._in_types = ['fp32', 'fp16', 'bf16', 'fp8'] + self._in_types = ['fp32', 'fp16', 'bf16', 'fp8', 'mxfp4'] self._in_type_map = { 'fp16': '--a_type f16_r --b_type f16_r --c_type f16_r --d_type f16_r --compute_type f32_r', 'fp32': '--a_type f32_r --b_type f32_r --c_type f32_r --d_type f32_r --compute_type f32_r', 'bf16': '--a_type bf16_r --b_type bf16_r --c_type bf16_r --d_type bf16_r --compute_type f32_r', 'fp8': '--a_type f8_r --b_type f8_r --c_type f8_r --d_type f8_r --compute_type f32_r', + 'mxfp4': '--a_type f4_r --b_type f4_r --c_type f32_r --d_type f32_r --compute_type f32_r' + ' --scaleA 3 --scaleB 3 --scaleABlockRowSize 32 --scaleABlockColSize 1' + ' --scaleBBlockRowSize 1 --scaleBBlockColSize 32 --alpha 1 --beta 0' + ' --algo_method heuristic --requested_solution 1 --verify 1 --use_gpu_timer 1 --print_kernel_info 1', } def add_parser_arguments(self): @@ -67,6 +76,66 @@ def add_parser_arguments(self): required=False, help='Transpose matrix B.', ) + self._parser.add_argument( + '--enable_experimental_fp4', + action='store_true', + help='Opt in to unvalidated MXFP4 on gfx950 with a block-scaling hipblaslt-bench client.', + ) + + def _validate_mxfp4_arguments(self) -> None: + """Validate the experimental non-batched, TN MXFP4 case contract.""" + if not self._args.enable_experimental_fp4: + raise ValueError('MXFP4 requires --enable_experimental_fp4; hardware validation is pending.') + if (self._args.transA, self._args.transB) != ('T', 'N'): + raise ValueError('MXFP4 currently requires --transA T --transB N.') + if self._args.initialization not in ['hpl', 'trig_float']: + raise ValueError('MXFP4 requires --initialization hpl or trig_float.') + if self._args.num_warmup < 0 or self._args.num_steps < 1: + raise ValueError('MXFP4 requires non-negative warmup and positive measurement iterations.') + for m, n, k, batch, precision in self._shapes_to_run: + if precision == 'mxfp4' and (batch != 0 or min(m, n, k) <= 0 or k % 32 != 0): + raise ValueError('MXFP4 requires --batch 0, positive dimensions, and K divisible by 32.') + + def _check_mxfp4_support(self) -> bool: + """Check the selected ROCm device and the client's block-scaling options.""" + try: + if torch.version.hip is None or not torch.cuda.is_available(): + raise RuntimeError('MXFP4 requires a working ROCm PyTorch device.') + arch = torch.cuda.get_device_properties(0).gcnArchName.split(':')[0] + except (AttributeError, RuntimeError) as e: + self._result.set_return_code(ReturnCode.MICROBENCHMARK_DEVICE_GETTING_FAILURE) + logger.error('Cannot identify the MXFP4 device - benchmark: {}, message: {}.'.format(self._name, str(e))) + return False + + if arch != 'gfx950': + self._result.set_return_code(ReturnCode.MICROBENCHMARK_UNSUPPORTED_ARCHITECTURE) + logger.error('Experimental MXFP4 only allows gfx950 - benchmark: {}, architecture: {}.'.format( + self._name, arch + )) + return False + + output = run_command(f'{shlex.quote(self.__bin_path)} --help', quiet=True) + self._result.add_raw_data('mxfp4_client_help', output.stdout, self._args.log_raw_data) + if output.returncode != 0: + self._result.set_return_code(ReturnCode.MICROBENCHMARK_EXECUTION_FAILURE) + logger.error( + 'Cannot query MXFP4 client options - benchmark: {}, output: {}.'.format(self._name, output.stdout) + ) + return False + required_options = [ + '--scaleA', '--scaleB', '--scaleABlockRowSize', '--scaleABlockColSize', + '--scaleBBlockRowSize', '--scaleBBlockColSize', '--verify', '--use_gpu_timer', + '--print_kernel_info', '3 = block', + ] + missing = [option for option in required_options if not re.search(re.escape(option) + r'\b', output.stdout)] + if missing: + self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) + logger.error('MXFP4 client is missing required options - benchmark: {}, missing: {}.'.format( + self._name, missing + )) + return False + self._result.add_raw_data('mxfp4_gpu_arch', arch, self._args.log_raw_data) + return True def _preprocess(self): """Preprocess/preparation operations before the benchmarking. @@ -81,6 +150,16 @@ def _preprocess(self): self._commands = [] self._precision_in_commands = [] + if 'mxfp4' in self._args.in_types: + try: + self._validate_mxfp4_arguments() + except ValueError as e: + self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) + logger.error('Invalid MXFP4 arguments - benchmark: {}, message: {}.'.format(self._name, str(e))) + return False + if not self._check_mxfp4_support(): + return False + for (_m, _n, _k, _b, _in_type) in self._shapes_to_run: command = f'{self.__bin_path} -m {_m} -n {_n} -k {_k} -j {self._args.num_warmup}' + \ f' -i {self._args.num_steps} {self._in_type_map[_in_type]}' + \ @@ -93,6 +172,72 @@ def _preprocess(self): return True + def _parse_result_row(self, raw_output: str, precision: str) -> Dict[str, str]: + """Parse one result using header names, preserving legacy column handling.""" + lines = raw_output.splitlines() + index = None + for i, line in enumerate(lines): + if 'hipblaslt-Gflops' in line: + index = i + break + if index is None: + raise ValueError('Line with "hipblaslt-Gflops" not found in the log.') + + header_fields = [field.strip() for field in lines[index].split(',')] + header_fields[0] = re.sub(r'^\s*\[\d+\]:?', '', header_fields[0]).strip() + if precision == 'mxfp4' and ( + len(set(header_fields)) != len(header_fields) + or sum('hipblaslt-Gflops' in line for line in lines) != 1 + or any(len(line.split(',')) == len(header_fields) for line in lines[index + 2:]) + ): + raise ValueError('MXFP4 requires unique columns and exactly one result.') + + col_idx_by_name: Dict[str, int] = {} + for col_idx, col_name in enumerate(header_fields): + col_idx_by_name.setdefault(col_name, col_idx) + required_columns = ['batch_count', 'm', 'n', 'k', 'hipblaslt-Gflops'] + missing_columns = [column for column in required_columns if column not in col_idx_by_name] + if missing_columns: + raise ValueError(f'Required column(s) not found in header: {missing_columns}.') + if index + 1 >= len(lines): + raise ValueError('Data line missing after "hipblaslt-Gflops" header.') + + fields = [field.strip() for field in lines[index + 1].split(',')] + if len(fields) != len(header_fields): + raise ValueError( + f'Field count mismatch: header has {len(header_fields)} columns but data has {len(fields)} columns' + ) + return {column: fields[col_idx] for column, col_idx in col_idx_by_name.items()} + + def _validate_mxfp4_result(self, cmd_idx: int, row: Dict[str, str], gflops: float) -> Tuple[float, float]: + """Require the requested MXFP4 case, valid timing, and CPU verification.""" + m, n, k, _, _ = self._shapes_to_run[cmd_idx] + expected = { + 'transA': 'T', 'transB': 'N', 'grouped_gemm': '0', 'batch_count': '1', + 'm': str(m), 'n': str(n), 'k': str(k), 'a_type': 'f4_r', 'b_type': 'f4_r', + 'c_type': 'f32_r', 'd_type': 'f32_r', 'compute_type': 'f32_r', + 'scaleA': '3', 'scaleB': '3', 'use_gpu_timer': '1', + } + for column, value in expected.items(): + if row.get(column) != value: + raise ValueError(f'MXFP4 column {column} must be {value}, got {row.get(column)}.') + + latency = float(row['us']) + if not math.isfinite(latency) or latency <= 0: + raise ValueError('MXFP4 latency must be finite and positive.') + if not math.isclose(gflops, 2 * m * n * k / latency / 1000, rel_tol=0.01): + raise ValueError('MXFP4 throughput does not match 2*M*N*K and the reported latency.') + + # hipblaslt-bench reports verification errors without asserting them. + norm_error = float(row['norm_error']) + if not 0 <= norm_error < 1e-5: + raise ValueError('MXFP4 FP32-output relative Frobenius norm error must be finite and below 1e-5.') + for column in ['atol', 'rtol']: + error = float(row[column]) + if not math.isfinite(error) or error < 0: + raise ValueError(f'MXFP4 verification column {column} must be finite and non-negative.') + return latency, norm_error + def _process_raw_result(self, cmd_idx, raw_output): """Function to parse raw results and save the summarized results. @@ -108,67 +253,19 @@ def _process_raw_result(self, cmd_idx, raw_output): self._result.add_raw_data(f'raw_output_{cmd_idx}', raw_output, self._args.log_raw_data) try: - lines = raw_output.splitlines() - index = None - - # Find the header line containing 'hipblaslt-Gflops' - for i, line in enumerate(lines): - if 'hipblaslt-Gflops' in line: - index = i - break - - if index is None: - raise ValueError('Line with "hipblaslt-Gflops" not found in the log.') - - # Parse the header and resolve every key column (batch_count/m/n/k/hipblaslt-Gflops) - # by name. This keeps the parser forward-compatible across known and future - # hipBLASLt output formats (v600: 23 columns; v1500: 34 columns with extra - # a_type/b_type/c_type/scaleA-D/amaxD/bias_type/aux_type/hipblaslt-GB/s), - # without relying on any fixed column position. - header_fields = lines[index].strip().split(',') - # Strip leading rank markers like '[0]' or '[0]:' from the first header field. - # Use a regex anchored at the start so a column name that legitimately contains - # ']' (unlikely, but defensive) is not truncated. - header_fields[0] = re.sub(r'^\s*\[\d+\]:?', '', header_fields[0]) - - # Build a name -> column-index map (first occurrence wins for any duplicates). - col_idx_by_name = {} - for col_idx, col_name in enumerate(header_fields): - col_idx_by_name.setdefault(col_name.strip(), col_idx) - - required_columns = ['batch_count', 'm', 'n', 'k', 'hipblaslt-Gflops'] - missing_columns = [c for c in required_columns if c not in col_idx_by_name] - if missing_columns: - raise ValueError(f'Required column(s) not found in header: {missing_columns}.') - - # Ensure a data line follows the header (e.g., hipblaslt-bench may have - # crashed after printing the header). - if index + 1 >= len(lines): - raise ValueError('Data line missing after "hipblaslt-Gflops" header.') - - # Split the data line into fields using a comma as the delimiter - fields = lines[index + 1].strip().split(',') - - # Validate that the data line has the same number of columns as the header - if len(fields) != len(header_fields): - raise ValueError( - f'Field count mismatch: header has {len(header_fields)} columns ' - f'but data has {len(fields)} columns' - ) - - # Resolve every key value by header name and strip whitespace from each, so - # any padding around CSV values does not bleed into the metric key. - batch_count = fields[col_idx_by_name['batch_count']].strip() - m_val = fields[col_idx_by_name['m']].strip() - n_val = fields[col_idx_by_name['n']].strip() - k_val = fields[col_idx_by_name['k']].strip() - gflops_col = col_idx_by_name['hipblaslt-Gflops'] - - self._result.add_result( - f'{self._precision_in_commands[cmd_idx]}_{batch_count}_{m_val}_{n_val}_{k_val}_flops', - float(fields[gflops_col]) / 1000 - ) - except BaseException as e: + precision = self._precision_in_commands[cmd_idx] + row = self._parse_result_row(raw_output, precision) + gflops = float(row['hipblaslt-Gflops']) + if not math.isfinite(gflops) or gflops <= 0: + raise ValueError('Throughput must be finite and positive.') + metric = f'{precision}_{row["batch_count"]}_{row["m"]}_{row["n"]}_{row["k"]}' + if precision == 'mxfp4': + latency, norm_error = self._validate_mxfp4_result(cmd_idx, row, gflops) + self._result.add_result(f'{metric}_time', latency) + self._result.add_result(f'{metric}_norm_error', norm_error) + self._result.add_result(f'{metric}_correctness', 1) + self._result.add_result(f'{metric}_flops', gflops / 1000) + except (IndexError, KeyError, TypeError, ValueError) as e: self._result.set_return_code(ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) logger.error( 'The result format is invalid - round: {}, benchmark: {}, raw output: {}, message: {}.'.format( diff --git a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py index 484790755..3f6515a1f 100644 --- a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py +++ b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py @@ -5,9 +5,11 @@ import unittest from types import SimpleNamespace +from unittest.mock import patch from tests.helper.testcase import BenchmarkTestCase from superbench.benchmarks import BenchmarkRegistry, BenchmarkType, ReturnCode, Platform +from superbench.benchmarks.micro_benchmarks import hipblaslt_function from superbench.benchmarks.result import BenchmarkResult @@ -21,10 +23,50 @@ def setUpClass(cls): cls.createMockEnvs(cls) cls.createMockFiles(cls, ['bin/hipblaslt-bench']) - def get_benchmark(self): + def get_benchmark(self, parameters=''): """Get Benchmark.""" (benchmark_cls, _) = BenchmarkRegistry._BenchmarkRegistry__select_benchmark(self.benchmark_name, Platform.ROCM) - return benchmark_cls(self.benchmark_name, parameters='') + return benchmark_cls(self.benchmark_name, parameters=parameters) + + def preprocess_mxfp4(self, parameters=None, arch='gfx950:sramecc+:xnack-', help_result=None, available=True): + """Preprocess with synthetic ROCm device and client capability information.""" + if parameters is None: + parameters = ( + '--in_types mxfp4 --enable_experimental_fp4 --shapes 128,128,128' + ' --transA T --transB N --initialization hpl' + ) + if help_result is None: + help_result = SimpleNamespace( + returncode=0, + stdout='--scaleA --scaleB 3 = block --scaleABlockRowSize --scaleABlockColSize' + ' --scaleBBlockRowSize --scaleBBlockColSize --verify --use_gpu_timer --print_kernel_info', + ) + benchmark = self.get_benchmark(parameters) + with patch.object(hipblaslt_function.torch.version, 'hip', '7.2.4'), \ + patch.object(hipblaslt_function.torch.cuda, 'is_available', return_value=available), \ + patch.object( + hipblaslt_function.torch.cuda, 'get_device_properties', + return_value=SimpleNamespace(gcnArchName=arch) + ), \ + patch.object(hipblaslt_function, 'run_command', return_value=help_result): + result = benchmark._preprocess() + return benchmark, result + + def mxfp4_output(self, overrides=None, missing=(), reverse=False): + """Build synthetic CSV, not a captured GPU result.""" + row = { + 'transA': 'T', 'transB': 'N', 'grouped_gemm': '0', 'batch_count': '1', + 'm': '128', 'n': '128', 'k': '128', 'a_type': 'f4_r', 'b_type': 'f4_r', + 'c_type': 'f32_r', 'd_type': 'f32_r', 'compute_type': 'f32_r', + 'scaleA': '3', 'scaleB': '3', 'use_gpu_timer': '1', + 'hipblaslt-Gflops': '1048.576', 'us': '4', 'norm_error': '1e-6', + 'atol': '0.0001', 'rtol': '0.0001', + } + row.update(overrides or {}) + for column in missing: + del row[column] + columns = list(reversed(row)) if reverse else list(row) + return '[0]:' + ','.join(columns) + '\n' + ','.join(row[column] for column in columns) + '\n' def test_hipblaslt_gemm_cls(self): """Test hipblaslt-bench benchmark class.""" @@ -80,6 +122,175 @@ def cmd(t, b, m, n, k): for _k in [8, 12, 16, 20, 24, 28, 32]: self.assertIn(cmd(_t, 0, _m, _n, _k), benchmark._commands) + def test_mxfp4_command_generation(self): + """Test explicit MXFP4 input, scale, verification, and device timing options.""" + benchmark, result = self.preprocess_mxfp4() + self.assertTrue(result) + self.assertEqual(len(benchmark._commands), 1) + expected = ( + f'{benchmark._HipBlasLtBenchmark__bin_path} -m 128 -n 128 -k 128 -j 20 -i 50' + ' --a_type f4_r --b_type f4_r --c_type f32_r --d_type f32_r --compute_type f32_r' + ' --scaleA 3 --scaleB 3 --scaleABlockRowSize 32 --scaleABlockColSize 1' + ' --scaleBBlockRowSize 1 --scaleBBlockColSize 32 --alpha 1 --beta 0' + ' --algo_method heuristic --requested_solution 1 --verify 1 --use_gpu_timer 1 --print_kernel_info 1' + ' --transA T --transB N --initialization hpl' + ) + self.assertEqual(benchmark._commands[0], expected) + self.assertEqual(benchmark.raw_data['mxfp4_gpu_arch'][0], 'gfx950') + + def test_mxfp4_invalid_arguments(self): + """Reject missing opt-in and unsupported layouts, initialization, shapes, or counts.""" + valid = ( + '--in_types mxfp4 --enable_experimental_fp4 --shapes 128,128,128' + ' --transA T --transB N --initialization hpl' + ) + invalid = [ + valid.replace('--enable_experimental_fp4', ''), + valid.replace('--transA T', '--transA N'), + valid.replace('--transB N', '--transB T'), + valid.replace('--initialization hpl', '--initialization rand_int'), + valid.replace('128,128,128', '128,128,129'), + valid.replace('128,128,128', '0,128,128'), + valid + ' --batch 1', + valid + ' --num_warmup -1', + valid + ' --num_steps 0', + ] + for parameters in invalid: + with self.subTest(parameters=parameters): + benchmark, result = self.preprocess_mxfp4(parameters) + self.assertFalse(result) + self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) + self.assertEqual(benchmark._commands, []) + + def test_mxfp4_unsupported_devices(self): + """Reject older GPUs and unqualified future architectures without generating commands.""" + for arch in ['gfx908', 'gfx90a', 'gfx942', 'gfx1201', 'gfx999']: + with self.subTest(arch=arch): + benchmark, result = self.preprocess_mxfp4(arch=arch) + self.assertFalse(result) + self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_UNSUPPORTED_ARCHITECTURE) + self.assertEqual(benchmark._commands, []) + benchmark, result = self.preprocess_mxfp4(available=False) + self.assertFalse(result) + self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_DEVICE_GETTING_FAILURE) + + def test_mxfp4_client_capabilities(self): + """Reject old client options and explicit capability-query failures.""" + for output in [ + SimpleNamespace(returncode=0, stdout='--scaleA --scaleB 0 = None, 1 = scalar, 2 = vector'), + SimpleNamespace(returncode=1, stdout='Cannot load hipBLASLt'), + ]: + with self.subTest(output=output): + benchmark, result = self.preprocess_mxfp4(help_result=output) + self.assertFalse(result) + expected = ReturnCode.INVALID_ARGUMENT if output.returncode == 0 else \ + ReturnCode.MICROBENCHMARK_EXECUTION_FAILURE + self.assertEqual(benchmark.return_code, expected) + self.assertEqual(benchmark._commands, []) + + options = [ + '--scaleA', '--scaleB', '--scaleABlockRowSize', '--scaleABlockColSize', + '--scaleBBlockRowSize', '--scaleBBlockColSize', '--verify', '--use_gpu_timer', + '--print_kernel_info', '3 = block', + ] + for missing in options: + with self.subTest(missing=missing): + help_result = SimpleNamespace( + returncode=0, stdout=' '.join(option for option in options if option != missing) + ) + benchmark, result = self.preprocess_mxfp4(help_result=help_result) + self.assertFalse(result) + self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) + + def test_mxfp4_subprocess_status(self): + """Propagate client and verification failures without emitting performance metrics.""" + for returncode, raw_output in [ + (0, self.mxfp4_output()), (1, 'No supported solutions found'), + (0, self.mxfp4_output({'atol': 'failed'})), + ]: + with self.subTest(returncode=returncode, raw_output=raw_output): + benchmark, result = self.preprocess_mxfp4() + self.assertTrue(result) + output = SimpleNamespace(returncode=returncode, stdout=raw_output) + with patch('superbench.benchmarks.micro_benchmarks.micro_base.run_command', return_value=output): + success = benchmark._benchmark() + expected = returncode == 0 and 'failed' not in raw_output + self.assertEqual(success, expected) + if not expected: + code = ReturnCode.MICROBENCHMARK_EXECUTION_FAILURE if returncode else \ + ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE + self.assertEqual(benchmark.return_code, code) + self.assertEqual(set(benchmark.result), {'return_code'}) + + def test_mxfp4_result_parsing(self): + """Check reordered columns, exact metric units, and the norm threshold boundary.""" + for reverse, norm in [(False, '1e-6'), (True, '9.999e-6')]: + with self.subTest(reverse=reverse, norm=norm): + benchmark, result = self.preprocess_mxfp4() + self.assertTrue(result) + self.assertTrue(benchmark._process_raw_result( + 0, self.mxfp4_output({'norm_error': norm}, reverse=reverse) + )) + self.assertAlmostEqual(benchmark.result['mxfp4_1_128_128_128_flops'][0], 1.048576) + self.assertEqual(benchmark.result['mxfp4_1_128_128_128_time'], [4]) + self.assertEqual(benchmark.result['mxfp4_1_128_128_128_norm_error'], [float(norm)]) + self.assertEqual(benchmark.result['mxfp4_1_128_128_128_correctness'], [1]) + self.assertEqual(benchmark.return_code, ReturnCode.SUCCESS) + + def test_mxfp4_invalid_results(self): + """Reject wrong cases, fallback dtypes, invalid metrics, and failed CPU verification.""" + overrides = [ + {'m': '256'}, {'n': '256'}, {'k': '256'}, {'batch_count': '2'}, + {'transA': 'N'}, {'transB': 'T'}, {'grouped_gemm': '1'}, + {'a_type': 'f16_r'}, {'b_type': 'f16_r'}, {'c_type': 'f16_r'}, + {'d_type': 'f16_r'}, {'compute_type': 'f16_r'}, {'scaleA': '0'}, + {'scaleB': '1'}, {'use_gpu_timer': '0'}, + {'us': '0'}, {'us': '-1'}, {'us': 'nan'}, {'us': 'inf'}, + {'hipblaslt-Gflops': '0'}, {'hipblaslt-Gflops': '-1'}, + {'hipblaslt-Gflops': 'nan'}, {'hipblaslt-Gflops': 'inf'}, + {'hipblaslt-Gflops': '10'}, + {'norm_error': '1e-5'}, {'norm_error': '-1'}, {'norm_error': 'nan'}, {'norm_error': 'inf'}, + {'atol': 'failed'}, {'rtol': 'failed'}, {'atol': 'nan'}, {'rtol': 'inf'}, {'rtol': '-1'}, + ] + for override in overrides: + with self.subTest(override=override): + benchmark, result = self.preprocess_mxfp4() + self.assertTrue(result) + self.assertFalse(benchmark._process_raw_result(0, self.mxfp4_output(override))) + self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) + self.assertEqual(set(benchmark.result), {'return_code'}) + + def test_mxfp4_incomplete_results(self): + """Reject absent verification columns, malformed CSV, and multiple algorithm results.""" + output = self.mxfp4_output() + header, row = output.splitlines() + invalid = [ + self.mxfp4_output(missing=[column]) + for column in ['a_type', 'scaleA', 'norm_error', 'atol', 'rtol', 'us', 'use_gpu_timer'] + ] + invalid.extend([ + header + '\n', header + '\n' + row + ',extra\n', + header + ',m\n' + row + ',128\n', output + output, output + row + '\n', 'No supported solutions found', + ]) + for raw_output in invalid: + with self.subTest(raw_output=raw_output): + benchmark, result = self.preprocess_mxfp4() + self.assertTrue(result) + self.assertFalse(benchmark._process_raw_result(0, raw_output)) + self.assertEqual(set(benchmark.result), {'return_code'}) + self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) + + def test_legacy_invalid_throughput(self): + """Reject non-finite or non-positive throughput without changing legacy metric names.""" + for value in ['nan', 'inf', '-1', '0']: + with self.subTest(value=value): + benchmark = self.get_benchmark('--shapes 128,128,128') + self.assertTrue(benchmark._preprocess()) + output = f'[0]:batch_count,m,n,k,hipblaslt-Gflops\n1,128,128,128,{value}\n' + self.assertFalse(benchmark._process_raw_result(0, output)) + self.assertEqual(set(benchmark.result), {'return_code'}) + self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) + def test_hipblaslt_gemm_result_parsing(self): """Test hipblaslt-bench benchmark result parsing.""" benchmark = self.get_benchmark() From 3130f8d29a5396eca07fd3c180a38e9ece6cb480 Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Thu, 15 Oct 2026 04:12:21 +0000 Subject: [PATCH 02/16] Tests - Keep MXFP4 fixtures compatible with Python 3.7 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py index 3f6515a1f..88e7a0e2f 100644 --- a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py +++ b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py @@ -65,7 +65,9 @@ def mxfp4_output(self, overrides=None, missing=(), reverse=False): row.update(overrides or {}) for column in missing: del row[column] - columns = list(reversed(row)) if reverse else list(row) + columns = list(row) + if reverse: + columns.reverse() return '[0]:' + ','.join(columns) + '\n' + ','.join(row[column] for column in columns) + '\n' def test_hipblaslt_gemm_cls(self): From 4a5bb7845270d23849ff59d619d535162993691f Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Thu, 15 Oct 2026 16:41:57 +0000 Subject: [PATCH 03/16] Bugfix - Correct hipBLASLt MXFP4 flags and lint Pass verify, GPU timing and kernel-info options as standalone boolean switches to the pinned hipBLASLt client. Add a token-contract regression that catches value-consuming syntax independently of the expected command string. Apply the repository-pinned YAPF formatting to both changed Python files. Validate the complete generated argv with the original vendor option parser on CPU and keep native GPU qualification pending. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/micro-benchmarks.md | 4 +- .../micro_benchmarks/hipblaslt_function.py | 64 ++++-- .../test_hipblaslt_function.py | 189 +++++++++++++++--- 3 files changed, 206 insertions(+), 51 deletions(-) diff --git a/docs/user-tutorial/benchmarks/micro-benchmarks.md b/docs/user-tutorial/benchmarks/micro-benchmarks.md index 23aa57ab3..c428999ea 100644 --- a/docs/user-tutorial/benchmarks/micro-benchmarks.md +++ b/docs/user-tutorial/benchmarks/micro-benchmarks.md @@ -131,7 +131,9 @@ Example wrapper parameters for an experimental smoke case: --transA T --transB N --initialization hpl --num_warmup 20 --num_steps 50 ``` -The wrapper always requests CPU verification for MXFP4. The pinned benchmark +The wrapper enables the standalone client flags `--verify`, `--use_gpu_timer`, +and `--print_kernel_info` without trailing values. The wrapper always requests +CPU verification for MXFP4. The pinned benchmark reports verification errors without asserting the norm check, so SuperBench requires a finite relative Frobenius `norm_error < 1e-5` and finite, non-negative `atol`/`rtol` fields (not `failed`). The norm threshold follows the vendor's FP32 diff --git a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py index 338c116a2..fcaeec089 100644 --- a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py +++ b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py @@ -30,14 +30,19 @@ def __init__(self, name, parameters=''): self._bin_name = 'hipblaslt-bench' self._in_types = ['fp32', 'fp16', 'bf16', 'fp8', 'mxfp4'] self._in_type_map = { - 'fp16': '--a_type f16_r --b_type f16_r --c_type f16_r --d_type f16_r --compute_type f32_r', - 'fp32': '--a_type f32_r --b_type f32_r --c_type f32_r --d_type f32_r --compute_type f32_r', - 'bf16': '--a_type bf16_r --b_type bf16_r --c_type bf16_r --d_type bf16_r --compute_type f32_r', - 'fp8': '--a_type f8_r --b_type f8_r --c_type f8_r --d_type f8_r --compute_type f32_r', - 'mxfp4': '--a_type f4_r --b_type f4_r --c_type f32_r --d_type f32_r --compute_type f32_r' + 'fp16': + '--a_type f16_r --b_type f16_r --c_type f16_r --d_type f16_r --compute_type f32_r', + 'fp32': + '--a_type f32_r --b_type f32_r --c_type f32_r --d_type f32_r --compute_type f32_r', + 'bf16': + '--a_type bf16_r --b_type bf16_r --c_type bf16_r --d_type bf16_r --compute_type f32_r', + 'fp8': + '--a_type f8_r --b_type f8_r --c_type f8_r --d_type f8_r --compute_type f32_r', + 'mxfp4': + '--a_type f4_r --b_type f4_r --c_type f32_r --d_type f32_r --compute_type f32_r' ' --scaleA 3 --scaleB 3 --scaleABlockRowSize 32 --scaleABlockColSize 1' ' --scaleBBlockRowSize 1 --scaleBBlockColSize 32 --alpha 1 --beta 0' - ' --algo_method heuristic --requested_solution 1 --verify 1 --use_gpu_timer 1 --print_kernel_info 1', + ' --algo_method heuristic --requested_solution 1 --verify --use_gpu_timer --print_kernel_info', } def add_parser_arguments(self): @@ -109,9 +114,9 @@ def _check_mxfp4_support(self) -> bool: if arch != 'gfx950': self._result.set_return_code(ReturnCode.MICROBENCHMARK_UNSUPPORTED_ARCHITECTURE) - logger.error('Experimental MXFP4 only allows gfx950 - benchmark: {}, architecture: {}.'.format( - self._name, arch - )) + logger.error( + 'Experimental MXFP4 only allows gfx950 - benchmark: {}, architecture: {}.'.format(self._name, arch) + ) return False output = run_command(f'{shlex.quote(self.__bin_path)} --help', quiet=True) @@ -123,16 +128,23 @@ def _check_mxfp4_support(self) -> bool: ) return False required_options = [ - '--scaleA', '--scaleB', '--scaleABlockRowSize', '--scaleABlockColSize', - '--scaleBBlockRowSize', '--scaleBBlockColSize', '--verify', '--use_gpu_timer', - '--print_kernel_info', '3 = block', + '--scaleA', + '--scaleB', + '--scaleABlockRowSize', + '--scaleABlockColSize', + '--scaleBBlockRowSize', + '--scaleBBlockColSize', + '--verify', + '--use_gpu_timer', + '--print_kernel_info', + '3 = block', ] missing = [option for option in required_options if not re.search(re.escape(option) + r'\b', output.stdout)] if missing: self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) - logger.error('MXFP4 client is missing required options - benchmark: {}, missing: {}.'.format( - self._name, missing - )) + logger.error( + 'MXFP4 client is missing required options - benchmark: {}, missing: {}.'.format(self._name, missing) + ) return False self._result.add_raw_data('mxfp4_gpu_arch', arch, self._args.log_raw_data) return True @@ -186,8 +198,7 @@ def _parse_result_row(self, raw_output: str, precision: str) -> Dict[str, str]: header_fields = [field.strip() for field in lines[index].split(',')] header_fields[0] = re.sub(r'^\s*\[\d+\]:?', '', header_fields[0]).strip() if precision == 'mxfp4' and ( - len(set(header_fields)) != len(header_fields) - or sum('hipblaslt-Gflops' in line for line in lines) != 1 + len(set(header_fields)) != len(header_fields) or sum('hipblaslt-Gflops' in line for line in lines) != 1 or any(len(line.split(',')) == len(header_fields) for line in lines[index + 2:]) ): raise ValueError('MXFP4 requires unique columns and exactly one result.') @@ -213,10 +224,21 @@ def _validate_mxfp4_result(self, cmd_idx: int, row: Dict[str, str], gflops: floa """Require the requested MXFP4 case, valid timing, and CPU verification.""" m, n, k, _, _ = self._shapes_to_run[cmd_idx] expected = { - 'transA': 'T', 'transB': 'N', 'grouped_gemm': '0', 'batch_count': '1', - 'm': str(m), 'n': str(n), 'k': str(k), 'a_type': 'f4_r', 'b_type': 'f4_r', - 'c_type': 'f32_r', 'd_type': 'f32_r', 'compute_type': 'f32_r', - 'scaleA': '3', 'scaleB': '3', 'use_gpu_timer': '1', + 'transA': 'T', + 'transB': 'N', + 'grouped_gemm': '0', + 'batch_count': '1', + 'm': str(m), + 'n': str(n), + 'k': str(k), + 'a_type': 'f4_r', + 'b_type': 'f4_r', + 'c_type': 'f32_r', + 'd_type': 'f32_r', + 'compute_type': 'f32_r', + 'scaleA': '3', + 'scaleB': '3', + 'use_gpu_timer': '1', } for column, value in expected.items(): if row.get(column) != value: diff --git a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py index 88e7a0e2f..6663e30e4 100644 --- a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py +++ b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py @@ -3,6 +3,7 @@ """Tests for hipblaslt-bench benchmark.""" +import shlex import unittest from types import SimpleNamespace from unittest.mock import patch @@ -55,12 +56,26 @@ def preprocess_mxfp4(self, parameters=None, arch='gfx950:sramecc+:xnack-', help_ def mxfp4_output(self, overrides=None, missing=(), reverse=False): """Build synthetic CSV, not a captured GPU result.""" row = { - 'transA': 'T', 'transB': 'N', 'grouped_gemm': '0', 'batch_count': '1', - 'm': '128', 'n': '128', 'k': '128', 'a_type': 'f4_r', 'b_type': 'f4_r', - 'c_type': 'f32_r', 'd_type': 'f32_r', 'compute_type': 'f32_r', - 'scaleA': '3', 'scaleB': '3', 'use_gpu_timer': '1', - 'hipblaslt-Gflops': '1048.576', 'us': '4', 'norm_error': '1e-6', - 'atol': '0.0001', 'rtol': '0.0001', + 'transA': 'T', + 'transB': 'N', + 'grouped_gemm': '0', + 'batch_count': '1', + 'm': '128', + 'n': '128', + 'k': '128', + 'a_type': 'f4_r', + 'b_type': 'f4_r', + 'c_type': 'f32_r', + 'd_type': 'f32_r', + 'compute_type': 'f32_r', + 'scaleA': '3', + 'scaleB': '3', + 'use_gpu_timer': '1', + 'hipblaslt-Gflops': '1048.576', + 'us': '4', + 'norm_error': '1e-6', + 'atol': '0.0001', + 'rtol': '0.0001', } row.update(overrides or {}) for column in missing: @@ -134,12 +149,26 @@ def test_mxfp4_command_generation(self): ' --a_type f4_r --b_type f4_r --c_type f32_r --d_type f32_r --compute_type f32_r' ' --scaleA 3 --scaleB 3 --scaleABlockRowSize 32 --scaleABlockColSize 1' ' --scaleBBlockRowSize 1 --scaleBBlockColSize 32 --alpha 1 --beta 0' - ' --algo_method heuristic --requested_solution 1 --verify 1 --use_gpu_timer 1 --print_kernel_info 1' + ' --algo_method heuristic --requested_solution 1 --verify --use_gpu_timer --print_kernel_info' ' --transA T --transB N --initialization hpl' ) self.assertEqual(benchmark._commands[0], expected) self.assertEqual(benchmark.raw_data['mxfp4_gpu_arch'][0], 'gfx950') + def test_mxfp4_boolean_flags_are_switches(self): + """Require standalone boolean switches rather than value-consuming options.""" + benchmark, result = self.preprocess_mxfp4() + self.assertTrue(result) + tokens = shlex.split(benchmark._commands[0]) + for option in ['--verify', '--use_gpu_timer', '--print_kernel_info']: + with self.subTest(option=option): + self.assertEqual(tokens.count(option), 1) + next_index = tokens.index(option) + 1 + self.assertTrue( + next_index == len(tokens) or tokens[next_index].startswith('-'), + '{} must not consume a value'.format(option), + ) + def test_mxfp4_invalid_arguments(self): """Reject missing opt-in and unsupported layouts, initialization, shapes, or counts.""" valid = ( @@ -191,9 +220,16 @@ def test_mxfp4_client_capabilities(self): self.assertEqual(benchmark._commands, []) options = [ - '--scaleA', '--scaleB', '--scaleABlockRowSize', '--scaleABlockColSize', - '--scaleBBlockRowSize', '--scaleBBlockColSize', '--verify', '--use_gpu_timer', - '--print_kernel_info', '3 = block', + '--scaleA', + '--scaleB', + '--scaleABlockRowSize', + '--scaleABlockColSize', + '--scaleBBlockRowSize', + '--scaleBBlockColSize', + '--verify', + '--use_gpu_timer', + '--print_kernel_info', + '3 = block', ] for missing in options: with self.subTest(missing=missing): @@ -207,7 +243,8 @@ def test_mxfp4_client_capabilities(self): def test_mxfp4_subprocess_status(self): """Propagate client and verification failures without emitting performance metrics.""" for returncode, raw_output in [ - (0, self.mxfp4_output()), (1, 'No supported solutions found'), + (0, self.mxfp4_output()), + (1, 'No supported solutions found'), (0, self.mxfp4_output({'atol': 'failed'})), ]: with self.subTest(returncode=returncode, raw_output=raw_output): @@ -230,9 +267,9 @@ def test_mxfp4_result_parsing(self): with self.subTest(reverse=reverse, norm=norm): benchmark, result = self.preprocess_mxfp4() self.assertTrue(result) - self.assertTrue(benchmark._process_raw_result( - 0, self.mxfp4_output({'norm_error': norm}, reverse=reverse) - )) + self.assertTrue( + benchmark._process_raw_result(0, self.mxfp4_output({'norm_error': norm}, reverse=reverse)) + ) self.assertAlmostEqual(benchmark.result['mxfp4_1_128_128_128_flops'][0], 1.048576) self.assertEqual(benchmark.result['mxfp4_1_128_128_128_time'], [4]) self.assertEqual(benchmark.result['mxfp4_1_128_128_128_norm_error'], [float(norm)]) @@ -242,17 +279,105 @@ def test_mxfp4_result_parsing(self): def test_mxfp4_invalid_results(self): """Reject wrong cases, fallback dtypes, invalid metrics, and failed CPU verification.""" overrides = [ - {'m': '256'}, {'n': '256'}, {'k': '256'}, {'batch_count': '2'}, - {'transA': 'N'}, {'transB': 'T'}, {'grouped_gemm': '1'}, - {'a_type': 'f16_r'}, {'b_type': 'f16_r'}, {'c_type': 'f16_r'}, - {'d_type': 'f16_r'}, {'compute_type': 'f16_r'}, {'scaleA': '0'}, - {'scaleB': '1'}, {'use_gpu_timer': '0'}, - {'us': '0'}, {'us': '-1'}, {'us': 'nan'}, {'us': 'inf'}, - {'hipblaslt-Gflops': '0'}, {'hipblaslt-Gflops': '-1'}, - {'hipblaslt-Gflops': 'nan'}, {'hipblaslt-Gflops': 'inf'}, - {'hipblaslt-Gflops': '10'}, - {'norm_error': '1e-5'}, {'norm_error': '-1'}, {'norm_error': 'nan'}, {'norm_error': 'inf'}, - {'atol': 'failed'}, {'rtol': 'failed'}, {'atol': 'nan'}, {'rtol': 'inf'}, {'rtol': '-1'}, + { + 'm': '256' + }, + { + 'n': '256' + }, + { + 'k': '256' + }, + { + 'batch_count': '2' + }, + { + 'transA': 'N' + }, + { + 'transB': 'T' + }, + { + 'grouped_gemm': '1' + }, + { + 'a_type': 'f16_r' + }, + { + 'b_type': 'f16_r' + }, + { + 'c_type': 'f16_r' + }, + { + 'd_type': 'f16_r' + }, + { + 'compute_type': 'f16_r' + }, + { + 'scaleA': '0' + }, + { + 'scaleB': '1' + }, + { + 'use_gpu_timer': '0' + }, + { + 'us': '0' + }, + { + 'us': '-1' + }, + { + 'us': 'nan' + }, + { + 'us': 'inf' + }, + { + 'hipblaslt-Gflops': '0' + }, + { + 'hipblaslt-Gflops': '-1' + }, + { + 'hipblaslt-Gflops': 'nan' + }, + { + 'hipblaslt-Gflops': 'inf' + }, + { + 'hipblaslt-Gflops': '10' + }, + { + 'norm_error': '1e-5' + }, + { + 'norm_error': '-1' + }, + { + 'norm_error': 'nan' + }, + { + 'norm_error': 'inf' + }, + { + 'atol': 'failed' + }, + { + 'rtol': 'failed' + }, + { + 'atol': 'nan' + }, + { + 'rtol': 'inf' + }, + { + 'rtol': '-1' + }, ] for override in overrides: with self.subTest(override=override): @@ -270,10 +395,16 @@ def test_mxfp4_incomplete_results(self): self.mxfp4_output(missing=[column]) for column in ['a_type', 'scaleA', 'norm_error', 'atol', 'rtol', 'us', 'use_gpu_timer'] ] - invalid.extend([ - header + '\n', header + '\n' + row + ',extra\n', - header + ',m\n' + row + ',128\n', output + output, output + row + '\n', 'No supported solutions found', - ]) + invalid.extend( + [ + header + '\n', + header + '\n' + row + ',extra\n', + header + ',m\n' + row + ',128\n', + output + output, + output + row + '\n', + 'No supported solutions found', + ] + ) for raw_output in invalid: with self.subTest(raw_output=raw_output): benchmark, result = self.preprocess_mxfp4() From 67f39dab1285455b7e133c4da142665106badab6 Mon Sep 17 00:00:00 2001 From: Guoxin Sui Date: Mon, 23 Nov 2026 15:29:01 -0700 Subject: [PATCH 04/16] Bugfix - Validate MXFP4 GEMM coefficients before recording results Require the reported alpha and beta to equal the requested values. Compare their decimal values exactly so alternate printed forms are valid but a different operation cannot produce correctness or performance metrics. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/micro-benchmarks.md | 2 ++ .../micro_benchmarks/hipblaslt_function.py | 8 ++++++- .../test_hipblaslt_function.py | 21 ++++++++++++++++++- 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/docs/user-tutorial/benchmarks/micro-benchmarks.md b/docs/user-tutorial/benchmarks/micro-benchmarks.md index c428999ea..dd7a98ed3 100644 --- a/docs/user-tutorial/benchmarks/micro-benchmarks.md +++ b/docs/user-tutorial/benchmarks/micro-benchmarks.md @@ -142,6 +142,8 @@ kernel error against the decoded quantized inputs, not quantization error agains the original unquantized inputs. MXFP4 results must match the requested shape, dtypes, layout and block-scale mode. +The client must also report `alpha=1` and `beta=0`; missing or different coefficients +are rejected before any performance or correctness metrics are recorded. Throughput must agree with `2*M*N*K / seconds` within 1% for printed-value rounding. Missing, malformed, duplicate, non-finite, unsupported or verification-failed results are errors and do not produce MXFP4 performance metrics. All ROCm input diff --git a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py index fcaeec089..49f5caca1 100644 --- a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py +++ b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py @@ -7,6 +7,7 @@ import os import re import shlex +from decimal import Decimal, InvalidOperation from typing import Dict, Tuple from superbench.common.utils import LazyImport, logger, run_command @@ -244,6 +245,11 @@ def _validate_mxfp4_result(self, cmd_idx: int, row: Dict[str, str], gflops: floa if row.get(column) != value: raise ValueError(f'MXFP4 column {column} must be {value}, got {row.get(column)}.') + for column, coefficient in [('alpha', 1), ('beta', 0)]: + scalar = Decimal(row[column]) + if not scalar.is_finite() or scalar != coefficient: + raise ValueError(f'MXFP4 column {column} must be {coefficient}, got {row[column]}.') + latency = float(row['us']) if not math.isfinite(latency) or latency <= 0: raise ValueError('MXFP4 latency must be finite and positive.') @@ -287,7 +293,7 @@ def _process_raw_result(self, cmd_idx, raw_output): self._result.add_result(f'{metric}_norm_error', norm_error) self._result.add_result(f'{metric}_correctness', 1) self._result.add_result(f'{metric}_flops', gflops / 1000) - except (IndexError, KeyError, TypeError, ValueError) as e: + except (IndexError, InvalidOperation, KeyError, TypeError, ValueError) as e: self._result.set_return_code(ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) logger.error( 'The result format is invalid - round: {}, benchmark: {}, raw output: {}, message: {}.'.format( diff --git a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py index 6663e30e4..ebb673466 100644 --- a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py +++ b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py @@ -63,6 +63,8 @@ def mxfp4_output(self, overrides=None, missing=(), reverse=False): 'm': '128', 'n': '128', 'k': '128', + 'alpha': '1', + 'beta': '0', 'a_type': 'f4_r', 'b_type': 'f4_r', 'c_type': 'f32_r', @@ -276,6 +278,23 @@ def test_mxfp4_result_parsing(self): self.assertEqual(benchmark.result['mxfp4_1_128_128_128_correctness'], [1]) self.assertEqual(benchmark.return_code, ReturnCode.SUCCESS) + def test_mxfp4_result_coefficients(self): + """Accept equivalent printed scalars, but never report metrics for a different GEMM.""" + benchmark, result = self.preprocess_mxfp4() + self.assertTrue(result) + self.assertTrue(benchmark._process_raw_result(0, self.mxfp4_output({'alpha': '1.00e+0', 'beta': '-0.0'}))) + + for column, value in [ + ('alpha', '0'), ('beta', '1'), ('alpha', '1.0000000000000001'), ('beta', '1e-400'), ('alpha', 'nan'), + ('beta', 'inf'), ('alpha', 'invalid') + ]: + with self.subTest(column=column, value=value): + benchmark, result = self.preprocess_mxfp4() + self.assertTrue(result) + self.assertFalse(benchmark._process_raw_result(0, self.mxfp4_output({column: value}))) + self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) + self.assertEqual(set(benchmark.result), {'return_code'}) + def test_mxfp4_invalid_results(self): """Reject wrong cases, fallback dtypes, invalid metrics, and failed CPU verification.""" overrides = [ @@ -393,7 +412,7 @@ def test_mxfp4_incomplete_results(self): header, row = output.splitlines() invalid = [ self.mxfp4_output(missing=[column]) - for column in ['a_type', 'scaleA', 'norm_error', 'atol', 'rtol', 'us', 'use_gpu_timer'] + for column in ['alpha', 'beta', 'a_type', 'scaleA', 'norm_error', 'atol', 'rtol', 'us', 'use_gpu_timer'] ] invalid.extend( [ From b255ef04f684776ff2de3e76fc22da3f2411dbf5 Mon Sep 17 00:00:00 2001 From: Guoxin Sui Date: Mon, 23 Nov 2026 16:59:23 -0700 Subject: [PATCH 05/16] Benchmarks - Keep MXFP4 validation isolated from legacy HIP modes Record experimental metrics only after validating the MXFP4 case. Preserve existing throughput behavior for other precisions, accept equivalent capability text and diagnostic footers, and shorten the tutorial and table-driven regression cases. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/micro-benchmarks.md | 72 +++----- .../micro_benchmarks/hipblaslt_function.py | 111 +++++++------ .../test_hipblaslt_function.py | 155 ++++-------------- 3 files changed, 108 insertions(+), 230 deletions(-) diff --git a/docs/user-tutorial/benchmarks/micro-benchmarks.md b/docs/user-tutorial/benchmarks/micro-benchmarks.md index dd7a98ed3..d6faaa6d4 100644 --- a/docs/user-tutorial/benchmarks/micro-benchmarks.md +++ b/docs/user-tutorial/benchmarks/micro-benchmarks.md @@ -103,58 +103,30 @@ For quick execution checks, set `num_warmup: 1` and `num_steps: 5` under `parame These shorter runs are useful for diagnosing support and configuration errors, not stable performance measurements. -The ROCm benchmark retains `fp32`, `fp16`, `bf16`, and `fp8` inputs and adds an -**experimental, opt-in `mxfp4`** input. Hardware validation is pending; this is not -a production performance baseline or a claim of MI455X support. The initial path -only allows `gfx950` (MI350X/MI355X/MI350P), TN layout, non-batched GEMM, positive -dimensions with K divisible by 32, and `hpl` or `trig_float` initialization. -Other architectures are explicitly rejected rather than converted to FP16. - -The client contract is based on -[hipBLASLt ROCm 7.2.4 at `b9d7970`](https://github.com/ROCm/hipBLASLt/tree/b9d797017b4d4d7c3692ccc5ac099ff9777ace0f) -(library 1.2.2, with RocRoller enabled). A compatible ROCm PyTorch device and a -`hipblaslt-bench` client with block-scaling options are required. Client option -checks do not prove that an algorithm is available for a particular shape. -The existing ROCm 6.4 image is not upgraded or certified for this mode. - -MXFP4 uses E2M1 A/B inputs, one E8M0 scale per 32 K elements, FP32 computation and -C/D, `alpha=1`, and `beta=0`. Packing, scale-buffer layout, and the decoded-input -CPU reference are supplied by the pinned vendor client, not a second SuperBench -quantization implementation. GPU-event timing excludes CPU reference, -initialization, and packing; no quantization-inclusive latency is reported. -Kernel information and full client output are retained in raw data. - -Example wrapper parameters for an experimental smoke case: - -```text ---in_types mxfp4 --enable_experimental_fp4 --shapes 128,128,128 ---transA T --transB N --initialization hpl --num_warmup 20 --num_steps 50 +**ROCm: experimental MXFP4** is opt-in and has not been validated on hardware. +It requires a `gfx950` ROCm PyTorch device and a block-scaling `hipblaslt-bench` +client (based on [ROCm 7.2.4 with RocRoller](https://github.com/ROCm/hipBLASLt/tree/b9d797017b4d4d7c3692ccc5ac099ff9777ace0f)). +The existing ROCm 6.4 image is not qualified. Use non-batched TN GEMM, positive +dimensions, K divisible by 32, and `hpl` or `trig_float` initialization: + +```yaml +hipblaslt-gemm: + parameters: + in_types: [mxfp4] + enable_experimental_fp4: true + shapes: ["128,128,128"] + transA: T + transB: N + initialization: hpl ``` -The wrapper enables the standalone client flags `--verify`, `--use_gpu_timer`, -and `--print_kernel_info` without trailing values. The wrapper always requests -CPU verification for MXFP4. The pinned benchmark -reports verification errors without asserting the norm check, so SuperBench -requires a finite relative Frobenius `norm_error < 1e-5` and finite, non-negative -`atol`/`rtol` fields (not `failed`). The norm threshold follows the vendor's FP32 -output check and still requires calibration on real MXFP4 hardware. It checks -kernel error against the decoded quantized inputs, not quantization error against -the original unquantized inputs. - -MXFP4 results must match the requested shape, dtypes, layout and block-scale mode. -The client must also report `alpha=1` and `beta=0`; missing or different coefficients -are rejected before any performance or correctness metrics are recorded. -Throughput must agree with `2*M*N*K / seconds` within 1% for printed-value rounding. -Missing, malformed, duplicate, non-finite, unsupported or verification-failed -results are errors and do not produce MXFP4 performance metrics. All ROCm input -types now reject non-finite or non-positive throughput; existing valid metric -names, units, commands and default input types remain unchanged. - -Before promoting this mode, run correctness and native-kernel checks on each -claimed GPU/SDK combination, replace synthetic parser fixtures with actual -versioned captures, and repeat a small fixed shape set at least three times. -MI455X needs a separate SDK, format and architecture qualification. No production -configuration or performance gate is enabled by this experimental path. +The client uses E2M1 inputs, one E8M0 scale per 32 K elements, FP32 computation +and output, `alpha=1` and `beta=0`. The wrapper checks the reported case and +coefficients, positive finite throughput and latency, and agreement with +`2*M*N*K / seconds` within 1%. GPU-event timing excludes initialization, packing, +and CPU verification. Verification compares against the decoded quantized inputs: +`norm_error` must be in `[0, 1e-5)` and `atol`/`rtol` finite and non-negative. +The norm threshold still needs hardware calibration. A failed check emits no MXFP4 metrics. #### Metrics diff --git a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py index 49f5caca1..4ddba13b1 100644 --- a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py +++ b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py @@ -8,7 +8,7 @@ import re import shlex from decimal import Decimal, InvalidOperation -from typing import Dict, Tuple +from typing import Dict from superbench.common.utils import LazyImport, logger, run_command from superbench.benchmarks import BenchmarkRegistry, Platform, ReturnCode @@ -138,9 +138,10 @@ def _check_mxfp4_support(self) -> bool: '--verify', '--use_gpu_timer', '--print_kernel_info', - '3 = block', ] missing = [option for option in required_options if not re.search(re.escape(option) + r'\b', output.stdout)] + if not re.search(r'\b3\s*=\s*block\b', output.stdout, re.IGNORECASE): + missing.append('block scaling mode (3)') if missing: self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) logger.error( @@ -185,44 +186,8 @@ def _preprocess(self): return True - def _parse_result_row(self, raw_output: str, precision: str) -> Dict[str, str]: - """Parse one result using header names, preserving legacy column handling.""" - lines = raw_output.splitlines() - index = None - for i, line in enumerate(lines): - if 'hipblaslt-Gflops' in line: - index = i - break - if index is None: - raise ValueError('Line with "hipblaslt-Gflops" not found in the log.') - - header_fields = [field.strip() for field in lines[index].split(',')] - header_fields[0] = re.sub(r'^\s*\[\d+\]:?', '', header_fields[0]).strip() - if precision == 'mxfp4' and ( - len(set(header_fields)) != len(header_fields) or sum('hipblaslt-Gflops' in line for line in lines) != 1 - or any(len(line.split(',')) == len(header_fields) for line in lines[index + 2:]) - ): - raise ValueError('MXFP4 requires unique columns and exactly one result.') - - col_idx_by_name: Dict[str, int] = {} - for col_idx, col_name in enumerate(header_fields): - col_idx_by_name.setdefault(col_name, col_idx) - required_columns = ['batch_count', 'm', 'n', 'k', 'hipblaslt-Gflops'] - missing_columns = [column for column in required_columns if column not in col_idx_by_name] - if missing_columns: - raise ValueError(f'Required column(s) not found in header: {missing_columns}.') - if index + 1 >= len(lines): - raise ValueError('Data line missing after "hipblaslt-Gflops" header.') - - fields = [field.strip() for field in lines[index + 1].split(',')] - if len(fields) != len(header_fields): - raise ValueError( - f'Field count mismatch: header has {len(header_fields)} columns but data has {len(fields)} columns' - ) - return {column: fields[col_idx] for column, col_idx in col_idx_by_name.items()} - - def _validate_mxfp4_result(self, cmd_idx: int, row: Dict[str, str], gflops: float) -> Tuple[float, float]: - """Require the requested MXFP4 case, valid timing, and CPU verification.""" + def _record_mxfp4_result(self, cmd_idx: int, row: Dict[str, str]) -> None: + """Record MXFP4 metrics only after the requested case, timing and verification match.""" m, n, k, _, _ = self._shapes_to_run[cmd_idx] expected = { 'transA': 'T', @@ -250,6 +215,9 @@ def _validate_mxfp4_result(self, cmd_idx: int, row: Dict[str, str], gflops: floa if not scalar.is_finite() or scalar != coefficient: raise ValueError(f'MXFP4 column {column} must be {coefficient}, got {row[column]}.') + gflops = float(row['hipblaslt-Gflops']) + if not math.isfinite(gflops) or gflops <= 0: + raise ValueError('MXFP4 throughput must be finite and positive.') latency = float(row['us']) if not math.isfinite(latency) or latency <= 0: raise ValueError('MXFP4 latency must be finite and positive.') @@ -264,7 +232,12 @@ def _validate_mxfp4_result(self, cmd_idx: int, row: Dict[str, str], gflops: floa error = float(row[column]) if not math.isfinite(error) or error < 0: raise ValueError(f'MXFP4 verification column {column} must be finite and non-negative.') - return latency, norm_error + + metric = f'mxfp4_{row["batch_count"]}_{m}_{n}_{k}' + self._result.add_result(f'{metric}_time', latency) + self._result.add_result(f'{metric}_norm_error', norm_error) + self._result.add_result(f'{metric}_correctness', 1) + self._result.add_result(f'{metric}_flops', gflops / 1000) def _process_raw_result(self, cmd_idx, raw_output): """Function to parse raw results and save the summarized results. @@ -281,18 +254,50 @@ def _process_raw_result(self, cmd_idx, raw_output): self._result.add_raw_data(f'raw_output_{cmd_idx}', raw_output, self._args.log_raw_data) try: - precision = self._precision_in_commands[cmd_idx] - row = self._parse_result_row(raw_output, precision) - gflops = float(row['hipblaslt-Gflops']) - if not math.isfinite(gflops) or gflops <= 0: - raise ValueError('Throughput must be finite and positive.') - metric = f'{precision}_{row["batch_count"]}_{row["m"]}_{row["n"]}_{row["k"]}' - if precision == 'mxfp4': - latency, norm_error = self._validate_mxfp4_result(cmd_idx, row, gflops) - self._result.add_result(f'{metric}_time', latency) - self._result.add_result(f'{metric}_norm_error', norm_error) - self._result.add_result(f'{metric}_correctness', 1) - self._result.add_result(f'{metric}_flops', gflops / 1000) + lines = raw_output.splitlines() + index = next((i for i, line in enumerate(lines) if 'hipblaslt-Gflops' in line), None) + if index is None: + raise ValueError('Line with "hipblaslt-Gflops" not found in the log.') + + header_fields = re.sub(r'^\s*\[\d+\]:?', '', lines[index]).split(',') + col_idx_by_name: Dict[str, int] = {} + for col_idx, col_name in enumerate(header_fields): + col_idx_by_name.setdefault(col_name.strip(), col_idx) + required_columns = ['batch_count', 'm', 'n', 'k', 'hipblaslt-Gflops'] + missing_columns = [c for c in required_columns if c not in col_idx_by_name] + if missing_columns: + raise ValueError(f'Required column(s) not found in header: {missing_columns}.') + if index + 1 >= len(lines): + raise ValueError('Data line missing after "hipblaslt-Gflops" header.') + fields = lines[index + 1].split(',') + if len(fields) != len(header_fields): + raise ValueError( + f'Field count mismatch: header has {len(header_fields)} columns but data has {len(fields)} columns' + ) + + if self._precision_in_commands[cmd_idx] == 'mxfp4': + if len(col_idx_by_name) != len(header_fields): + raise ValueError('MXFP4 requires unique result columns.') + for line in lines[index + 2:]: + extra = [v.strip() for v in re.sub(r'^\s*\[\d+\]:?', '', line).split(',')] + if 'hipblaslt-Gflops' in extra or ( + len(extra) == len(fields) + and all(extra[col_idx_by_name[t]] in ('N', 'T', 'C') for t in ('transA', 'transB')) + ): + raise ValueError('MXFP4 requires exactly one result.') + self._record_mxfp4_result(cmd_idx, {col: fields[i].strip() for col, i in col_idx_by_name.items()}) + return True + + batch_count = fields[col_idx_by_name['batch_count']].strip() + m_val = fields[col_idx_by_name['m']].strip() + n_val = fields[col_idx_by_name['n']].strip() + k_val = fields[col_idx_by_name['k']].strip() + gflops_col = col_idx_by_name['hipblaslt-Gflops'] + + self._result.add_result( + f'{self._precision_in_commands[cmd_idx]}_{batch_count}_{m_val}_{n_val}_{k_val}_flops', + float(fields[gflops_col]) / 1000 + ) except (IndexError, InvalidOperation, KeyError, TypeError, ValueError) as e: self._result.set_return_code(ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) logger.error( diff --git a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py index ebb673466..c857f3c09 100644 --- a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py +++ b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py @@ -146,15 +146,17 @@ def test_mxfp4_command_generation(self): benchmark, result = self.preprocess_mxfp4() self.assertTrue(result) self.assertEqual(len(benchmark._commands), 1) - expected = ( - f'{benchmark._HipBlasLtBenchmark__bin_path} -m 128 -n 128 -k 128 -j 20 -i 50' - ' --a_type f4_r --b_type f4_r --c_type f32_r --d_type f32_r --compute_type f32_r' - ' --scaleA 3 --scaleB 3 --scaleABlockRowSize 32 --scaleABlockColSize 1' - ' --scaleBBlockRowSize 1 --scaleBBlockColSize 32 --alpha 1 --beta 0' - ' --algo_method heuristic --requested_solution 1 --verify --use_gpu_timer --print_kernel_info' - ' --transA T --transB N --initialization hpl' - ) - self.assertEqual(benchmark._commands[0], expected) + tokens = shlex.split(benchmark._commands[0]) + for option, value in [ + ('--a_type', 'f4_r'), ('--b_type', 'f4_r'), ('--c_type', 'f32_r'), ('--d_type', 'f32_r'), + ('--compute_type', 'f32_r'), ('--scaleA', '3'), ('--scaleB', '3'), ('--scaleABlockRowSize', '32'), + ('--scaleABlockColSize', '1'), ('--scaleBBlockRowSize', '1'), ('--scaleBBlockColSize', '32'), + ('--alpha', '1'), ('--beta', '0'), ('--algo_method', 'heuristic'), ('--requested_solution', '1'), + ('--transA', 'T'), ('--transB', 'N'), ('--initialization', 'hpl') + ]: + with self.subTest(option=option): + self.assertEqual(tokens.count(option), 1) + self.assertEqual(tokens[tokens.index(option) + 1], value) self.assertEqual(benchmark.raw_data['mxfp4_gpu_arch'][0], 'gfx950') def test_mxfp4_boolean_flags_are_switches(self): @@ -233,6 +235,8 @@ def test_mxfp4_client_capabilities(self): '--print_kernel_info', '3 = block', ] + help_result = SimpleNamespace(returncode=0, stdout=' '.join(options).replace('3 = block', '3=Block')) + self.assertTrue(self.preprocess_mxfp4(help_result=help_result)[1]) for missing in options: with self.subTest(missing=missing): help_result = SimpleNamespace( @@ -269,9 +273,10 @@ def test_mxfp4_result_parsing(self): with self.subTest(reverse=reverse, norm=norm): benchmark, result = self.preprocess_mxfp4() self.assertTrue(result) - self.assertTrue( - benchmark._process_raw_result(0, self.mxfp4_output({'norm_error': norm}, reverse=reverse)) - ) + output = self.mxfp4_output({'norm_error': norm}, reverse=reverse) + column_count = len(output.splitlines()[0].split(',')) + footer = 'diagnostic: ' + ','.join(['detail'] * column_count) + self.assertTrue(benchmark._process_raw_result(0, output + footer)) self.assertAlmostEqual(benchmark.result['mxfp4_1_128_128_128_flops'][0], 1.048576) self.assertEqual(benchmark.result['mxfp4_1_128_128_128_time'], [4]) self.assertEqual(benchmark.result['mxfp4_1_128_128_128_norm_error'], [float(norm)]) @@ -297,112 +302,19 @@ def test_mxfp4_result_coefficients(self): def test_mxfp4_invalid_results(self): """Reject wrong cases, fallback dtypes, invalid metrics, and failed CPU verification.""" - overrides = [ - { - 'm': '256' - }, - { - 'n': '256' - }, - { - 'k': '256' - }, - { - 'batch_count': '2' - }, - { - 'transA': 'N' - }, - { - 'transB': 'T' - }, - { - 'grouped_gemm': '1' - }, - { - 'a_type': 'f16_r' - }, - { - 'b_type': 'f16_r' - }, - { - 'c_type': 'f16_r' - }, - { - 'd_type': 'f16_r' - }, - { - 'compute_type': 'f16_r' - }, - { - 'scaleA': '0' - }, - { - 'scaleB': '1' - }, - { - 'use_gpu_timer': '0' - }, - { - 'us': '0' - }, - { - 'us': '-1' - }, - { - 'us': 'nan' - }, - { - 'us': 'inf' - }, - { - 'hipblaslt-Gflops': '0' - }, - { - 'hipblaslt-Gflops': '-1' - }, - { - 'hipblaslt-Gflops': 'nan' - }, - { - 'hipblaslt-Gflops': 'inf' - }, - { - 'hipblaslt-Gflops': '10' - }, - { - 'norm_error': '1e-5' - }, - { - 'norm_error': '-1' - }, - { - 'norm_error': 'nan' - }, - { - 'norm_error': 'inf' - }, - { - 'atol': 'failed' - }, - { - 'rtol': 'failed' - }, - { - 'atol': 'nan' - }, - { - 'rtol': 'inf' - }, - { - 'rtol': '-1' - }, - ] - for override in overrides: - with self.subTest(override=override): + for column, value in [ + ('m', '256'), ('n', '256'), ('k', '256'), ('batch_count', '2'), ('transA', 'N'), ('transB', 'T'), + ('grouped_gemm', '1'), ('a_type', 'f16_r'), ('b_type', 'f16_r'), ('c_type', 'f16_r'), ('d_type', 'f16_r'), + ('compute_type', 'f16_r'), ('scaleA', '0'), ('scaleB', '1'), ('use_gpu_timer', '0'), ('us', '0'), + ('us', '-1'), ('us', 'nan'), ('us', 'inf'), ('hipblaslt-Gflops', '0'), ('hipblaslt-Gflops', '-1'), + ('hipblaslt-Gflops', 'nan'), ('hipblaslt-Gflops', 'inf'), ('hipblaslt-Gflops', '10'), + ('norm_error', '1e-5'), ('norm_error', '-1'), ('norm_error', 'nan'), ('norm_error', 'inf'), + ('atol', 'failed'), ('rtol', 'failed'), ('atol', 'nan'), ('rtol', 'inf'), ('rtol', '-1') + ]: + with self.subTest(column=column, value=value): benchmark, result = self.preprocess_mxfp4() self.assertTrue(result) - self.assertFalse(benchmark._process_raw_result(0, self.mxfp4_output(override))) + self.assertFalse(benchmark._process_raw_result(0, self.mxfp4_output({column: value}))) self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) self.assertEqual(set(benchmark.result), {'return_code'}) @@ -432,17 +344,6 @@ def test_mxfp4_incomplete_results(self): self.assertEqual(set(benchmark.result), {'return_code'}) self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) - def test_legacy_invalid_throughput(self): - """Reject non-finite or non-positive throughput without changing legacy metric names.""" - for value in ['nan', 'inf', '-1', '0']: - with self.subTest(value=value): - benchmark = self.get_benchmark('--shapes 128,128,128') - self.assertTrue(benchmark._preprocess()) - output = f'[0]:batch_count,m,n,k,hipblaslt-Gflops\n1,128,128,128,{value}\n' - self.assertFalse(benchmark._process_raw_result(0, output)) - self.assertEqual(set(benchmark.result), {'return_code'}) - self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) - def test_hipblaslt_gemm_result_parsing(self): """Test hipblaslt-bench benchmark result parsing.""" benchmark = self.get_benchmark() From febfd5dce68bcd75c7c381be5b77cb4fa05ee53d Mon Sep 17 00:00:00 2001 From: Guoxin Sui Date: Mon, 23 Nov 2026 17:08:57 -0700 Subject: [PATCH 06/16] Bugfix - Simplify MXFP4 result validation Separate recognition of a unique result row from metric validation and apply the same finite-positive rule to device throughput and latency. This keeps the parser within the existing complexity limit without changing the legacy path. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../micro_benchmarks/hipblaslt_function.py | 33 ++++++++++--------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py index 4ddba13b1..69dfce025 100644 --- a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py +++ b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py @@ -8,7 +8,7 @@ import re import shlex from decimal import Decimal, InvalidOperation -from typing import Dict +from typing import Dict, List from superbench.common.utils import LazyImport, logger, run_command from superbench.benchmarks import BenchmarkRegistry, Platform, ReturnCode @@ -186,6 +186,19 @@ def _preprocess(self): return True + @staticmethod + def _mxfp4_result_row(columns: Dict[str, int], fields: List[str], trailer: List[str]) -> Dict[str, str]: + """Require one result row with unique columns; kernel diagnostics may follow it.""" + if len(columns) != len(fields): + raise ValueError('MXFP4 requires unique result columns.') + for line in trailer: + extra = [v.strip() for v in re.sub(r'^\s*\[\d+\]:?', '', line).split(',')] + if 'hipblaslt-Gflops' in extra or ( + len(extra) == len(fields) and all(extra[columns[t]] in ('N', 'T', 'C') for t in ('transA', 'transB')) + ): + raise ValueError('MXFP4 requires exactly one result.') + return {col: fields[i].strip() for col, i in columns.items()} + def _record_mxfp4_result(self, cmd_idx: int, row: Dict[str, str]) -> None: """Record MXFP4 metrics only after the requested case, timing and verification match.""" m, n, k, _, _ = self._shapes_to_run[cmd_idx] @@ -216,11 +229,9 @@ def _record_mxfp4_result(self, cmd_idx: int, row: Dict[str, str]) -> None: raise ValueError(f'MXFP4 column {column} must be {coefficient}, got {row[column]}.') gflops = float(row['hipblaslt-Gflops']) - if not math.isfinite(gflops) or gflops <= 0: - raise ValueError('MXFP4 throughput must be finite and positive.') latency = float(row['us']) - if not math.isfinite(latency) or latency <= 0: - raise ValueError('MXFP4 latency must be finite and positive.') + if not all(math.isfinite(value) and value > 0 for value in (gflops, latency)): + raise ValueError('MXFP4 throughput and latency must be finite and positive.') if not math.isclose(gflops, 2 * m * n * k / latency / 1000, rel_tol=0.01): raise ValueError('MXFP4 throughput does not match 2*M*N*K and the reported latency.') @@ -276,16 +287,8 @@ def _process_raw_result(self, cmd_idx, raw_output): ) if self._precision_in_commands[cmd_idx] == 'mxfp4': - if len(col_idx_by_name) != len(header_fields): - raise ValueError('MXFP4 requires unique result columns.') - for line in lines[index + 2:]: - extra = [v.strip() for v in re.sub(r'^\s*\[\d+\]:?', '', line).split(',')] - if 'hipblaslt-Gflops' in extra or ( - len(extra) == len(fields) - and all(extra[col_idx_by_name[t]] in ('N', 'T', 'C') for t in ('transA', 'transB')) - ): - raise ValueError('MXFP4 requires exactly one result.') - self._record_mxfp4_result(cmd_idx, {col: fields[i].strip() for col, i in col_idx_by_name.items()}) + row = self._mxfp4_result_row(col_idx_by_name, fields, lines[index + 2:]) + self._record_mxfp4_result(cmd_idx, row) return True batch_count = fields[col_idx_by_name['batch_count']].strip() From e32e41894ca6ac680e0cfa7aadc46abb39df7ab7 Mon Sep 17 00:00:00 2001 From: Guoxin Sui Date: Tue, 24 Nov 2026 14:01:24 -0700 Subject: [PATCH 07/16] Benchmarks - Trim MXFP4 probe logging and parser fixtures Retain full client help only on failure or explicit raw logging. Exercise the results parser without probing a device or client, and use distinct M/N/K dimensions so a swapped output cannot pass. Keep the MXFP4 metrics in the existing GEMM table. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/micro-benchmarks.md | 11 +- .../micro_benchmarks/hipblaslt_function.py | 15 +- .../test_hipblaslt_function.py | 136 +++++++++--------- 3 files changed, 78 insertions(+), 84 deletions(-) diff --git a/docs/user-tutorial/benchmarks/micro-benchmarks.md b/docs/user-tutorial/benchmarks/micro-benchmarks.md index d6faaa6d4..924432f73 100644 --- a/docs/user-tutorial/benchmarks/micro-benchmarks.md +++ b/docs/user-tutorial/benchmarks/micro-benchmarks.md @@ -134,14 +134,9 @@ The norm threshold still needs hardware calibration. A failed check emits no MXF |-----------------------------------------------------------|----------------|---------------------------------| | cublaslt-gemm/${dtype}\_${batch}\_${m}\_${n}\_${k}_flops | FLOPS (TFLOPS) | TFLOPS of measured GEMM kernel. | | hipblaslt-gemm/${dtype}\_${batch}\_${m}\_${n}\_${k}_flops | FLOPS (TFLOPS) | TFLOPS of measured GEMM kernel. | - -MXFP4 additionally reports the following metrics only after validation succeeds: - -| Name | Unit | Description | -|------|------|-------------| -| hipblaslt-gemm/mxfp4\_1\_${m}\_${n}\_${k}_time | time (us) | GEMM-only GPU-event latency. | -| hipblaslt-gemm/mxfp4\_1\_${m}\_${n}\_${k}_norm_error | ratio | Relative Frobenius error against the vendor CPU reference. | -| hipblaslt-gemm/mxfp4\_1\_${m}\_${n}\_${k}_correctness | flag | 1 after the wrapper verification checks pass; failed cases return an error without performance metrics. | +| hipblaslt-gemm/mxfp4\_1\_${m}\_${n}\_${k}_time | time (us) | GEMM-only GPU-event latency. | +| hipblaslt-gemm/mxfp4\_1\_${m}\_${n}\_${k}_norm_error | ratio | Relative Frobenius error against the vendor CPU reference. | +| hipblaslt-gemm/mxfp4\_1\_${m}\_${n}\_${k}_correctness | flag | 1 after all MXFP4 checks pass. | ### `cublas-function` diff --git a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py index 69dfce025..ba0070c9a 100644 --- a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py +++ b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py @@ -121,13 +121,6 @@ def _check_mxfp4_support(self) -> bool: return False output = run_command(f'{shlex.quote(self.__bin_path)} --help', quiet=True) - self._result.add_raw_data('mxfp4_client_help', output.stdout, self._args.log_raw_data) - if output.returncode != 0: - self._result.set_return_code(ReturnCode.MICROBENCHMARK_EXECUTION_FAILURE) - logger.error( - 'Cannot query MXFP4 client options - benchmark: {}, output: {}.'.format(self._name, output.stdout) - ) - return False required_options = [ '--scaleA', '--scaleB', @@ -142,6 +135,14 @@ def _check_mxfp4_support(self) -> bool: missing = [option for option in required_options if not re.search(re.escape(option) + r'\b', output.stdout)] if not re.search(r'\b3\s*=\s*block\b', output.stdout, re.IGNORECASE): missing.append('block scaling mode (3)') + if output.returncode != 0 or missing or self._args.log_raw_data: + self._result.add_raw_data('mxfp4_client_help', output.stdout, self._args.log_raw_data) + if output.returncode != 0: + self._result.set_return_code(ReturnCode.MICROBENCHMARK_EXECUTION_FAILURE) + logger.error( + 'Cannot query MXFP4 client options - benchmark: {}, output: {}.'.format(self._name, output.stdout) + ) + return False if missing: self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) logger.error( diff --git a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py index c857f3c09..1e4a18a20 100644 --- a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py +++ b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py @@ -13,6 +13,15 @@ from superbench.benchmarks.micro_benchmarks import hipblaslt_function from superbench.benchmarks.result import BenchmarkResult +_MXFP4_PARAMETERS = ( + '--in_types mxfp4 --enable_experimental_fp4 --shapes 64,128,256' + ' --transA T --transB N --initialization hpl' +) +_MXFP4_HELP_OPTIONS = ( + '--scaleA', '--scaleB', '--scaleABlockRowSize', '--scaleABlockColSize', '--scaleBBlockRowSize', + '--scaleBBlockColSize', '--verify', '--use_gpu_timer', '--print_kernel_info', '3 = block' +) + class HipblasLtBenchmarkTestCase(BenchmarkTestCase, unittest.TestCase): """Class for hipblaslt-bench benchmark test cases.""" @@ -29,30 +38,37 @@ def get_benchmark(self, parameters=''): (benchmark_cls, _) = BenchmarkRegistry._BenchmarkRegistry__select_benchmark(self.benchmark_name, Platform.ROCM) return benchmark_cls(self.benchmark_name, parameters=parameters) - def preprocess_mxfp4(self, parameters=None, arch='gfx950:sramecc+:xnack-', help_result=None, available=True): + def preprocess_mxfp4( + self, parameters=_MXFP4_PARAMETERS, arch='gfx950:sramecc+:xnack-', help_result=None, available=True + ): """Preprocess with synthetic ROCm device and client capability information.""" - if parameters is None: - parameters = ( - '--in_types mxfp4 --enable_experimental_fp4 --shapes 128,128,128' - ' --transA T --transB N --initialization hpl' - ) if help_result is None: - help_result = SimpleNamespace( - returncode=0, - stdout='--scaleA --scaleB 3 = block --scaleABlockRowSize --scaleABlockColSize' - ' --scaleBBlockRowSize --scaleBBlockColSize --verify --use_gpu_timer --print_kernel_info', - ) + help_result = SimpleNamespace(returncode=0, stdout=' '.join(_MXFP4_HELP_OPTIONS)) benchmark = self.get_benchmark(parameters) - with patch.object(hipblaslt_function.torch.version, 'hip', '7.2.4'), \ - patch.object(hipblaslt_function.torch.cuda, 'is_available', return_value=available), \ - patch.object( - hipblaslt_function.torch.cuda, 'get_device_properties', - return_value=SimpleNamespace(gcnArchName=arch) - ), \ + with patch.object(hipblaslt_function, 'torch') as torch, \ patch.object(hipblaslt_function, 'run_command', return_value=help_result): + torch.version.hip = '7.2.4' + torch.cuda.is_available.return_value = available + torch.cuda.get_device_properties.return_value.gcnArchName = arch result = benchmark._preprocess() return benchmark, result + def mxfp4_parser(self): + """Make a fresh result collector for one requested shape without probing a device or client.""" + benchmark = hipblaslt_function.HipBlasLtBenchmark(self.benchmark_name) + benchmark._args = SimpleNamespace(log_raw_data=False) + benchmark._result = BenchmarkResult(self.benchmark_name, BenchmarkType.MICRO, ReturnCode.SUCCESS, run_count=1) + benchmark._shapes_to_run = [(64, 128, 256, 0, 'mxfp4')] + benchmark._precision_in_commands = ['mxfp4'] + return benchmark + + def assert_invalid_mxfp4(self, output): + """Check that a rejected row publishes neither correctness nor performance metrics.""" + benchmark = self.mxfp4_parser() + self.assertFalse(benchmark._process_raw_result(0, output)) + self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) + self.assertEqual(set(benchmark.result), {'return_code'}) + def mxfp4_output(self, overrides=None, missing=(), reverse=False): """Build synthetic CSV, not a captured GPU result.""" row = { @@ -60,9 +76,9 @@ def mxfp4_output(self, overrides=None, missing=(), reverse=False): 'transB': 'N', 'grouped_gemm': '0', 'batch_count': '1', - 'm': '128', + 'm': '64', 'n': '128', - 'k': '128', + 'k': '256', 'alpha': '1', 'beta': '0', 'a_type': 'f4_r', @@ -148,16 +164,18 @@ def test_mxfp4_command_generation(self): self.assertEqual(len(benchmark._commands), 1) tokens = shlex.split(benchmark._commands[0]) for option, value in [ - ('--a_type', 'f4_r'), ('--b_type', 'f4_r'), ('--c_type', 'f32_r'), ('--d_type', 'f32_r'), - ('--compute_type', 'f32_r'), ('--scaleA', '3'), ('--scaleB', '3'), ('--scaleABlockRowSize', '32'), - ('--scaleABlockColSize', '1'), ('--scaleBBlockRowSize', '1'), ('--scaleBBlockColSize', '32'), - ('--alpha', '1'), ('--beta', '0'), ('--algo_method', 'heuristic'), ('--requested_solution', '1'), - ('--transA', 'T'), ('--transB', 'N'), ('--initialization', 'hpl') + ('-m', '64'), ('-n', '128'), ('-k', '256'), ('--a_type', 'f4_r'), ('--b_type', 'f4_r'), + ('--c_type', 'f32_r'), ('--d_type', 'f32_r'), ('--compute_type', 'f32_r'), ('--scaleA', '3'), + ('--scaleB', '3'), ('--scaleABlockRowSize', '32'), ('--scaleABlockColSize', '1'), + ('--scaleBBlockRowSize', '1'), ('--scaleBBlockColSize', '32'), ('--alpha', '1'), ('--beta', '0'), + ('--algo_method', 'heuristic'), ('--requested_solution', '1'), ('--transA', 'T'), ('--transB', 'N'), + ('--initialization', 'hpl') ]: with self.subTest(option=option): self.assertEqual(tokens.count(option), 1) self.assertEqual(tokens[tokens.index(option) + 1], value) self.assertEqual(benchmark.raw_data['mxfp4_gpu_arch'][0], 'gfx950') + self.assertNotIn('mxfp4_client_help', benchmark.raw_data) def test_mxfp4_boolean_flags_are_switches(self): """Require standalone boolean switches rather than value-consuming options.""" @@ -175,17 +193,14 @@ def test_mxfp4_boolean_flags_are_switches(self): def test_mxfp4_invalid_arguments(self): """Reject missing opt-in and unsupported layouts, initialization, shapes, or counts.""" - valid = ( - '--in_types mxfp4 --enable_experimental_fp4 --shapes 128,128,128' - ' --transA T --transB N --initialization hpl' - ) + valid = _MXFP4_PARAMETERS invalid = [ valid.replace('--enable_experimental_fp4', ''), valid.replace('--transA T', '--transA N'), valid.replace('--transB N', '--transB T'), valid.replace('--initialization hpl', '--initialization rand_int'), - valid.replace('128,128,128', '128,128,129'), - valid.replace('128,128,128', '0,128,128'), + valid.replace('64,128,256', '64,128,257'), + valid.replace('64,128,256', '0,128,256'), valid + ' --batch 1', valid + ' --num_warmup -1', valid + ' --num_steps 0', @@ -211,6 +226,11 @@ def test_mxfp4_unsupported_devices(self): def test_mxfp4_client_capabilities(self): """Reject old client options and explicit capability-query failures.""" + with patch.object(BenchmarkResult, 'add_raw_data', autospec=True) as record: + benchmark, ready = self.preprocess_mxfp4(_MXFP4_PARAMETERS + ' --log_raw_data') + self.assertTrue(ready) + record.assert_any_call(benchmark._result, 'mxfp4_client_help', ' '.join(_MXFP4_HELP_OPTIONS), True) + for output in [ SimpleNamespace(returncode=0, stdout='--scaleA --scaleB 0 = None, 1 = scalar, 2 = vector'), SimpleNamespace(returncode=1, stdout='Cannot load hipBLASLt'), @@ -222,25 +242,16 @@ def test_mxfp4_client_capabilities(self): ReturnCode.MICROBENCHMARK_EXECUTION_FAILURE self.assertEqual(benchmark.return_code, expected) self.assertEqual(benchmark._commands, []) + self.assertEqual(benchmark.raw_data['mxfp4_client_help'], [output.stdout]) - options = [ - '--scaleA', - '--scaleB', - '--scaleABlockRowSize', - '--scaleABlockColSize', - '--scaleBBlockRowSize', - '--scaleBBlockColSize', - '--verify', - '--use_gpu_timer', - '--print_kernel_info', - '3 = block', - ] - help_result = SimpleNamespace(returncode=0, stdout=' '.join(options).replace('3 = block', '3=Block')) + help_result = SimpleNamespace( + returncode=0, stdout=' '.join(_MXFP4_HELP_OPTIONS).replace('3 = block', '3=Block') + ) self.assertTrue(self.preprocess_mxfp4(help_result=help_result)[1]) - for missing in options: + for missing in _MXFP4_HELP_OPTIONS: with self.subTest(missing=missing): help_result = SimpleNamespace( - returncode=0, stdout=' '.join(option for option in options if option != missing) + returncode=0, stdout=' '.join(option for option in _MXFP4_HELP_OPTIONS if option != missing) ) benchmark, result = self.preprocess_mxfp4(help_result=help_result) self.assertFalse(result) @@ -271,22 +282,21 @@ def test_mxfp4_result_parsing(self): """Check reordered columns, exact metric units, and the norm threshold boundary.""" for reverse, norm in [(False, '1e-6'), (True, '9.999e-6')]: with self.subTest(reverse=reverse, norm=norm): - benchmark, result = self.preprocess_mxfp4() - self.assertTrue(result) + benchmark = self.mxfp4_parser() output = self.mxfp4_output({'norm_error': norm}, reverse=reverse) column_count = len(output.splitlines()[0].split(',')) footer = 'diagnostic: ' + ','.join(['detail'] * column_count) self.assertTrue(benchmark._process_raw_result(0, output + footer)) - self.assertAlmostEqual(benchmark.result['mxfp4_1_128_128_128_flops'][0], 1.048576) - self.assertEqual(benchmark.result['mxfp4_1_128_128_128_time'], [4]) - self.assertEqual(benchmark.result['mxfp4_1_128_128_128_norm_error'], [float(norm)]) - self.assertEqual(benchmark.result['mxfp4_1_128_128_128_correctness'], [1]) + self.assertAlmostEqual(benchmark.result['mxfp4_1_64_128_256_flops'][0], 1.048576) + self.assertEqual(benchmark.result['mxfp4_1_64_128_256_time'], [4]) + self.assertEqual(benchmark.result['mxfp4_1_64_128_256_norm_error'], [float(norm)]) + self.assertEqual(benchmark.result['mxfp4_1_64_128_256_correctness'], [1]) self.assertEqual(benchmark.return_code, ReturnCode.SUCCESS) + self.assert_invalid_mxfp4(self.mxfp4_output({'m': '128', 'n': '64'})) def test_mxfp4_result_coefficients(self): """Accept equivalent printed scalars, but never report metrics for a different GEMM.""" - benchmark, result = self.preprocess_mxfp4() - self.assertTrue(result) + benchmark = self.mxfp4_parser() self.assertTrue(benchmark._process_raw_result(0, self.mxfp4_output({'alpha': '1.00e+0', 'beta': '-0.0'}))) for column, value in [ @@ -294,16 +304,12 @@ def test_mxfp4_result_coefficients(self): ('beta', 'inf'), ('alpha', 'invalid') ]: with self.subTest(column=column, value=value): - benchmark, result = self.preprocess_mxfp4() - self.assertTrue(result) - self.assertFalse(benchmark._process_raw_result(0, self.mxfp4_output({column: value}))) - self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) - self.assertEqual(set(benchmark.result), {'return_code'}) + self.assert_invalid_mxfp4(self.mxfp4_output({column: value})) def test_mxfp4_invalid_results(self): """Reject wrong cases, fallback dtypes, invalid metrics, and failed CPU verification.""" for column, value in [ - ('m', '256'), ('n', '256'), ('k', '256'), ('batch_count', '2'), ('transA', 'N'), ('transB', 'T'), + ('m', '256'), ('n', '256'), ('k', '128'), ('batch_count', '2'), ('transA', 'N'), ('transB', 'T'), ('grouped_gemm', '1'), ('a_type', 'f16_r'), ('b_type', 'f16_r'), ('c_type', 'f16_r'), ('d_type', 'f16_r'), ('compute_type', 'f16_r'), ('scaleA', '0'), ('scaleB', '1'), ('use_gpu_timer', '0'), ('us', '0'), ('us', '-1'), ('us', 'nan'), ('us', 'inf'), ('hipblaslt-Gflops', '0'), ('hipblaslt-Gflops', '-1'), @@ -312,11 +318,7 @@ def test_mxfp4_invalid_results(self): ('atol', 'failed'), ('rtol', 'failed'), ('atol', 'nan'), ('rtol', 'inf'), ('rtol', '-1') ]: with self.subTest(column=column, value=value): - benchmark, result = self.preprocess_mxfp4() - self.assertTrue(result) - self.assertFalse(benchmark._process_raw_result(0, self.mxfp4_output({column: value}))) - self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) - self.assertEqual(set(benchmark.result), {'return_code'}) + self.assert_invalid_mxfp4(self.mxfp4_output({column: value})) def test_mxfp4_incomplete_results(self): """Reject absent verification columns, malformed CSV, and multiple algorithm results.""" @@ -338,11 +340,7 @@ def test_mxfp4_incomplete_results(self): ) for raw_output in invalid: with self.subTest(raw_output=raw_output): - benchmark, result = self.preprocess_mxfp4() - self.assertTrue(result) - self.assertFalse(benchmark._process_raw_result(0, raw_output)) - self.assertEqual(set(benchmark.result), {'return_code'}) - self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) + self.assert_invalid_mxfp4(raw_output) def test_hipblaslt_gemm_result_parsing(self): """Test hipblaslt-bench benchmark result parsing.""" From 8932911dffa5a9a782637be9d4a9feacf1ffb64f Mon Sep 17 00:00:00 2001 From: Guoxin Sui Date: Tue, 24 Nov 2026 14:30:55 -0700 Subject: [PATCH 08/16] Benchmarks - Limit the MXFP4 diff to feature code and tests Keep existing precision arguments, parser formatting and test helpers intact. Restore the public tutorial and leave the example, deployment scope and hardware qualification notes in the PR description instead. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/micro-benchmarks.md | 28 ----- .../micro_benchmarks/hipblaslt_function.py | 113 +++++++++--------- .../test_hipblaslt_function.py | 6 +- 3 files changed, 59 insertions(+), 88 deletions(-) diff --git a/docs/user-tutorial/benchmarks/micro-benchmarks.md b/docs/user-tutorial/benchmarks/micro-benchmarks.md index 924432f73..6ce505657 100644 --- a/docs/user-tutorial/benchmarks/micro-benchmarks.md +++ b/docs/user-tutorial/benchmarks/micro-benchmarks.md @@ -103,40 +103,12 @@ For quick execution checks, set `num_warmup: 1` and `num_steps: 5` under `parame These shorter runs are useful for diagnosing support and configuration errors, not stable performance measurements. -**ROCm: experimental MXFP4** is opt-in and has not been validated on hardware. -It requires a `gfx950` ROCm PyTorch device and a block-scaling `hipblaslt-bench` -client (based on [ROCm 7.2.4 with RocRoller](https://github.com/ROCm/hipBLASLt/tree/b9d797017b4d4d7c3692ccc5ac099ff9777ace0f)). -The existing ROCm 6.4 image is not qualified. Use non-batched TN GEMM, positive -dimensions, K divisible by 32, and `hpl` or `trig_float` initialization: - -```yaml -hipblaslt-gemm: - parameters: - in_types: [mxfp4] - enable_experimental_fp4: true - shapes: ["128,128,128"] - transA: T - transB: N - initialization: hpl -``` - -The client uses E2M1 inputs, one E8M0 scale per 32 K elements, FP32 computation -and output, `alpha=1` and `beta=0`. The wrapper checks the reported case and -coefficients, positive finite throughput and latency, and agreement with -`2*M*N*K / seconds` within 1%. GPU-event timing excludes initialization, packing, -and CPU verification. Verification compares against the decoded quantized inputs: -`norm_error` must be in `[0, 1e-5)` and `atol`/`rtol` finite and non-negative. -The norm threshold still needs hardware calibration. A failed check emits no MXFP4 metrics. - #### Metrics | Name | Unit | Description | |-----------------------------------------------------------|----------------|---------------------------------| | cublaslt-gemm/${dtype}\_${batch}\_${m}\_${n}\_${k}_flops | FLOPS (TFLOPS) | TFLOPS of measured GEMM kernel. | | hipblaslt-gemm/${dtype}\_${batch}\_${m}\_${n}\_${k}_flops | FLOPS (TFLOPS) | TFLOPS of measured GEMM kernel. | -| hipblaslt-gemm/mxfp4\_1\_${m}\_${n}\_${k}_time | time (us) | GEMM-only GPU-event latency. | -| hipblaslt-gemm/mxfp4\_1\_${m}\_${n}\_${k}_norm_error | ratio | Relative Frobenius error against the vendor CPU reference. | -| hipblaslt-gemm/mxfp4\_1\_${m}\_${n}\_${k}_correctness | flag | 1 after all MXFP4 checks pass. | ### `cublas-function` diff --git a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py index ba0070c9a..9c6a17466 100644 --- a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py +++ b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py @@ -16,6 +16,13 @@ torch = LazyImport('torch') +_MXFP4_ARGS = ( + '--a_type f4_r --b_type f4_r --c_type f32_r --d_type f32_r --compute_type f32_r' + ' --scaleA 3 --scaleB 3 --scaleABlockRowSize 32 --scaleABlockColSize 1' + ' --scaleBBlockRowSize 1 --scaleBBlockColSize 32 --alpha 1 --beta 0' + ' --algo_method heuristic --requested_solution 1 --verify --use_gpu_timer --print_kernel_info' +) + class HipBlasLtBenchmark(BlasLtBaseBenchmark): """The hipBlasLt GEMM benchmark class.""" @@ -31,19 +38,11 @@ def __init__(self, name, parameters=''): self._bin_name = 'hipblaslt-bench' self._in_types = ['fp32', 'fp16', 'bf16', 'fp8', 'mxfp4'] self._in_type_map = { - 'fp16': - '--a_type f16_r --b_type f16_r --c_type f16_r --d_type f16_r --compute_type f32_r', - 'fp32': - '--a_type f32_r --b_type f32_r --c_type f32_r --d_type f32_r --compute_type f32_r', - 'bf16': - '--a_type bf16_r --b_type bf16_r --c_type bf16_r --d_type bf16_r --compute_type f32_r', - 'fp8': - '--a_type f8_r --b_type f8_r --c_type f8_r --d_type f8_r --compute_type f32_r', - 'mxfp4': - '--a_type f4_r --b_type f4_r --c_type f32_r --d_type f32_r --compute_type f32_r' - ' --scaleA 3 --scaleB 3 --scaleABlockRowSize 32 --scaleABlockColSize 1' - ' --scaleBBlockRowSize 1 --scaleBBlockColSize 32 --alpha 1 --beta 0' - ' --algo_method heuristic --requested_solution 1 --verify --use_gpu_timer --print_kernel_info', + 'fp16': '--a_type f16_r --b_type f16_r --c_type f16_r --d_type f16_r --compute_type f32_r', + 'fp32': '--a_type f32_r --b_type f32_r --c_type f32_r --d_type f32_r --compute_type f32_r', + 'bf16': '--a_type bf16_r --b_type bf16_r --c_type bf16_r --d_type bf16_r --compute_type f32_r', + 'fp8': '--a_type f8_r --b_type f8_r --c_type f8_r --d_type f8_r --compute_type f32_r', + 'mxfp4': _MXFP4_ARGS, } def add_parser_arguments(self): @@ -115,23 +114,14 @@ def _check_mxfp4_support(self) -> bool: if arch != 'gfx950': self._result.set_return_code(ReturnCode.MICROBENCHMARK_UNSUPPORTED_ARCHITECTURE) - logger.error( - 'Experimental MXFP4 only allows gfx950 - benchmark: {}, architecture: {}.'.format(self._name, arch) - ) + logger.error(f'Experimental MXFP4 only allows gfx950 - benchmark: {self._name}, architecture: {arch}.') return False output = run_command(f'{shlex.quote(self.__bin_path)} --help', quiet=True) - required_options = [ - '--scaleA', - '--scaleB', - '--scaleABlockRowSize', - '--scaleABlockColSize', - '--scaleBBlockRowSize', - '--scaleBBlockColSize', - '--verify', - '--use_gpu_timer', - '--print_kernel_info', - ] + required_options = ( + '--scaleA', '--scaleB', '--scaleABlockRowSize', '--scaleABlockColSize', '--scaleBBlockRowSize', + '--scaleBBlockColSize', '--verify', '--use_gpu_timer', '--print_kernel_info' + ) missing = [option for option in required_options if not re.search(re.escape(option) + r'\b', output.stdout)] if not re.search(r'\b3\s*=\s*block\b', output.stdout, re.IGNORECASE): missing.append('block scaling mode (3)') @@ -139,15 +129,11 @@ def _check_mxfp4_support(self) -> bool: self._result.add_raw_data('mxfp4_client_help', output.stdout, self._args.log_raw_data) if output.returncode != 0: self._result.set_return_code(ReturnCode.MICROBENCHMARK_EXECUTION_FAILURE) - logger.error( - 'Cannot query MXFP4 client options - benchmark: {}, output: {}.'.format(self._name, output.stdout) - ) + logger.error(f'Cannot query MXFP4 client options - benchmark: {self._name}, output: {output.stdout}.') return False if missing: self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) - logger.error( - 'MXFP4 client is missing required options - benchmark: {}, missing: {}.'.format(self._name, missing) - ) + logger.error(f'MXFP4 client is missing required options - benchmark: {self._name}, missing: {missing}.') return False self._result.add_raw_data('mxfp4_gpu_arch', arch, self._args.log_raw_data) return True @@ -203,24 +189,11 @@ def _mxfp4_result_row(columns: Dict[str, int], fields: List[str], trailer: List[ def _record_mxfp4_result(self, cmd_idx: int, row: Dict[str, str]) -> None: """Record MXFP4 metrics only after the requested case, timing and verification match.""" m, n, k, _, _ = self._shapes_to_run[cmd_idx] - expected = { - 'transA': 'T', - 'transB': 'N', - 'grouped_gemm': '0', - 'batch_count': '1', - 'm': str(m), - 'n': str(n), - 'k': str(k), - 'a_type': 'f4_r', - 'b_type': 'f4_r', - 'c_type': 'f32_r', - 'd_type': 'f32_r', - 'compute_type': 'f32_r', - 'scaleA': '3', - 'scaleB': '3', - 'use_gpu_timer': '1', - } - for column, value in expected.items(): + for column, value in ( + ('transA', 'T'), ('transB', 'N'), ('grouped_gemm', '0'), ('batch_count', '1'), ('m', str(m)), ('n', str(n)), + ('k', str(k)), ('a_type', 'f4_r'), ('b_type', 'f4_r'), ('c_type', 'f32_r'), ('d_type', 'f32_r'), + ('compute_type', 'f32_r'), ('scaleA', '3'), ('scaleB', '3'), ('use_gpu_timer', '1') + ): if row.get(column) != value: raise ValueError(f'MXFP4 column {column} must be {value}, got {row.get(column)}.') @@ -267,24 +240,48 @@ def _process_raw_result(self, cmd_idx, raw_output): try: lines = raw_output.splitlines() - index = next((i for i, line in enumerate(lines) if 'hipblaslt-Gflops' in line), None) - if index is None: + + # Find the header line containing 'hipblaslt-Gflops' + for index, line in enumerate(lines): + if 'hipblaslt-Gflops' in line: + break + else: raise ValueError('Line with "hipblaslt-Gflops" not found in the log.') - header_fields = re.sub(r'^\s*\[\d+\]:?', '', lines[index]).split(',') - col_idx_by_name: Dict[str, int] = {} + # Parse the header and resolve every key column (batch_count/m/n/k/hipblaslt-Gflops) + # by name. This keeps the parser forward-compatible across known and future + # hipBLASLt output formats (v600: 23 columns; v1500: 34 columns with extra + # a_type/b_type/c_type/scaleA-D/amaxD/bias_type/aux_type/hipblaslt-GB/s), + # without relying on any fixed column position. + header_fields = lines[index].strip().split(',') + # Strip leading rank markers like '[0]' or '[0]:' from the first header field. + # Use a regex anchored at the start so a column name that legitimately contains + # ']' (unlikely, but defensive) is not truncated. + header_fields[0] = re.sub(r'^\s*\[\d+\]:?', '', header_fields[0]) + + # Build a name -> column-index map (first occurrence wins for any duplicates). + col_idx_by_name = {} for col_idx, col_name in enumerate(header_fields): col_idx_by_name.setdefault(col_name.strip(), col_idx) + required_columns = ['batch_count', 'm', 'n', 'k', 'hipblaslt-Gflops'] missing_columns = [c for c in required_columns if c not in col_idx_by_name] if missing_columns: raise ValueError(f'Required column(s) not found in header: {missing_columns}.') + + # Ensure a data line follows the header (e.g., hipblaslt-bench may have + # crashed after printing the header). if index + 1 >= len(lines): raise ValueError('Data line missing after "hipblaslt-Gflops" header.') - fields = lines[index + 1].split(',') + + # Split the data line into fields using a comma as the delimiter + fields = lines[index + 1].strip().split(',') + + # Validate that the data line has the same number of columns as the header if len(fields) != len(header_fields): raise ValueError( - f'Field count mismatch: header has {len(header_fields)} columns but data has {len(fields)} columns' + f'Field count mismatch: header has {len(header_fields)} columns ' + f'but data has {len(fields)} columns' ) if self._precision_in_commands[cmd_idx] == 'mxfp4': @@ -292,6 +289,8 @@ def _process_raw_result(self, cmd_idx, raw_output): self._record_mxfp4_result(cmd_idx, row) return True + # Resolve every key value by header name and strip whitespace from each, so + # any padding around CSV values does not bleed into the metric key. batch_count = fields[col_idx_by_name['batch_count']].strip() m_val = fields[col_idx_by_name['m']].strip() n_val = fields[col_idx_by_name['n']].strip() diff --git a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py index 1e4a18a20..661735c91 100644 --- a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py +++ b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py @@ -33,10 +33,10 @@ def setUpClass(cls): cls.createMockEnvs(cls) cls.createMockFiles(cls, ['bin/hipblaslt-bench']) - def get_benchmark(self, parameters=''): + def get_benchmark(self): """Get Benchmark.""" (benchmark_cls, _) = BenchmarkRegistry._BenchmarkRegistry__select_benchmark(self.benchmark_name, Platform.ROCM) - return benchmark_cls(self.benchmark_name, parameters=parameters) + return benchmark_cls(self.benchmark_name, parameters='') def preprocess_mxfp4( self, parameters=_MXFP4_PARAMETERS, arch='gfx950:sramecc+:xnack-', help_result=None, available=True @@ -44,7 +44,7 @@ def preprocess_mxfp4( """Preprocess with synthetic ROCm device and client capability information.""" if help_result is None: help_result = SimpleNamespace(returncode=0, stdout=' '.join(_MXFP4_HELP_OPTIONS)) - benchmark = self.get_benchmark(parameters) + benchmark = hipblaslt_function.HipBlasLtBenchmark(self.benchmark_name, parameters=parameters) with patch.object(hipblaslt_function, 'torch') as torch, \ patch.object(hipblaslt_function, 'run_command', return_value=help_result): torch.version.hip = '7.2.4' From 375989e518822d23c9c068bdfefb9ce0bf0d7568 Mon Sep 17 00:00:00 2001 From: Guoxin Sui Date: Tue, 24 Nov 2026 14:51:24 -0700 Subject: [PATCH 09/16] Benchmarks - Select hipBLASLt MXFP4 by input type alone Selecting mxfp4 already opts in to the experimental path. Drop the duplicate boolean option while retaining the default FP16 input, architecture, client and verification checks. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/micro_benchmarks/hipblaslt_function.py | 7 ------- .../micro_benchmarks/test_hipblaslt_function.py | 10 +++------- 2 files changed, 3 insertions(+), 14 deletions(-) diff --git a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py index 9c6a17466..b02c35162 100644 --- a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py +++ b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py @@ -81,16 +81,9 @@ def add_parser_arguments(self): required=False, help='Transpose matrix B.', ) - self._parser.add_argument( - '--enable_experimental_fp4', - action='store_true', - help='Opt in to unvalidated MXFP4 on gfx950 with a block-scaling hipblaslt-bench client.', - ) def _validate_mxfp4_arguments(self) -> None: """Validate the experimental non-batched, TN MXFP4 case contract.""" - if not self._args.enable_experimental_fp4: - raise ValueError('MXFP4 requires --enable_experimental_fp4; hardware validation is pending.') if (self._args.transA, self._args.transB) != ('T', 'N'): raise ValueError('MXFP4 currently requires --transA T --transB N.') if self._args.initialization not in ['hpl', 'trig_float']: diff --git a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py index 661735c91..1b08de33f 100644 --- a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py +++ b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py @@ -13,10 +13,7 @@ from superbench.benchmarks.micro_benchmarks import hipblaslt_function from superbench.benchmarks.result import BenchmarkResult -_MXFP4_PARAMETERS = ( - '--in_types mxfp4 --enable_experimental_fp4 --shapes 64,128,256' - ' --transA T --transB N --initialization hpl' -) +_MXFP4_PARAMETERS = '--in_types mxfp4 --shapes 64,128,256 --transA T --transB N --initialization hpl' _MXFP4_HELP_OPTIONS = ( '--scaleA', '--scaleB', '--scaleABlockRowSize', '--scaleABlockColSize', '--scaleBBlockRowSize', '--scaleBBlockColSize', '--verify', '--use_gpu_timer', '--print_kernel_info', '3 = block' @@ -158,7 +155,7 @@ def cmd(t, b, m, n, k): self.assertIn(cmd(_t, 0, _m, _n, _k), benchmark._commands) def test_mxfp4_command_generation(self): - """Test explicit MXFP4 input, scale, verification, and device timing options.""" + """Select MXFP4 by input type alone and check its scale, verification and device timing options.""" benchmark, result = self.preprocess_mxfp4() self.assertTrue(result) self.assertEqual(len(benchmark._commands), 1) @@ -192,10 +189,9 @@ def test_mxfp4_boolean_flags_are_switches(self): ) def test_mxfp4_invalid_arguments(self): - """Reject missing opt-in and unsupported layouts, initialization, shapes, or counts.""" + """Reject unsupported layouts, initialization, shapes, or counts.""" valid = _MXFP4_PARAMETERS invalid = [ - valid.replace('--enable_experimental_fp4', ''), valid.replace('--transA T', '--transA N'), valid.replace('--transB N', '--transB T'), valid.replace('--initialization hpl', '--initialization rand_int'), From b705ca50ab546dce5e5e46c298bda4637ddb7f5c Mon Sep 17 00:00:00 2001 From: Guoxin Sui Date: Tue, 24 Nov 2026 16:25:09 -0700 Subject: [PATCH 10/16] Benchmarks - Target MI455X native B32E8 MXFP4 GEMM Use the gfx1250 hipBLASLt client contract rather than obsolete block-dimension options. Check B32E8 on both operands, support the MAF2 input pattern, require strict CPU verification and kernel identification, and retain the default and legacy precision behavior. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../micro_benchmarks/hipblaslt_function.py | 39 ++++++++----- .../test_hipblaslt_function.py | 55 +++++++++++-------- 2 files changed, 55 insertions(+), 39 deletions(-) diff --git a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py index b02c35162..a87b3e8a0 100644 --- a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py +++ b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py @@ -18,9 +18,8 @@ _MXFP4_ARGS = ( '--a_type f4_r --b_type f4_r --c_type f32_r --d_type f32_r --compute_type f32_r' - ' --scaleA 3 --scaleB 3 --scaleABlockRowSize 32 --scaleABlockColSize 1' - ' --scaleBBlockRowSize 1 --scaleBBlockColSize 32 --alpha 1 --beta 0' - ' --algo_method heuristic --requested_solution 1 --verify --use_gpu_timer --print_kernel_info' + ' --scaleA 3 --scaleB 3 --alpha 1 --beta 0 --algo_method heuristic --requested_solution 1' + ' --verify --verify_strict --use_gpu_timer --print_kernel_info' ) @@ -61,7 +60,7 @@ def add_parser_arguments(self): '--initialization', type=str, default='rand_int', - choices=['trig_float', 'rand_int', 'hpl'], + choices=['trig_float', 'rand_int', 'hpl', 'maf2_0'], required=False, help='Initialize matrix data.', ) @@ -86,8 +85,8 @@ def _validate_mxfp4_arguments(self) -> None: """Validate the experimental non-batched, TN MXFP4 case contract.""" if (self._args.transA, self._args.transB) != ('T', 'N'): raise ValueError('MXFP4 currently requires --transA T --transB N.') - if self._args.initialization not in ['hpl', 'trig_float']: - raise ValueError('MXFP4 requires --initialization hpl or trig_float.') + if self._args.initialization not in ['hpl', 'trig_float', 'maf2_0']: + raise ValueError('MXFP4 requires --initialization hpl, trig_float or maf2_0.') if self._args.num_warmup < 0 or self._args.num_steps < 1: raise ValueError('MXFP4 requires non-negative warmup and positive measurement iterations.') for m, n, k, batch, precision in self._shapes_to_run: @@ -105,19 +104,21 @@ def _check_mxfp4_support(self) -> bool: logger.error('Cannot identify the MXFP4 device - benchmark: {}, message: {}.'.format(self._name, str(e))) return False - if arch != 'gfx950': + if arch != 'gfx1250': self._result.set_return_code(ReturnCode.MICROBENCHMARK_UNSUPPORTED_ARCHITECTURE) - logger.error(f'Experimental MXFP4 only allows gfx950 - benchmark: {self._name}, architecture: {arch}.') + logger.error(f'MI455X MXFP4 requires gfx1250 - benchmark: {self._name}, architecture: {arch}.') return False output = run_command(f'{shlex.quote(self.__bin_path)} --help', quiet=True) + b32e8 = r'[^\n]*\b3[ \t]*=[ \t]*(?i:B32E8)\b' required_options = ( - '--scaleA', '--scaleB', '--scaleABlockRowSize', '--scaleABlockColSize', '--scaleBBlockRowSize', - '--scaleBBlockColSize', '--verify', '--use_gpu_timer', '--print_kernel_info' + ('--scaleA', b32e8), ('--scaleB', b32e8), ('--initialization', rf'[^\n]*\b{self._args.initialization}\b'), + ('--verify', ''), ('--verify_strict', ''), ('--use_gpu_timer', ''), ('--print_kernel_info', '') ) - missing = [option for option in required_options if not re.search(re.escape(option) + r'\b', output.stdout)] - if not re.search(r'\b3\s*=\s*block\b', output.stdout, re.IGNORECASE): - missing.append('block scaling mode (3)') + missing = [ + option for option, value in required_options + if not re.search(rf'^[ \t]*{option}\b{value}', output.stdout, re.MULTILINE) + ] if output.returncode != 0 or missing or self._args.log_raw_data: self._result.add_raw_data('mxfp4_client_help', output.stdout, self._args.log_raw_data) if output.returncode != 0: @@ -126,7 +127,7 @@ def _check_mxfp4_support(self) -> bool: return False if missing: self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) - logger.error(f'MXFP4 client is missing required options - benchmark: {self._name}, missing: {missing}.') + logger.error(f'MXFP4 client lacks B32E8 or required options - benchmark: {self._name}, missing: {missing}.') return False self._result.add_raw_data('mxfp4_gpu_arch', arch, self._args.log_raw_data) return True @@ -144,6 +145,12 @@ def _preprocess(self): self._commands = [] self._precision_in_commands = [] + if self._args.initialization == 'maf2_0' and any(t != 'mxfp4' for t in self._args.in_types): + self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) + logger.error( + f'Use a separate MXFP4 benchmark instance for maf2_0 initialization - benchmark: {self._name}.' + ) + return False if 'mxfp4' in self._args.in_types: try: self._validate_mxfp4_arguments() @@ -171,6 +178,8 @@ def _mxfp4_result_row(columns: Dict[str, int], fields: List[str], trailer: List[ """Require one result row with unique columns; kernel diagnostics may follow it.""" if len(columns) != len(fields): raise ValueError('MXFP4 requires unique result columns.') + if not any(re.match(r'^\s*--kernel name:\s*\S', line) for line in trailer): + raise ValueError('MXFP4 requires the client to report the selected kernel.') for line in trailer: extra = [v.strip() for v in re.sub(r'^\s*\[\d+\]:?', '', line).split(',')] if 'hipblaslt-Gflops' in extra or ( @@ -202,7 +211,7 @@ def _record_mxfp4_result(self, cmd_idx: int, row: Dict[str, str]) -> None: if not math.isclose(gflops, 2 * m * n * k / latency / 1000, rel_tol=0.01): raise ValueError('MXFP4 throughput does not match 2*M*N*K and the reported latency.') - # hipblaslt-bench reports verification errors without asserting them. + # Keep the wrapper's conservative FP32-output bound in addition to the client's strict verification. norm_error = float(row['norm_error']) if not 0 <= norm_error < 1e-5: raise ValueError('MXFP4 FP32-output relative Frobenius norm error must be finite and below 1e-5.') diff --git a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py index 1b08de33f..f51885a2b 100644 --- a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py +++ b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py @@ -13,10 +13,11 @@ from superbench.benchmarks.micro_benchmarks import hipblaslt_function from superbench.benchmarks.result import BenchmarkResult -_MXFP4_PARAMETERS = '--in_types mxfp4 --shapes 64,128,256 --transA T --transB N --initialization hpl' +_MXFP4_PARAMETERS = '--in_types mxfp4 --shapes 64,128,256 --transA T --transB N --initialization maf2_0' _MXFP4_HELP_OPTIONS = ( - '--scaleA', '--scaleB', '--scaleABlockRowSize', '--scaleABlockColSize', '--scaleBBlockRowSize', - '--scaleBBlockColSize', '--verify', '--use_gpu_timer', '--print_kernel_info', '3 = block' + '--scaleA 0 = None, 3 = B32E8, 4 = B16E8', '--scaleB 0 = None, 3 = B32E8, 4 = B16E8', + '--initialization hpl, trig_float, maf2_0', '--verify |-v', '--verify_strict', '--use_gpu_timer', + '--print_kernel_info' ) @@ -36,15 +37,15 @@ def get_benchmark(self): return benchmark_cls(self.benchmark_name, parameters='') def preprocess_mxfp4( - self, parameters=_MXFP4_PARAMETERS, arch='gfx950:sramecc+:xnack-', help_result=None, available=True + self, parameters=_MXFP4_PARAMETERS, arch='gfx1250:sramecc+:xnack-', help_result=None, available=True ): """Preprocess with synthetic ROCm device and client capability information.""" if help_result is None: - help_result = SimpleNamespace(returncode=0, stdout=' '.join(_MXFP4_HELP_OPTIONS)) + help_result = SimpleNamespace(returncode=0, stdout='\n'.join(_MXFP4_HELP_OPTIONS)) benchmark = hipblaslt_function.HipBlasLtBenchmark(self.benchmark_name, parameters=parameters) with patch.object(hipblaslt_function, 'torch') as torch, \ patch.object(hipblaslt_function, 'run_command', return_value=help_result): - torch.version.hip = '7.2.4' + torch.version.hip = 'test-rocm' torch.cuda.is_available.return_value = available torch.cuda.get_device_properties.return_value.gcnArchName = arch result = benchmark._preprocess() @@ -98,7 +99,8 @@ def mxfp4_output(self, overrides=None, missing=(), reverse=False): columns = list(row) if reverse: columns.reverse() - return '[0]:' + ','.join(columns) + '\n' + ','.join(row[column] for column in columns) + '\n' + return '[0]:' + ','.join(columns) + '\n' + ','.join(row[column] for column in columns) + \ + '\n --kernel name: synthetic_mxfp4_kernel\n' def test_hipblaslt_gemm_cls(self): """Test hipblaslt-bench benchmark class.""" @@ -163,15 +165,14 @@ def test_mxfp4_command_generation(self): for option, value in [ ('-m', '64'), ('-n', '128'), ('-k', '256'), ('--a_type', 'f4_r'), ('--b_type', 'f4_r'), ('--c_type', 'f32_r'), ('--d_type', 'f32_r'), ('--compute_type', 'f32_r'), ('--scaleA', '3'), - ('--scaleB', '3'), ('--scaleABlockRowSize', '32'), ('--scaleABlockColSize', '1'), - ('--scaleBBlockRowSize', '1'), ('--scaleBBlockColSize', '32'), ('--alpha', '1'), ('--beta', '0'), - ('--algo_method', 'heuristic'), ('--requested_solution', '1'), ('--transA', 'T'), ('--transB', 'N'), - ('--initialization', 'hpl') + ('--scaleB', '3'), ('--alpha', '1'), ('--beta', '0'), ('--algo_method', 'heuristic'), + ('--requested_solution', '1'), ('--transA', 'T'), ('--transB', 'N'), ('--initialization', 'maf2_0') ]: with self.subTest(option=option): self.assertEqual(tokens.count(option), 1) self.assertEqual(tokens[tokens.index(option) + 1], value) - self.assertEqual(benchmark.raw_data['mxfp4_gpu_arch'][0], 'gfx950') + self.assertFalse(any(token.startswith(('--scaleABlock', '--scaleBBlock')) for token in tokens)) + self.assertEqual(benchmark.raw_data['mxfp4_gpu_arch'][0], 'gfx1250') self.assertNotIn('mxfp4_client_help', benchmark.raw_data) def test_mxfp4_boolean_flags_are_switches(self): @@ -179,7 +180,7 @@ def test_mxfp4_boolean_flags_are_switches(self): benchmark, result = self.preprocess_mxfp4() self.assertTrue(result) tokens = shlex.split(benchmark._commands[0]) - for option in ['--verify', '--use_gpu_timer', '--print_kernel_info']: + for option in ['--verify', '--verify_strict', '--use_gpu_timer', '--print_kernel_info']: with self.subTest(option=option): self.assertEqual(tokens.count(option), 1) next_index = tokens.index(option) + 1 @@ -194,7 +195,9 @@ def test_mxfp4_invalid_arguments(self): invalid = [ valid.replace('--transA T', '--transA N'), valid.replace('--transB N', '--transB T'), - valid.replace('--initialization hpl', '--initialization rand_int'), + valid.replace('--initialization maf2_0', '--initialization rand_int'), + valid.replace('--in_types mxfp4', '--in_types fp16'), + valid.replace('--in_types mxfp4', '--in_types mxfp4 fp16'), valid.replace('64,128,256', '64,128,257'), valid.replace('64,128,256', '0,128,256'), valid + ' --batch 1', @@ -210,7 +213,7 @@ def test_mxfp4_invalid_arguments(self): def test_mxfp4_unsupported_devices(self): """Reject older GPUs and unqualified future architectures without generating commands.""" - for arch in ['gfx908', 'gfx90a', 'gfx942', 'gfx1201', 'gfx999']: + for arch in ['gfx942', 'gfx950', 'gfx1201', 'gfx1251']: with self.subTest(arch=arch): benchmark, result = self.preprocess_mxfp4(arch=arch) self.assertFalse(result) @@ -222,13 +225,16 @@ def test_mxfp4_unsupported_devices(self): def test_mxfp4_client_capabilities(self): """Reject old client options and explicit capability-query failures.""" + help_text = '\n'.join(_MXFP4_HELP_OPTIONS) with patch.object(BenchmarkResult, 'add_raw_data', autospec=True) as record: benchmark, ready = self.preprocess_mxfp4(_MXFP4_PARAMETERS + ' --log_raw_data') self.assertTrue(ready) - record.assert_any_call(benchmark._result, 'mxfp4_client_help', ' '.join(_MXFP4_HELP_OPTIONS), True) + record.assert_any_call(benchmark._result, 'mxfp4_client_help', help_text, True) for output in [ - SimpleNamespace(returncode=0, stdout='--scaleA --scaleB 0 = None, 1 = scalar, 2 = vector'), + SimpleNamespace(returncode=0, stdout=help_text.replace('3 = B32E8', '3 = block')), + SimpleNamespace(returncode=0, stdout=help_text.replace('3 = B32E8', '3 = B16E8', 1)), + SimpleNamespace(returncode=0, stdout=help_text.replace('maf2_0', 'maf2_0_unit_scale')), SimpleNamespace(returncode=1, stdout='Cannot load hipBLASLt'), ]: with self.subTest(output=output): @@ -240,14 +246,12 @@ def test_mxfp4_client_capabilities(self): self.assertEqual(benchmark._commands, []) self.assertEqual(benchmark.raw_data['mxfp4_client_help'], [output.stdout]) - help_result = SimpleNamespace( - returncode=0, stdout=' '.join(_MXFP4_HELP_OPTIONS).replace('3 = block', '3=Block') - ) + help_result = SimpleNamespace(returncode=0, stdout=help_text.replace('3 = B32E8', '3=b32e8')) self.assertTrue(self.preprocess_mxfp4(help_result=help_result)[1]) for missing in _MXFP4_HELP_OPTIONS: with self.subTest(missing=missing): help_result = SimpleNamespace( - returncode=0, stdout=' '.join(option for option in _MXFP4_HELP_OPTIONS if option != missing) + returncode=0, stdout='\n'.join(option for option in _MXFP4_HELP_OPTIONS if option != missing) ) benchmark, result = self.preprocess_mxfp4(help_result=help_result) self.assertFalse(result) @@ -258,6 +262,7 @@ def test_mxfp4_subprocess_status(self): for returncode, raw_output in [ (0, self.mxfp4_output()), (1, 'No supported solutions found'), + (2, self.mxfp4_output()), (0, self.mxfp4_output({'atol': 'failed'})), ]: with self.subTest(returncode=returncode, raw_output=raw_output): @@ -319,7 +324,7 @@ def test_mxfp4_invalid_results(self): def test_mxfp4_incomplete_results(self): """Reject absent verification columns, malformed CSV, and multiple algorithm results.""" output = self.mxfp4_output() - header, row = output.splitlines() + header, row, kernel = output.splitlines() invalid = [ self.mxfp4_output(missing=[column]) for column in ['alpha', 'beta', 'a_type', 'scaleA', 'norm_error', 'atol', 'rtol', 'us', 'use_gpu_timer'] @@ -327,8 +332,10 @@ def test_mxfp4_incomplete_results(self): invalid.extend( [ header + '\n', - header + '\n' + row + ',extra\n', - header + ',m\n' + row + ',128\n', + header + '\n' + row + ',extra\n' + kernel, + header + ',m\n' + row + ',128\n' + kernel, + header + '\n' + row + '\n', + output.replace('synthetic_mxfp4_kernel', ' '), output + output, output + row + '\n', 'No supported solutions found', From 74e251a49dabd4c7d3090df92de61449af6aca2d Mon Sep 17 00:00:00 2001 From: Guoxin Sui Date: Tue, 24 Nov 2026 17:09:07 -0700 Subject: [PATCH 11/16] Tests - Simplify MXFP4 hipBLASLt wrapper coverage Consolidate command checks and keep the subprocess failure case that can otherwise record misleading metrics from a valid result row. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../test_hipblaslt_function.py | 44 ++++++------------- 1 file changed, 13 insertions(+), 31 deletions(-) diff --git a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py index f51885a2b..a0ee87e62 100644 --- a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py +++ b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py @@ -157,7 +157,7 @@ def cmd(t, b, m, n, k): self.assertIn(cmd(_t, 0, _m, _n, _k), benchmark._commands) def test_mxfp4_command_generation(self): - """Select MXFP4 by input type alone and check its scale, verification and device timing options.""" + """Check MXFP4 scaling, layout, and standalone verification and timing switches.""" benchmark, result = self.preprocess_mxfp4() self.assertTrue(result) self.assertEqual(len(benchmark._commands), 1) @@ -171,15 +171,6 @@ def test_mxfp4_command_generation(self): with self.subTest(option=option): self.assertEqual(tokens.count(option), 1) self.assertEqual(tokens[tokens.index(option) + 1], value) - self.assertFalse(any(token.startswith(('--scaleABlock', '--scaleBBlock')) for token in tokens)) - self.assertEqual(benchmark.raw_data['mxfp4_gpu_arch'][0], 'gfx1250') - self.assertNotIn('mxfp4_client_help', benchmark.raw_data) - - def test_mxfp4_boolean_flags_are_switches(self): - """Require standalone boolean switches rather than value-consuming options.""" - benchmark, result = self.preprocess_mxfp4() - self.assertTrue(result) - tokens = shlex.split(benchmark._commands[0]) for option in ['--verify', '--verify_strict', '--use_gpu_timer', '--print_kernel_info']: with self.subTest(option=option): self.assertEqual(tokens.count(option), 1) @@ -188,6 +179,9 @@ def test_mxfp4_boolean_flags_are_switches(self): next_index == len(tokens) or tokens[next_index].startswith('-'), '{} must not consume a value'.format(option), ) + self.assertFalse(any(token.startswith(('--scaleABlock', '--scaleBBlock')) for token in tokens)) + self.assertEqual(benchmark.raw_data['mxfp4_gpu_arch'][0], 'gfx1250') + self.assertNotIn('mxfp4_client_help', benchmark.raw_data) def test_mxfp4_invalid_arguments(self): """Reject unsupported layouts, initialization, shapes, or counts.""" @@ -213,7 +207,7 @@ def test_mxfp4_invalid_arguments(self): def test_mxfp4_unsupported_devices(self): """Reject older GPUs and unqualified future architectures without generating commands.""" - for arch in ['gfx942', 'gfx950', 'gfx1201', 'gfx1251']: + for arch in ['gfx942', 'gfx1251']: with self.subTest(arch=arch): benchmark, result = self.preprocess_mxfp4(arch=arch) self.assertFalse(result) @@ -258,26 +252,14 @@ def test_mxfp4_client_capabilities(self): self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) def test_mxfp4_subprocess_status(self): - """Propagate client and verification failures without emitting performance metrics.""" - for returncode, raw_output in [ - (0, self.mxfp4_output()), - (1, 'No supported solutions found'), - (2, self.mxfp4_output()), - (0, self.mxfp4_output({'atol': 'failed'})), - ]: - with self.subTest(returncode=returncode, raw_output=raw_output): - benchmark, result = self.preprocess_mxfp4() - self.assertTrue(result) - output = SimpleNamespace(returncode=returncode, stdout=raw_output) - with patch('superbench.benchmarks.micro_benchmarks.micro_base.run_command', return_value=output): - success = benchmark._benchmark() - expected = returncode == 0 and 'failed' not in raw_output - self.assertEqual(success, expected) - if not expected: - code = ReturnCode.MICROBENCHMARK_EXECUTION_FAILURE if returncode else \ - ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE - self.assertEqual(benchmark.return_code, code) - self.assertEqual(set(benchmark.result), {'return_code'}) + """A nonzero client exit must suppress metrics even when it prints a valid row.""" + benchmark, result = self.preprocess_mxfp4() + self.assertTrue(result) + output = SimpleNamespace(returncode=2, stdout=self.mxfp4_output()) + with patch('superbench.benchmarks.micro_benchmarks.micro_base.run_command', return_value=output): + self.assertFalse(benchmark._benchmark()) + self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_EXECUTION_FAILURE) + self.assertEqual(set(benchmark.result), {'return_code'}) def test_mxfp4_result_parsing(self): """Check reordered columns, exact metric units, and the norm threshold boundary.""" From e1530da892f53eef7febd34b64a7425db54d9e4d Mon Sep 17 00:00:00 2001 From: Guoxin Sui Date: Wed, 25 Nov 2026 10:11:23 -0700 Subject: [PATCH 12/16] Benchmarks - Simplify the hipBLASLt MXFP4 capability probe Check the advertised scale and initialization values. Let the client reject unsupported ordinary switches during execution, where a nonzero exit already suppresses metrics. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../micro_benchmarks/hipblaslt_function.py | 13 +++++-------- .../micro_benchmarks/test_hipblaslt_function.py | 3 +-- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py index a87b3e8a0..6b454840d 100644 --- a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py +++ b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py @@ -110,14 +110,11 @@ def _check_mxfp4_support(self) -> bool: return False output = run_command(f'{shlex.quote(self.__bin_path)} --help', quiet=True) - b32e8 = r'[^\n]*\b3[ \t]*=[ \t]*(?i:B32E8)\b' - required_options = ( - ('--scaleA', b32e8), ('--scaleB', b32e8), ('--initialization', rf'[^\n]*\b{self._args.initialization}\b'), - ('--verify', ''), ('--verify_strict', ''), ('--use_gpu_timer', ''), ('--print_kernel_info', '') - ) + b32e8 = r'3[ \t]*=[ \t]*(?i:B32E8)' + required_values = (('--scaleA', b32e8), ('--scaleB', b32e8), ('--initialization', self._args.initialization)) missing = [ - option for option, value in required_options - if not re.search(rf'^[ \t]*{option}\b{value}', output.stdout, re.MULTILINE) + option for option, value in required_values + if not re.search(rf'^[ \t]*{option}\b.*\b{value}\b', output.stdout, re.MULTILINE) ] if output.returncode != 0 or missing or self._args.log_raw_data: self._result.add_raw_data('mxfp4_client_help', output.stdout, self._args.log_raw_data) @@ -127,7 +124,7 @@ def _check_mxfp4_support(self) -> bool: return False if missing: self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) - logger.error(f'MXFP4 client lacks B32E8 or required options - benchmark: {self._name}, missing: {missing}.') + logger.error(f'Client lacks B32E8 or {self._args.initialization} for {missing} - benchmark: {self._name}.') return False self._result.add_raw_data('mxfp4_gpu_arch', arch, self._args.log_raw_data) return True diff --git a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py index a0ee87e62..3a5eee07c 100644 --- a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py +++ b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py @@ -16,8 +16,7 @@ _MXFP4_PARAMETERS = '--in_types mxfp4 --shapes 64,128,256 --transA T --transB N --initialization maf2_0' _MXFP4_HELP_OPTIONS = ( '--scaleA 0 = None, 3 = B32E8, 4 = B16E8', '--scaleB 0 = None, 3 = B32E8, 4 = B16E8', - '--initialization hpl, trig_float, maf2_0', '--verify |-v', '--verify_strict', '--use_gpu_timer', - '--print_kernel_info' + '--initialization hpl, trig_float, maf2_0' ) From f7e9a4b27aa369e07e932dfd26eb658ed76ed526 Mon Sep 17 00:00:00 2001 From: Guoxin Sui Date: Wed, 25 Nov 2026 10:33:24 -0700 Subject: [PATCH 13/16] Benchmarks - Simplify MXFP4 preflight and parser errors Return argument diagnostics directly and query the visible GPU architecture once. Only classify missing fields or invalid scalar text and case values as client output errors; leave wrapper bookkeeping failures to the benchmark runner. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../micro_benchmarks/hipblaslt_function.py | 45 +++++++++---------- .../test_hipblaslt_function.py | 20 ++++++--- 2 files changed, 33 insertions(+), 32 deletions(-) diff --git a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py index 6b454840d..7a1376d83 100644 --- a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py +++ b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py @@ -8,7 +8,7 @@ import re import shlex from decimal import Decimal, InvalidOperation -from typing import Dict, List +from typing import Dict, List, Optional from superbench.common.utils import LazyImport, logger, run_command from superbench.benchmarks import BenchmarkRegistry, Platform, ReturnCode @@ -81,25 +81,27 @@ def add_parser_arguments(self): help='Transpose matrix B.', ) - def _validate_mxfp4_arguments(self) -> None: - """Validate the experimental non-batched, TN MXFP4 case contract.""" - if (self._args.transA, self._args.transB) != ('T', 'N'): - raise ValueError('MXFP4 currently requires --transA T --transB N.') - if self._args.initialization not in ['hpl', 'trig_float', 'maf2_0']: - raise ValueError('MXFP4 requires --initialization hpl, trig_float or maf2_0.') - if self._args.num_warmup < 0 or self._args.num_steps < 1: - raise ValueError('MXFP4 requires non-negative warmup and positive measurement iterations.') + def _mxfp4_argument_error(self) -> Optional[str]: + """Return the first MXFP4 argument error, or None for a supported case.""" + args = self._args + if args.initialization == 'maf2_0' and any(t != 'mxfp4' for t in args.in_types): + return 'Use a separate MXFP4 benchmark instance for maf2_0 initialization.' + if (args.transA, args.transB) != ('T', 'N'): + return 'MXFP4 currently requires --transA T --transB N.' + if args.initialization not in ('hpl', 'trig_float', 'maf2_0'): + return 'MXFP4 requires --initialization hpl, trig_float or maf2_0.' + if args.num_warmup < 0 or args.num_steps < 1: + return 'MXFP4 requires non-negative warmup and positive measurement iterations.' for m, n, k, batch, precision in self._shapes_to_run: if precision == 'mxfp4' and (batch != 0 or min(m, n, k) <= 0 or k % 32 != 0): - raise ValueError('MXFP4 requires --batch 0, positive dimensions, and K divisible by 32.') + return 'MXFP4 requires --batch 0, positive dimensions, and K divisible by 32.' + return None def _check_mxfp4_support(self) -> bool: """Check the selected ROCm device and the client's block-scaling options.""" try: - if torch.version.hip is None or not torch.cuda.is_available(): - raise RuntimeError('MXFP4 requires a working ROCm PyTorch device.') arch = torch.cuda.get_device_properties(0).gcnArchName.split(':')[0] - except (AttributeError, RuntimeError) as e: + except (AssertionError, AttributeError, ImportError, RuntimeError) as e: self._result.set_return_code(ReturnCode.MICROBENCHMARK_DEVICE_GETTING_FAILURE) logger.error('Cannot identify the MXFP4 device - benchmark: {}, message: {}.'.format(self._name, str(e))) return False @@ -142,18 +144,11 @@ def _preprocess(self): self._commands = [] self._precision_in_commands = [] - if self._args.initialization == 'maf2_0' and any(t != 'mxfp4' for t in self._args.in_types): - self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) - logger.error( - f'Use a separate MXFP4 benchmark instance for maf2_0 initialization - benchmark: {self._name}.' - ) - return False - if 'mxfp4' in self._args.in_types: - try: - self._validate_mxfp4_arguments() - except ValueError as e: + if 'mxfp4' in self._args.in_types or self._args.initialization == 'maf2_0': + error = self._mxfp4_argument_error() + if error: self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) - logger.error('Invalid MXFP4 arguments - benchmark: {}, message: {}.'.format(self._name, str(e))) + logger.error('Invalid MXFP4 arguments - benchmark: %s, message: %s', self._name, error) return False if not self._check_mxfp4_support(): return False @@ -300,7 +295,7 @@ def _process_raw_result(self, cmd_idx, raw_output): f'{self._precision_in_commands[cmd_idx]}_{batch_count}_{m_val}_{n_val}_{k_val}_flops', float(fields[gflops_col]) / 1000 ) - except (IndexError, InvalidOperation, KeyError, TypeError, ValueError) as e: + except (InvalidOperation, KeyError, ValueError) as e: self._result.set_return_code(ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) logger.error( 'The result format is invalid - round: {}, benchmark: {}, raw output: {}, message: {}.'.format( diff --git a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py index 3a5eee07c..91d85596c 100644 --- a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py +++ b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py @@ -6,7 +6,7 @@ import shlex import unittest from types import SimpleNamespace -from unittest.mock import patch +from unittest.mock import Mock, patch from tests.helper.testcase import BenchmarkTestCase from superbench.benchmarks import BenchmarkRegistry, BenchmarkType, ReturnCode, Platform @@ -36,17 +36,16 @@ def get_benchmark(self): return benchmark_cls(self.benchmark_name, parameters='') def preprocess_mxfp4( - self, parameters=_MXFP4_PARAMETERS, arch='gfx1250:sramecc+:xnack-', help_result=None, available=True + self, parameters=_MXFP4_PARAMETERS, arch='gfx1250:sramecc+:xnack-', help_result=None, device_error=None ): """Preprocess with synthetic ROCm device and client capability information.""" if help_result is None: help_result = SimpleNamespace(returncode=0, stdout='\n'.join(_MXFP4_HELP_OPTIONS)) benchmark = hipblaslt_function.HipBlasLtBenchmark(self.benchmark_name, parameters=parameters) - with patch.object(hipblaslt_function, 'torch') as torch, \ + properties = Mock(return_value=SimpleNamespace(gcnArchName=arch), side_effect=device_error) + cuda = SimpleNamespace(get_device_properties=properties) + with patch.object(hipblaslt_function, 'torch', SimpleNamespace(cuda=cuda)), \ patch.object(hipblaslt_function, 'run_command', return_value=help_result): - torch.version.hip = 'test-rocm' - torch.cuda.is_available.return_value = available - torch.cuda.get_device_properties.return_value.gcnArchName = arch result = benchmark._preprocess() return benchmark, result @@ -212,9 +211,10 @@ def test_mxfp4_unsupported_devices(self): self.assertFalse(result) self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_UNSUPPORTED_ARCHITECTURE) self.assertEqual(benchmark._commands, []) - benchmark, result = self.preprocess_mxfp4(available=False) + benchmark, result = self.preprocess_mxfp4(device_error=AssertionError('Invalid device id')) self.assertFalse(result) self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_DEVICE_GETTING_FAILURE) + self.assertEqual(benchmark._commands, []) def test_mxfp4_client_capabilities(self): """Reject old client options and explicit capability-query failures.""" @@ -276,6 +276,12 @@ def test_mxfp4_result_parsing(self): self.assertEqual(benchmark.return_code, ReturnCode.SUCCESS) self.assert_invalid_mxfp4(self.mxfp4_output({'m': '128', 'n': '64'})) + def test_mxfp4_result_requires_valid_command_index(self): + """Do not report wrapper bookkeeping errors as malformed client output.""" + for index, error in [(1, IndexError), (None, TypeError)]: + with self.subTest(index=index), self.assertRaises(error): + self.mxfp4_parser()._process_raw_result(index, self.mxfp4_output()) + def test_mxfp4_result_coefficients(self): """Accept equivalent printed scalars, but never report metrics for a different GEMM.""" benchmark = self.mxfp4_parser() From a04e3cefdbd1f6a46699976727b580b017e62c56 Mon Sep 17 00:00:00 2001 From: Guoxin Sui Date: Wed, 25 Nov 2026 10:53:07 -0700 Subject: [PATCH 14/16] Benchmarks - Simplify MXFP4 verification and result helpers Use strict verification without the redundant verify flag, and name the row parser and test benchmark factory for what they return. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../micro_benchmarks/hipblaslt_function.py | 6 +++--- .../micro_benchmarks/test_hipblaslt_function.py | 13 +++++++------ 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py index 7a1376d83..6bfb7e55a 100644 --- a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py +++ b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py @@ -19,7 +19,7 @@ _MXFP4_ARGS = ( '--a_type f4_r --b_type f4_r --c_type f32_r --d_type f32_r --compute_type f32_r' ' --scaleA 3 --scaleB 3 --alpha 1 --beta 0 --algo_method heuristic --requested_solution 1' - ' --verify --verify_strict --use_gpu_timer --print_kernel_info' + ' --verify_strict --use_gpu_timer --print_kernel_info' ) @@ -166,7 +166,7 @@ def _preprocess(self): return True @staticmethod - def _mxfp4_result_row(columns: Dict[str, int], fields: List[str], trailer: List[str]) -> Dict[str, str]: + def _parse_mxfp4_result_row(columns: Dict[str, int], fields: List[str], trailer: List[str]) -> Dict[str, str]: """Require one result row with unique columns; kernel diagnostics may follow it.""" if len(columns) != len(fields): raise ValueError('MXFP4 requires unique result columns.') @@ -279,7 +279,7 @@ def _process_raw_result(self, cmd_idx, raw_output): ) if self._precision_in_commands[cmd_idx] == 'mxfp4': - row = self._mxfp4_result_row(col_idx_by_name, fields, lines[index + 2:]) + row = self._parse_mxfp4_result_row(col_idx_by_name, fields, lines[index + 2:]) self._record_mxfp4_result(cmd_idx, row) return True diff --git a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py index 91d85596c..d69ad4c0b 100644 --- a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py +++ b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py @@ -49,7 +49,7 @@ def preprocess_mxfp4( result = benchmark._preprocess() return benchmark, result - def mxfp4_parser(self): + def make_mxfp4_result_benchmark(self): """Make a fresh result collector for one requested shape without probing a device or client.""" benchmark = hipblaslt_function.HipBlasLtBenchmark(self.benchmark_name) benchmark._args = SimpleNamespace(log_raw_data=False) @@ -60,7 +60,7 @@ def mxfp4_parser(self): def assert_invalid_mxfp4(self, output): """Check that a rejected row publishes neither correctness nor performance metrics.""" - benchmark = self.mxfp4_parser() + benchmark = self.make_mxfp4_result_benchmark() self.assertFalse(benchmark._process_raw_result(0, output)) self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) self.assertEqual(set(benchmark.result), {'return_code'}) @@ -169,7 +169,8 @@ def test_mxfp4_command_generation(self): with self.subTest(option=option): self.assertEqual(tokens.count(option), 1) self.assertEqual(tokens[tokens.index(option) + 1], value) - for option in ['--verify', '--verify_strict', '--use_gpu_timer', '--print_kernel_info']: + self.assertNotIn('--verify', tokens) + for option in ['--verify_strict', '--use_gpu_timer', '--print_kernel_info']: with self.subTest(option=option): self.assertEqual(tokens.count(option), 1) next_index = tokens.index(option) + 1 @@ -264,7 +265,7 @@ def test_mxfp4_result_parsing(self): """Check reordered columns, exact metric units, and the norm threshold boundary.""" for reverse, norm in [(False, '1e-6'), (True, '9.999e-6')]: with self.subTest(reverse=reverse, norm=norm): - benchmark = self.mxfp4_parser() + benchmark = self.make_mxfp4_result_benchmark() output = self.mxfp4_output({'norm_error': norm}, reverse=reverse) column_count = len(output.splitlines()[0].split(',')) footer = 'diagnostic: ' + ','.join(['detail'] * column_count) @@ -280,11 +281,11 @@ def test_mxfp4_result_requires_valid_command_index(self): """Do not report wrapper bookkeeping errors as malformed client output.""" for index, error in [(1, IndexError), (None, TypeError)]: with self.subTest(index=index), self.assertRaises(error): - self.mxfp4_parser()._process_raw_result(index, self.mxfp4_output()) + self.make_mxfp4_result_benchmark()._process_raw_result(index, self.mxfp4_output()) def test_mxfp4_result_coefficients(self): """Accept equivalent printed scalars, but never report metrics for a different GEMM.""" - benchmark = self.mxfp4_parser() + benchmark = self.make_mxfp4_result_benchmark() self.assertTrue(benchmark._process_raw_result(0, self.mxfp4_output({'alpha': '1.00e+0', 'beta': '-0.0'}))) for column, value in [ From 56a45be87c06083ad6982c58cc9c3a0e4e55f4dc Mon Sep 17 00:00:00 2001 From: Guoxin Sui Date: Mon, 30 Nov 2026 10:39:13 -0700 Subject: [PATCH 15/16] Bugfix - Require a dedicated benchmark instance for MXFP4 Reject mixed --in_types whenever mxfp4 or maf2_0 is requested, not only with maf2_0 initialization, so mixed lists with hpl or trig_float fail argument validation instead of aborting device preflight across legacy datatypes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/micro_benchmarks/hipblaslt_function.py | 8 ++++---- .../micro_benchmarks/test_hipblaslt_function.py | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py index 6bfb7e55a..c0fb1a924 100644 --- a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py +++ b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py @@ -84,16 +84,16 @@ def add_parser_arguments(self): def _mxfp4_argument_error(self) -> Optional[str]: """Return the first MXFP4 argument error, or None for a supported case.""" args = self._args - if args.initialization == 'maf2_0' and any(t != 'mxfp4' for t in args.in_types): - return 'Use a separate MXFP4 benchmark instance for maf2_0 initialization.' + if any(t != 'mxfp4' for t in args.in_types): + return 'MXFP4 and maf2_0 require a dedicated mxfp4 benchmark instance.' if (args.transA, args.transB) != ('T', 'N'): return 'MXFP4 currently requires --transA T --transB N.' if args.initialization not in ('hpl', 'trig_float', 'maf2_0'): return 'MXFP4 requires --initialization hpl, trig_float or maf2_0.' if args.num_warmup < 0 or args.num_steps < 1: return 'MXFP4 requires non-negative warmup and positive measurement iterations.' - for m, n, k, batch, precision in self._shapes_to_run: - if precision == 'mxfp4' and (batch != 0 or min(m, n, k) <= 0 or k % 32 != 0): + for m, n, k, batch, _ in self._shapes_to_run: + if batch != 0 or min(m, n, k) <= 0 or k % 32 != 0: return 'MXFP4 requires --batch 0, positive dimensions, and K divisible by 32.' return None diff --git a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py index d69ad4c0b..5f600e52f 100644 --- a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py +++ b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py @@ -191,6 +191,7 @@ def test_mxfp4_invalid_arguments(self): valid.replace('--initialization maf2_0', '--initialization rand_int'), valid.replace('--in_types mxfp4', '--in_types fp16'), valid.replace('--in_types mxfp4', '--in_types mxfp4 fp16'), + valid.replace('--in_types mxfp4', '--in_types fp16 mxfp4').replace('maf2_0', 'hpl') + ' --tolerant_fail', valid.replace('64,128,256', '64,128,257'), valid.replace('64,128,256', '0,128,256'), valid + ' --batch 1', From b01008a6923aef71f618474dfc4e1df14463dc77 Mon Sep 17 00:00:00 2001 From: Guoxin Sui Date: Mon, 30 Nov 2026 13:02:53 -0700 Subject: [PATCH 16/16] Benchmarks - Trim redundant MXFP4 row and constant checks Count result headers directly instead of guessing trailing CSV rows, and stop re-parsing hardcoded CLI constants with Decimal while preserving case, kernel, timing and verification guards. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../micro_benchmarks/hipblaslt_function.py | 96 ++++++++----------- .../test_hipblaslt_function.py | 32 ++----- 2 files changed, 49 insertions(+), 79 deletions(-) diff --git a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py index c0fb1a924..2ace93fca 100644 --- a/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py +++ b/superbench/benchmarks/micro_benchmarks/hipblaslt_function.py @@ -7,7 +7,6 @@ import os import re import shlex -from decimal import Decimal, InvalidOperation from typing import Dict, List, Optional from superbench.common.utils import LazyImport, logger, run_command @@ -84,18 +83,26 @@ def add_parser_arguments(self): def _mxfp4_argument_error(self) -> Optional[str]: """Return the first MXFP4 argument error, or None for a supported case.""" args = self._args - if any(t != 'mxfp4' for t in args.in_types): - return 'MXFP4 and maf2_0 require a dedicated mxfp4 benchmark instance.' - if (args.transA, args.transB) != ('T', 'N'): - return 'MXFP4 currently requires --transA T --transB N.' - if args.initialization not in ('hpl', 'trig_float', 'maf2_0'): - return 'MXFP4 requires --initialization hpl, trig_float or maf2_0.' - if args.num_warmup < 0 or args.num_steps < 1: - return 'MXFP4 requires non-negative warmup and positive measurement iterations.' - for m, n, k, batch, _ in self._shapes_to_run: - if batch != 0 or min(m, n, k) <= 0 or k % 32 != 0: - return 'MXFP4 requires --batch 0, positive dimensions, and K divisible by 32.' - return None + checks = ( + ( + any(t != 'mxfp4' for t in args.in_types), + 'MXFP4 and maf2_0 require a dedicated mxfp4 benchmark instance.', + ), + ((args.transA, args.transB) != ('T', 'N'), 'MXFP4 currently requires --transA T --transB N.'), + ( + args.initialization not in ('hpl', 'trig_float', 'maf2_0'), + 'MXFP4 requires --initialization hpl, trig_float or maf2_0.', + ), + ( + args.num_warmup < 0 or args.num_steps < 1, + 'MXFP4 requires non-negative warmup and positive measurement iterations.', + ), + ( + any(b != 0 or min(m, n, k) <= 0 or k % 32 != 0 for m, n, k, b, _ in self._shapes_to_run), + 'MXFP4 requires --batch 0, positive dimensions, and K divisible by 32.', + ), + ) + return next((message for failed, message in checks if failed), None) def _check_mxfp4_support(self) -> bool: """Check the selected ROCm device and the client's block-scaling options.""" @@ -165,52 +172,37 @@ def _preprocess(self): return True - @staticmethod - def _parse_mxfp4_result_row(columns: Dict[str, int], fields: List[str], trailer: List[str]) -> Dict[str, str]: - """Require one result row with unique columns; kernel diagnostics may follow it.""" - if len(columns) != len(fields): - raise ValueError('MXFP4 requires unique result columns.') + def _record_mxfp4_result( + self, cmd_idx: int, columns: Dict[str, int], fields: List[str], trailer: List[str], header_count: int + ) -> None: + """Record MXFP4 metrics only after the single result row, kernel, timing and verification match.""" + if header_count != 1 or len(columns) != len(fields): + raise ValueError('MXFP4 requires one result row with unique columns.') if not any(re.match(r'^\s*--kernel name:\s*\S', line) for line in trailer): raise ValueError('MXFP4 requires the client to report the selected kernel.') - for line in trailer: - extra = [v.strip() for v in re.sub(r'^\s*\[\d+\]:?', '', line).split(',')] - if 'hipblaslt-Gflops' in extra or ( - len(extra) == len(fields) and all(extra[columns[t]] in ('N', 'T', 'C') for t in ('transA', 'transB')) - ): - raise ValueError('MXFP4 requires exactly one result.') - return {col: fields[i].strip() for col, i in columns.items()} - - def _record_mxfp4_result(self, cmd_idx: int, row: Dict[str, str]) -> None: - """Record MXFP4 metrics only after the requested case, timing and verification match.""" + row = {col: fields[i].strip() for col, i in columns.items()} m, n, k, _, _ = self._shapes_to_run[cmd_idx] for column, value in ( - ('transA', 'T'), ('transB', 'N'), ('grouped_gemm', '0'), ('batch_count', '1'), ('m', str(m)), ('n', str(n)), - ('k', str(k)), ('a_type', 'f4_r'), ('b_type', 'f4_r'), ('c_type', 'f32_r'), ('d_type', 'f32_r'), - ('compute_type', 'f32_r'), ('scaleA', '3'), ('scaleB', '3'), ('use_gpu_timer', '1') + ('transA', 'T'), ('transB', 'N'), ('batch_count', '1'), ('m', str(m)), ('n', str(n)), ('k', str(k)), + ('a_type', 'f4_r'), ('b_type', 'f4_r'), ('c_type', 'f32_r'), ('d_type', 'f32_r'), ('compute_type', 'f32_r'), + ('scaleA', '3'), ('scaleB', '3') ): if row.get(column) != value: raise ValueError(f'MXFP4 column {column} must be {value}, got {row.get(column)}.') - for column, coefficient in [('alpha', 1), ('beta', 0)]: - scalar = Decimal(row[column]) - if not scalar.is_finite() or scalar != coefficient: - raise ValueError(f'MXFP4 column {column} must be {coefficient}, got {row[column]}.') - - gflops = float(row['hipblaslt-Gflops']) - latency = float(row['us']) - if not all(math.isfinite(value) and value > 0 for value in (gflops, latency)): + gflops, latency = float(row['hipblaslt-Gflops']), float(row['us']) + if not (math.isfinite(gflops) and gflops > 0 and math.isfinite(latency) and latency > 0): raise ValueError('MXFP4 throughput and latency must be finite and positive.') if not math.isclose(gflops, 2 * m * n * k / latency / 1000, rel_tol=0.01): raise ValueError('MXFP4 throughput does not match 2*M*N*K and the reported latency.') # Keep the wrapper's conservative FP32-output bound in addition to the client's strict verification. norm_error = float(row['norm_error']) - if not 0 <= norm_error < 1e-5: - raise ValueError('MXFP4 FP32-output relative Frobenius norm error must be finite and below 1e-5.') - for column in ['atol', 'rtol']: - error = float(row[column]) - if not math.isfinite(error) or error < 0: - raise ValueError(f'MXFP4 verification column {column} must be finite and non-negative.') + if not ( + 0 <= norm_error < 1e-5 + and all(math.isfinite(v) and v >= 0 for v in (float(row['atol']), float(row['rtol']))) + ): + raise ValueError('MXFP4 verification error columns must be finite and within bounds.') metric = f'mxfp4_{row["batch_count"]}_{m}_{n}_{k}' self._result.add_result(f'{metric}_time', latency) @@ -234,13 +226,10 @@ def _process_raw_result(self, cmd_idx, raw_output): try: lines = raw_output.splitlines() - - # Find the header line containing 'hipblaslt-Gflops' - for index, line in enumerate(lines): - if 'hipblaslt-Gflops' in line: - break - else: + headers = [i for i, line in enumerate(lines) if 'hipblaslt-Gflops' in line] + if not headers: raise ValueError('Line with "hipblaslt-Gflops" not found in the log.') + index = headers[0] # Parse the header and resolve every key column (batch_count/m/n/k/hipblaslt-Gflops) # by name. This keeps the parser forward-compatible across known and future @@ -279,8 +268,7 @@ def _process_raw_result(self, cmd_idx, raw_output): ) if self._precision_in_commands[cmd_idx] == 'mxfp4': - row = self._parse_mxfp4_result_row(col_idx_by_name, fields, lines[index + 2:]) - self._record_mxfp4_result(cmd_idx, row) + self._record_mxfp4_result(cmd_idx, col_idx_by_name, fields, lines[index + 2:], len(headers)) return True # Resolve every key value by header name and strip whitespace from each, so @@ -295,7 +283,7 @@ def _process_raw_result(self, cmd_idx, raw_output): f'{self._precision_in_commands[cmd_idx]}_{batch_count}_{m_val}_{n_val}_{k_val}_flops', float(fields[gflops_col]) / 1000 ) - except (InvalidOperation, KeyError, ValueError) as e: + except (KeyError, ValueError) as e: self._result.set_return_code(ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) logger.error( 'The result format is invalid - round: {}, benchmark: {}, raw output: {}, message: {}.'.format( diff --git a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py index 5f600e52f..a0744b108 100644 --- a/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py +++ b/tests/benchmarks/micro_benchmarks/test_hipblaslt_function.py @@ -70,13 +70,10 @@ def mxfp4_output(self, overrides=None, missing=(), reverse=False): row = { 'transA': 'T', 'transB': 'N', - 'grouped_gemm': '0', 'batch_count': '1', 'm': '64', 'n': '128', 'k': '256', - 'alpha': '1', - 'beta': '0', 'a_type': 'f4_r', 'b_type': 'f4_r', 'c_type': 'f32_r', @@ -84,7 +81,6 @@ def mxfp4_output(self, overrides=None, missing=(), reverse=False): 'compute_type': 'f32_r', 'scaleA': '3', 'scaleB': '3', - 'use_gpu_timer': '1', 'hipblaslt-Gflops': '1048.576', 'us': '4', 'norm_error': '1e-6', @@ -284,28 +280,16 @@ def test_mxfp4_result_requires_valid_command_index(self): with self.subTest(index=index), self.assertRaises(error): self.make_mxfp4_result_benchmark()._process_raw_result(index, self.mxfp4_output()) - def test_mxfp4_result_coefficients(self): - """Accept equivalent printed scalars, but never report metrics for a different GEMM.""" - benchmark = self.make_mxfp4_result_benchmark() - self.assertTrue(benchmark._process_raw_result(0, self.mxfp4_output({'alpha': '1.00e+0', 'beta': '-0.0'}))) - - for column, value in [ - ('alpha', '0'), ('beta', '1'), ('alpha', '1.0000000000000001'), ('beta', '1e-400'), ('alpha', 'nan'), - ('beta', 'inf'), ('alpha', 'invalid') - ]: - with self.subTest(column=column, value=value): - self.assert_invalid_mxfp4(self.mxfp4_output({column: value})) - def test_mxfp4_invalid_results(self): """Reject wrong cases, fallback dtypes, invalid metrics, and failed CPU verification.""" for column, value in [ ('m', '256'), ('n', '256'), ('k', '128'), ('batch_count', '2'), ('transA', 'N'), ('transB', 'T'), - ('grouped_gemm', '1'), ('a_type', 'f16_r'), ('b_type', 'f16_r'), ('c_type', 'f16_r'), ('d_type', 'f16_r'), - ('compute_type', 'f16_r'), ('scaleA', '0'), ('scaleB', '1'), ('use_gpu_timer', '0'), ('us', '0'), - ('us', '-1'), ('us', 'nan'), ('us', 'inf'), ('hipblaslt-Gflops', '0'), ('hipblaslt-Gflops', '-1'), - ('hipblaslt-Gflops', 'nan'), ('hipblaslt-Gflops', 'inf'), ('hipblaslt-Gflops', '10'), - ('norm_error', '1e-5'), ('norm_error', '-1'), ('norm_error', 'nan'), ('norm_error', 'inf'), - ('atol', 'failed'), ('rtol', 'failed'), ('atol', 'nan'), ('rtol', 'inf'), ('rtol', '-1') + ('a_type', 'f16_r'), ('b_type', 'f16_r'), ('c_type', 'f16_r'), ('d_type', 'f16_r'), + ('compute_type', 'f16_r'), ('scaleA', '0'), ('scaleB', '1'), ('us', '0'), ('us', '-1'), ('us', 'nan'), + ('us', 'inf'), ('hipblaslt-Gflops', '0'), ('hipblaslt-Gflops', '-1'), ('hipblaslt-Gflops', 'nan'), + ('hipblaslt-Gflops', 'inf'), ('hipblaslt-Gflops', '10'), ('norm_error', '1e-5'), ('norm_error', '-1'), + ('norm_error', 'nan'), ('norm_error', 'inf'), ('atol', 'failed'), ('rtol', 'failed'), ('atol', 'nan'), + ('rtol', 'inf'), ('rtol', '-1') ]: with self.subTest(column=column, value=value): self.assert_invalid_mxfp4(self.mxfp4_output({column: value})) @@ -315,8 +299,7 @@ def test_mxfp4_incomplete_results(self): output = self.mxfp4_output() header, row, kernel = output.splitlines() invalid = [ - self.mxfp4_output(missing=[column]) - for column in ['alpha', 'beta', 'a_type', 'scaleA', 'norm_error', 'atol', 'rtol', 'us', 'use_gpu_timer'] + self.mxfp4_output(missing=[column]) for column in ['a_type', 'scaleA', 'norm_error', 'atol', 'rtol', 'us'] ] invalid.extend( [ @@ -326,7 +309,6 @@ def test_mxfp4_incomplete_results(self): header + '\n' + row + '\n', output.replace('synthetic_mxfp4_kernel', ' '), output + output, - output + row + '\n', 'No supported solutions found', ] )