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
46 changes: 34 additions & 12 deletions docs/user-tutorial/benchmarks/micro-benchmarks.md
Original file line number Diff line number Diff line change
Expand Up @@ -441,22 +441,44 @@ For measurements of peer-to-peer communication performance between AMD GPUs, GPU

#### Introduction

Measure the memory bandwidth of GPU using the STREAM benchmark. The benchmark tests various memory operations including copy, scale, add, and triad for double and float datatypes.
Measures Copy, Scale, Add, and Triad memory bandwidth for one `data_type` (`float` or `double`, default `double`). Use a separate benchmark entry for each data type.

__Note__: When `--check_data` is enabled, each process allocates 6× `--size` bytes of host memory (data\_buf + check\_buf + 4 validation buffers, e.g. 24 GiB with the default 4 GiB `--size`). Under `default_local_mode` with 8 GPUs this totals ~192 GiB of host RAM. Recommend using a small `--size` such as `1048576` (1 MiB) when `--check_data` is enabled.
By default, each operation sweeps block sizes (128, 256, 512, 1024) and unroll factors (1, 2, 3, 4, 6, 8) and reports the best result. `kernel_configs` sets `block_size` and `unroll` per operation as inline JSON; unlisted operations still sweep. `size` is bytes per array (default 8 GiB). `check_data` validates output outside timing and needs 6x `size` in host memory, so use small size like 1048576.

Native sweep:

```yaml
gpu-stream:fp64:
<<: *default_local_mode
parameters:
data_type: double
```

Fixed launch configuration:

```yaml
gpu-stream:fp64:
<<: *default_local_mode
parameters:
data_type: double
size: 4294967296
kernel_configs: >-
'{
"STREAM_COPY_double": {"block_size": 256, "unroll": 2},
"STREAM_SCALE_double": {"block_size": 256, "unroll": 2},
"STREAM_ADD_double": {"block_size": 256, "unroll": 2},
"STREAM_TRIAD_double": {"block_size": 256, "unroll": 2}
}'
```

#### Metrics

| Metric Name | Unit | Description |
|------------------------------------------------------------|------------------|-----------------------------------------------------------------------------------------------------------------------------------------|
| STREAM\_COPY\_(double\|float)\_buffer\_[0-9]+\_block\_[0-9]+\_bw | bandwidth (GB/s) | The memory bandwidth of the GPU for the copy operation with the selected data type (double for fp64, float for fp32), for the specified buffer size and block size. |
| STREAM\_SCALE\_(double\|float)\_buffer\_[0-9]+\_block\_[0-9]+\_bw | bandwidth (GB/s) | The memory bandwidth of the GPU for the scale operation with the selected data type (double for fp64, float for fp32), for the specified buffer size and block size. |
| STREAM\_ADD\_(double\|float)\_buffer\_[0-9]+\_block\_[0-9]+\_bw | bandwidth (GB/s) | The memory bandwidth of the GPU for the add operation with the selected data type (double for fp64, float for fp32), for the specified buffer size and block size. |
| STREAM\_TRIAD\_(double\|float)\_buffer\_[0-9]+\_block\_[0-9]+\_bw | bandwidth (GB/s) | The memory bandwidth of the GPU for the triad operation with the selected data type (double for fp64, float for fp32), for the specified buffer size and block size. |
| STREAM\_COPY\_(double\|float)\_buffer\_[0-9]+\_block\_[0-9]+\_ratio | Efficiency (%) | The memory bandwidth efficiency of the GPU for the copy operation with the selected data type (double for fp64, float for fp32), for the specified buffer size and block size. |
| STREAM\_SCALE\_(double\|float)\_buffer\_[0-9]+\_block\_[0-9]+\_ratio | Efficiency (%) | The memory bandwidth efficiency of the GPU for the scale operation with the selected data type (double for fp64, float for fp32), for the specified buffer size and block size. |
| STREAM\_ADD\_(double\|float)\_buffer\_[0-9]+\_block\_[0-9]+\_ratio | Efficiency (%) | The memory bandwidth efficiency of the GPU for the add operation with the selected data type (double for fp64, float for fp32), for the specified buffer size and block size. |
| STREAM\_TRIAD\_(double\|float)\_buffer\_[0-9]+\_block\_[0-9]+\_ratio | Efficiency (%) | The memory bandwidth efficiency of the GPU for the triad operation with the selected data type (double for fp64, float for fp32), for the specified buffer size and block size. |
| Metric Name | Unit | Description |
|-------------|------|-------------|
| STREAM\_(COPY\|SCALE\|ADD\|TRIAD)\_(double\|float)\_bw | GB/s | Bandwidth with the configured launch, or the best bandwidth from the sweep. |
| STREAM\_(COPY\|SCALE\|ADD\|TRIAD)\_(double\|float)\_ratio | % | Bandwidth as a percentage of theoretical peak; -1 if peak is unavailable. |

For example: `gpu-stream:fp64/STREAM_ADD_double_bw`. Selected launch parameters stay in raw output.

