From fc8b760098522714910eecd89cc27352ae388f90 Mon Sep 17 00:00:00 2001 From: "Nguyen Vuong (from Dev Box)" Date: Fri, 9 Oct 2026 13:59:58 -0700 Subject: [PATCH 1/5] Benchmarks: Add ROCm TransferBench mem-bw backend and model benchmark fixes Split out of the ROCm 10 image PR (#867), ported from arsdragonfly/superbenchmark@rocm10. - mem-bw: opt-in TransferBench backend (SB_ROCM_MEM_BW_BACKEND=transferbench) that keeps the hipBusBandwidth size sweep, trial counts and reduction. - model-benchmarks: --optimizer_eps; bfloat16 for BERT/GPT-2/LLaMA. - megatron-gpt: SB_MEGATRON_PATH default code base, apply --extra, fail on nonzero training exit and restore OMPI_COMM_WORLD_LOCAL_RANK. - Add synthetic TransferBench fixtures and document the new options. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/micro-benchmarks.md | 13 + .../benchmarks/model-benchmarks.md | 8 + .../rocm_memory_bw_performance.py | 183 +++++++++- .../model_benchmarks/megatron_gpt3.py | 17 +- .../model_benchmarks/pytorch_base.py | 18 +- .../model_benchmarks/pytorch_bert.py | 1 + .../model_benchmarks/pytorch_gpt2.py | 1 + .../model_benchmarks/pytorch_llama.py | 1 + .../test_rocm_memory_bw_performance.py | 343 +++++++++++++++++- .../model_benchmarks/test_megatron_launch.py | 85 +++++ .../test_transformer_precisions.py | 38 ++ tests/data/rocm_transferbench_pinned_dtoh.log | 31 ++ tests/data/rocm_transferbench_pinned_htod.log | 31 ++ .../data/rocm_transferbench_unpinned_dtoh.log | 31 ++ .../data/rocm_transferbench_unpinned_htod.log | 31 ++ 15 files changed, 823 insertions(+), 9 deletions(-) create mode 100644 tests/benchmarks/model_benchmarks/test_megatron_launch.py create mode 100644 tests/benchmarks/model_benchmarks/test_transformer_precisions.py create mode 100644 tests/data/rocm_transferbench_pinned_dtoh.log create mode 100644 tests/data/rocm_transferbench_pinned_htod.log create mode 100644 tests/data/rocm_transferbench_unpinned_dtoh.log create mode 100644 tests/data/rocm_transferbench_unpinned_htod.log diff --git a/docs/user-tutorial/benchmarks/micro-benchmarks.md b/docs/user-tutorial/benchmarks/micro-benchmarks.md index e8cda7eea..1f39e479e 100644 --- a/docs/user-tutorial/benchmarks/micro-benchmarks.md +++ b/docs/user-tutorial/benchmarks/micro-benchmarks.md @@ -375,6 +375,19 @@ performed by [NVIDIA](https://github.com/NVIDIA/cuda-samples/tree/master/Samples or [AMD](https://github.com/ROCm-Developer-Tools/HIP/tree/master/samples/1_Utils/hipBusBandwidth) bandwidth test tool. The bandwidthTest sample was out-of-date and has been removed as of the CUDA Samples 12.9 release. For up-to-date bandwidth measurements, refer instead to the nvbandwidth benchmark. +On ROCm, set `SB_ROCM_MEM_BW_BACKEND=transferbench` to measure `h2d_bw` and `d2h_bw` with +[TransferBench](https://github.com/ROCm/TransferBench) instead of `hipBusBandwidth`, which is not available on +ROCm 10. The default (`hipbusbandwidth`) is unchanged. The TransferBench backend keeps the `hipBusBandwidth` policy: + +* The same size sweep (64, 256 and 512 bytes, then 1 KiB to 512 MiB) and trial counts per size. +* One `TransferBench cmdline` run per size, copying with one DMA engine of the visible GPU (`G0`, honoring + `HIP_VISIBLE_DEVICES`). Pinned memory uses `P0` (the GPU's nearest NUMA node); pageable (`--memory unpinned`) + uses `H`, where `` is the NUMA node of the CPU running the benchmark. +* Each size reports the arithmetic mean of its per-iteration bandwidths, and the metric is the maximum over sizes. + +A size sweep fails on any TransferBench error, missing iteration or unexpected route; there is no fallback to +`hipBusBandwidth`. Container policies must permit NUMA placement queries for pageable memory. + #### Metrics | Name | Unit | Description | diff --git a/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index c782abbcc..22227bef8 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -34,6 +34,11 @@ For inference, supported percentiles include **New: Support fp8_hybrid and fp8_e4m3 precision for BERT models.** +**New: Support bfloat16 precision for BERT, GPT-2 and LLaMA models.** + +Use `--optimizer_eps ` to set the Adam/AdamW epsilon (default: 1e-8). The default underflows in native +float16 training; use a representable value such as 1e-4. + **New: Deterministic Training Support** SuperBench now supports deterministic training to ensure reproducibility across runs. This includes fixed seeds and deterministic algorithms. To enable deterministic training, use the following flags: @@ -154,6 +159,9 @@ Run GPT pretrain tasks with float32, float16, bfloat16 precisions with [Megatron `tips: batch_size in this benchmark represents global batch size, the batch size on each GPU instance is micro_batch_size.` +Without `--code_base`, the Megatron-LM checkout defaults to `$SB_MEGATRON_PATH` when set, otherwise to the +`third_party/Megatron/Megatron-LM` submodule. A nonzero training exit code fails the benchmark. + #### Metrics | Name | Unit | Description | |---------------------------------------------------|------------------------|---------------------------------------------------------| diff --git a/superbench/benchmarks/micro_benchmarks/rocm_memory_bw_performance.py b/superbench/benchmarks/micro_benchmarks/rocm_memory_bw_performance.py index e7f25da86..347d82171 100644 --- a/superbench/benchmarks/micro_benchmarks/rocm_memory_bw_performance.py +++ b/superbench/benchmarks/micro_benchmarks/rocm_memory_bw_performance.py @@ -3,15 +3,43 @@ """Module of the ROCm memory performance benchmarks.""" +import csv +import ctypes +import math import os +from pathlib import Path +import re +import shlex +import statistics from superbench.common.utils import logger -from superbench.benchmarks import BenchmarkRegistry, Platform +from superbench.benchmarks import BenchmarkRegistry, Platform, ReturnCode from superbench.benchmarks.micro_benchmarks import MemBwBenchmark class RocmMemBwBenchmark(MemBwBenchmark): """The ROCm memory performance benchmark class.""" + + # HIP rocm-5.5.0 samples/1_Utils/hipBusBandwidth/hipBusBandwidth.cpp. + _TRANSFERBENCH_SIZES = (64, 256, 512) + tuple(2**power for power in range(10, 30)) + _TRANSFERBENCH_ITERATIONS = ( + 1000, 1000, 1000, 1000, 500, 500, 500, 500, 500, 200, 200, 200, + 200, 200, 100, 100, 100, 100, 50, 50, 50, 20, 20 + ) + _TRANSFERBENCH_ENV = { + 'NUM_WARMUPS': 0, + 'NUM_SUBITERATIONS': 1, + 'SHOW_ITERATIONS': 1, + 'USE_HIP_EVENTS': 1, + 'USE_HSA_DMA': 0, + 'USE_SINGLE_STREAM': 1, + 'USE_INTERACTIVE': 0, + 'ALWAYS_VALIDATE': 0, + 'VALIDATE_DIRECT': 0, + 'VALIDATE_SOURCE': 0, + 'BYTE_OFFSET': 0, + } + def __init__(self, name, parameters=''): """Constructor. @@ -21,14 +49,24 @@ def __init__(self, name, parameters=''): """ super().__init__(name, parameters) - self._bin_name = 'hipBusBandwidth' + self._backend = os.getenv('SB_ROCM_MEM_BW_BACKEND', 'hipbusbandwidth').lower() + self._bin_name = 'TransferBench' if self._backend == 'transferbench' else 'hipBusBandwidth' self._mem_types = ['htod', 'dtoh'] self._parse_logline_map = {'htod': 'H2D_Bandwidth', 'dtoh': 'D2H_Bandwidth'} + self._worker_numa_node = None def add_parser_arguments(self): """Add the specified arguments.""" super().add_parser_arguments() + def _set_binary_path(self): + """Validate explicit backend selection before looking up an executable.""" + if self._backend not in ('hipbusbandwidth', 'transferbench'): + self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) + logger.error('Unsupported ROCm mem-bw backend: {}.'.format(self._backend)) + return False + return super()._set_binary_path() + def _preprocess(self): """Preprocess/preparation operations before the benchmarking. @@ -38,8 +76,15 @@ def _preprocess(self): if not super()._preprocess(): return False + if self._backend == 'transferbench' and self._args.memory == 'unpinned': + if not self._set_worker_numa_node(): + return False + # Check the arguments and generate the commands for mem_type in self._args.mem_type: + if self._backend == 'transferbench': + self._commands.append(self._transferbench_command(mem_type)) + continue command = os.path.join(self._args.bin_dir, self._bin_name) command += ' --' + mem_type.replace('to', '2') if self._args.memory == 'unpinned': @@ -48,6 +93,137 @@ def _preprocess(self): return True + def _set_worker_numa_node(self): + """Resolve the executing worker CPU's NUMA node once for this sweep.""" + try: + getcpu = ctypes.CDLL(None, use_errno=True).sched_getcpu + getcpu.argtypes = [] + getcpu.restype = ctypes.c_int + cpu = getcpu() + if cpu < 0: + raise OSError(ctypes.get_errno(), 'sched_getcpu failed') + cpu_path = Path('/sys/devices/system/cpu/cpu{}'.format(cpu)) + nodes = [entry for entry in cpu_path.iterdir() if re.fullmatch(r'node[0-9]+', entry.name)] + if len(nodes) != 1: + raise ValueError('Expected one NUMA node for CPU {}, found {}'.format(cpu, len(nodes))) + self._worker_numa_node = int(nodes[0].name[4:]) + except (AttributeError, OSError, ValueError) as error: + self._result.set_return_code(ReturnCode.MICROBENCHMARK_DEVICE_GETTING_FAILURE) + logger.error( + 'Cannot determine worker-local NUMA placement - benchmark: {}, error: {}.'.format(self._name, error) + ) + return False + logger.info( + 'TransferBench pageable placement - benchmark: {}, worker CPU: {}, NUMA node: {}, endpoint: H{}.'.format( + self._name, cpu, self._worker_numa_node, self._worker_numa_node + ) + ) + return True + + def _transferbench_route(self, mem_type): + """Return the single-device DMA route, using HIP's logical device zero.""" + host = 'P0' if self._args.memory == 'pinned' else 'H{}'.format(self._worker_numa_node) + return (host, 'G0') if mem_type == 'htod' else ('G0', host) + + def _transferbench_command(self, mem_type): + """Build one fail-fast sweep per direction, retaining one raw log per direction.""" + source, destination = self._transferbench_route(mem_type) + binary = shlex.quote(os.path.join(self._args.bin_dir, self._bin_name)) + environment = dict(self._TRANSFERBENCH_ENV, OUTPUT_TO_CSV=1, HIDE_ENV=0, SHOW_PERCENTILES='') + options = ' '.join('{}={}'.format(key, value) for key, value in environment.items()) + commands = [] + for size, iterations in zip(self._TRANSFERBENCH_SIZES, self._TRANSFERBENCH_ITERATIONS): + commands.append( + "env {} NUM_ITERATIONS={} {} cmdline {} '1 1 {} D0 {}'".format( + options, iterations, binary, size, source, destination + ) + ) + return ' && '.join(commands) + + @staticmethod + def _transferbench_quantity(value, unit, allow_zero=False): + """Parse a finite numeric field with its explicit unit.""" + fields = value.split() + if len(fields) != 2 or fields[1] != unit: + raise ValueError('Invalid TransferBench quantity: {}'.format(value)) + number = float(fields[0]) + if not math.isfinite(number) or number < 0 or (number == 0 and not allow_zero): + raise ValueError('Invalid TransferBench quantity: {}'.format(value)) + return number + + def _transferbench_samples(self, rows, size, iterations): + """Extract every timed iteration, not the reciprocal-mean-time summary.""" + samples = {} + for row in rows: + if not row[0].startswith('Iter '): + continue + index = int(row[0].split()[1]) + if index in samples or not 1 <= index <= iterations: + raise ValueError('Duplicate or unexpected TransferBench iteration') + bandwidth = self._transferbench_quantity(row[1], 'GB/s', allow_zero=True) + duration = self._transferbench_quantity(row[2], 'ms') + # Three-decimal CLI output can round a genuine small-copy bandwidth to zero. + if bandwidth == 0 and size / (duration + 0.0005) / 1e6 >= 0.0005: + raise ValueError('Nonpositive TransferBench bandwidth') + # Preserve HIP5.5's integer nbytes/1000 division, including sub-KB zeros. + samples[index] = (size // 1000) / 1000 / duration + if len(samples) != iterations: + raise ValueError('Incomplete TransferBench iterations') + return statistics.mean(samples.values()) + + def _transferbench_report(self, report, size, iterations, mem_type): + """Validate one CSV-mode report, which also contains banners and typed table rows.""" + rows = [[field.strip() for field in row] for row in csv.reader(report.splitlines()) if row] + settings = dict(self._TRANSFERBENCH_ENV, NUM_ITERATIONS=iterations) + for key, value in settings.items(): + matches = [row for row in rows if row[0] == key] + if len(matches) != 1 or int(matches[0][1]) != value: + raise ValueError('Unexpected TransferBench setting: {}'.format(key)) + + executors = [row for row in rows if row[0].startswith('Executor:')] + transfers = [row for row in rows if row[0].startswith('Transfer ')] + aggregates = [row for row in rows if row[0] == 'Aggregate (CPU)'] + deviations = [row for row in rows if row[0] == 'StandardDev'] + if len(executors) != 1 or len(transfers) != 1 or len(aggregates) != 1 or len(deviations) != 1: + raise ValueError('Incomplete or multi-device TransferBench report') + if executors[0][0] != 'Executor: DMA 00' or transfers[0][0] != 'Transfer 0': + raise ValueError('Unexpected TransferBench executor') + source, destination = self._transferbench_route(mem_type) + if transfers[0][4].split() != [source, '->', 'D0:1', '->', destination]: + raise ValueError('Unexpected TransferBench route') + for row in (executors[0], transfers[0], aggregates[0]): + if row[3].split() != [str(size), 'bytes']: + raise ValueError('Unexpected TransferBench byte count') + return self._transferbench_samples(rows, size, iterations) + + def _process_transferbench_result(self, cmd_idx, raw_output): + """Reduce a complete size sweep to the maximum arithmetic mean bandwidth.""" + try: + if '[ERROR]' in raw_output: + raise ValueError('TransferBench reported an error') + reports = re.split(r'(?m)^TransferBench v[^\n]*\n', raw_output) + if len(reports) != len(self._TRANSFERBENCH_SIZES) + 1: + raise ValueError('Incomplete TransferBench size sweep') + means = [ + self._transferbench_report(report, size, iterations, self._args.mem_type[cmd_idx]) + for report, size, iterations in zip( + reports[1:], self._TRANSFERBENCH_SIZES, self._TRANSFERBENCH_ITERATIONS + ) + ] + bandwidth = max(means) + if not math.isfinite(bandwidth) or bandwidth <= 0: + raise ValueError('Nonpositive TransferBench result') + except (ValueError, IndexError, OverflowError) as error: + logger.error( + 'The result format is invalid - round: {}, benchmark: {}, error: {}, raw output: {}.'.format( + self._curr_run_index, self._name, error, raw_output + ) + ) + return False + metric = self._metrics[self._mem_types.index(self._args.mem_type[cmd_idx])] + self._result.add_result(metric, bandwidth) + return True + def _process_raw_result(self, cmd_idx, raw_output): """Function to parse raw results and save the summarized results. @@ -62,6 +238,9 @@ def _process_raw_result(self, cmd_idx, raw_output): """ self._result.add_raw_data('raw_output_' + self._args.mem_type[cmd_idx], raw_output, self._args.log_raw_data) + if self._backend == 'transferbench': + return self._process_transferbench_result(cmd_idx, raw_output) + mem_bw = -1 value_index = -1 valid = True diff --git a/superbench/benchmarks/model_benchmarks/megatron_gpt3.py b/superbench/benchmarks/model_benchmarks/megatron_gpt3.py index 86612f053..50a439194 100644 --- a/superbench/benchmarks/model_benchmarks/megatron_gpt3.py +++ b/superbench/benchmarks/model_benchmarks/megatron_gpt3.py @@ -240,7 +240,9 @@ def _preprocess(self): os.getenv('SB_MICRO_PATH'), 'third_party/Megatron/Megatron-DeepSpeed/' ) else: - self._args.code_base = os.path.join(os.getenv('SB_MICRO_PATH'), 'third_party/Megatron/Megatron-LM') + self._args.code_base = os.getenv('SB_MEGATRON_PATH') or os.path.join( + os.getenv('SB_MICRO_PATH'), 'third_party/Megatron/Megatron-LM' + ) if not os.path.exists(self._args.code_base) or not os.path.exists( os.path.join(self._args.code_base, f'pretrain_{self._args.model}.py') @@ -540,6 +542,8 @@ def _megatron_command(self, precision): # noqa: C901 else: command = f'torchrun {self._distributed_args} {script_path} {megatron_options} {self._data_options}' + if self._args.extra: + command += f' {self._args.extra}' return command def _train_step(self, precision): # noqa: E501 @@ -547,8 +551,13 @@ def _train_step(self, precision): # noqa: E501 command = self._megatron_command(precision) local_rank = os.environ.pop('OMPI_COMM_WORLD_LOCAL_RANK', None) logger.info('Running command: {}.'.format(command)) - output = run_command(command, flush_output=True) - os.environ['OMPI_COMM_WORLD_LOCAL_RANK'] = local_rank + try: + output = run_command(command, flush_output=True) + finally: + if local_rank is not None: + os.environ['OMPI_COMM_WORLD_LOCAL_RANK'] = local_rank + if output.returncode != 0: + raise RuntimeError('Megatron training failed with exit code {}.'.format(output.returncode)) iteration_times = [] info = {} @@ -644,6 +653,8 @@ def _generate_dataset(self): # noqa: C901 Return: True if dataset is created successfully. """ + if not self._args.code_base and not self._args.deepspeed: + self._args.code_base = os.getenv('SB_MEGATRON_PATH') or self._args.code_base # Validate num_workers unconditionally so a negative value is rejected even when # dataset files already exist (it would otherwise be emitted as `--num-workers -1` # into the Megatron training command). diff --git a/superbench/benchmarks/model_benchmarks/pytorch_base.py b/superbench/benchmarks/model_benchmarks/pytorch_base.py index 7810b982d..dd21db20e 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_base.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_base.py @@ -131,6 +131,12 @@ def _finalize_periodic_logging(self, periodic, info_key='loss'): def add_parser_arguments(self): """Add PyTorch model benchmark-specific arguments to the argument parser.""" super().add_parser_arguments() + self._parser.add_argument( + '--optimizer_eps', + type=float, + default=1e-8, + help='Adam/AdamW epsilon. Use a representable value (for example 1e-4) for native FP16 training.', + ) self._parser.add_argument( '--deterministic_seed', type=int, @@ -446,12 +452,18 @@ def _create_optimizer(self): self._model.parameters(), lr=1e-5, momentum=0.9, weight_decay=1e-4, nesterov=True ) elif self._optimizer_type == Optimizer.ADAM: - self._optimizer = torch.optim.Adam(self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=1e-08) + self._optimizer = torch.optim.Adam( + self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=self._args.optimizer_eps + ) elif self._optimizer_type == Optimizer.ADAMW: if hasattr(torch.optim, 'AdamW'): - self._optimizer = torch.optim.AdamW(self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=1e-08) + self._optimizer = torch.optim.AdamW( + self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=self._args.optimizer_eps + ) else: - self._optimizer = transformers.AdamW(self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=1e-08) + self._optimizer = transformers.AdamW( + self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=self._args.optimizer_eps + ) else: self._optimizer = None diff --git a/superbench/benchmarks/model_benchmarks/pytorch_bert.py b/superbench/benchmarks/model_benchmarks/pytorch_bert.py index 94c0d9c45..f052c1b3a 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_bert.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_bert.py @@ -62,6 +62,7 @@ def __init__(self, name, parameters=''): self._supported_precision = [ Precision.FLOAT32, Precision.FLOAT16, + Precision.BFLOAT16, Precision.FP8_HYBRID, Precision.FP8_E4M3, ] diff --git a/superbench/benchmarks/model_benchmarks/pytorch_gpt2.py b/superbench/benchmarks/model_benchmarks/pytorch_gpt2.py index 67f781d0a..aaee40cc6 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_gpt2.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_gpt2.py @@ -62,6 +62,7 @@ def __init__(self, name, parameters=''): self._supported_precision = [ Precision.FLOAT32, Precision.FLOAT16, + Precision.BFLOAT16, Precision.FP8_HYBRID, Precision.FP8_E4M3, ] diff --git a/superbench/benchmarks/model_benchmarks/pytorch_llama.py b/superbench/benchmarks/model_benchmarks/pytorch_llama.py index d57b60821..c418932b2 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_llama.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_llama.py @@ -62,6 +62,7 @@ def __init__(self, name, parameters=''): self._supported_precision = [ Precision.FLOAT32, Precision.FLOAT16, + Precision.BFLOAT16, Precision.FP8_HYBRID, Precision.FP8_E4M3, ] diff --git a/tests/benchmarks/micro_benchmarks/test_rocm_memory_bw_performance.py b/tests/benchmarks/micro_benchmarks/test_rocm_memory_bw_performance.py index 139716cdc..051cb9bbb 100644 --- a/tests/benchmarks/micro_benchmarks/test_rocm_memory_bw_performance.py +++ b/tests/benchmarks/micro_benchmarks/test_rocm_memory_bw_performance.py @@ -4,11 +4,18 @@ """Tests for mem-bw benchmark.""" import numbers +import os +from pathlib import Path +import re +import shlex +import subprocess import unittest +from unittest import mock from tests.helper import decorator from tests.helper.testcase import BenchmarkTestCase from superbench.benchmarks import BenchmarkRegistry, BenchmarkType, ReturnCode, Platform +from superbench.benchmarks.micro_benchmarks.rocm_memory_bw_performance import RocmMemBwBenchmark class RocmMemBwTest(BenchmarkTestCase, unittest.TestCase): @@ -18,7 +25,52 @@ def setUpClass(cls): """Hook method for setting up class fixture before running tests in the class.""" super().setUpClass() cls.createMockEnvs(cls) - cls.createMockFiles(cls, ['bin/hipBusBandwidth']) + cls.createMockFiles(cls, ['bin/hipBusBandwidth', 'bin/TransferBench']) + + def setUp(self): + """Keep the legacy default independent of the image's backend selection.""" + self.environment = mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'hipbusbandwidth'}) + self.environment.start() + self.addCleanup(self.environment.stop) + module = 'superbench.benchmarks.micro_benchmarks.rocm_memory_bw_performance' + libc_patch = mock.patch(module + '.ctypes.CDLL') + self.libc = libc_patch.start() + self.addCleanup(libc_patch.stop) + self.libc.return_value.sched_getcpu.return_value = 0 + nodes_patch = mock.patch(module + '.Path.iterdir', autospec=True) + self.cpu_nodes = nodes_patch.start() + self.addCleanup(nodes_patch.stop) + self.cpu_nodes.return_value = [Path('/sys/devices/system/cpu/cpu0/node0')] + + def _transferbench(self, parameters=''): + """Prepare the explicitly selected backend with mock executables.""" + with mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'transferbench'}): + benchmark = RocmMemBwBenchmark('mem-bw', parameters) + self.assertTrue(benchmark._preprocess()) + return benchmark + + @staticmethod + def _fixture(memory='pinned', direction='htod'): + """Read synthetic TransferBench v1.69.00 CSV-mode output for logical device zero.""" + return Path('tests/data/rocm_transferbench_{}_{}.log'.format(memory, direction)).read_text() + + def _report(self, size, durations, direction='htod', memory='pinned'): + """Build variable-size reports using the measured CLI format, including misleading summaries.""" + header = self._fixture(memory, direction).split(' Executor:')[0] + header = re.sub(r'(NUM_ITERATIONS\s*,\s*)3,', r'\g<1>{},'.format(len(durations)), header) + host = 'P0' if memory == 'pinned' else 'H0' + route = '{} -> D0:1 -> G0'.format(host) if direction == 'htod' else 'G0 -> D0:1 -> {}'.format(host) + rows = [ + 'Executor: DMA 00, 999.000 GB/s, 1.000 ms, {} bytes, 999.000 GB/s (sum),'.format(size), + 'Transfer 0, 888.000 GB/s, 1.000 ms, {} bytes, {},'.format(size, route), + ] + for index, duration in reversed(list(enumerate(durations, 1))): + rows.append('Iter {:03d}, {:.3f} GB/s, {:.3f} ms, , ,'.format(index, size / duration / 1e6, duration)) + rows.extend([ + 'StandardDev, 0.000 GB/s, 0.000 ms, , ,', + 'Aggregate (CPU), 777.000 GB/s, 1.000 ms, {} bytes, Overhead 0.000 ms,'.format(size), + ]) + return header + '\n'.join(rows) + '\n' @decorator.load_data('tests/data/rocm_memory_h2d_bw.log') @decorator.load_data('tests/data/rocm_memory_d2h_bw.log') @@ -56,3 +108,292 @@ def test_rocm_memory_bw_performance(self, raw_output_h2d, raw_output_d2h): assert (benchmark.result['h2d_bw'][0] == 25.2351) assert (benchmark.result['d2h_bw'][0] == 27.9348) + + def test_legacy_default_and_arguments(self): + """Retain the old executable, flags, normalization and ignored NUMA argument.""" + with mock.patch.dict(os.environ): + os.environ.pop('SB_ROCM_MEM_BW_BACKEND', None) + benchmark = RocmMemBwBenchmark('mem-bw', '--mem_type DTOH --memory unpinned --numa 3') + self.assertTrue(benchmark._preprocess()) + self.assertEqual(benchmark._bin_name, 'hipBusBandwidth') + self.assertEqual(len(benchmark._commands), 1) + self.assertTrue(benchmark._commands[0].endswith('hipBusBandwidth --d2h --unpinned')) + self.assertEqual(benchmark._args.numa, 3) + self.assertNotIn('numactl', benchmark._commands[0]) + + def test_transferbench_exact_legacy_policy(self): + """Cover the complete HIP5.5 size/trial arrays and all controllable timing settings.""" + benchmark = self._transferbench('--numa 3') + sizes = ( + 64, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, + 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, + 134217728, 268435456, 536870912 + ) + iterations = ( + 1000, 1000, 1000, 1000, 500, 500, 500, 500, 500, 200, 200, 200, + 200, 200, 100, 100, 100, 100, 50, 50, 50, 20, 20 + ) + self.assertEqual(benchmark._TRANSFERBENCH_SIZES, sizes) + self.assertEqual(benchmark._TRANSFERBENCH_ITERATIONS, iterations) + self.assertEqual(len(benchmark._commands), 2) + for direction, command in enumerate(benchmark._commands): + commands = command.split(' && ') + self.assertEqual(len(commands), 23) + for subcommand, size, count in zip(commands, sizes, iterations): + tokens = shlex.split(subcommand) + self.assertEqual(tokens[-3:], [ + 'cmdline', str(size), '1 1 P0 D0 G0' if direction == 0 else '1 1 G0 D0 P0' + ]) + for setting in ( + 'NUM_ITERATIONS={}'.format(count), 'NUM_WARMUPS=0', 'NUM_SUBITERATIONS=1', + 'SHOW_ITERATIONS=1', 'OUTPUT_TO_CSV=1', 'USE_HIP_EVENTS=1', 'USE_HSA_DMA=0', + 'USE_INTERACTIVE=0', 'ALWAYS_VALIDATE=0' + ): + self.assertIn(setting, tokens) + self.assertNotIn('numactl', command) + self.assertNotIn('G1', command) + self.assertEqual(benchmark._args.numa, 3) + + def test_transferbench_pageable_subset(self): + """Preserve memory and direction selection without introducing new CLI arguments.""" + benchmark = self._transferbench('--memory unpinned --mem_type DTOH') + self.assertEqual(len(benchmark._commands), 1) + self.assertIn("'1 1 G0 D0 H0'", benchmark._commands[0]) + self.assertNotIn('P0', benchmark._commands[0]) + + def test_transferbench_numa_does_not_override_logical_gpu_locality(self): + """P0 means the visible GPU's nearest node, not physical GPU zero or NUMA zero.""" + with mock.patch.dict(os.environ, {'HIP_VISIBLE_DEVICES': '5'}): + for memory, host in (('pinned', 'P0'), ('unpinned', 'H0')): + with self.subTest(memory=memory): + baseline = self._transferbench('--memory {}'.format(memory)) + explicit = self._transferbench('--memory {} --numa 1'.format(memory)) + self.assertEqual(baseline._commands, explicit._commands) + self.assertIn("'1 1 {} D0 G0'".format(host), explicit._commands[0]) + self.assertIn("'1 1 G0 D0 {}'".format(host), explicit._commands[1]) + self.assertNotIn('C0', explicit._commands[0]) + self.assertNotIn('G5', explicit._commands[0]) + self.assertEqual(explicit._args.numa, 1) + + def test_transferbench_pageable_worker_nodes(self): + """Resolve node0/node1 from the worker CPU, not --numa or the GPU index.""" + for cpu, node in ((0, 0), (48, 1)): + with self.subTest(cpu=cpu, node=node): + self.libc.return_value.sched_getcpu.return_value = cpu + self.cpu_nodes.return_value = [Path('/sys/devices/system/cpu/cpu{}/node{}'.format(cpu, node))] + benchmark = self._transferbench('--memory unpinned --numa 3') + self.cpu_nodes.assert_called_with(Path('/sys/devices/system/cpu/cpu{}'.format(cpu))) + self.assertEqual(benchmark._worker_numa_node, node) + self.assertIn("'1 1 H{} D0 G0'".format(node), benchmark._commands[0]) + self.assertIn("'1 1 G0 D0 H{}'".format(node), benchmark._commands[1]) + benchmark._TRANSFERBENCH_SIZES = (4194304,) + benchmark._TRANSFERBENCH_ITERATIONS = (3,) + raw = self._fixture('unpinned').replace('H0', 'H{}'.format(node)) + self.assertTrue(benchmark._process_raw_result(0, raw)) + wrong_node = self._fixture('unpinned').replace('H0', 'H{}'.format(1 - node)) + self.assertFalse(benchmark._process_raw_result(0, wrong_node)) + self.assertEqual(len(benchmark.result['h2d_bw']), 1) + self.assertEqual(benchmark._args.numa, 3) + + def test_transferbench_pageable_detection_errors(self): + """Fail explicitly on unavailable CPU detection or missing/ambiguous/inaccessible topology.""" + module = 'superbench.benchmarks.micro_benchmarks.rocm_memory_bw_performance' + for error in ('library', 'symbol', 'cpu', 'missing', 'ambiguous', 'permission'): + with self.subTest(error=error): + self.libc.side_effect = None + self.libc.return_value.sched_getcpu.side_effect = None + self.libc.return_value.sched_getcpu.return_value = 0 + self.cpu_nodes.side_effect = None + self.cpu_nodes.return_value = [Path('node0')] + if error == 'library': + self.libc.side_effect = OSError('libc unavailable') + elif error == 'symbol': + self.libc.return_value.sched_getcpu.side_effect = AttributeError('sched_getcpu unavailable') + elif error == 'cpu': + self.libc.return_value.sched_getcpu.return_value = -1 + elif error == 'missing': + self.cpu_nodes.return_value = [Path('topology'), Path('node-invalid')] + elif error == 'ambiguous': + self.cpu_nodes.return_value = [Path('node0'), Path('node1')] + else: + self.cpu_nodes.side_effect = PermissionError('sysfs denied') + with mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'transferbench'}): + benchmark = RocmMemBwBenchmark('mem-bw', '--memory unpinned') + with mock.patch(module + '.logger.error') as log: + self.assertFalse(benchmark._preprocess()) + self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_DEVICE_GETTING_FAILURE) + self.assertEqual(benchmark._commands, []) + self.assertIsNone(benchmark._worker_numa_node) + self.assertIn('Cannot determine worker-local NUMA placement', log.call_args[0][0]) + + def test_pinned_and_legacy_do_not_detect_worker_numa(self): + """Keep pinned P0 GPU-local and leave both legacy allocation modes unchanged.""" + self.libc.side_effect = OSError('CPU detection unavailable') + benchmark = self._transferbench('--memory pinned --numa 1') + self.assertIn("'1 1 P0 D0 G0'", benchmark._commands[0]) + for memory in ('pinned', 'unpinned'): + with self.subTest(memory=memory): + benchmark = RocmMemBwBenchmark('mem-bw', '--memory {} --numa 1'.format(memory)) + self.assertTrue(benchmark._preprocess()) + self.assertNotIn('numactl', benchmark._commands[0]) + self.libc.assert_not_called() + + def test_transferbench_measured_fixtures(self): + """Use pinned/pageable sample output, not flat CSV or aggregate executor bandwidth.""" + expected_times = { + ('pinned', 'htod'): (0.100, 0.104, 23.315), + ('pinned', 'dtoh'): (0.093, 0.094, 23.555), + ('unpinned', 'htod'): (0.131, 0.139, 23.634), + ('unpinned', 'dtoh'): (0.133, 0.135, 23.265), + } + for (memory, direction), times in expected_times.items(): + with self.subTest(memory=memory, direction=direction): + benchmark = self._transferbench('--memory {} --mem_type {}'.format(memory, direction)) + benchmark._TRANSFERBENCH_SIZES = (4194304,) + benchmark._TRANSFERBENCH_ITERATIONS = (3,) + raw = self._fixture(memory, direction) + self.assertTrue(benchmark._process_raw_result(0, raw)) + metric = 'h2d_bw' if direction == 'htod' else 'd2h_bw' + self.assertEqual(len(benchmark.result[metric]), 1) + self.assertAlmostEqual(benchmark.result[metric][0], sum(4.194 / time for time in times) / 3) + self.assertEqual(benchmark.raw_data['raw_output_' + direction], [raw]) + + def test_transferbench_arithmetic_mean_then_max(self): + """Neither fastest sample, inverse mean duration nor aggregate rows are the metric.""" + benchmark = self._transferbench() + benchmark._TRANSFERBENCH_SIZES = (1000000, 2000000) + benchmark._TRANSFERBENCH_ITERATIONS = (2, 2) + raw = self._report(1000000, (1, 0.125)) + self._report(2000000, (0.5, 0.5)) + self.assertTrue(benchmark._process_raw_result(0, raw)) + self.assertEqual(benchmark.result['h2d_bw'], [4.5]) + + def test_transferbench_full_sweep_and_integer_conversion(self): + """Include all trial IDs, sub-KB zero contributions and old integer-byte truncation.""" + benchmark = self._transferbench() + raw = ''.join( + self._report(size, [1] * count) + for size, count in zip(benchmark._TRANSFERBENCH_SIZES, benchmark._TRANSFERBENCH_ITERATIONS) + ) + self.assertTrue(benchmark._process_raw_result(0, raw)) + self.assertEqual(benchmark.result['h2d_bw'], [536.870]) + benchmark._TRANSFERBENCH_SIZES = (64, 1024) + benchmark._TRANSFERBENCH_ITERATIONS = (2, 2) + raw = self._report(64, (16, 1)) + self._report(1024, (1, 1)) + self.assertTrue(benchmark._process_raw_result(0, raw)) + self.assertEqual(benchmark.result['h2d_bw'][-1], 0.001) + + def test_transferbench_rejects_incomplete_and_wrong_reports(self): + """Reject missing/extra sizes, samples, executors, settings and incorrect routes.""" + raw = self._fixture() + corruptions = [ + '', raw + raw, raw[:raw.index('Aggregate (CPU)')], + re.sub(r'^.*Iter 001.*\n', '', raw, flags=re.MULTILINE), + raw.replace('Iter 001', 'Iter 002'), raw.replace('Iter 001', 'Iter 004'), + raw.replace('DMA 00', 'DMA 01'), raw.replace('DMA 00', 'GFX 00'), + raw.replace('Transfer 0', 'Transfer 1'), raw.replace('G0', 'G1'), + raw.replace('D0:1', 'D1:1'), raw.replace('P0', 'H0'), + raw.replace('P0 -> D0:1 -> G0', 'G0 -> D0:1 -> P0'), + raw.replace('4194304 bytes', '4194305 bytes'), + raw.replace('NUM_WARMUPS , 0', 'NUM_WARMUPS , 3'), + raw.replace('NUM_ITERATIONS , 3', 'NUM_ITERATIONS , 2'), + raw + '[ERROR] validation failed\n', + raw.replace('Transfer 0', 'Transfer 0, bad'), + raw.replace('StandardDev', 'missing'), + raw.replace(' Iter 001', 'Transfer 1, 1 GB/s, 1 ms, 4194304 bytes, P0 -> D0:1 -> G0\nIter 001'), + ] + for index, corrupted in enumerate(corruptions): + with self.subTest(case=index): + benchmark = self._transferbench() + benchmark._TRANSFERBENCH_SIZES = (4194304,) + benchmark._TRANSFERBENCH_ITERATIONS = (3,) + self.assertFalse(benchmark._process_raw_result(0, corrupted)) + self.assertNotIn('h2d_bw', benchmark.result) + self.assertEqual(benchmark.raw_data['raw_output_htod'], [corrupted]) + + def test_transferbench_rejects_invalid_numeric_samples(self): + """Reject nonfinite/nonpositive timings and nonphysical bandwidths before reduction.""" + raw = self._fixture() + for field in ('42.133 GB/s', '0.100 ms'): + for invalid in ('nan', 'inf', '-inf', '-1', '0', 'bogus'): + with self.subTest(field=field, invalid=invalid): + benchmark = self._transferbench() + benchmark._TRANSFERBENCH_SIZES = (4194304,) + benchmark._TRANSFERBENCH_ITERATIONS = (3,) + corrupted = raw.replace(field, invalid + ' ' + field.split()[1]) + self.assertFalse(benchmark._process_raw_result(0, corrupted)) + self.assertNotIn('h2d_bw', benchmark.result) + + def test_transferbench_rejects_partial_size_sweep(self): + """Do not accept a valid single-size run as a full legacy-policy sweep.""" + benchmark = self._transferbench() + self.assertFalse(benchmark._process_raw_result(0, self._fixture())) + + def test_transferbench_failure_does_not_fall_back(self): + """Execution and parse errors use framework return codes without invoking hipBusBandwidth.""" + for code, raw, expected in ( + (1, '[ERROR] allocation failed', ReturnCode.MICROBENCHMARK_EXECUTION_FAILURE), + (0, 'malformed', ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE), + ): + with self.subTest(code=code): + benchmark = self._transferbench() + with mock.patch( + 'superbench.benchmarks.micro_benchmarks.micro_base.run_command', + return_value=subprocess.CompletedProcess([], code, raw) + ) as invoke: + self.assertFalse(benchmark._benchmark()) + self.assertEqual(benchmark.return_code, expected) + self.assertEqual(invoke.call_count, 1) + self.assertNotIn('hipBusBandwidth', invoke.call_args[0][0]) + + def test_transferbench_missing_binary_and_unknown_backend(self): + """Explicit selection is never replaced by an available legacy binary.""" + with mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'transferbench'}): + benchmark = RocmMemBwBenchmark('mem-bw') + with mock.patch('shutil.which', return_value=None): + self.assertFalse(benchmark._preprocess()) + self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_BINARY_NOT_EXIST) + with mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'invalid'}): + benchmark = RocmMemBwBenchmark('mem-bw') + with mock.patch('shutil.which', return_value=None) as lookup: + self.assertFalse(benchmark._preprocess()) + lookup.assert_not_called() + self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) + + def test_transferbench_tolerant_failure_keeps_direction_mapping(self): + """An invalid H2D result must not mislabel a subsequent successful D2H result.""" + benchmark = self._transferbench('--tolerant_fail') + benchmark._TRANSFERBENCH_SIZES = (4194304,) + benchmark._TRANSFERBENCH_ITERATIONS = (3,) + results = [ + subprocess.CompletedProcess([], 0, 'invalid'), + subprocess.CompletedProcess([], 0, self._fixture(direction='dtoh')), + ] + with mock.patch( + 'superbench.benchmarks.micro_benchmarks.micro_base.run_command', side_effect=results + ) as invoke: + self.assertFalse(benchmark._benchmark()) + self.assertEqual(invoke.call_count, 2) + self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) + self.assertNotIn('h2d_bw', benchmark.result) + self.assertEqual(len(benchmark.result['d2h_bw']), 1) + + def test_transferbench_shell_quoting_and_failure_chain(self): + """Quote explicit binary paths and stop a failed sweep before subsequent sizes.""" + binary_dir = Path(self._tmp_dir) / 'bin with spaces' + binary_dir.mkdir(exist_ok=True) + binary = binary_dir / 'TransferBench' + binary.write_text('#!/bin/sh\necho "[ERROR] synthetic failure"\nexit 3\n') + binary.chmod(0o755) + benchmark = self._transferbench('--bin_dir {}'.format(shlex.quote(str(binary_dir)))) + result = subprocess.run(benchmark._commands[0], shell=True, text=True, stdout=subprocess.PIPE, timeout=5) + self.assertEqual(result.returncode, 3) + self.assertEqual(result.stdout.count('[ERROR] synthetic failure'), 1) + + def test_transferbench_invalid_memory_and_direction(self): + """Retain existing validation for unsupported YAML/CLI options.""" + for parameters in ('--memory registered', '--mem_type dtod', '--memory PINNED'): + with self.subTest(parameters=parameters): + with mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'transferbench'}): + benchmark = RocmMemBwBenchmark('mem-bw', parameters) + self.assertFalse(benchmark._preprocess()) + self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) diff --git a/tests/benchmarks/model_benchmarks/test_megatron_launch.py b/tests/benchmarks/model_benchmarks/test_megatron_launch.py new file mode 100644 index 000000000..81677341a --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_megatron_launch.py @@ -0,0 +1,85 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Regression tests for Megatron command forwarding and failure reporting.""" + +import os +from subprocess import CompletedProcess +from unittest import mock + +import pytest + +from superbench.benchmarks import Precision +from superbench.benchmarks.model_benchmarks.megatron_gpt3 import MegatronGPT +from superbench.benchmarks.model_benchmarks.model_base import ModelBenchmark + + +def make_benchmark(parameters=''): + """Build a command-only benchmark without initializing MPI or downloading data.""" + benchmark = MegatronGPT('megatron-gpt', parameters) + benchmark.add_parser_arguments() + valid, benchmark._args, _ = benchmark.parse_args() + assert valid + benchmark._distributed_args = '--nproc_per_node 2' + benchmark._data_options = '--mock-data' + return benchmark + + +def test_extra_arguments_forwarded(): + """Version-specific options must reach the selected Megatron checkout.""" + benchmark = make_benchmark('--extra "--vocab-size 128 --attention-backend unfused"') + command = benchmark._megatron_command(Precision.BFLOAT16) + assert command.endswith('--mock-data --vocab-size 128 --attention-backend unfused') + + +@pytest.mark.parametrize( + 'explicit,deepspeed,override,expected', + [ + ('', False, '/rocm10/Megatron-LM', '/rocm10/Megatron-LM'), + ('', False, '', '/legacy/third_party/Megatron/Megatron-LM'), + ('', True, '/rocm10/Megatron-LM', '/legacy/third_party/Megatron/Megatron-DeepSpeed/'), + ('/explicit', False, '/rocm10/Megatron-LM', '/explicit'), + ] +) +def test_code_base_selection(explicit, deepspeed, override, expected): + """The image override must preserve explicit paths and legacy/DeepSpeed defaults.""" + benchmark = make_benchmark('--batch_size 32 --num_gpus 2') + benchmark._args.code_base = explicit + benchmark._args.deepspeed = deepspeed + benchmark._num_nodes = 1 + with mock.patch.dict(os.environ, {'SB_MICRO_PATH': '/legacy', 'SB_MEGATRON_PATH': override}): + with mock.patch.object(ModelBenchmark, '_preprocess', return_value=True): + with mock.patch('superbench.benchmarks.model_benchmarks.megatron_gpt3.os.path.exists', return_value=True): + assert benchmark._preprocess() + assert benchmark._args.code_base == expected + + +@pytest.mark.parametrize( + 'explicit,deepspeed,expected', + [('', False, '/rocm10/Megatron-LM'), ('/explicit', False, '/explicit'), ('', True, '')] +) +def test_environment_path_available_during_dataset_generation(explicit, deepspeed, expected): + """Apply the environment path before dataset generation and final path validation.""" + benchmark = make_benchmark('--mock_data --num_workers 0') + benchmark._args.code_base = explicit + benchmark._args.deepspeed = deepspeed + with mock.patch.dict(os.environ, {'SB_MEGATRON_PATH': '/rocm10/Megatron-LM'}): + assert benchmark._generate_dataset() + assert benchmark._args.code_base == expected + + +@pytest.mark.parametrize('local_rank', [None, '0']) +def test_training_failure_restores_environment(local_rank): + """Do not report failed subprocesses as successful timings or assign None to environ.""" + benchmark = make_benchmark() + with mock.patch.dict(os.environ): + os.environ.pop('OMPI_COMM_WORLD_LOCAL_RANK', None) + if local_rank is not None: + os.environ['OMPI_COMM_WORLD_LOCAL_RANK'] = local_rank + with mock.patch( + 'superbench.benchmarks.model_benchmarks.megatron_gpt3.run_command', + return_value=CompletedProcess('torchrun', 2, 'training failed') + ): + with pytest.raises(RuntimeError, match='exit code 2'): + benchmark._train_step(Precision.FLOAT32) + assert os.environ.get('OMPI_COMM_WORLD_LOCAL_RANK') == local_rank diff --git a/tests/benchmarks/model_benchmarks/test_transformer_precisions.py b/tests/benchmarks/model_benchmarks/test_transformer_precisions.py new file mode 100644 index 000000000..b1c6ca585 --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_transformer_precisions.py @@ -0,0 +1,38 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Precision coverage for Transformer Engine consumers.""" + +import pytest +import torch + +from superbench.benchmarks import Precision +from superbench.benchmarks.model_benchmarks.model_base import Optimizer +from superbench.benchmarks.model_benchmarks.pytorch_bert import PytorchBERT +from superbench.benchmarks.model_benchmarks.pytorch_gpt2 import PytorchGPT2 +from superbench.benchmarks.model_benchmarks.pytorch_llama import PytorchLlama + + +@pytest.mark.parametrize('benchmark', [PytorchBERT, PytorchGPT2, PytorchLlama]) +def test_transformer_bfloat16_supported(benchmark): + """BF16 must not be silently skipped by the generic precision filter.""" + instance = benchmark('precision-test') + assert Precision.BFLOAT16 in instance._supported_precision + instance.add_parser_arguments() + valid, arguments, _ = instance.parse_args() + assert valid + assert Precision.BFLOAT16 not in arguments.precision + + +@pytest.mark.parametrize('optimizer', [Optimizer.ADAM, Optimizer.ADAMW]) +@pytest.mark.parametrize('parameters,epsilon', [('', 1e-8), ('--optimizer_eps 1e-4', 1e-4)]) +def test_optimizer_epsilon(optimizer, parameters, epsilon): + """Preserve the default and permit an explicitly FP16-representable epsilon.""" + benchmark = PytorchGPT2('precision-test', parameters) + benchmark.add_parser_arguments() + valid, benchmark._args, _ = benchmark.parse_args() + assert valid + benchmark._model = torch.nn.Linear(16, 16) + benchmark._optimizer_type = optimizer + assert benchmark._create_optimizer() + assert benchmark._optimizer.param_groups[0]['eps'] == epsilon diff --git a/tests/data/rocm_transferbench_pinned_dtoh.log b/tests/data/rocm_transferbench_pinned_dtoh.log new file mode 100644 index 000000000..3026e9977 --- /dev/null +++ b/tests/data/rocm_transferbench_pinned_dtoh.log @@ -0,0 +1,31 @@ +TransferBench v1.69.00 +=============================================================== +[Common] (Suppress by setting HIDE_ENV=1) +ALWAYS_VALIDATE , 0,Validating after all iterations +BLOCK_BYTES , 256,Each CU gets a mulitple of 256 bytes to copy +BYTE_OFFSET , 0,Using byte offset of 0 +CU_MASK , 0,All +FILL_PATTERN , 0,Element i = ((i * 517) modulo 383 + 31) * (srcBufferIdx + 1) +GFX_UNROLL , 4,Using GFX unroll factor of 4 +HIDE_ENV , 0,Printing environment variable values +MIN_VAR_SUBEXEC , 1,Using at least 1 subexecutor(s) for variable subExec tranfers +NUM_ITERATIONS , 3,Running 3 timed iteration(s) +NUM_SUBITERATIONS , 1,Running 1 subiterations +NUM_WARMUPS , 0,Running 0 warmup iteration(s) per Test +OUTPUT_TO_CSV , 1,Output to CSV +SHOW_ITERATIONS , 1,Showing per-iteration timing info +USE_HIP_EVENTS , 1,Using HIP events for DMA executor timing +USE_HSA_DMA , 0,Using hipMemcpyAsync for DMA execution +USE_INTERACTIVE , 0,Running in non-interactive mode +USE_SINGLE_STREAM , 1,Using single stream per device +VALIDATE_DIRECT , 0,Validate GPU destination memory via device-to-host copy +VALIDATE_SOURCE , 0,Do not perform source buffer validation + +Test 1: + Executor: DMA 00, 0.530 GB/s, 7.914 ms, 4194304 bytes, 0.530 GB/s (sum), + Transfer 0, 0.530 GB/s, 7.914 ms, 4194304 bytes, G0 -> D0:1 -> P0, + Iter 003, 44.620 GB/s, 0.094 ms, , , + Iter 002, 45.100 GB/s, 0.093 ms, , , + Iter 001, 0.178 GB/s, 23.555 ms, , , + StandardDev, 0.000 GB/s, 11.060 ms, , , + Aggregate (CPU), 0.529 GB/s, 7.926 ms, 4194304 bytes, Overhead 0.012 ms, diff --git a/tests/data/rocm_transferbench_pinned_htod.log b/tests/data/rocm_transferbench_pinned_htod.log new file mode 100644 index 000000000..3611566e5 --- /dev/null +++ b/tests/data/rocm_transferbench_pinned_htod.log @@ -0,0 +1,31 @@ +TransferBench v1.69.00 +=============================================================== +[Common] (Suppress by setting HIDE_ENV=1) +ALWAYS_VALIDATE , 0,Validating after all iterations +BLOCK_BYTES , 256,Each CU gets a mulitple of 256 bytes to copy +BYTE_OFFSET , 0,Using byte offset of 0 +CU_MASK , 0,All +FILL_PATTERN , 0,Element i = ((i * 517) modulo 383 + 31) * (srcBufferIdx + 1) +GFX_UNROLL , 4,Using GFX unroll factor of 4 +HIDE_ENV , 0,Printing environment variable values +MIN_VAR_SUBEXEC , 1,Using at least 1 subexecutor(s) for variable subExec tranfers +NUM_ITERATIONS , 3,Running 3 timed iteration(s) +NUM_SUBITERATIONS , 1,Running 1 subiterations +NUM_WARMUPS , 0,Running 0 warmup iteration(s) per Test +OUTPUT_TO_CSV , 1,Output to CSV +SHOW_ITERATIONS , 1,Showing per-iteration timing info +USE_HIP_EVENTS , 1,Using HIP events for DMA executor timing +USE_HSA_DMA , 0,Using hipMemcpyAsync for DMA execution +USE_INTERACTIVE , 0,Running in non-interactive mode +USE_SINGLE_STREAM , 1,Using single stream per device +VALIDATE_DIRECT , 0,Validate GPU destination memory via device-to-host copy +VALIDATE_SOURCE , 0,Do not perform source buffer validation + +Test 1: + Executor: DMA 00, 0.535 GB/s, 7.840 ms, 4194304 bytes, 0.535 GB/s (sum), + Transfer 0, 0.535 GB/s, 7.840 ms, 4194304 bytes, P0 -> D0:1 -> G0, + Iter 003, 40.330 GB/s, 0.104 ms, , , + Iter 002, 42.133 GB/s, 0.100 ms, , , + Iter 001, 0.180 GB/s, 23.315 ms, , , + StandardDev, 0.000 GB/s, 10.943 ms, , , + Aggregate (CPU), 0.534 GB/s, 7.852 ms, 4194304 bytes, Overhead 0.012 ms, diff --git a/tests/data/rocm_transferbench_unpinned_dtoh.log b/tests/data/rocm_transferbench_unpinned_dtoh.log new file mode 100644 index 000000000..935d61be5 --- /dev/null +++ b/tests/data/rocm_transferbench_unpinned_dtoh.log @@ -0,0 +1,31 @@ +TransferBench v1.69.00 +=============================================================== +[Common] (Suppress by setting HIDE_ENV=1) +ALWAYS_VALIDATE , 0,Validating after all iterations +BLOCK_BYTES , 256,Each CU gets a mulitple of 256 bytes to copy +BYTE_OFFSET , 0,Using byte offset of 0 +CU_MASK , 0,All +FILL_PATTERN , 0,Element i = ((i * 517) modulo 383 + 31) * (srcBufferIdx + 1) +GFX_UNROLL , 4,Using GFX unroll factor of 4 +HIDE_ENV , 0,Printing environment variable values +MIN_VAR_SUBEXEC , 1,Using at least 1 subexecutor(s) for variable subExec tranfers +NUM_ITERATIONS , 3,Running 3 timed iteration(s) +NUM_SUBITERATIONS , 1,Running 1 subiterations +NUM_WARMUPS , 0,Running 0 warmup iteration(s) per Test +OUTPUT_TO_CSV , 1,Output to CSV +SHOW_ITERATIONS , 1,Showing per-iteration timing info +USE_HIP_EVENTS , 1,Using HIP events for DMA executor timing +USE_HSA_DMA , 0,Using hipMemcpyAsync for DMA execution +USE_INTERACTIVE , 0,Running in non-interactive mode +USE_SINGLE_STREAM , 1,Using single stream per device +VALIDATE_DIRECT , 0,Validate GPU destination memory via device-to-host copy +VALIDATE_SOURCE , 0,Do not perform source buffer validation + +Test 1: + Executor: DMA 00, 0.535 GB/s, 7.844 ms, 4194304 bytes, 0.535 GB/s (sum), + Transfer 0, 0.535 GB/s, 7.844 ms, 4194304 bytes, G0 -> D0:1 -> H0, + Iter 003, 31.069 GB/s, 0.135 ms, , , + Iter 002, 31.536 GB/s, 0.133 ms, , , + Iter 001, 0.180 GB/s, 23.265 ms, , , + StandardDev, 0.000 GB/s, 10.904 ms, , , + Aggregate (CPU), 0.534 GB/s, 7.856 ms, 4194304 bytes, Overhead 0.012 ms, diff --git a/tests/data/rocm_transferbench_unpinned_htod.log b/tests/data/rocm_transferbench_unpinned_htod.log new file mode 100644 index 000000000..4ccfaa5ba --- /dev/null +++ b/tests/data/rocm_transferbench_unpinned_htod.log @@ -0,0 +1,31 @@ +TransferBench v1.69.00 +=============================================================== +[Common] (Suppress by setting HIDE_ENV=1) +ALWAYS_VALIDATE , 0,Validating after all iterations +BLOCK_BYTES , 256,Each CU gets a mulitple of 256 bytes to copy +BYTE_OFFSET , 0,Using byte offset of 0 +CU_MASK , 0,All +FILL_PATTERN , 0,Element i = ((i * 517) modulo 383 + 31) * (srcBufferIdx + 1) +GFX_UNROLL , 4,Using GFX unroll factor of 4 +HIDE_ENV , 0,Printing environment variable values +MIN_VAR_SUBEXEC , 1,Using at least 1 subexecutor(s) for variable subExec tranfers +NUM_ITERATIONS , 3,Running 3 timed iteration(s) +NUM_SUBITERATIONS , 1,Running 1 subiterations +NUM_WARMUPS , 0,Running 0 warmup iteration(s) per Test +OUTPUT_TO_CSV , 1,Output to CSV +SHOW_ITERATIONS , 1,Showing per-iteration timing info +USE_HIP_EVENTS , 1,Using HIP events for DMA executor timing +USE_HSA_DMA , 0,Using hipMemcpyAsync for DMA execution +USE_INTERACTIVE , 0,Running in non-interactive mode +USE_SINGLE_STREAM , 1,Using single stream per device +VALIDATE_DIRECT , 0,Validate GPU destination memory via device-to-host copy +VALIDATE_SOURCE , 0,Do not perform source buffer validation + +Test 1: + Executor: DMA 00, 0.526 GB/s, 7.968 ms, 4194304 bytes, 0.526 GB/s (sum), + Transfer 0, 0.526 GB/s, 7.968 ms, 4194304 bytes, H0 -> D0:1 -> G0, + Iter 003, 30.175 GB/s, 0.139 ms, , , + Iter 002, 32.018 GB/s, 0.131 ms, , , + Iter 001, 0.177 GB/s, 23.634 ms, , , + StandardDev, 0.000 GB/s, 11.078 ms, , , + Aggregate (CPU), 0.526 GB/s, 7.980 ms, 4194304 bytes, Overhead 0.012 ms, From 9a250de529988efa520c1272e13946f0f3c1e4f8 Mon Sep 17 00:00:00 2001 From: "Nguyen Vuong (from Dev Box)" Date: Fri, 9 Oct 2026 14:15:44 -0700 Subject: [PATCH 2/5] Tests - Fix misspellings in synthetic TransferBench fixtures Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/data/rocm_transferbench_pinned_dtoh.log | 4 ++-- tests/data/rocm_transferbench_pinned_htod.log | 4 ++-- tests/data/rocm_transferbench_unpinned_dtoh.log | 4 ++-- tests/data/rocm_transferbench_unpinned_htod.log | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/data/rocm_transferbench_pinned_dtoh.log b/tests/data/rocm_transferbench_pinned_dtoh.log index 3026e9977..0683114a0 100644 --- a/tests/data/rocm_transferbench_pinned_dtoh.log +++ b/tests/data/rocm_transferbench_pinned_dtoh.log @@ -2,13 +2,13 @@ TransferBench v1.69.00 =============================================================== [Common] (Suppress by setting HIDE_ENV=1) ALWAYS_VALIDATE , 0,Validating after all iterations -BLOCK_BYTES , 256,Each CU gets a mulitple of 256 bytes to copy +BLOCK_BYTES , 256,Each CU gets a multiple of 256 bytes to copy BYTE_OFFSET , 0,Using byte offset of 0 CU_MASK , 0,All FILL_PATTERN , 0,Element i = ((i * 517) modulo 383 + 31) * (srcBufferIdx + 1) GFX_UNROLL , 4,Using GFX unroll factor of 4 HIDE_ENV , 0,Printing environment variable values -MIN_VAR_SUBEXEC , 1,Using at least 1 subexecutor(s) for variable subExec tranfers +MIN_VAR_SUBEXEC , 1,Using at least 1 subexecutor(s) for variable subExec transfers NUM_ITERATIONS , 3,Running 3 timed iteration(s) NUM_SUBITERATIONS , 1,Running 1 subiterations NUM_WARMUPS , 0,Running 0 warmup iteration(s) per Test diff --git a/tests/data/rocm_transferbench_pinned_htod.log b/tests/data/rocm_transferbench_pinned_htod.log index 3611566e5..d3c093ec1 100644 --- a/tests/data/rocm_transferbench_pinned_htod.log +++ b/tests/data/rocm_transferbench_pinned_htod.log @@ -2,13 +2,13 @@ TransferBench v1.69.00 =============================================================== [Common] (Suppress by setting HIDE_ENV=1) ALWAYS_VALIDATE , 0,Validating after all iterations -BLOCK_BYTES , 256,Each CU gets a mulitple of 256 bytes to copy +BLOCK_BYTES , 256,Each CU gets a multiple of 256 bytes to copy BYTE_OFFSET , 0,Using byte offset of 0 CU_MASK , 0,All FILL_PATTERN , 0,Element i = ((i * 517) modulo 383 + 31) * (srcBufferIdx + 1) GFX_UNROLL , 4,Using GFX unroll factor of 4 HIDE_ENV , 0,Printing environment variable values -MIN_VAR_SUBEXEC , 1,Using at least 1 subexecutor(s) for variable subExec tranfers +MIN_VAR_SUBEXEC , 1,Using at least 1 subexecutor(s) for variable subExec transfers NUM_ITERATIONS , 3,Running 3 timed iteration(s) NUM_SUBITERATIONS , 1,Running 1 subiterations NUM_WARMUPS , 0,Running 0 warmup iteration(s) per Test diff --git a/tests/data/rocm_transferbench_unpinned_dtoh.log b/tests/data/rocm_transferbench_unpinned_dtoh.log index 935d61be5..79b497f36 100644 --- a/tests/data/rocm_transferbench_unpinned_dtoh.log +++ b/tests/data/rocm_transferbench_unpinned_dtoh.log @@ -2,13 +2,13 @@ TransferBench v1.69.00 =============================================================== [Common] (Suppress by setting HIDE_ENV=1) ALWAYS_VALIDATE , 0,Validating after all iterations -BLOCK_BYTES , 256,Each CU gets a mulitple of 256 bytes to copy +BLOCK_BYTES , 256,Each CU gets a multiple of 256 bytes to copy BYTE_OFFSET , 0,Using byte offset of 0 CU_MASK , 0,All FILL_PATTERN , 0,Element i = ((i * 517) modulo 383 + 31) * (srcBufferIdx + 1) GFX_UNROLL , 4,Using GFX unroll factor of 4 HIDE_ENV , 0,Printing environment variable values -MIN_VAR_SUBEXEC , 1,Using at least 1 subexecutor(s) for variable subExec tranfers +MIN_VAR_SUBEXEC , 1,Using at least 1 subexecutor(s) for variable subExec transfers NUM_ITERATIONS , 3,Running 3 timed iteration(s) NUM_SUBITERATIONS , 1,Running 1 subiterations NUM_WARMUPS , 0,Running 0 warmup iteration(s) per Test diff --git a/tests/data/rocm_transferbench_unpinned_htod.log b/tests/data/rocm_transferbench_unpinned_htod.log index 4ccfaa5ba..ce416f348 100644 --- a/tests/data/rocm_transferbench_unpinned_htod.log +++ b/tests/data/rocm_transferbench_unpinned_htod.log @@ -2,13 +2,13 @@ TransferBench v1.69.00 =============================================================== [Common] (Suppress by setting HIDE_ENV=1) ALWAYS_VALIDATE , 0,Validating after all iterations -BLOCK_BYTES , 256,Each CU gets a mulitple of 256 bytes to copy +BLOCK_BYTES , 256,Each CU gets a multiple of 256 bytes to copy BYTE_OFFSET , 0,Using byte offset of 0 CU_MASK , 0,All FILL_PATTERN , 0,Element i = ((i * 517) modulo 383 + 31) * (srcBufferIdx + 1) GFX_UNROLL , 4,Using GFX unroll factor of 4 HIDE_ENV , 0,Printing environment variable values -MIN_VAR_SUBEXEC , 1,Using at least 1 subexecutor(s) for variable subExec tranfers +MIN_VAR_SUBEXEC , 1,Using at least 1 subexecutor(s) for variable subExec transfers NUM_ITERATIONS , 3,Running 3 timed iteration(s) NUM_SUBITERATIONS , 1,Running 1 subiterations NUM_WARMUPS , 0,Running 0 warmup iteration(s) per Test From 37260eabcbb7b8f4bf7ba3e8df4cd457abe2aa9a Mon Sep 17 00:00:00 2001 From: "Nguyen Vuong (from Dev Box)" Date: Fri, 9 Oct 2026 14:27:13 -0700 Subject: [PATCH 3/5] Benchmarks - Run TransferBench mem-bw sweep through an explicit shell run_command(flush_output=True), used with --log_flushing, splits the command without a shell, so the && chain was passed to the first TransferBench as arguments. Wrap each direction's sweep in sh -c and test both paths. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../rocm_memory_bw_performance.py | 3 +- .../test_rocm_memory_bw_performance.py | 46 ++++++++++++++++--- 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/superbench/benchmarks/micro_benchmarks/rocm_memory_bw_performance.py b/superbench/benchmarks/micro_benchmarks/rocm_memory_bw_performance.py index 347d82171..1c6f04176 100644 --- a/superbench/benchmarks/micro_benchmarks/rocm_memory_bw_performance.py +++ b/superbench/benchmarks/micro_benchmarks/rocm_memory_bw_performance.py @@ -138,7 +138,8 @@ def _transferbench_command(self, mem_type): options, iterations, binary, size, source, destination ) ) - return ' && '.join(commands) + # run_command() does not use a shell when --log_flushing is set, so invoke one explicitly. + return 'sh -c {}'.format(shlex.quote(' && '.join(commands))) @staticmethod def _transferbench_quantity(value, unit, allow_zero=False): diff --git a/tests/benchmarks/micro_benchmarks/test_rocm_memory_bw_performance.py b/tests/benchmarks/micro_benchmarks/test_rocm_memory_bw_performance.py index 051cb9bbb..0388042ce 100644 --- a/tests/benchmarks/micro_benchmarks/test_rocm_memory_bw_performance.py +++ b/tests/benchmarks/micro_benchmarks/test_rocm_memory_bw_performance.py @@ -16,6 +16,7 @@ from tests.helper.testcase import BenchmarkTestCase from superbench.benchmarks import BenchmarkRegistry, BenchmarkType, ReturnCode, Platform from superbench.benchmarks.micro_benchmarks.rocm_memory_bw_performance import RocmMemBwBenchmark +from superbench.common.utils import run_command class RocmMemBwTest(BenchmarkTestCase, unittest.TestCase): @@ -49,6 +50,16 @@ def _transferbench(self, parameters=''): self.assertTrue(benchmark._preprocess()) return benchmark + def _chains(self, benchmark): + """Unwrap each direction's explicit `sh -c` invocation into its && chain.""" + chains = [] + for command in benchmark._commands: + tokens = shlex.split(command) + self.assertEqual(tokens[:2], ['sh', '-c']) + self.assertEqual(len(tokens), 3) + chains.append(tokens[2]) + return chains + @staticmethod def _fixture(memory='pinned', direction='htod'): """Read synthetic TransferBench v1.69.00 CSV-mode output for logical device zero.""" @@ -136,7 +147,7 @@ def test_transferbench_exact_legacy_policy(self): self.assertEqual(benchmark._TRANSFERBENCH_SIZES, sizes) self.assertEqual(benchmark._TRANSFERBENCH_ITERATIONS, iterations) self.assertEqual(len(benchmark._commands), 2) - for direction, command in enumerate(benchmark._commands): + for direction, command in enumerate(self._chains(benchmark)): commands = command.split(' && ') self.assertEqual(len(commands), 23) for subcommand, size, count in zip(commands, sizes, iterations): @@ -158,7 +169,7 @@ def test_transferbench_pageable_subset(self): """Preserve memory and direction selection without introducing new CLI arguments.""" benchmark = self._transferbench('--memory unpinned --mem_type DTOH') self.assertEqual(len(benchmark._commands), 1) - self.assertIn("'1 1 G0 D0 H0'", benchmark._commands[0]) + self.assertIn("'1 1 G0 D0 H0'", self._chains(benchmark)[0]) self.assertNotIn('P0', benchmark._commands[0]) def test_transferbench_numa_does_not_override_logical_gpu_locality(self): @@ -169,8 +180,9 @@ def test_transferbench_numa_does_not_override_logical_gpu_locality(self): baseline = self._transferbench('--memory {}'.format(memory)) explicit = self._transferbench('--memory {} --numa 1'.format(memory)) self.assertEqual(baseline._commands, explicit._commands) - self.assertIn("'1 1 {} D0 G0'".format(host), explicit._commands[0]) - self.assertIn("'1 1 G0 D0 {}'".format(host), explicit._commands[1]) + chains = self._chains(explicit) + self.assertIn("'1 1 {} D0 G0'".format(host), chains[0]) + self.assertIn("'1 1 G0 D0 {}'".format(host), chains[1]) self.assertNotIn('C0', explicit._commands[0]) self.assertNotIn('G5', explicit._commands[0]) self.assertEqual(explicit._args.numa, 1) @@ -184,8 +196,8 @@ def test_transferbench_pageable_worker_nodes(self): benchmark = self._transferbench('--memory unpinned --numa 3') self.cpu_nodes.assert_called_with(Path('/sys/devices/system/cpu/cpu{}'.format(cpu))) self.assertEqual(benchmark._worker_numa_node, node) - self.assertIn("'1 1 H{} D0 G0'".format(node), benchmark._commands[0]) - self.assertIn("'1 1 G0 D0 H{}'".format(node), benchmark._commands[1]) + self.assertIn("'1 1 H{} D0 G0'".format(node), self._chains(benchmark)[0]) + self.assertIn("'1 1 G0 D0 H{}'".format(node), self._chains(benchmark)[1]) benchmark._TRANSFERBENCH_SIZES = (4194304,) benchmark._TRANSFERBENCH_ITERATIONS = (3,) raw = self._fixture('unpinned').replace('H0', 'H{}'.format(node)) @@ -230,7 +242,7 @@ def test_pinned_and_legacy_do_not_detect_worker_numa(self): """Keep pinned P0 GPU-local and leave both legacy allocation modes unchanged.""" self.libc.side_effect = OSError('CPU detection unavailable') benchmark = self._transferbench('--memory pinned --numa 1') - self.assertIn("'1 1 P0 D0 G0'", benchmark._commands[0]) + self.assertIn("'1 1 P0 D0 G0'", self._chains(benchmark)[0]) for memory in ('pinned', 'unpinned'): with self.subTest(memory=memory): benchmark = RocmMemBwBenchmark('mem-bw', '--memory {} --numa 1'.format(memory)) @@ -389,6 +401,26 @@ def test_transferbench_shell_quoting_and_failure_chain(self): self.assertEqual(result.returncode, 3) self.assertEqual(result.stdout.count('[ERROR] synthetic failure'), 1) + def test_transferbench_sweep_runs_with_and_without_log_flushing(self): + """Run every size whether or not run_command() uses a shell (--log_flushing).""" + binary_dir = Path(self._tmp_dir) / 'bin flushing' + binary_dir.mkdir(exist_ok=True) + binary = binary_dir / 'TransferBench' + binary.write_text('#!/bin/sh\necho "size $2 route $3"\n') + binary.chmod(0o755) + for flushing in (False, True): + with self.subTest(flushing=flushing): + parameters = '--bin_dir {}{}'.format( + shlex.quote(str(binary_dir)), ' --log_flushing' if flushing else '' + ) + benchmark = self._transferbench(parameters) + output = run_command(benchmark._commands[0], quiet=True, flush_output=flushing) + self.assertEqual(output.returncode, 0, output.stdout) + self.assertEqual( + output.stdout.splitlines(), + ['size {} route 1 1 P0 D0 G0'.format(size) for size in benchmark._TRANSFERBENCH_SIZES], + ) + def test_transferbench_invalid_memory_and_direction(self): """Retain existing validation for unsupported YAML/CLI options.""" for parameters in ('--memory registered', '--mem_type dtod', '--memory PINNED'): From f2fb6452787371110735231581ae6a63a1538353 Mon Sep 17 00:00:00 2001 From: "Nguyen Vuong (from Dev Box)" Date: Fri, 9 Oct 2026 14:41:15 -0700 Subject: [PATCH 4/5] Benchmarks - Fail megatron-gpt run on nonzero training exit Benchmark.run() records exceptions but still returns True, so raising on a nonzero Megatron exit did not fail the run. Log the failure and return no timings so ModelBenchmark.__train() takes its normal failure path. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../model_benchmarks/megatron_gpt3.py | 8 +++++- .../model_benchmarks/test_megatron_launch.py | 28 +++++++++++++++++-- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/superbench/benchmarks/model_benchmarks/megatron_gpt3.py b/superbench/benchmarks/model_benchmarks/megatron_gpt3.py index 50a439194..f76c941f0 100644 --- a/superbench/benchmarks/model_benchmarks/megatron_gpt3.py +++ b/superbench/benchmarks/model_benchmarks/megatron_gpt3.py @@ -557,7 +557,13 @@ def _train_step(self, precision): # noqa: E501 if local_rank is not None: os.environ['OMPI_COMM_WORLD_LOCAL_RANK'] = local_rank if output.returncode != 0: - raise RuntimeError('Megatron training failed with exit code {}.'.format(output.returncode)) + # Return no timings so ModelBenchmark.__train() fails; Benchmark.run() does not fail on exceptions. + logger.error( + 'Megatron training failed - model: {}, precision: {}, exit code: {}.'.format( + self._name, precision, output.returncode + ) + ) + return [], {} iteration_times = [] info = {} diff --git a/tests/benchmarks/model_benchmarks/test_megatron_launch.py b/tests/benchmarks/model_benchmarks/test_megatron_launch.py index 81677341a..a72ee4770 100644 --- a/tests/benchmarks/model_benchmarks/test_megatron_launch.py +++ b/tests/benchmarks/model_benchmarks/test_megatron_launch.py @@ -9,7 +9,8 @@ import pytest -from superbench.benchmarks import Precision +from superbench.benchmarks import Precision, ReturnCode +from superbench.benchmarks.result import BenchmarkResult from superbench.benchmarks.model_benchmarks.megatron_gpt3 import MegatronGPT from superbench.benchmarks.model_benchmarks.model_base import ModelBenchmark @@ -80,6 +81,27 @@ def test_training_failure_restores_environment(local_rank): 'superbench.benchmarks.model_benchmarks.megatron_gpt3.run_command', return_value=CompletedProcess('torchrun', 2, 'training failed') ): - with pytest.raises(RuntimeError, match='exit code 2'): - benchmark._train_step(Precision.FLOAT32) + assert benchmark._train_step(Precision.FLOAT32) == ([], {}) assert os.environ.get('OMPI_COMM_WORLD_LOCAL_RANK') == local_rank + + +def test_training_failure_fails_run(): + """A nonzero training exit must make run() return False, not only set a return code.""" + benchmark = MegatronGPT('megatron-gpt', '--precision float32 --model_action train') + with mock.patch.object(MegatronGPT, '_preprocess', return_value=True), \ + mock.patch.object(MegatronGPT, '_postprocess', return_value=True), \ + mock.patch.object(MegatronGPT, '_megatron_command', return_value='torchrun pretrain_gpt.py'), \ + mock.patch.object(MegatronGPT, '_sync_result') as sync, \ + mock.patch( + 'superbench.benchmarks.model_benchmarks.megatron_gpt3.run_command', + return_value=CompletedProcess('torchrun', 2, 'training failed') + ): + benchmark.add_parser_arguments() + valid, benchmark._args, _ = benchmark.parse_args() + assert valid + benchmark._result = BenchmarkResult( + benchmark._name, benchmark._benchmark_type, ReturnCode.SUCCESS, run_count=benchmark._args.run_count + ) + assert benchmark.run() is False + assert benchmark.return_code == ReturnCode.INVALID_BENCHMARK_RESULT + sync.assert_not_called() From 74a924946e8d8d4c93438dd7389013de2a361b77 Mon Sep 17 00:00:00 2001 From: "Nguyen Vuong (from Dev Box)" Date: Mon, 2 Nov 2026 13:38:06 -0800 Subject: [PATCH 5/5] Benchmarks - Join torchrun agent store for PyTorch DDP init Binding a TCPStore server on MASTER_PORT + 1 can collide with an ephemeral port. Because MASTER_PORT was also rewritten to that port, torch ignored the bind failure under TORCHELASTIC_USE_AGENT_STORE and rank 0 silently became a client of an unrelated socket, crashing ResNet/BERT DDP runs. Under torchrun, join the agent's store on MASTER_PORT as a client, matching torch.distributed.rendezvous; otherwise rank 0 hosts it on MASTER_PORT. MASTER_PORT is no longer modified, and a per-process sequence keeps the store keys of successive benchmarks apart. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../model_benchmarks/pytorch_base.py | 23 ++++++++--- .../model_benchmarks/test_pytorch_base.py | 40 +++++++++++++++++++ 2 files changed, 58 insertions(+), 5 deletions(-) diff --git a/superbench/benchmarks/model_benchmarks/pytorch_base.py b/superbench/benchmarks/model_benchmarks/pytorch_base.py index dd21db20e..ce6c45123 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_base.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_base.py @@ -30,6 +30,9 @@ class PytorchBase(ModelBenchmark): """The base class of Pytorch model benchmarks.""" + # Number of DDP stores created in this process; keeps the keys of successive benchmarks apart. + _store_seq = 0 + def __init__(self, name, parameters=''): """Constructor. @@ -354,16 +357,26 @@ def _init_distributed_setting(self): ' distributed implementation: {}.'.format(self._name, self._args.distributed_impl) ) return False - # torch >= 1.9.0a0 torch.distributed.elastic is used by default - port = int(os.environ.get('MASTER_PORT', '29500')) + 1 - os.environ['MASTER_PORT'] = str(port) + port = int(os.environ.get('MASTER_PORT', '29500')) addr = os.environ['MASTER_ADDR'] self._global_rank = int(os.environ['RANK']) self._local_rank = int(os.environ['LOCAL_RANK']) self._world_size = int(os.environ['WORLD_SIZE']) - logger.debug('ip:{},port:{},rank:{},world:{}'.format(addr, port, self._global_rank, self._world_size)) + # Under torchrun the agent already hosts a TCPStore on MASTER_PORT, so join it as a client, the + # same way torch.distributed.rendezvous does. Binding a new server on another port can collide + # with an ephemeral port, and torch ignores that bind failure under TORCHELASTIC_USE_AGENT_STORE. + use_agent_store = os.environ.get('TORCHELASTIC_USE_AGENT_STORE') == str(True) + is_master = not use_agent_store and self._global_rank == 0 + logger.debug( + 'ip:{},port:{},rank:{},world:{},agent_store:{}'.format( + addr, port, self._global_rank, self._world_size, use_agent_store + ) + ) + # The store can outlive one benchmark in the same process, so give each init its own key prefix. + PytorchBase._store_seq += 1 store = PrefixStore( - self._name, TCPStore(addr, port, self._world_size, self._global_rank == 0, timedelta(seconds=300)) + '{}/{}'.format(self._name, PytorchBase._store_seq), + TCPStore(addr, port, self._world_size, is_master, timedelta(seconds=300)) ) torch.distributed.init_process_group( backend=self._args.distributed_backend.value, diff --git a/tests/benchmarks/model_benchmarks/test_pytorch_base.py b/tests/benchmarks/model_benchmarks/test_pytorch_base.py index b397f7c6b..ba45f8cfa 100644 --- a/tests/benchmarks/model_benchmarks/test_pytorch_base.py +++ b/tests/benchmarks/model_benchmarks/test_pytorch_base.py @@ -3,7 +3,9 @@ """Tests for BenchmarkRegistry module.""" +import os import numbers +from unittest import mock import torch import transformers @@ -246,6 +248,44 @@ def test_pytorch_base(): assert (benchmark._postprocess()) +@decorator.pytorch_test +def test_pytorch_ddp_store(): + """Test the TCPStore used for DDP initialization with and without the torchrun agent store.""" + benchmark = PytorchMNIST('pytorch-mnist', parameters='--no_gpu') + assert (benchmark._preprocess()) + benchmark._args.distributed_impl = DistributedImpl.DDP + benchmark._args.distributed_backend = DistributedBackend.NCCL + module = 'superbench.benchmarks.model_benchmarks.pytorch_base' + base_env = {'WORLD_SIZE': '2', 'RANK': '0', 'LOCAL_RANK': '0', 'MASTER_ADDR': 'localhost', 'MASTER_PORT': '29600'} + + def init(env): + with mock.patch.dict(os.environ, env), \ + mock.patch(f'{module}.TCPStore') as tcp_store, \ + mock.patch(f'{module}.PrefixStore') as prefix_store, \ + mock.patch('torch.distributed.init_process_group') as init_process_group: + assert (benchmark._init_distributed_setting() is True) + assert (os.environ['MASTER_PORT'] == '29600') + assert (init_process_group.call_args.kwargs['store'] is prefix_store.return_value) + return tcp_store.call_args.args, prefix_store.call_args.args[0] + + # Under torchrun every rank, including rank 0, joins the agent store on MASTER_PORT. + for rank in ['0', '1']: + args, _ = init({**base_env, 'RANK': rank, 'TORCHELASTIC_USE_AGENT_STORE': 'True'}) + assert (args[:4] == ('localhost', 29600, 2, False)) + + # Without an agent store, rank 0 hosts the store on MASTER_PORT. + with mock.patch.dict(os.environ): + os.environ.pop('TORCHELASTIC_USE_AGENT_STORE', None) + args, first_prefix = init(base_env) + assert (args[:4] == ('localhost', 29600, 2, True)) + args, second_prefix = init({**base_env, 'RANK': '1', 'TORCHELASTIC_USE_AGENT_STORE': 'False'}) + assert (args[:4] == ('localhost', 29600, 2, False)) + + # Each initialization uses a distinct key prefix. + assert (first_prefix.startswith('pytorch-mnist/')) + assert (first_prefix != second_prefix) + + @decorator.cuda_test @decorator.pytorch_test def test_pytorch_empty_cache():