Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 128 additions & 13 deletions superbench/benchmarks/micro_benchmarks/hipblaslt_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,24 @@

"""Module of the hipBlasLt GEMM benchmark."""

import math
import os
import re
import shlex
from typing import Dict, List, Optional

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')

_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_strict --use_gpu_timer --print_kernel_info'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NON-BLOCKING] Always-on CPU reference verification is expensive at default shapes

Location: superbench/benchmarks/micro_benchmarks/hipblaslt_function.py -- _MXFP4_ARGS

Evidence:

    ' --verify_strict --use_gpu_timer --print_kernel_info'

Issue:
Upstream help: --verify_strict "Implies --verify. Computes a CPU reference per problem". The base default --shapes is 2048,4096,8192 cubed, so an mxfp4 run without explicit shapes performs CPU GEMMs up to ~1.1 TFLOP each.

Impact:
Very long runtimes and possible benchmark timeouts when users do not override shapes.

Recommendation:
Document the cost and recommend small shapes for mxfp4, or reject/warn when mxfp4 is used with the default shape list.

)


class HipBlasLtBenchmark(BlasLtBaseBenchmark):
"""The hipBlasLt GEMM benchmark class."""
Expand All @@ -23,12 +34,13 @@ 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']

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SHOULD-FIX] User docs not updated for mxfp4, maf2_0, MXFP4 constraints and new metrics

Location: superbench/benchmarks/micro_benchmarks/hipblaslt_function.py -- HipBlasLtBenchmark.init / _record_mxfp4_result; docs/user-tutorial/benchmarks/micro-benchmarks.md

Evidence:

        self._in_types = ['fp32', 'fp16', 'bf16', 'fp8', 'mxfp4']
...
        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)

Issue:
docs/user-tutorial/benchmarks/micro-benchmarks.md only documents hipblaslt-gemm/${dtype}_${batch}_${m}_${n}_${k}_flops. It does not mention the mxfp4 in_type, maf2_0 initialization, the required overrides (defaults --transA N and --initialization rand_int are rejected), the gfx1250 / dedicated-instance / K%32 / batch 0 constraints, or the new _time, _norm_error, _correctness metrics.

Impact:
Users enabling in_types: [mxfp4] with default parameters get INVALID_ARGUMENT without guidance; downstream result consumers do not know about the three new metric suffixes.

Recommendation:
Add an experimental MXFP4 note under cublaslt-gemm / hipblaslt-gemm (required parameters, gfx1250 only, dedicated instance) and add hipblaslt-gemm/mxfp4_${batch}_${m}_${n}_${k}_{time,norm_error,correctness} rows to the metrics table (time unit: us).

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': _MXFP4_ARGS,
}

def add_parser_arguments(self):
Expand All @@ -47,7 +59,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.',
)
Expand All @@ -68,6 +80,64 @@ def add_parser_arguments(self):
help='Transpose matrix B.',
)

def _mxfp4_argument_error(self) -> Optional[str]:
"""Return the first MXFP4 argument error, or None for a supported case."""
args = self._args
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."""
try:
arch = torch.cuda.get_device_properties(0).gcnArchName.split(':')[0]
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

if arch != 'gfx1250':
self._result.set_return_code(ReturnCode.MICROBENCHMARK_UNSUPPORTED_ARCHITECTURE)
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'3[ \t]*=[ \t]*(?i:B32E8)'
required_values = (('--scaleA', b32e8), ('--scaleB', b32e8), ('--initialization', self._args.initialization))
missing = [
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)
if output.returncode != 0:
self._result.set_return_code(ReturnCode.MICROBENCHMARK_EXECUTION_FAILURE)
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(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

def _preprocess(self):
"""Preprocess/preparation operations before the benchmarking.

Expand All @@ -81,6 +151,15 @@ def _preprocess(self):

self._commands = []
self._precision_in_commands = []
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: %s, message: %s', self._name, error)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NON-BLOCKING] Mixed logger formatting styles and inline magic constants

Location: superbench/benchmarks/micro_benchmarks/hipblaslt_function.py -- _check_mxfp4_support / _preprocess / _record_mxfp4_result

Evidence:

                logger.error('Invalid MXFP4 arguments - benchmark: %s, message: %s', self._name, error)

Issue:
New code mixes %s, .format() and f-strings in adjacent logger calls. The expected CSV values (f4_r, f32_r, scale 3), 'gfx1250', block size 32, rel_tol=0.01 and 1e-5 are inline literals duplicated between _MXFP4_ARGS and _record_mxfp4_result.

Impact:
Minor readability; future changes to MXFP4 options require synchronized edits in several places.

Recommendation:
Use one logger style, and hoist the shared type/scale values and tolerances into named module constants used by both command generation and validation.

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}' + \

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NON-BLOCKING] Executable path quoted in help probe but not in benchmark command

Location: superbench/benchmarks/micro_benchmarks/hipblaslt_function.py -- _preprocess