### `ib-loopback`

Expand Down
9 changes: 4 additions & 5 deletions examples/benchmarks/gpu_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,18 @@

Commands to run:
python3 examples/benchmarks/gpu_stream.py

Omit kernel_configs to autotune; supply --kernel_configs with a quoted JSON
mapping of workload tags to block_size/unroll overrides to skip tuning.
"""

from superbench.benchmarks import BenchmarkRegistry, Platform
from superbench.common.utils import logger

if __name__ == '__main__':
context = BenchmarkRegistry.create_benchmark_context(
'gpu-stream', platform=Platform.CUDA, parameters='--num_warm_up 1 --num_loops 10 --data_type double'
'gpu-stream', platform=Platform.CUDA, parameters='--num_warm_up 10 --num_loops 40 --data_type double'
)
# For ROCm environment, please specify the benchmark name and the platform as the following.
# context = BenchmarkRegistry.create_benchmark_context(
# 'gpu-stream', platform=Platform.ROCM, parameters='--num_warm_up 1 --num_loops 10'
# )
# To enable data checking, please add '--check_data'.

benchmark = BenchmarkRegistry.launch_benchmark(context)
Expand Down
207 changes: 124 additions & 83 deletions superbench/benchmarks/micro_benchmarks/gpu_stream.py
Original file line number Diff line number Diff line change
@@ -1,129 +1,170 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

"""Module of the GPU Stream Performance benchmark."""
"""GPU STREAM bandwidth with inline launch overrides and a fixed fallback sweep."""

import json
import math
import os
import re
import shlex

from superbench.common.utils import logger
from superbench.benchmarks import BenchmarkRegistry, Platform, ReturnCode
from superbench.benchmarks.micro_benchmarks import MicroBenchmarkWithInvoke

_OPERATIONS = ['copy', 'scale', 'add', 'triad']
_BLOCKS = [128, 256, 512, 1024]
_UNROLLS = [1, 2, 3, 4, 6, 8]
_DEFAULT_SIZE = 8 * 1024**3
_TAG = re.compile(r'^STREAM_(COPY|SCALE|ADD|TRIAD)_(float|double)$')


class GpuStreamBenchmark(MicroBenchmarkWithInvoke):
"""The GPU stream performance benchmark class."""
"""Report one bandwidth per operation and datatype."""
def __init__(self, name, parameters=''):
"""Constructor.

Args:
name (str): benchmark name.
parameters (str): benchmark parameters.
"""
"""Initialize the native benchmark."""
super().__init__(name, parameters)

self._bin_name = 'gpu_stream'
self._command_targets = []

def add_parser_arguments(self):
"""Add the specified arguments."""
"""Retain the normal benchmark arguments; search dimensions are fixed."""
super().add_parser_arguments()

self._parser.add_argument(
'--size',
type=int,
default=4096 * 1024**2,
required=False,
help='Size of data buffer in bytes.',
)

self._parser.add_argument(
'--num_warm_up',
type=int,
default=20,
required=False,
help='Number of warm up rounds',
'--kernel_configs',
type=str,
default=None,
help='JSON mapping of workload tags to block_size/unroll. Omit to autotune.'
)

self._parser.add_argument(
'--num_loops',
'--size',
type=int,
default=100,
required=False,
help='Number of data buffer copies performed.',
default=_DEFAULT_SIZE,
help='Bytes per array, independent of launch overrides (default: 8 GiB).'
)

self._parser.add_argument('--num_warm_up', type=int, default=20)
self._parser.add_argument('--num_loops', type=int, default=100)
self._parser.add_argument(
'--data_type',
type=str,
default='double',
choices=['float', 'double'],
required=False,
help='Data type of the buffer elements.',
default='double',
help='Element type; use one benchmark entry per data type.'
)

self._parser.add_argument(
'--check_data',
action='store_true',
help='Enable data checking. Note: allocates 6x --size bytes of host memory per process '
'(data_buf + check_buf + 4 validation buffers, e.g. 24 GiB with default 4 GiB --size). '
'Recommend using a small --size such as 1048576 (1 MiB) when this flag is enabled.',
help='Validate output. Requires 6x buffer size in host memory; use small sizes.'
)

def _preprocess(self):
"""Preprocess/preparation operations before the benchmarking.
@staticmethod
def _check_config(tag, config):
"""Check only the parameters needed to launch a workload."""
match = _TAG.fullmatch(tag)
if match is None or not isinstance(config, dict):
raise ValueError('Invalid workload configuration key: {}'.format(tag))
if set(config) != {'block_size', 'unroll'} or any(type(value) is not int for value in config.values()):
raise ValueError('{} needs integer block_size and unroll'.format(tag))
if config['block_size'] not in _BLOCKS or config['unroll'] not in _UNROLLS:
raise ValueError('Unsupported block size/unroll for {}'.format(tag))

