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


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