Evidence:

            command = f'{self.__bin_path} -m {_m} -n {_n} -k {_k} -j {self._args.num_warmup}' + \

Issue:
_check_mxfp4_support uses shlex.quote(self.__bin_path), but the main command (run via run_command, shell=True) does not. Pre-existing for the main command; the PR introduces the inconsistency.

Impact:
A bin_dir with spaces passes preflight but fails at execution.

Recommendation:
Use shlex.quote(self.__bin_path) in the command as well.

f' -i {self._args.num_steps} {self._in_type_map[_in_type]}' + \
Expand All @@ -93,6 +172,44 @@ def _preprocess(self):

return True

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.')
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'), ('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)}.')

gflops, latency = float(row['hipblaslt-Gflops']), float(row['us'])
Comment thread
gusui-msft marked this conversation as resolved.
Resolved
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SHOULD-FIX] Uncalibrated norm_error < 1e-5 bound can reject every real MXFP4 run

Location: superbench/benchmarks/micro_benchmarks/hipblaslt_function.py -- _record_mxfp4_result

Evidence:

        # 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

Issue:
Verified: upstream norm.hpp returns 0.3 for HIP_R_4F_E2M1 and norm_tolerance() takes std::max over output and input types, so --verify_strict already fails the client (exit 2) at norm_error >= 0.3. The wrapper adds an extra bound that is ~30,000x tighter. Inferred: FP32 accumulation-order differences between GPU and CPU reference grow roughly with sqrt(K)*eps; at the default K=8192 this is on the order of 5e-6, i.e. right at the 1e-5 boundary. The bound is only exercised by synthetic rows (1e-6, 9.999e-6), and the PR description itself states it "needs hardware calibration".

Impact:
On gfx1250, valid runs (especially large-K shapes) may be reported as MICROBENCHMARK_RESULT_PARSING_FAILURE with no throughput published.

Recommendation:
Calibrate on MI455X across the documented shapes before merging, or make the bound configurable and rely on --verify_strict by default, e.g.:

self._parser.add_argument('--mxfp4_max_norm_error', type=float, default=None, required=False,
                          help='Optional extra norm_error bound for mxfp4 on top of --verify_strict.')
...
limit = self._args.mxfp4_max_norm_error
if not (math.isfinite(norm_error) and norm_error >= 0 and (limit is None or norm_error < limit)):
    raise ValueError(...)

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.')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NON-BLOCKING] Numerical verification failure is logged as a result-format error

Location: superbench/benchmarks/micro_benchmarks/hipblaslt_function.py -- _record_mxfp4_result / _process_raw_result

Evidence:

            raise ValueError('MXFP4 verification error columns must be finite and within bounds.')
...
        self._result.add_result(f'{metric}_correctness', 1)

Issue:
A genuine accuracy failure (e.g. norm_error >= 1e-5) raises ValueError, which _process_raw_result maps to MICROBENCHMARK_RESULT_PARSING_FAILURE with the message "The result format is invalid". _correctness is therefore either 1 or absent, never 0 (unlike cublas_function.py).

Impact:
Operators cannot easily tell a numerical failure from malformed client output; _correctness carries no information beyond metric presence.

Recommendation:
Either emit _correctness = 0 (and skip flops) on a verification miss with a distinct log message, or document that _correctness is emitted only on success and log verification failures separately.


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.

Expand All @@ -109,16 +226,10 @@ def _process_raw_result(self, cmd_idx, raw_output):

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:
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
Expand Down Expand Up @@ -156,6 +267,10 @@ def _process_raw_result(self, cmd_idx, raw_output):
f'but data has {len(fields)} columns'
)

if self._precision_in_commands[cmd_idx] == 'mxfp4':
Comment thread
gusui-msft marked this conversation as resolved.
Resolved
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
# any padding around CSV values does not bleed into the metric key.
batch_count = fields[col_idx_by_name['batch_count']].strip()
Expand All @@ -168,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 BaseException as e:
except (KeyError, ValueError) as e:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NON-BLOCKING] Exception narrowing changes failure mode for wrapper bookkeeping bugs

Location: superbench/benchmarks/micro_benchmarks/hipblaslt_function.py -- _process_raw_result

Evidence:

        except (KeyError, ValueError) as e:

Issue:
Verified: client output can only raise KeyError/ValueError in this path, so parsing behavior is unchanged. However, an IndexError/TypeError from a wrapper bug now escapes to Benchmark.run() (except BaseException -> RUNTIME_EXCEPTION_ERROR) and aborts remaining commands, whereas previously it was a per-command parsing failure. This is intentional and tested (test_mxfp4_result_requires_valid_command_index).

Impact:
Affects all precisions, not only mxfp4; no impact on valid client output.

Recommendation:
Keep as is, but call the behavior change out in the PR description since it applies to legacy precisions too.

self._result.set_return_code(ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE)
logger.error(
'The result format is invalid - round: {}, benchmark: {}, raw output: {}, message: {}.'.format(
Expand Down
Loading
Loading