def _kernel_configs(self):
"""Load explicit workload overrides for the selected data type only."""
if self._args.kernel_configs is None:
return {}
configs = json.loads(self._args.kernel_configs)
if not isinstance(configs, dict):
raise ValueError('Expected a workload-tag to configuration mapping')
for tag, config in configs.items():
self._check_config(tag, config)
if not tag.endswith('_' + self._args.data_type):
raise ValueError('{} does not match data_type {}'.format(tag, self._args.data_type))
return configs

def _command(self, dtype, operation, size, config=None):
"""Use singleton native parameters for overrides, or the native fixed sweep."""
parts = [
shlex.quote(self.__bin_path),
'--size',
str(size),
'--data_type',
dtype,
'--operation',
operation,
'--num_warm_up',
str(self._args.num_warm_up),
'--num_loops',
str(self._args.num_loops),
]
if config:
parts.extend(['--block_size', str(config['block_size']), '--unroll', str(config['unroll'])])
if self._args.check_data:
parts.append('--check_data')
return ' '.join(parts)

Return:
True if _preprocess() succeed.
"""
def _preprocess(self):
"""Resolve size once, independently of workload launch overrides."""
if not super()._preprocess():
return False

self.__bin_path = os.path.join(self._args.bin_dir, self._bin_name)

args = '--size %d --num_warm_up %d --num_loops %d --data_type %s' % (
self._args.size, self._args.num_warm_up, self._args.num_loops, self._args.data_type
)

if self._args.check_data:
args += ' --check_data'

self._commands = ['%s %s' % (self.__bin_path, args)]

self._commands, self._command_targets = [], []
try:
if (
self._args.num_warm_up < 0 or self._args.num_loops <= 0
or self._args.num_warm_up + self._args.num_loops >= 2**64
):
raise ValueError('Invalid warm-up/loop counts')
width = 4 if self._args.data_type == 'float' else 8
if not 0 < self._args.size < 2**64 or self._args.size % width:
raise ValueError('Size must be a positive multiple of {} bytes'.format(width))
configs = self._kernel_configs()
size, dtype = self._args.size, self._args.data_type
commands, targets = [], []
if not configs:
commands.append(self._command(dtype, 'all', size))
targets.append({'STREAM_{}_{}'.format(op.upper(), dtype) for op in _OPERATIONS})
else:
for operation in _OPERATIONS:
tag = 'STREAM_{}_{}'.format(operation.upper(), dtype)
commands.append(self._command(dtype, operation, size, configs.get(tag)))
targets.append({tag})
self._commands, self._command_targets = commands, targets
except ValueError as error:
self._result.set_return_code(ReturnCode.INVALID_ARGUMENT)
logger.error('Invalid GPU STREAM configuration: {}.'.format(error))
return False
return True

def _process_raw_result(self, cmd_idx, raw_output):
"""Function to parse raw results and save the summarized results.

self._result.add_raw_data() and self._result.add_result() need to be called to save the results.

Args:
cmd_idx (int): the index of command corresponding with the raw_output.
raw_output (str): raw output string of the micro-benchmark.

Return:
True if the raw output string is valid and result can be extracted.
"""
"""Read only canonical native winners; launch details stay in raw output."""
self._result.add_raw_data('raw_output_' + str(cmd_idx), raw_output, self._args.log_raw_data)

try:
output_lines = [x.strip() for x in raw_output.strip().splitlines()]
count = 0
for output_line in output_lines:
if output_line.startswith('STREAM_'):
count += 1
tag, bw_str, ratio = output_line.split()
self._result.add_result(tag + '_bw', float(bw_str))
self._result.add_result(tag + '_ratio', float(ratio))
if count == 0:
raise BaseException('No valid results found.')
except BaseException as e:
if not 0 <= cmd_idx < len(self._commands):
raise ValueError('Unexpected command index')
results = {}
for line in raw_output.splitlines():
if not line.startswith('STREAM_'):
continue
fields = line.split()
if len(fields) != 3 or _TAG.fullmatch(fields[0]) is None or fields[0] in results:
raise ValueError('Invalid or duplicate canonical result')
tag, bandwidth, ratio = fields
bandwidth, ratio = float(bandwidth), float(ratio)
if (
not math.isfinite(bandwidth) or bandwidth <= 0 or not math.isfinite(ratio)
or (ratio < 0 and ratio != -1)
):
raise ValueError('Invalid bandwidth/efficiency for {}'.format(tag))
results[tag] = bandwidth, ratio
if set(results) != self._command_targets[cmd_idx]:
raise ValueError('Missing or unexpected workload results')
for tag, (bandwidth, ratio) in sorted(results.items()):
self._result.add_result(tag + '_bw', bandwidth)
self._result.add_result(tag + '_ratio', ratio)
except ValueError as error:
self._result.set_return_code(ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE)
logger.error(
'The result format is invalid - round: {}, benchmark: {}, raw output: {}, message: {}.'.format(
self._curr_run_index, self._name, raw_output, str(e)
)
)
logger.error('Invalid GPU STREAM output: {}.'.format(error))
return False

return True


Expand Down
Loading
Loading