From d557aa9aa43268da93ab15e83451029a236f9c76 Mon Sep 17 00:00:00 2001 From: "Nguyen Vuong (from Dev Box)" Date: Mon, 23 Nov 2026 17:45:04 -0800 Subject: [PATCH 1/2] Benchmarks - Add pytorch-simplenet model and support CPU-only DDP over gloo Add the pytorch-simplenet model benchmark: the small CIFAR-10 CNN from the PyTorch tutorial on synthetic 3x32x32 images, used for lightweight DDP smoke tests. Make torch.distributed DDP work on CPU-only nodes: - runner: use distributed_backend from the benchmark parameters in torch.distributed mode instead of always forcing nccl. - pytorch_base: do not pass device_ids/output_device to DistributedDataParallel for CPU modules, which PyTorch rejects. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/superbench-config.mdx | 3 + .../benchmarks/model-benchmarks.md | 3 + .../benchmarks/model_benchmarks/__init__.py | 5 +- .../model_benchmarks/pytorch_base.py | 10 +- .../model_benchmarks/pytorch_simplenet.py | 88 +++++++++++++ superbench/runner/runner.py | 6 +- .../test_pytorch_simplenet.py | 121 ++++++++++++++++++ tests/runner/test_runner.py | 33 +++++ 8 files changed, 263 insertions(+), 6 deletions(-) create mode 100644 superbench/benchmarks/model_benchmarks/pytorch_simplenet.py create mode 100644 tests/benchmarks/model_benchmarks/test_pytorch_simplenet.py diff --git a/docs/superbench-config.mdx b/docs/superbench-config.mdx index feebef6d6..dc8a1f30e 100644 --- a/docs/superbench-config.mdx +++ b/docs/superbench-config.mdx @@ -328,6 +328,7 @@ A list of models to run, only supported in model-benchmark. shufflenet_v2_x0_5 | shufflenet_v2_x1_0 | shufflenet_v2_x1_5 | shufflenet_v2_x2_0 | squeezenet1_0 | squeezenet1_1 | vgg11 | vgg11_bn | vgg13 | vgg13_bn | vgg16 | vgg16_bn | vgg19_bn | vgg19 | + simplenet | bert-base | bert-large | gpt2-small | gpt2-medium | gpt2-large | gpt2-xl | llama2-7b | llama2-13b | llama2-70b | mixtral-8x7b | mixtral-8x22b ] @@ -392,6 +393,8 @@ parallel: yes Mode name to use. Here lists available modes: + `local`: run benchmark as local process. + `torch.distributed`: launch benchmark through [PyTorch DDP](https://pytorch.org/docs/stable/distributed.html#launch-utility), each process will run on one GPU. + The `nccl` backend is used unless the benchmark sets `distributed_backend` in its `parameters`, + e.g. `distributed_backend: gloo` together with `no_gpu: yes` for CPU-only training. + `mpi`: launch benchmark through MPI, the benchmark implementation could leverage MPI interface. Some attributes may only be suitable for specific mode. diff --git a/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index c782abbcc..96091ab8a 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -28,6 +28,9 @@ including the following categories: * shufflenet: shufflenet_v2_x0_5, shufflenet_v2_x1_0, shufflenet_v2_x1_5, shufflenet_v2_x2_0 * squeezenet: squeezenet1_0, squeezenet1_1 * others: alexnet, googlenet, inception_v3 +* SimpleNet: simplenet, the small CNN from the PyTorch CIFAR-10 tutorial (two convolution and three fully-connected + layers) on synthetic 3x32x32 images with 10 classes. It is lightweight enough for DDP smoke tests on CPU-only nodes, + e.g. with `no_gpu: yes` and `distributed_backend: gloo` in `torch.distributed` mode. For inference, supported percentiles include 50th, 90th, 95th, 99th, and 99.9th. diff --git a/superbench/benchmarks/model_benchmarks/__init__.py b/superbench/benchmarks/model_benchmarks/__init__.py index 818469822..f8a0d77cf 100644 --- a/superbench/benchmarks/model_benchmarks/__init__.py +++ b/superbench/benchmarks/model_benchmarks/__init__.py @@ -7,14 +7,15 @@ from superbench.benchmarks.model_benchmarks.pytorch_bert import PytorchBERT from superbench.benchmarks.model_benchmarks.pytorch_gpt2 import PytorchGPT2 from superbench.benchmarks.model_benchmarks.pytorch_cnn import PytorchCNN +from superbench.benchmarks.model_benchmarks.pytorch_simplenet import PytorchSimpleNet from superbench.benchmarks.model_benchmarks.pytorch_lstm import PytorchLSTM from superbench.benchmarks.model_benchmarks.megatron_gpt3 import MegatronGPT from superbench.benchmarks.model_benchmarks.pytorch_llama import PytorchLlama from superbench.benchmarks.model_benchmarks.pytorch_mixtral import PytorchMixtral __all__ = [ - 'ModelBenchmark', 'PytorchBERT', 'PytorchGPT2', 'PytorchCNN', 'PytorchLSTM', 'MegatronGPT', 'PytorchLlama', - 'PytorchMixtral' + 'ModelBenchmark', 'PytorchBERT', 'PytorchGPT2', 'PytorchCNN', 'PytorchSimpleNet', 'PytorchLSTM', 'MegatronGPT', + 'PytorchLlama', 'PytorchMixtral' ] if PytorchMixtral is not None: diff --git a/superbench/benchmarks/model_benchmarks/pytorch_base.py b/superbench/benchmarks/model_benchmarks/pytorch_base.py index 7810b982d..781fa0ae8 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_base.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_base.py @@ -437,9 +437,13 @@ def _create_optimizer(self): True if optimizer instance is created successfully. """ if self._args.distributed_impl == DistributedImpl.DDP: - self._model = torch.nn.parallel.DistributedDataParallel( - self._model, device_ids=[self._local_rank], output_device=self._local_rank - ) + if self._gpu_available: + self._model = torch.nn.parallel.DistributedDataParallel( + self._model, device_ids=[self._local_rank], output_device=self._local_rank + ) + else: + # DDP rejects device_ids/output_device for CPU modules, e.g. CPU-only training over gloo. + self._model = torch.nn.parallel.DistributedDataParallel(self._model) if self._optimizer_type == Optimizer.SGD: self._optimizer = torch.optim.SGD( diff --git a/superbench/benchmarks/model_benchmarks/pytorch_simplenet.py b/superbench/benchmarks/model_benchmarks/pytorch_simplenet.py new file mode 100644 index 000000000..592e9e63a --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/pytorch_simplenet.py @@ -0,0 +1,88 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Module of the Pytorch SimpleNet model.""" + +import torch + +from superbench.common.utils import logger +from superbench.benchmarks import BenchmarkRegistry +from superbench.benchmarks.model_benchmarks.pytorch_cnn import PytorchCNN + + +class SimpleNet(torch.nn.Module): + """Small CNN with two convolution and three fully-connected layers for 3x32x32 images (e.g. CIFAR-10). + + It is the network from the PyTorch CIFAR-10 tutorial, commonly used as a lightweight DDP smoke test. + """ + image_size = 32 + + def __init__(self, num_classes): + """Constructor. + + Args: + num_classes (int): Number of output classes. + """ + super().__init__() + self.conv1 = torch.nn.Conv2d(3, 6, 5) + self.pool = torch.nn.MaxPool2d(2, 2) + self.conv2 = torch.nn.Conv2d(6, 16, 5) + self.fc1 = torch.nn.Linear(16 * 5 * 5, 120) + self.fc2 = torch.nn.Linear(120, 84) + self.fc3 = torch.nn.Linear(84, num_classes) + + def forward(self, x): + """Forward propagation function. + + Args: + x (torch.Tensor): Input images, shape (batch_size, 3, 32, 32). + + Return: + torch.Tensor: Logits, shape (batch_size, num_classes). + """ + x = self.pool(torch.nn.functional.relu(self.conv1(x))) + x = self.pool(torch.nn.functional.relu(self.conv2(x))) + x = torch.flatten(x, 1) + x = torch.nn.functional.relu(self.fc1(x)) + x = torch.nn.functional.relu(self.fc2(x)) + return self.fc3(x) + + +class PytorchSimpleNet(PytorchCNN): + """The SimpleNet benchmark class, trained on synthetic 3x32x32 images.""" + def _create_model(self, precision): + """Construct the model for benchmarking. + + Args: + precision (Precision): precision of model and input data, such as float32, float16. + """ + if self._args.image_size != SimpleNet.image_size: + logger.error( + 'SimpleNet only supports image size {} - model: {}, image size: {}.'.format( + SimpleNet.image_size, self._name, self._args.image_size + ) + ) + return False + + try: + self._model = SimpleNet(self._args.num_classes) + self._model = self._model.to(dtype=getattr(torch, precision.value)) + if self._gpu_available: + self._model = self._model.cuda() + except BaseException as e: + logger.error( + 'Create model with specified precision failed - model: {}, precision: {}, message: {}.'.format( + self._name, precision, str(e) + ) + ) + return False + + self._target = self._create_target(self._args.num_classes) + + return True + + +# Register SimpleNet benchmark. +BenchmarkRegistry.register_benchmark( + 'pytorch-simplenet', PytorchSimpleNet, parameters='--model_type simplenet --image_size 32 --num_classes 10' +) diff --git a/superbench/runner/runner.py b/superbench/runner/runner.py index 7a8fd4417..7b786d3dd 100644 --- a/superbench/runner/runner.py +++ b/superbench/runner/runner.py @@ -219,12 +219,16 @@ def __get_mode_command(self, benchmark_name, mode, timeout=None): benchmark_name, '', enable_nsys, enable_rocprof, trace_dir, rocprof_trace_dir ) + # Use the backend configured in the benchmark parameters (e.g. gloo for CPU-only training), + # defaulting to nccl. + benchmark_params = self._sb_benchmarks.get(benchmark_name, {}).get('parameters', {}) + distributed_backend = benchmark_params.get('distributed_backend', 'nccl') mode_command = ( f'{trace_prefix}' f'torchrun' f' --no_python --nproc_per_node={mode.proc_num} {torch_dist_params}{exec_command}' f' superbench.benchmarks.{benchmark_name}.parameters.distributed_impl=ddp' - f' superbench.benchmarks.{benchmark_name}.parameters.distributed_backend=nccl' + f' superbench.benchmarks.{benchmark_name}.parameters.distributed_backend={distributed_backend}' ) elif mode.name == 'mpi': trace_command = self.__build_trace_command( diff --git a/tests/benchmarks/model_benchmarks/test_pytorch_simplenet.py b/tests/benchmarks/model_benchmarks/test_pytorch_simplenet.py new file mode 100644 index 000000000..ba87270e7 --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_pytorch_simplenet.py @@ -0,0 +1,121 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Tests for SimpleNet model benchmarks.""" + +import os +import socket +from unittest import mock + +from tests.helper import decorator +from superbench.benchmarks import BenchmarkRegistry, Platform, Framework, BenchmarkType, ReturnCode +from superbench.benchmarks.model_benchmarks.pytorch_simplenet import PytorchSimpleNet + + +def _free_port(): + """Get a free local TCP port. + + Return: + int: Port number. + """ + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + sock.bind(('localhost', 0)) + return sock.getsockname()[1] + + +def run_pytorch_simplenet(parameters='', check_metrics=None): + """Run pytorch simplenet benchmark and check its results. + + Args: + parameters (str): Benchmark parameters. + check_metrics (list): Metrics which should be reported for every step. + + Return: + PytorchSimpleNet: The benchmark after running. + """ + context = BenchmarkRegistry.create_benchmark_context( + 'simplenet', platform=Platform.CUDA, parameters=parameters, framework=Framework.PYTORCH + ) + assert (BenchmarkRegistry.is_benchmark_context_valid(context)) + + benchmark = BenchmarkRegistry.launch_benchmark(context) + + # Check basic information. + assert (benchmark) + assert (isinstance(benchmark, PytorchSimpleNet)) + assert (benchmark.name == 'pytorch-simplenet') + assert (benchmark.type == BenchmarkType.MODEL) + + # Check predefined parameters. + assert (benchmark._args.model_type == 'simplenet') + assert (benchmark._args.image_size == 32) + assert (benchmark._args.num_classes == 10) + + # Check results and metrics. + assert (benchmark.run_count == 1) + assert (benchmark.return_code == ReturnCode.SUCCESS) + for metric in check_metrics or []: + assert (len(benchmark.raw_data[metric]) == benchmark.run_count) + assert (len(benchmark.raw_data[metric][0]) == benchmark._args.num_steps) + assert (len(benchmark.result[metric]) == benchmark.run_count) + return benchmark + + +@decorator.cuda_test +@decorator.pytorch_test +def test_pytorch_simplenet_with_gpu(): + """Test pytorch simplenet benchmark with GPU.""" + run_pytorch_simplenet( + parameters='--batch_size 4 --num_warmup 2 --num_steps 4 --model_action train inference', + check_metrics=[ + 'fp32_train_step_time', 'fp32_train_throughput', 'fp16_train_step_time', 'fp16_train_throughput', + 'fp32_inference_step_time', 'fp32_inference_throughput', 'fp16_inference_step_time', + 'fp16_inference_throughput' + ] + ) + + +@decorator.pytorch_test +def test_pytorch_simplenet_no_gpu(): + """Test pytorch simplenet benchmark with CPU.""" + benchmark = run_pytorch_simplenet( + parameters='--batch_size 4 --num_warmup 2 --num_steps 4 --model_action train inference ' + '--precision float32 --no_gpu', + check_metrics=[ + 'fp32_train_step_time', 'fp32_train_throughput', 'fp32_inference_step_time', 'fp32_inference_throughput' + ] + ) + # Check Dataset. + assert (len(benchmark._dataset) == benchmark._args.sample_count * benchmark._world_size) + + +@decorator.pytorch_test +def test_pytorch_simplenet_ddp_gloo_no_gpu(): + """Test pytorch simplenet benchmark with CPU-only DDP over gloo.""" + env = { + 'MASTER_ADDR': 'localhost', + 'MASTER_PORT': str(_free_port()), + 'WORLD_SIZE': '1', + 'RANK': '0', + 'LOCAL_RANK': '0', + } + with mock.patch.dict(os.environ, env): + run_pytorch_simplenet( + parameters='--batch_size 4 --num_warmup 2 --num_steps 4 --model_action train --precision float32 ' + '--no_gpu --distributed_impl ddp --distributed_backend gloo', + check_metrics=['fp32_train_step_time', 'fp32_train_throughput'] + ) + + +@decorator.pytorch_test +def test_pytorch_simplenet_invalid_image_size(): + """Test pytorch simplenet benchmark with an unsupported image size.""" + context = BenchmarkRegistry.create_benchmark_context( + 'simplenet', + platform=Platform.CUDA, + parameters='--image_size 64 --num_steps 2 --precision float32 --no_gpu', + framework=Framework.PYTORCH + ) + benchmark = BenchmarkRegistry.launch_benchmark(context) + assert (benchmark) + assert (benchmark.return_code == ReturnCode.MODEL_CREATION_FAILURE) diff --git a/tests/runner/test_runner.py b/tests/runner/test_runner.py index 6a718c2c2..53e84dbae 100644 --- a/tests/runner/test_runner.py +++ b/tests/runner/test_runner.py @@ -499,6 +499,39 @@ def test_generate_metric_name(self): ), test_case['expected'] ) + def test_get_mode_command_torch_distributed_backend(self): + """Test __get_mode_command honors distributed_backend from benchmark parameters.""" + self.runner._sb_benchmarks = OmegaConf.create( + { + 'cpu_bench': { + 'parameters': { + 'distributed_backend': 'gloo', + 'no_gpu': True + } + }, + 'gpu_bench': { + 'parameters': { + 'batch_size': 32 + } + }, + } + ) + mode = OmegaConf.create({'name': 'torch.distributed', 'proc_num': 1, 'node_num': 'all'}) + for benchmark_name, backend in [('cpu_bench', 'gloo'), ('gpu_bench', 'nccl'), ('missing_bench', 'nccl')]: + with self.subTest(benchmark_name=benchmark_name): + self.assertEqual( + self.runner._SuperBenchRunner__get_mode_command(benchmark_name, mode), ( + 'torchrun ' + '--no_python --nproc_per_node=1 ' + '--nnodes=$NNODES --node_rank=$NODE_RANK ' + '--master_addr=$MASTER_ADDR --master_port=$MASTER_PORT ' + f'sb exec --output-dir {self.sb_output_dir} -c sb.config.yaml ' + f'-C superbench.enable={benchmark_name} ' + f'superbench.benchmarks.{benchmark_name}.parameters.distributed_impl=ddp ' + f'superbench.benchmarks.{benchmark_name}.parameters.distributed_backend={backend}' + ) + ) + def test_run_proc_timeout(self): """Test run_proc_ timeout.""" self.runner._sb_benchmarks = { From bdbf18f3b71aedc69cf91e42b897293714374b43 Mon Sep 17 00:00:00 2001 From: "Nguyen Vuong (from Dev Box)" Date: Mon, 30 Nov 2026 14:48:47 -0800 Subject: [PATCH 2/2] Bugfix - Fall back to nccl for null distributed parameters in torch.distributed mode Null benchmark parameters or a null distributed_backend now default to nccl instead of raising AttributeError or passing distributed_backend=None, matching the executor skipping null values. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- superbench/runner/runner.py | 7 ++++--- tests/runner/test_runner.py | 16 +++++++++++++++- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/superbench/runner/runner.py b/superbench/runner/runner.py index 7b786d3dd..bdf9e1edb 100644 --- a/superbench/runner/runner.py +++ b/superbench/runner/runner.py @@ -220,9 +220,10 @@ def __get_mode_command(self, benchmark_name, mode, timeout=None): ) # Use the backend configured in the benchmark parameters (e.g. gloo for CPU-only training), - # defaulting to nccl. - benchmark_params = self._sb_benchmarks.get(benchmark_name, {}).get('parameters', {}) - distributed_backend = benchmark_params.get('distributed_backend', 'nccl') + # defaulting to nccl. Null parameters or a null backend also fall back to nccl, as the executor skips + # null values. + benchmark_params = (self._sb_benchmarks.get(benchmark_name) or {}).get('parameters') or {} + distributed_backend = benchmark_params.get('distributed_backend') or 'nccl' mode_command = ( f'{trace_prefix}' f'torchrun' diff --git a/tests/runner/test_runner.py b/tests/runner/test_runner.py index 53e84dbae..baae595fb 100644 --- a/tests/runner/test_runner.py +++ b/tests/runner/test_runner.py @@ -514,10 +514,24 @@ def test_get_mode_command_torch_distributed_backend(self): 'batch_size': 32 } }, + 'null_params_bench': { + 'parameters': None + }, + 'null_backend_bench': { + 'parameters': { + 'distributed_backend': None + } + }, } ) mode = OmegaConf.create({'name': 'torch.distributed', 'proc_num': 1, 'node_num': 'all'}) - for benchmark_name, backend in [('cpu_bench', 'gloo'), ('gpu_bench', 'nccl'), ('missing_bench', 'nccl')]: + for benchmark_name, backend in [ + ('cpu_bench', 'gloo'), + ('gpu_bench', 'nccl'), + ('missing_bench', 'nccl'), + ('null_params_bench', 'nccl'), + ('null_backend_bench', 'nccl'), + ]: with self.subTest(benchmark_name=benchmark_name): self.assertEqual( self.runner._SuperBenchRunner__get_mode_command(benchmark_name, mode), (