|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | + |
| 5 | +import argparse |
| 6 | +import json |
| 7 | +import subprocess |
| 8 | +import sys |
| 9 | +import tempfile |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +PROJECT_ROOT = Path(__file__).resolve().parent.parent |
| 13 | +BUILD_DIR = PROJECT_ROOT / ".build" / "cpp" |
| 14 | +DEFAULT_OUTPUT = PROJECT_ROOT / "results-cpp.json" |
| 15 | + |
| 16 | +BINARY_PREFIX = "bench_" |
| 17 | +BINARY_SUFFIX = "_cpp" |
| 18 | + |
| 19 | + |
| 20 | +def discover_binaries() -> dict[str, Path]: |
| 21 | + """Discover C++ benchmark binaries in the build directory """ |
| 22 | + if not BUILD_DIR.is_dir(): |
| 23 | + return {} |
| 24 | + |
| 25 | + registry: dict[str, Path] = {} |
| 26 | + for path in sorted(BUILD_DIR.iterdir()): |
| 27 | + if not path.is_file() or not path.name.startswith(BINARY_PREFIX): |
| 28 | + continue |
| 29 | + if not path.name.endswith(BINARY_SUFFIX): |
| 30 | + continue |
| 31 | + name = path.name.removeprefix(BINARY_PREFIX).removesuffix(BINARY_SUFFIX) |
| 32 | + registry[name] = path |
| 33 | + return registry |
| 34 | + |
| 35 | + |
| 36 | +def strip_output_args(argv: list[str]) -> list[str]: |
| 37 | + cleaned: list[str] = [] |
| 38 | + skip_next = False |
| 39 | + for arg in argv: |
| 40 | + if skip_next: |
| 41 | + skip_next = False |
| 42 | + continue |
| 43 | + if arg in ("-o", "--output"): |
| 44 | + skip_next = True |
| 45 | + continue |
| 46 | + if arg.startswith("-o=") or arg.startswith("--output="): |
| 47 | + continue |
| 48 | + cleaned.append(arg) |
| 49 | + return cleaned |
| 50 | + |
| 51 | + |
| 52 | +def merge_pyperf_json(individual_files: list[Path], output_path: Path) -> int: |
| 53 | + """Merge individual pyperf JSON files into a single BenchmarkSuite file. |
| 54 | +
|
| 55 | + Each C++ binary produces a file with structure: |
| 56 | + {"version": "1.0", "metadata": {...}, "benchmarks": [{...}]} |
| 57 | +
|
| 58 | + We merge them by collecting all benchmark entries into one file. |
| 59 | + """ |
| 60 | + all_benchmarks = [] |
| 61 | + |
| 62 | + for path in individual_files: |
| 63 | + with open(path) as f: |
| 64 | + data = json.load(f) |
| 65 | + |
| 66 | + file_metadata = data.get("metadata", {}) |
| 67 | + bench_name = file_metadata.get("name", "") |
| 68 | + loops = file_metadata.get("loops") |
| 69 | + unit = file_metadata.get("unit", "second") |
| 70 | + |
| 71 | + for bench in data.get("benchmarks", []): |
| 72 | + for run in bench.get("runs", []): |
| 73 | + run_meta = run.setdefault("metadata", {}) |
| 74 | + if bench_name: |
| 75 | + run_meta.setdefault("name", bench_name) |
| 76 | + if loops is not None: |
| 77 | + run_meta.setdefault("loops", loops) |
| 78 | + run_meta.setdefault("unit", unit) |
| 79 | + |
| 80 | + all_benchmarks.append(bench) |
| 81 | + |
| 82 | + merged = { |
| 83 | + "version": "1.0", |
| 84 | + "benchmarks": all_benchmarks, |
| 85 | + } |
| 86 | + |
| 87 | + with open(output_path, "w") as f: |
| 88 | + json.dump(merged, f) |
| 89 | + |
| 90 | + return len(all_benchmarks) |
| 91 | + |
| 92 | + |
| 93 | +def parse_args(argv: list[str]) -> tuple[argparse.Namespace, list[str]]: |
| 94 | + parser = argparse.ArgumentParser( |
| 95 | + description="Run C++ CUDA benchmarks", |
| 96 | + add_help=False, |
| 97 | + ) |
| 98 | + parser.add_argument( |
| 99 | + "--benchmark", |
| 100 | + action="append", |
| 101 | + default=[], |
| 102 | + help="Benchmark name to run (e.g. 'ctx_device'). Repeat for multiple. Defaults to all.", |
| 103 | + ) |
| 104 | + parser.add_argument( |
| 105 | + "--list", |
| 106 | + action="store_true", |
| 107 | + help="Print discovered benchmark names and exit.", |
| 108 | + ) |
| 109 | + parser.add_argument( |
| 110 | + "-o", |
| 111 | + "--output", |
| 112 | + type=Path, |
| 113 | + default=DEFAULT_OUTPUT, |
| 114 | + help=f"JSON output file path (default: {DEFAULT_OUTPUT.name})", |
| 115 | + ) |
| 116 | + parsed, remaining = parser.parse_known_args(argv) |
| 117 | + return parsed, remaining |
| 118 | + |
| 119 | + |
| 120 | +def main() -> None: |
| 121 | + parsed, remaining_argv = parse_args(sys.argv[1:]) |
| 122 | + |
| 123 | + registry = discover_binaries() |
| 124 | + if not registry: |
| 125 | + print( |
| 126 | + f"No C++ benchmark binaries found in {BUILD_DIR}.\n" |
| 127 | + "Run 'pixi run bench-cpp-build' first.", |
| 128 | + file=sys.stderr, |
| 129 | + ) |
| 130 | + sys.exit(1) |
| 131 | + |
| 132 | + if parsed.list: |
| 133 | + for name in sorted(registry): |
| 134 | + print(name) |
| 135 | + return |
| 136 | + |
| 137 | + if parsed.benchmark: |
| 138 | + missing = sorted(set(parsed.benchmark) - set(registry)) |
| 139 | + if missing: |
| 140 | + known = ", ".join(sorted(registry)) |
| 141 | + unknown = ", ".join(missing) |
| 142 | + print( |
| 143 | + f"Unknown benchmark(s): {unknown}. Known benchmarks: {known}", |
| 144 | + file=sys.stderr, |
| 145 | + ) |
| 146 | + sys.exit(1) |
| 147 | + names = parsed.benchmark |
| 148 | + else: |
| 149 | + names = sorted(registry) |
| 150 | + |
| 151 | + # Strip any --output args to avoid conflicts with our output handling |
| 152 | + passthrough_argv = strip_output_args(remaining_argv) |
| 153 | + |
| 154 | + output_path = parsed.output.resolve() |
| 155 | + failed = False |
| 156 | + individual_files: list[Path] = [] |
| 157 | + |
| 158 | + with tempfile.TemporaryDirectory(prefix="cuda_bench_cpp_") as tmpdir: |
| 159 | + tmpdir_path = Path(tmpdir) |
| 160 | + |
| 161 | + for name in names: |
| 162 | + binary = registry[name] |
| 163 | + tmp_json = tmpdir_path / f"{name}.json" |
| 164 | + cmd = [str(binary), "-o", str(tmp_json), *passthrough_argv] |
| 165 | + result = subprocess.run(cmd) |
| 166 | + if result.returncode != 0: |
| 167 | + print(f"FAILED: {name} (exit code {result.returncode})", file=sys.stderr) |
| 168 | + failed = True |
| 169 | + elif tmp_json.exists(): |
| 170 | + individual_files.append(tmp_json) |
| 171 | + |
| 172 | + if individual_files: |
| 173 | + count = merge_pyperf_json(individual_files, output_path) |
| 174 | + print(f"\nResults saved to {output_path} ({count} benchmark(s))") |
| 175 | + |
| 176 | + if failed: |
| 177 | + sys.exit(1) |
| 178 | + |
| 179 | + |
| 180 | +if __name__ == "__main__": |
| 181 | + main() |
0 commit comments