From a9507410f00c966a23219e6e57d2aa61bb1ffb1c Mon Sep 17 00:00:00 2001 From: Massimiliano Meneghin Date: Fri, 6 Nov 2026 03:22:49 -0500 Subject: [PATCH 1/8] Distributed LBM strong-scaling sweep; benchmark --reps, barrier timing, process_grid Add lbm-dist-sweep-run.sh + lbm-dist-sweep.yml (N x GPUs x slab/pencil/brick x NCCL/MPI-P2P x --hp-halo off/on, plus a 1-GPU ref run per N), the plot_dist_scaling.py plotter and data/lbm-dist-sweep/reproduce.sh. The distributed benchmark gains --reps with results.repetitions, timing marks taken after a GPU drain plus Distributed::barrier(), and config.process_grid. lbm_sweep_config.py loaders take optional key/choice tables. Co-authored-by: Cursor --- .../scripts/lbm_sweep_config.py | 43 ++- .../data/lbm-dist-sweep/lbm-dist-sweep.yml | 76 ++++ .../data/lbm-dist-sweep/reproduce.sh | 46 +++ .../lbm_lid_driven_cavity_distributed.cu | 108 +++++- .../scripts/lbm-dist-sweep-run.sh | 248 +++++++++++++ .../scripts/lbm-dist-sweep.yml | 76 ++++ .../scripts/lbm_dist_sweep_config.py | 78 ++++ .../scripts/plotting/plot_dist_scaling.py | 336 ++++++++++++++++++ docs/CHANGELOG.md | 18 + 9 files changed, 1007 insertions(+), 22 deletions(-) create mode 100644 benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep.yml create mode 100755 benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/reproduce.sh create mode 100755 benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep-run.sh create mode 100644 benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep.yml create mode 100755 benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm_dist_sweep_config.py create mode 100755 benchmarks/lbm_lid_driven_cavity_distributed/scripts/plotting/plot_dist_scaling.py diff --git a/benchmarks/lbm_lid_driven_cavity/scripts/lbm_sweep_config.py b/benchmarks/lbm_lid_driven_cavity/scripts/lbm_sweep_config.py index 75e34fc4..038d37ea 100644 --- a/benchmarks/lbm_lid_driven_cavity/scripts/lbm_sweep_config.py +++ b/benchmarks/lbm_lid_driven_cavity/scripts/lbm_sweep_config.py @@ -74,7 +74,7 @@ def _as_list(key: str, v: object) -> list: return [v] -def _parse_value(key: str, kind: str, value: object) -> object: +def _parse_value(key: str, kind: str, value: object, choices: dict[str, set[str]]) -> object: if kind == "int": return _as_int(key, value) if kind == "bool": @@ -98,32 +98,44 @@ def _parse_value(key: str, kind: str, value: object) -> object: for x in items: if not isinstance(x, str) or not pattern.match(x): raise SweepConfigError(f"{key} has an invalid value {x!r}") - if key in CHOICES and x not in CHOICES[key]: - raise SweepConfigError(f"{key} value {x!r} not in {sorted(CHOICES[key])}") + if key in choices and x not in choices[key]: + raise SweepConfigError(f"{key} value {x!r} not in {sorted(choices[key])}") return items if kind == "words" else items[0] -def load_sweep_config(text: str) -> dict[str, object]: - """Validate YAML text; returns every key in ``KEYS``, omitted ones at their default.""" +def load_sweep_config( + text: str, + keys: dict[str, tuple[str, str, object]] = KEYS, + choices: dict[str, set[str]] = CHOICES, +) -> dict[str, object]: + """Validate YAML text; returns every key in ``keys``, omitted ones at their default. + + ``keys`` / ``choices`` default to this sweep's tables; other sweeps (e.g. the + distributed benchmark's) pass their own in the same format. + """ import yaml cfg = yaml.safe_load(text) or {} if not isinstance(cfg, dict): raise SweepConfigError("top level must be a mapping") - out = {key: default for key, (_, _, default) in KEYS.items()} + out = {key: default for key, (_, _, default) in keys.items()} for key, value in cfg.items(): - if key not in KEYS: - raise SweepConfigError(f"unknown key {key!r} (known: {', '.join(KEYS)})") - out[key] = _parse_value(key, KEYS[key][1], value) + if key not in keys: + raise SweepConfigError(f"unknown key {key!r} (known: {', '.join(keys)})") + out[key] = _parse_value(key, keys[key][1], value, choices) return out -def read_sweep_config(path: Path) -> dict[str, object]: +def read_sweep_config( + path: Path, + keys: dict[str, tuple[str, str, object]] = KEYS, + choices: dict[str, set[str]] = CHOICES, +) -> dict[str, object]: """Load a sweep YAML file; the path must be an existing ``.yml`` / ``.yaml`` file.""" path = Path(path).resolve() if path.suffix not in (".yml", ".yaml") or not path.is_file(): raise SweepConfigError(f"not a .yml/.yaml file: {path}") - return load_sweep_config(path.read_text()) + return load_sweep_config(path.read_text(), keys, choices) def series_prefixes(cfg: dict[str, object]) -> list[tuple[str, str, str, str]]: @@ -151,13 +163,16 @@ def _shell_value(kind: str, value: object) -> str: return str(value) -def main() -> int: +def main( + keys: dict[str, tuple[str, str, object]] = KEYS, + choices: dict[str, set[str]] = CHOICES, +) -> int: try: - cfg = load_sweep_config(os.environ.get("LBM_SWEEP_CONFIG", "")) + cfg = load_sweep_config(os.environ.get("LBM_SWEEP_CONFIG", ""), keys, choices) except SweepConfigError as e: sys.stderr.write(f"error: config: {e}\n") return 1 - for key, (var, kind, _) in KEYS.items(): + for key, (var, kind, _) in keys.items(): print(f"{var}={_shell_value(kind, cfg[key])}") return 0 diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep.yml b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep.yml new file mode 100644 index 00000000..23e62de6 --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep.yml @@ -0,0 +1,76 @@ +# Sweep configuration for lbm-dist-sweep-run.sh and its plotter. +# +# ./benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep-run.sh \ +# benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep.yml +# python3 benchmarks/lbm_lid_driven_cavity_distributed/scripts/plotting/plot_dist_scaling.py \ +# --config benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep.yml +# +# Every run uses --grid dense_distributed under mpiexec, one rank per GPU. +# Every key is optional; omitted keys use the script defaults, and an env var +# of the same name in upper case (CONFIGS, SIZES, GPUS_LIST, ...) overrides +# the file. + +# Lattice:collision pairs, each its own series (populations are always fp32): +# q19:bgk D3Q19 + BGK +# q27:bgk D3Q27 + BGK +# q27:kbc D3Q27 + KBC (KBC is only implemented for D3Q27) +configs: [q19:bgk] + +# Domain edge lengths N: a list, or an inclusive {start, stop, step} range. +sizes: {start: 256, stop: 512, step: 64} + +# GPU counts (= MPI ranks). The 1-GPU point is a single "ref" run per size +# (every decomposition is 1x1x1 there) and is the efficiency baseline. +# ProcessGrid factorises the rank count, so for prime counts (2, 3, 5, 7) +# pencil and brick fall back to a slab, and brick at 4 is a pencil; the +# plots print the process grid under each GPU count. +gpus: {start: 1, stop: 8, step: 1} + +# Process decompositions, one plot panel each: +# slab split z +# pencil split y and z +# brick split x, y and z +decompositions: [slab, pencil, brick] + +# Halo transports, one curve each: +# mpi NCCL (default) +# mpip2p MPI point-to-point (CARBON_DIST_TRANSPORT=mpi) +transports: [mpi] + +# Halo stream priority, one curve each: off = normal priority, on = --hp-halo +# (Skeleton halo_stream_priority = High). Only meaningful with overlap != none. +hp_halo: ["off", "on"] + +# Skeleton OCC mode of every run: none, standard, extended, twoway-extended. +overlap: standard + +# Timing: warmup untimed solver steps, then reps repetitions of +# iters_per_rep solver steps, each closed by a GPU drain and an MPI barrier. +warmup: 400 +iters_per_rep: 1000 +reps: 5 + +# CUDA compute capability the binary is compiled for +# (CMAKE_CUDA_ARCHITECTURES). auto detects it from the GPUs via nvidia-smi. +# Changing it needs a rebuild, so keep skip_build: false for that run. +sm_arch: auto + +# Docker image that builds the binary and does every run. Its NCCL must match +# the host driver: carbon-cuda:local ships an NCCL that needs driver >= 580, +# carbon-cuda-nccl-pinned:local pins NCCL 2.27.7 (CUDA 12.2). +image: carbon-cuda-nccl-pinned:local + +# CUDA+MPI build tree, relative to the carbon repo root. Kept apart from the +# single-process sweep's build-mpi/, which is configured in another image. +build_dir: build-dist + +# Report prefix and output folder: +# benchmarks/lbm_lid_driven_cavity_distributed/data//json/ +prefix: lbm-dist-sweep + +# true reuses the existing build tree; false (re)builds it first. +skip_build: false +# true redoes runs whose JSON already exists; false skips them (resume). +force: true +# Per-run timeout in seconds; a hung run is logged in failed.txt. +run_timeout: 1800 diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/reproduce.sh b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/reproduce.sh new file mode 100755 index 00000000..00261376 --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/reproduce.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# +# benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/reproduce.sh +# +# Reproduces this result set: runs the sweep described by lbm-dist-sweep.yml +# (the frozen copy next to this script) and renders every plot in this folder. +# +# D3Q19 + BGK, fp32, --grid dense_distributed, --overlap standard; +# N = 256..512 step 64; 1..8 GPUs (one MPI rank each); slab, pencil and +# brick decompositions; NCCL halos with --hp-halo off and on; +# 400 warmup steps, then 5 timed repetitions of 1000 solver steps. +# +# Usage: +# ./benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/reproduce.sh [--plot-only] +# +# (no flag) build build-dist/ in Docker, redo every run (force: true +# overwrites json/), then plot; takes about two hours on 8 GPUs +# --plot-only only re-render the PNGs from the reports already in json/ +# +# Needs docker with the NVIDIA container toolkit, the image named in the yml, +# and python3 with PyYAML and matplotlib. Run it from tmux (or similar) because +# the sweep outlives an SSH session. + +set -euo pipefail + +plot_only=0 +case "${1:-}" in + "") ;; + --plot-only) plot_only=1 ;; + *) + echo "usage: $0 [--plot-only]" >&2 + exit 2 + ;; +esac + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +repo_root="$(cd "${here}/../../../.." && pwd)" +scripts="${repo_root}/benchmarks/lbm_lid_driven_cavity_distributed/scripts" +config="${here}/lbm-dist-sweep.yml" + +if [[ "${plot_only}" -eq 0 ]]; then + "${scripts}/lbm-dist-sweep-run.sh" "${config}" +fi + +python3 "${scripts}/plotting/plot_dist_scaling.py" --config "${config}" --output-dir "${here}" +echo "==> plots written to ${here}" diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu b/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu index 4486cad6..7dd74c4b 100644 --- a/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu +++ b/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu @@ -55,6 +55,7 @@ #include +#include #include #include #include @@ -108,6 +109,7 @@ struct Options { int64_t n = 128; int64_t iters = 1000; int64_t warmup = 100; + int64_t reps = 1; double re = 100.0; double ulb = 0.05; bool ulb_set = false; @@ -175,6 +177,10 @@ build_cli(Options& opts) -> clipp::group { "Total iterations including warmup (default 1000)", (option("--warmup") & integer("warmup", opts.warmup)) % "Warmup iterations excluded from timing (default 100)", + (option("--reps") & integer("reps", opts.reps)) % + "Split the timed iterations into N equal repetitions, each closed by a GPU drain " + "and (under MPI) a barrier, and report per-repetition MLUPS plus " + "mean/min/max/stddev (default 1). Timed iterations must divide by N.", (option("--re") & number("re", opts.re)) % "Reynolds number (default 1e2)", (option("--ulb") & number("ulb", opts.ulb).set(opts.ulb_set)) % "Override lid velocity in lattice units (default 0.05)", @@ -257,6 +263,12 @@ parse_cli(int argc, << " for iters=" << opts.iters << ")\n"; return false; } + const int64_t timed_iters = opts.no_warmup_skip ? opts.iters : opts.iters - opts.warmup; + if (opts.reps < 1 || timed_iters % opts.reps != 0) { + std::cerr << "lbm_lid_driven_cavity: --reps must be >= 1 and divide the " << timed_iters + << " timed iterations (got " << opts.reps << ")\n"; + return false; + } if (opts.lattice != "q19" && opts.lattice != "q27") { std::cerr << "lbm_lid_driven_cavity: --lattice must be q19 or q27 (got '" << opts.lattice << "')\n"; @@ -683,22 +695,50 @@ run_benchmark(const Options& opts, using Clock = std::chrono::steady_clock; using Seconds = std::chrono::duration; const int64_t timed_start = opts.no_warmup_skip ? 0 : opts.warmup; + const int64_t iters_per_rep = (opts.iters - timed_start) / opts.reps; + + // Every timing mark is taken after all ranks drained, so rank 0's window spans the + // slowest rank and the reported MLUPS is a true global figure. + auto drain_all_ranks = [&]() { + sk_ab.wait(); + sk_ba.wait(); +#ifdef CARBON_HAVE_MPI_NCCL + if (use_mpi) { + distributed->barrier(); + } +#endif + }; Clock::time_point timing_started{}; + Clock::time_point rep_started{}; Clock::time_point overall_started = Clock::now(); bool timing_running = false; + std::vector rep_seconds; + rep_seconds.reserve(static_cast(opts.reps)); for (int64_t it = 0; it < opts.iters; ++it) { + if (it > timed_start && (it - timed_start) % iters_per_rep == 0) { + try { + drain_all_ranks(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: repetition drain failed at iter {}: {}", it, + e.what()); + return EXIT_FAILURE; + } + const auto now = Clock::now(); + rep_seconds.push_back(Seconds(now - rep_started).count()); + rep_started = now; + } if (it == timed_start) { try { - sk_ab.wait(); - sk_ba.wait(); + drain_all_ranks(); } catch (const std::exception& e) { CARBON_LOG_ERROR("lbm_lid_driven_cavity: pre-timing drain failed at iter {}: {}", it, e.what()); return EXIT_FAILURE; } timing_started = Clock::now(); + rep_started = timing_started; timing_running = true; if (!opts.no_warmup_skip) { CARBON_LOG_INFO("lbm_lid_driven_cavity: warmup complete ({} iters), starting timing window", @@ -733,8 +773,7 @@ run_benchmark(const Options& opts, } try { - sk_ab.wait(); - sk_ba.wait(); + drain_all_ranks(); } catch (const std::exception& e) { CARBON_LOG_ERROR("lbm_lid_driven_cavity: final sync failed: {}", e.what()); return EXIT_FAILURE; @@ -754,10 +793,32 @@ run_benchmark(const Options& opts, const double mlups = (cells_per_iter * static_cast(timed_iters)) / (1.0e6 * timing_seconds); const double overall_seconds = Seconds(timing_ended - overall_started).count(); + rep_seconds.push_back(Seconds(timing_ended - rep_started).count()); - // Under MPI all ranks measure the same `cells_per_iter` (= global N^3) and - // run lock-step (halo exchanges synchronise them), so each rank's `mlups` - // is the global throughput up to small per-rank timing noise. Print only on + std::vector rep_mlups; + rep_mlups.reserve(rep_seconds.size()); + for (const double s : rep_seconds) { + rep_mlups.push_back((cells_per_iter * static_cast(iters_per_rep)) / (1.0e6 * s)); + } + double rep_mlups_mean = 0.0; + double rep_mlups_min = rep_mlups.front(); + double rep_mlups_max = rep_mlups.front(); + for (const double m : rep_mlups) { + rep_mlups_mean += m; + rep_mlups_min = std::min(rep_mlups_min, m); + rep_mlups_max = std::max(rep_mlups_max, m); + } + rep_mlups_mean /= static_cast(rep_mlups.size()); + double rep_mlups_var = 0.0; + for (const double m : rep_mlups) { + rep_mlups_var += (m - rep_mlups_mean) * (m - rep_mlups_mean); + } + const double rep_mlups_stddev = + rep_mlups.size() > 1 ? std::sqrt(rep_mlups_var / static_cast(rep_mlups.size() - 1)) + : 0.0; + + // Under MPI all ranks measure the same `cells_per_iter` (= global N^3) between the + // same barriers, so each rank's `mlups` is the global throughput. Print only on // rank 0 to keep the scrape-friendly headline single-shot. `total_gpu_count` // is the world size under MPI (one rank per GPU) and the local GPU count // otherwise; `local_gpu_count` stays useful on multi-GPU single-process runs. @@ -774,6 +835,12 @@ run_benchmark(const Options& opts, << " ranks=" << world_size << " decomposition=" << decomposition_mode_name(dec_mode) << " lattice=" << lattice_name << " collision=" << collision_name << (use_mpi ? " transport=mpi+nccl" : "") << ")" << '\n'; + if (opts.reps > 1) { + CARBON_LOG_INFO( + "lbm_lid_driven_cavity: {} repetitions x {} iters => MLUPS mean={:.2f} min={:.2f} " + "max={:.2f} stddev={:.2f}", + opts.reps, iters_per_rep, rep_mlups_mean, rep_mlups_min, rep_mlups_max, rep_mlups_stddev); + } } // Optional grid-family parity checksum: Sum-reduce the whole final population @@ -924,10 +991,17 @@ run_benchmark(const Options& opts, out << " \"n\": " << opts.n << ",\n"; out << " \"iters\": " << opts.iters << ",\n"; out << " \"warmup\": " << opts.warmup << ",\n"; + out << " \"reps\": " << opts.reps << ",\n"; out << " \"lattice\": \"" << json_escape(lattice_name) << "\",\n"; out << " \"collision\": \"" << json_escape(collision_name) << "\",\n"; out << " \"grid\": \"" << json_escape(opts.grid) << "\",\n"; out << " \"decomposition\": \"" << decomposition_mode_name(dec_mode) << "\",\n"; + if (pg) { + const carbon::int32_3d dims = pg->dims(); + out << " \"process_grid\": [" << dims.x << ", " << dims.y << ", " << dims.z << "],\n"; + } else { + out << " \"process_grid\": null,\n"; + } out << " \"q\": " << Lattice::Q << ",\n"; out << " \"re\": " << opts.re << ",\n"; out << " \"ulb\": " << ulb << ",\n"; @@ -980,7 +1054,25 @@ run_benchmark(const Options& opts, out << " \"cells_per_iter\": " << static_cast(cells_per_iter) << ",\n"; out << " \"mlups\": " << mlups << ",\n"; out << " \"mlups_per_gpu\": " << (mlups / static_cast(total_gpu_count)) << ",\n"; - out << " \"effective_bandwidth_gb_s\": " << effective_bandwidth_gb_s << "\n"; + out << " \"effective_bandwidth_gb_s\": " << effective_bandwidth_gb_s << ",\n"; + out << " \"repetitions\": {\n"; + out << " \"count\": " << opts.reps << ",\n"; + out << " \"iters_per_rep\": " << iters_per_rep << ",\n"; + out << " \"seconds\": ["; + for (size_t i = 0; i < rep_seconds.size(); ++i) { + out << (i == 0 ? "" : ", ") << rep_seconds[i]; + } + out << "],\n"; + out << " \"mlups\": ["; + for (size_t i = 0; i < rep_mlups.size(); ++i) { + out << (i == 0 ? "" : ", ") << rep_mlups[i]; + } + out << "],\n"; + out << " \"mlups_mean\": " << rep_mlups_mean << ",\n"; + out << " \"mlups_min\": " << rep_mlups_min << ",\n"; + out << " \"mlups_max\": " << rep_mlups_max << ",\n"; + out << " \"mlups_stddev\": " << rep_mlups_stddev << "\n"; + out << " }\n"; out << " }\n"; out << "}\n"; out.close(); diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep-run.sh b/benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep-run.sh new file mode 100755 index 00000000..230bedce --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep-run.sh @@ -0,0 +1,248 @@ +#!/usr/bin/env bash +# +# benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep-run.sh +# +# Strong-scaling sweep of the distributed LBM benchmark on one multi-GPU node: +# lattice/collision x domain size x GPU count x decomposition x transport x +# halo priority. Builds the CUDA+MPI Release tree inside Docker and does one +# `mpiexec -n G` run per combination (one rank per GPU, --grid +# dense_distributed, --overlap OVERLAP). +# +# decompositions slab (split z), pencil (y, z), brick (x, y, z) +# transports mpi = NCCL; mpip2p = MPI point-to-point (CARBON_DIST_TRANSPORT=mpi) +# hp_halo off = normal halo stream; on = --hp-halo (high-priority halo stream) +# +# At G=1 every decomposition is 1x1x1 and there is no halo exchange, so each +# (series, N) gets a single `ref` run instead (mpiexec -n 1, hp-halo off): it +# is the efficiency baseline and the 1-GPU point of every curve. +# +# Timing: after WARMUP solver steps, each run times REPS repetitions of +# ITERS_PER_REP solver steps (binary --reps); every repetition ends with a GPU +# drain and an MPI barrier, so rank 0's clock covers the slowest rank. +# results.mlups is the MLUPS over all timed steps (what the plotter reads); +# results.repetitions holds the per-repetition MLUPS; config.process_grid the +# rank grid ProcessGrid actually chose. +# +# Reports are named +# ---fp32-