From c8030384bd78e0948d8cec8cbfc4ae1548515191 Mon Sep 17 00:00:00 2001 From: Shenghsun Cho Date: Wed, 28 Oct 2026 19:22:28 +0000 Subject: [PATCH 1/4] fix(profiler): Preserve Configuration-Specific PyTorch Traces Derive the benchmark configuration from the executor's benchmarks//rank working directory and retain an independent configuration-qualified copy after writing the legacy trace. Preserve legacy filenames and last-write behavior, and retain legacy-only output outside the recognized executor layout. Validated on MI300X and GB200: successful configuration/rank captures remain distinct and legacy copies match the last corresponding capture. The unchanged diagnosis converter preserves old-baseline/new-target conversion results. Focused exporter checks, YAPF, and Flake8 pass. --- superbench/benchmarks/model_benchmarks/pytorch_base.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/superbench/benchmarks/model_benchmarks/pytorch_base.py b/superbench/benchmarks/model_benchmarks/pytorch_base.py index 7810b982d..d98240513 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_base.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_base.py @@ -4,6 +4,7 @@ """Module of the Pytorch model-benchmark base class.""" import os +import shutil import statistics import time from datetime import timedelta @@ -628,6 +629,12 @@ def _benchmark(self): # ROCm 6.3.4). dump_file_dir = os.environ.get('SB_TORCH_PROFILER_TRACE_DIR', '.') diag_agent_dump_file_path = f'{dump_file_dir}/torch-profiler-sb-{self._name}-{local_rank}.json' + benchmark_dir, rank_dir = os.path.split(os.getcwd()) + config_name = os.path.basename(benchmark_dir) + has_config_name = ( + os.path.basename(os.path.dirname(benchmark_dir)) == 'benchmarks' and rank_dir.startswith('rank') + and rank_dir[4:].isdigit() + ) diag_agent_prof.__enter__() ret = super()._benchmark() @@ -648,6 +655,9 @@ def _benchmark(self): diag_agent_events.append(diag_agent_event) with open(diag_agent_dump_file_path, 'w') as f: json.dump(diag_agent_events, f, sort_keys=True) + if has_config_name: + config_trace_path = f'{dump_file_dir}/torch-profiler-sb-{self._name}__cfg={config_name}-{local_rank}.json' + shutil.copyfile(diag_agent_dump_file_path, config_trace_path) # Handle post-run model log save/compare regardless of profiling self._post_run_model_log() From 1f0242fea01259016c4a58e0e01babb282d8cb4c Mon Sep 17 00:00:00 2001 From: Shenghsun Cho Date: Wed, 28 Oct 2026 20:16:03 +0000 Subject: [PATCH 2/4] fix(profiler): Isolate Qualified Traces Between Local Workers Use the validated executor-directory rank for configuration-qualified filenames. Serialize each worker's own events directly to its qualified file so concurrent writes to the shared legacy file cannot corrupt the preserved trace. Keep legacy filenames and writes unchanged. Validation: six CUDA/HIP mocked exporter race and rank checks, five legacy compatibility checks against the pre-PR exporter, and the existing PyTorch base CPU unit test pass. One CUDA-only test was skipped. YAPF, Flake8, scoped mypy, and whitespace checks pass. No hardware captures were rerun for this revision. --- superbench/benchmarks/model_benchmarks/pytorch_base.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/superbench/benchmarks/model_benchmarks/pytorch_base.py b/superbench/benchmarks/model_benchmarks/pytorch_base.py index d98240513..0c8410d62 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_base.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_base.py @@ -4,7 +4,6 @@ """Module of the Pytorch model-benchmark base class.""" import os -import shutil import statistics import time from datetime import timedelta @@ -656,8 +655,9 @@ def _benchmark(self): with open(diag_agent_dump_file_path, 'w') as f: json.dump(diag_agent_events, f, sort_keys=True) if has_config_name: - config_trace_path = f'{dump_file_dir}/torch-profiler-sb-{self._name}__cfg={config_name}-{local_rank}.json' - shutil.copyfile(diag_agent_dump_file_path, config_trace_path) + config_trace_path = f'{dump_file_dir}/torch-profiler-sb-{self._name}__cfg={config_name}-{rank_dir[4:]}.json' + with open(config_trace_path, 'w') as trace_file: + json.dump(diag_agent_events, trace_file, sort_keys=True) # Handle post-run model log save/compare regardless of profiling self._post_run_model_log() From 6ee090f93bd5da6b08520c2b66bcf00f852d33e8 Mon Sep 17 00:00:00 2001 From: Shenghsun Cho Date: Wed, 28 Oct 2026 20:51:57 +0000 Subject: [PATCH 3/4] test(profiler): Cover Configuration-Specific Trace Exports Exercise the real profiler exporter with CPU-safe CUDA/HIP mocks. Cover multiple configurations and local/distributed ranks, independent legacy and qualified files, forced legacy overwrite/truncation, CPU event filtering, and legacy-only fallback. Validation: 15 tests passed and 1 CUDA-only test skipped in the existing PyTorch base test file. All seven new executable production lines are covered locally (100% patch coverage). YAPF, Flake8, scoped mypy, and whitespace checks pass. Production code is unchanged. --- .../model_benchmarks/test_pytorch_base.py | 99 ++++++++++++++++++- 1 file changed, 98 insertions(+), 1 deletion(-) diff --git a/tests/benchmarks/model_benchmarks/test_pytorch_base.py b/tests/benchmarks/model_benchmarks/test_pytorch_base.py index b397f7c6b..c13360f1f 100644 --- a/tests/benchmarks/model_benchmarks/test_pytorch_base.py +++ b/tests/benchmarks/model_benchmarks/test_pytorch_base.py @@ -3,15 +3,24 @@ """Tests for BenchmarkRegistry module.""" +import builtins +import json import numbers +from contextlib import contextmanager +from types import SimpleNamespace +from unittest.mock import MagicMock +import pytest import torch import transformers from tests.helper import decorator from superbench.common.utils import logger from superbench.benchmarks import BenchmarkRegistry, Precision, ReturnCode -from superbench.benchmarks.model_benchmarks.model_base import Optimizer, DistributedImpl, DistributedBackend +from superbench.benchmarks.model_benchmarks import pytorch_base +from superbench.benchmarks.model_benchmarks.model_base import ( + Optimizer, DistributedImpl, DistributedBackend, ModelBenchmark +) from superbench.benchmarks.model_benchmarks.pytorch_base import PytorchBase from superbench.benchmarks.model_benchmarks.random_dataset import TorchRandomDataset @@ -246,6 +255,94 @@ def test_pytorch_base(): assert (benchmark._postprocess()) +@pytest.fixture(params=['cuda', 'hip']) +def mocked_profiler(request, monkeypatch, tmp_path): + """Provide CPU-safe profiler events for the real trace exporter.""" + event = SimpleNamespace( + device_type=torch.autograd.DeviceType.CPU, + name='capture', + input_shapes=[], + concrete_inputs=[], + cpu_time=2.0, + cuda_time=1.0, + time_range=SimpleNamespace(start=0.0) + ) + profiler = MagicMock() + profiler.events.return_value = [event, SimpleNamespace(device_type=torch.autograd.DeviceType.CUDA)] + monkeypatch.setenv('SB_ENABLE_PYTORCH_PROFILER', '1') + monkeypatch.setenv('SB_TORCH_PROFILER_TRACE_DIR', str(tmp_path)) + monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) + monkeypatch.setattr(torch.version, 'cuda', '12.0' if request.param == 'cuda' else None) + monkeypatch.setattr(torch.version, 'hip', '6.4' if request.param == 'hip' else None, raising=False) + monkeypatch.setattr(torch.profiler, 'profile', lambda **kwargs: profiler) + monkeypatch.setattr(ModelBenchmark, '_benchmark', lambda self: True) + return PytorchMNIST('pytorch-mnist'), event + + +@decorator.pytorch_test +@pytest.mark.parametrize('distributed', [False, True]) +def test_pytorch_profiler_config_traces(mocked_profiler, monkeypatch, tmp_path, distributed): + """Keep configuration/rank traces distinct while preserving legacy writes.""" + benchmark, event = mocked_profiler + captures = {} + for config_name in ['model-benchmarks:mnist@fp16', 'model-benchmarks:mnist@fp32']: + for rank in range(2): + work_dir = tmp_path / 'benchmarks' / config_name / f'rank{rank}' + work_dir.mkdir(parents=True) + monkeypatch.chdir(work_dir) + benchmark._local_rank = rank if distributed else None + event.name = f'{config_name}-rank{rank}' + assert (benchmark._benchmark()) + qualified = tmp_path / f'torch-profiler-sb-pytorch-mnist__cfg={config_name}-{rank}.json' + legacy = tmp_path / f'torch-profiler-sb-pytorch-mnist-{rank if distributed else 0}.json' + assert (qualified.read_bytes() == legacy.read_bytes()) + assert (qualified.stat().st_ino != legacy.stat().st_ino) + captures[qualified] = event.name + assert (len(list(tmp_path.glob('*__cfg=*.json'))) == 4) + for path, marker in captures.items(): + events = json.loads(path.read_text(encoding='utf-8')) + assert (len(events) == 1) + assert (events[0]['name'] == marker) + + +@decorator.pytorch_test +@pytest.mark.parametrize('replacement', ['', '[{"name": "other-worker"}]']) +def test_pytorch_profiler_shared_legacy(mocked_profiler, monkeypatch, tmp_path, replacement): + """Do not source qualified events from a concurrently changed legacy file.""" + benchmark, event = mocked_profiler + work_dir = tmp_path / 'benchmarks' / 'model-benchmarks:mnist' / 'rank1' + work_dir.mkdir(parents=True) + monkeypatch.chdir(work_dir) + legacy = tmp_path / 'torch-profiler-sb-pytorch-mnist-0.json' + + @contextmanager + def racing_open(path, *args, **kwargs): + with builtins.open(path, *args, **kwargs) as stream: + yield stream + if str(path) == str(legacy): + legacy.write_text(replacement, encoding='utf-8') + + monkeypatch.setattr(pytorch_base, 'open', racing_open, raising=False) + assert (benchmark._benchmark()) + qualified = tmp_path / 'torch-profiler-sb-pytorch-mnist__cfg=model-benchmarks:mnist-1.json' + assert (json.loads(qualified.read_text(encoding='utf-8'))[0]['name'] == event.name) + assert (legacy.read_text(encoding='utf-8') == replacement) + + +@decorator.pytorch_test +@pytest.mark.parametrize('directory', ['other', 'benchmarks/config/worker0', 'benchmarks/config/rankx']) +def test_pytorch_profiler_legacy_fallback(mocked_profiler, monkeypatch, tmp_path, directory): + """Keep legacy-only output outside the recognized executor layout.""" + benchmark, event = mocked_profiler + work_dir = tmp_path / directory + work_dir.mkdir(parents=True) + monkeypatch.chdir(work_dir) + assert (benchmark._benchmark()) + legacy = tmp_path / 'torch-profiler-sb-pytorch-mnist-0.json' + assert ([path.name for path in tmp_path.glob('*.json')] == [legacy.name]) + assert (json.loads(legacy.read_text(encoding='utf-8'))[0]['name'] == event.name) + + @decorator.cuda_test @decorator.pytorch_test def test_pytorch_empty_cache(): From c9a49759bea28bc2d9001ebb6b1bb00699b245f6 Mon Sep 17 00:00:00 2001 From: Shenghsun Cho Date: Tue, 24 Nov 2026 22:46:32 +0000 Subject: [PATCH 4/4] fix(profiler): Harden Configuration-Specific Trace Exports Encode and bound qualified filenames with stable configuration hashes. Carry complete configuration keys through the executor and restore the caller's environment after each launch. Use global distributed ranks to prevent shared-output collisions while preserving legacy filenames and independent trace writes. Add regressions for filename limits, reserved and multibyte names, configuration collisions, nested annotations, global ranks, and legacy-only fallback. Validation: 52 tests passed, 1 CUDA-only test skipped; YAPF, Flake8, scoped mypy, and whitespace checks passed. No hardware rerun. --- .../model_benchmarks/pytorch_base.py | 51 +++++-- superbench/executor/executor.py | 14 +- .../model_benchmarks/test_pytorch_base.py | 131 +++++++++++++++++- tests/executor/test_executor.py | 32 +++++ 4 files changed, 212 insertions(+), 16 deletions(-) diff --git a/superbench/benchmarks/model_benchmarks/pytorch_base.py b/superbench/benchmarks/model_benchmarks/pytorch_base.py index 0c8410d62..a310780b3 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_base.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_base.py @@ -3,10 +3,13 @@ """Module of the Pytorch model-benchmark base class.""" +import hashlib +import json import os import statistics import time from datetime import timedelta +from urllib.parse import quote import torch import transformers @@ -585,6 +588,43 @@ def _timer(self): torch.cuda.synchronize() return time.time() + def _get_config_trace_path(self, dump_file_dir): + """Build a portable trace path from configuration and worker identity. + + Args: + dump_file_dir (str): Directory containing profiler exports. + + Return: + str or None: Qualified path, or None outside an executor context. + """ + benchmark_dir, rank_dir = os.path.split(os.getcwd()) + if not rank_dir.startswith('rank') or not rank_dir[4:].isdigit(): + return None + config_name = os.environ.get('SB_BENCHMARK_CONFIG_NAME') + if config_name is None: + if os.path.basename(os.path.dirname(benchmark_dir)) != 'benchmarks': + return None + config_name = os.path.basename(benchmark_dir) + + worker_rank = self._global_rank if self._global_rank is not None else int(rank_dir[4:]) + identity = json.dumps([self._name, config_name], ensure_ascii=True).encode('ascii') + digest = hashlib.sha256(identity).hexdigest() + filename_limit = 255 + try: + filesystem_limit = os.pathconf(dump_file_dir, 'PC_NAME_MAX') + if filesystem_limit > 0: + filename_limit = min(filename_limit, filesystem_limit) + except (AttributeError, OSError, ValueError): + pass + prefix = 'torch-profiler-sb-' + suffix = f'__{digest}-{worker_rank}.json' + label_budget = filename_limit - len(prefix + '__cfg=' + suffix) + if label_budget < 0: + raise ValueError('Filesystem filename limit is too small for a qualified profiler trace.') + model_label = quote(self._name, safe='')[:label_budget // 2] + config_label = quote(config_name, safe='')[:label_budget - len(model_label)] + return os.path.join(dump_file_dir, f'{prefix}{model_label}__cfg={config_label}{suffix}') + def _benchmark(self): """Wrap super._benchmark with profiler context if enabled by environment variable. @@ -615,7 +655,6 @@ def _benchmark(self): from torch.profiler import profile, ProfilerActivity from torch.autograd import DeviceType - import json if self._local_rank is None: local_rank = 0 @@ -628,12 +667,7 @@ def _benchmark(self): # ROCm 6.3.4). dump_file_dir = os.environ.get('SB_TORCH_PROFILER_TRACE_DIR', '.') diag_agent_dump_file_path = f'{dump_file_dir}/torch-profiler-sb-{self._name}-{local_rank}.json' - benchmark_dir, rank_dir = os.path.split(os.getcwd()) - config_name = os.path.basename(benchmark_dir) - has_config_name = ( - os.path.basename(os.path.dirname(benchmark_dir)) == 'benchmarks' and rank_dir.startswith('rank') - and rank_dir[4:].isdigit() - ) + config_trace_path = self._get_config_trace_path(dump_file_dir) diag_agent_prof.__enter__() ret = super()._benchmark() @@ -654,8 +688,7 @@ def _benchmark(self): diag_agent_events.append(diag_agent_event) with open(diag_agent_dump_file_path, 'w') as f: json.dump(diag_agent_events, f, sort_keys=True) - if has_config_name: - config_trace_path = f'{dump_file_dir}/torch-profiler-sb-{self._name}__cfg={config_name}-{rank_dir[4:]}.json' + if config_trace_path is not None: with open(config_trace_path, 'w') as trace_file: json.dump(diag_agent_events, trace_file, sort_keys=True) diff --git a/superbench/executor/executor.py b/superbench/executor/executor.py index a4c007e31..654973335 100644 --- a/superbench/executor/executor.py +++ b/superbench/executor/executor.py @@ -117,17 +117,20 @@ def __get_arguments(self, parameters): argv.append('--{} {}'.format(name, ' '.join(val))) return ' '.join(argv) - def __exec_benchmark(self, benchmark_full_name, context): + def __exec_benchmark(self, benchmark_full_name, context, benchmark_config_name): """Launch benchmark for context. Args: benchmark_full_name (str): Benchmark full name. context (BenchmarkContext): Benchmark context to launch. + benchmark_config_name (str): Original configuration key, including annotations. Return: dict: Benchmark result. """ + previous_config_name = os.environ.get('SB_BENCHMARK_CONFIG_NAME') try: + os.environ['SB_BENCHMARK_CONFIG_NAME'] = benchmark_config_name benchmark = BenchmarkRegistry.launch_benchmark(context) if benchmark: logger.info( @@ -146,6 +149,11 @@ def __exec_benchmark(self, benchmark_full_name, context): except Exception as e: logger.error(e) logger.error('Executor failed in %s.', benchmark_full_name) + finally: + if previous_config_name is None: + os.environ.pop('SB_BENCHMARK_CONFIG_NAME', None) + else: + os.environ['SB_BENCHMARK_CONFIG_NAME'] = previous_config_name return None def __get_rank_id(self): @@ -244,7 +252,7 @@ def exec(self): {} if 'parameters' not in benchmark_config else benchmark_config.parameters ) ) - result = self.__exec_benchmark(full_name, context) + result = self.__exec_benchmark(full_name, context, benchmark_name) benchmark_results.append(result) else: full_name = benchmark_name @@ -256,7 +264,7 @@ def exec(self): parameters=self. __get_arguments({} if 'parameters' not in benchmark_config else benchmark_config.parameters) ) - result = self.__exec_benchmark(full_name, context) + result = self.__exec_benchmark(full_name, context, benchmark_name) benchmark_results.append(result) if monitor: diff --git a/tests/benchmarks/model_benchmarks/test_pytorch_base.py b/tests/benchmarks/model_benchmarks/test_pytorch_base.py index c13360f1f..1eb5c67ef 100644 --- a/tests/benchmarks/model_benchmarks/test_pytorch_base.py +++ b/tests/benchmarks/model_benchmarks/test_pytorch_base.py @@ -13,16 +13,18 @@ import pytest import torch import transformers +from omegaconf import OmegaConf from tests.helper import decorator from superbench.common.utils import logger -from superbench.benchmarks import BenchmarkRegistry, Precision, ReturnCode +from superbench.benchmarks import BenchmarkRegistry, Platform, Precision, ReturnCode from superbench.benchmarks.model_benchmarks import pytorch_base from superbench.benchmarks.model_benchmarks.model_base import ( Optimizer, DistributedImpl, DistributedBackend, ModelBenchmark ) from superbench.benchmarks.model_benchmarks.pytorch_base import PytorchBase from superbench.benchmarks.model_benchmarks.random_dataset import TorchRandomDataset +from superbench.executor import SuperBenchExecutor class MNISTModel(torch.nn.Module): @@ -271,6 +273,7 @@ def mocked_profiler(request, monkeypatch, tmp_path): profiler.events.return_value = [event, SimpleNamespace(device_type=torch.autograd.DeviceType.CUDA)] monkeypatch.setenv('SB_ENABLE_PYTORCH_PROFILER', '1') monkeypatch.setenv('SB_TORCH_PROFILER_TRACE_DIR', str(tmp_path)) + monkeypatch.delenv('SB_BENCHMARK_CONFIG_NAME', raising=False) monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) monkeypatch.setattr(torch.version, 'cuda', '12.0' if request.param == 'cuda' else None) monkeypatch.setattr(torch.version, 'hip', '6.4' if request.param == 'hip' else None, raising=False) @@ -291,9 +294,11 @@ def test_pytorch_profiler_config_traces(mocked_profiler, monkeypatch, tmp_path, work_dir.mkdir(parents=True) monkeypatch.chdir(work_dir) benchmark._local_rank = rank if distributed else None + benchmark._global_rank = rank if distributed else None event.name = f'{config_name}-rank{rank}' assert (benchmark._benchmark()) - qualified = tmp_path / f'torch-profiler-sb-pytorch-mnist__cfg={config_name}-{rank}.json' + qualified, = set(tmp_path.glob('*__cfg=*.json')) - set(captures) + assert (qualified.name.endswith(f'-{rank}.json')) legacy = tmp_path / f'torch-profiler-sb-pytorch-mnist-{rank if distributed else 0}.json' assert (qualified.read_bytes() == legacy.read_bytes()) assert (qualified.stat().st_ino != legacy.stat().st_ino) @@ -324,13 +329,131 @@ def racing_open(path, *args, **kwargs): monkeypatch.setattr(pytorch_base, 'open', racing_open, raising=False) assert (benchmark._benchmark()) - qualified = tmp_path / 'torch-profiler-sb-pytorch-mnist__cfg=model-benchmarks:mnist-1.json' + qualified, = tmp_path.glob('*__cfg=*.json') + assert (qualified.name.endswith('-1.json')) assert (json.loads(qualified.read_text(encoding='utf-8'))[0]['name'] == event.name) assert (legacy.read_text(encoding='utf-8') == replacement) @decorator.pytorch_test -@pytest.mark.parametrize('directory', ['other', 'benchmarks/config/worker0', 'benchmarks/config/rankx']) +@pytest.mark.parametrize('filename_limit', [255, 143]) +@pytest.mark.parametrize( + 'config_name', [ + 'model-benchmarks:' + 'x' * 191, + 'model-benchmarks:' + 'x' * 192, + 'model-benchmarks:' + '\u00e9' * 100, + 'model-benchmarks:mnist?*|<>"', + ] +) +def test_pytorch_profiler_portable_filenames(mocked_profiler, monkeypatch, tmp_path, config_name, filename_limit): + """Bound qualified filenames without failing otherwise valid captures.""" + benchmark, event = mocked_profiler + benchmark._name = 'pytorch-resnet50' + work_dir = tmp_path / 'benchmarks' / config_name / 'rank0' + work_dir.mkdir(parents=True) + monkeypatch.chdir(work_dir) + monkeypatch.setattr(pytorch_base.os, 'pathconf', lambda *args: filename_limit, raising=False) + + def portable_open(path, *args, **kwargs): + filename = pytorch_base.os.path.basename(path) + assert (filename.isascii()) + assert (len(filename.encode('ascii')) <= filename_limit) + assert (not set('"\\/:|<>*?').intersection(filename)) + return builtins.open(path, *args, **kwargs) + + monkeypatch.setattr(pytorch_base, 'open', portable_open, raising=False) + assert (benchmark._benchmark()) + qualified, = tmp_path.glob('*__cfg=*.json') + legacy = tmp_path / 'torch-profiler-sb-pytorch-resnet50-0.json' + assert (qualified.read_bytes() == legacy.read_bytes()) + event.name = 'second-capture' + assert (benchmark._benchmark()) + assert (list(tmp_path.glob('*__cfg=*.json')) == [qualified]) + assert (json.loads(qualified.read_text(encoding='utf-8'))[0]['name'] == event.name) + + +@decorator.pytorch_test +def test_pytorch_profiler_configuration_identity(mocked_profiler, monkeypatch, tmp_path): + """Keep similar configuration names distinct on case-insensitive storage.""" + benchmark, event = mocked_profiler + configurations = [ + 'model-benchmarks:MNIST', 'model-benchmarks:mnist', 'model-benchmarks%3Amnist', + 'model-benchmarks:' + 'x' * 190 + 'a', 'model-benchmarks:' + 'x' * 190 + 'b' + ] + for config_name in configurations: + work_dir = tmp_path / 'benchmarks' / config_name / 'rank0' + work_dir.mkdir(parents=True) + monkeypatch.chdir(work_dir) + event.name = config_name + assert (benchmark._benchmark()) + qualified = list(tmp_path.glob('*__cfg=*.json')) + assert (len({path.name.casefold() for path in qualified}) == len(configurations)) + assert ({json.loads(path.read_text(encoding='utf-8'))[0]['name'] for path in qualified} == set(configurations)) + + +@decorator.pytorch_test +def test_pytorch_profiler_nested_configurations(mocked_profiler, monkeypatch, tmp_path): + """Carry complete slash-containing configuration keys through the executor.""" + benchmark, event = mocked_profiler + configurations = [ + 'model-benchmarks:experiment/fp16', 'model-benchmarks:experiment/fp32', 'model-benchmarks:other/fp16', + 'model-benchmarks:experiment/benchmarks/fp16' + ] + executor = SuperBenchExecutor.__new__(SuperBenchExecutor) + executor._output_path = tmp_path / 'executor' + executor._sb_enabled = configurations + executor._sb_benchmarks = OmegaConf.create( + {name: { + 'models': ['mnist'], + 'frameworks': ['pytorch'] + } + for name in configurations} + ) + executor._sb_monitor_config = None + monkeypatch.setenv('PROC_RANK', '0') + monkeypatch.setenv('SB_BENCHMARK_CONFIG_NAME', 'outer-configuration') + monkeypatch.setattr(executor, '_SuperBenchExecutor__get_platform', lambda: Platform.CPU) + + def launch(context): + event.name = pytorch_base.os.environ['SB_BENCHMARK_CONFIG_NAME'] + assert (benchmark._benchmark()) + return SimpleNamespace(name=benchmark.name, return_code=ReturnCode.SUCCESS, result={}, serialized_result='{}') + + monkeypatch.setattr(BenchmarkRegistry, 'launch_benchmark', launch) + executor.exec() + qualified = list(tmp_path.glob('*__cfg=*.json')) + assert (len(qualified) == len(configurations)) + assert ({json.loads(path.read_text(encoding='utf-8'))[0]['name'] for path in qualified} == set(configurations)) + assert (pytorch_base.os.environ['SB_BENCHMARK_CONFIG_NAME'] == 'outer-configuration') + + +@decorator.pytorch_test +@pytest.mark.parametrize('local_rank', [0, 1]) +def test_pytorch_profiler_global_ranks(mocked_profiler, monkeypatch, tmp_path, local_rank): + """Preserve different nodes' traces when their local ranks coincide.""" + benchmark, event = mocked_profiler + for global_rank in [local_rank, local_rank + 8]: + work_dir = (tmp_path / f'node{global_rank}' / 'benchmarks' / 'model-benchmarks:mnist' / f'rank{local_rank}') + work_dir.mkdir(parents=True) + monkeypatch.chdir(work_dir) + benchmark._local_rank = local_rank + benchmark._global_rank = global_rank + event.name = f'global-rank-{global_rank}' + assert (benchmark._benchmark()) + qualified = list(tmp_path.glob('*__cfg=*.json')) + assert (len(qualified) == 2) + assert ( + {json.loads(path.read_text(encoding='utf-8'))[0]['name'] + for path in qualified} == {f'global-rank-{local_rank}', f'global-rank-{local_rank + 8}'} + ) + legacy = tmp_path / f'torch-profiler-sb-pytorch-mnist-{local_rank}.json' + assert (json.loads(legacy.read_text(encoding='utf-8'))[0]['name'] == f'global-rank-{local_rank + 8}') + + +@decorator.pytorch_test +@pytest.mark.parametrize( + 'directory', ['other', 'other/config/rank0', 'benchmarks/config/worker0', 'benchmarks/config/rankx'] +) def test_pytorch_profiler_legacy_fallback(mocked_profiler, monkeypatch, tmp_path, directory): """Keep legacy-only output outside the recognized executor layout.""" benchmark, event = mocked_profiler diff --git a/tests/executor/test_executor.py b/tests/executor/test_executor.py index 2c287eb37..84dd14fc2 100644 --- a/tests/executor/test_executor.py +++ b/tests/executor/test_executor.py @@ -4,10 +4,12 @@ """SuperBench Executor test.""" import json +import os import unittest import shutil import tempfile from pathlib import Path +from types import SimpleNamespace from unittest import mock import yaml @@ -136,6 +138,36 @@ def test_exec_empty_benchmarks(self): self.executor._sb_enabled = [] self.executor.exec() + @mock.patch('superbench.benchmarks.BenchmarkRegistry.launch_benchmark') + def test_exec_benchmark_configuration_scope(self, mock_launch_benchmark): + """Restore the caller's configuration identity after success or failure.""" + configuration = 'model-benchmarks:experiment/fp16' + for previous_name in [None, 'outer-configuration']: + for should_fail in [False, True]: + with self.subTest(previous_name=previous_name, should_fail=should_fail): + with mock.patch.dict(os.environ, {}, clear=True): + if previous_name is not None: + os.environ['SB_BENCHMARK_CONFIG_NAME'] = previous_name + + def launch(context): + self.assertIs(context, mock.sentinel.context) + self.assertEqual(os.environ['SB_BENCHMARK_CONFIG_NAME'], configuration) + if should_fail: + raise RuntimeError('Test benchmark failure.') + return SimpleNamespace( + name='mnist', return_code=ReturnCode.SUCCESS, result={}, serialized_result='{}' + ) + + mock_launch_benchmark.side_effect = launch + result = self.executor._SuperBenchExecutor__exec_benchmark( + configuration + '/pytorch-mnist', mock.sentinel.context, configuration + ) + if should_fail: + self.assertIsNone(result) + else: + self.assertEqual(result['name'], configuration + '/pytorch-mnist') + self.assertEqual(os.environ.get('SB_BENCHMARK_CONFIG_NAME'), previous_name) + @mock.patch('superbench.benchmarks.BenchmarkRegistry.launch_benchmark') def test_exec_default_benchmarks(self, mock_launch_benchmark): """Test execute default benchmarks, mock exec function.