diff --git a/benchmarks/cg/cg_poisson.cu b/benchmarks/cg/cg_poisson.cu index f539352d..6d958bfa 100644 --- a/benchmarks/cg/cg_poisson.cu +++ b/benchmarks/cg/cg_poisson.cu @@ -554,7 +554,7 @@ build_matvec(const Grid& grid, 1>& out, double invh2, std::string name) -> carbon::Kernel { - using Span = typename Grid::Span; + using Span = typename Grid::Span; using Idx = typename Grid::Idx; return carbon::Kernel::compute( grid, diff --git a/benchmarks/lbm_lid_driven_cavity/scripts/lbm_sweep_config.py b/benchmarks/lbm_lid_driven_cavity/scripts/lbm_sweep_config.py new file mode 100644 index 00000000..038d37ea --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity/scripts/lbm_sweep_config.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Parse and validate the sweep YAML (see ``lbm-dgx-sweep.yml``). + +Single source of truth for the keys, their defaults and their validation, shared by +``lbm-dgx-sweep-run.sh`` and the plotters in ``plotting/``: + +- ``load_sweep_config(text)`` / ``read_sweep_config(path)`` return every key as a Python + value (lists of ints or strings, ints, bools, strings), defaults filled in. +- Run as a script, it reads the YAML text from ``$LBM_SWEEP_CONFIG`` (empty = all + defaults) and prints ``VAR=value`` lines with the run script's env var names. + +Values end up in shell variables, docker / mpiexec arguments and file names, so only +plain tokens (letters, digits, ``. _ : / -``) are accepted, and ``prefix`` must be a +single path component. +""" + +from __future__ import annotations + +import os +import re +import sys +from pathlib import Path + +# key: (env var of lbm-dgx-sweep-run.sh, kind, default) +KEYS: dict[str, tuple[str, str, object]] = { + "configs": ("CONFIGS", "words", ["q19:bgk"]), + "precisions": ("PRECISIONS", "words", ["fp32"]), + "sizes": ("SIZES", "ints", list(range(256, 513, 64))), + "gpus": ("GPUS_LIST", "ints", list(range(1, 9))), + "grids": ("GRIDS", "words", ["dense", "disg"]), + "transports": ("TRANSPORTS", "words", ["intra", "mpi", "mpip2p"]), + "warmup": ("WARMUP", "int", 400), + "iters_per_rep": ("ITERS_PER_REP", "int", 400), + "reps": ("REPS", "int", 4), + "sm_arch": ("SM_ARCH", "arch", "auto"), + "image_intra": ("IMAGE_INTRA", "word", "carbon-cuda:local"), + "image_mpi": ("IMAGE_MPI", "word", "carbon-cuda-nccl-pinned:local"), + "prefix": ("PREFIX", "name", "lbm-dgx-sweep"), + "skip_build": ("SKIP_BUILD", "bool", False), + "force": ("FORCE", "bool", False), + "run_timeout": ("RUN_TIMEOUT", "int", 1800), +} +CHOICES = { + "configs": {"q19:bgk", "q27:bgk", "q27:kbc"}, + "precisions": {"fp32", "fp64"}, + "grids": {"dense", "disg"}, + "transports": {"intra", "mpi", "mpip2p"}, +} +TOKEN = re.compile(r"^[A-Za-z0-9._:/-]+$") +NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$") + + +class SweepConfigError(ValueError): + """Invalid sweep YAML.""" + + +def _as_int(key: str, v: object) -> int: + minimum = 0 if key == "warmup" else 1 + if isinstance(v, bool) or not isinstance(v, int) or v < minimum: + raise SweepConfigError(f"{key} must be an integer >= {minimum} (got {v!r})") + return v + + +def _as_list(key: str, v: object) -> list: + if isinstance(v, dict): + if set(v) != {"start", "stop", "step"}: + raise SweepConfigError(f"{key} range needs exactly start, stop, step") + start, stop, step = (_as_int(key, v[k]) for k in ("start", "stop", "step")) + return list(range(start, stop + 1, step)) + if isinstance(v, str): + return v.split() + if isinstance(v, list): + return v + return [v] + + +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": + if not isinstance(value, bool): + raise SweepConfigError(f"{key} must be true or false (got {value!r})") + return value + if kind == "arch" and value == "auto": + return "auto" + if kind in ("ints", "arch"): + items = [ + _as_int(key, int(x) if isinstance(x, str) and x.isdigit() else x) + for x in _as_list(key, value) + ] + if not items: + raise SweepConfigError(f"{key} is empty") + return items + items = _as_list(key, value) if kind == "words" else [value] + if not items: + raise SweepConfigError(f"{key} is empty") + pattern = NAME if kind == "name" else TOKEN + 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])}") + return items if kind == "words" else items[0] + + +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()} + 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, choices) + return out + + +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(), keys, choices) + + +def series_prefixes(cfg: dict[str, object]) -> list[tuple[str, str, str, str]]: + """``(series_prefix, lattice, collision, precision)`` for every configs x precisions entry. + + A series prefix (``---``) is what the run script + puts in front of ``--n-g.json``. + """ + out = [] + for c in cfg["configs"]: + lattice, collision = c.split(":") + for precision in cfg["precisions"]: + out.append((f"{cfg['prefix']}-{lattice}-{collision}-{precision}", lattice, collision, + precision)) + return out + + +def _shell_value(kind: str, value: object) -> str: + if kind == "bool": + return "1" if value else "0" + if kind == "arch" and value != "auto": + return ";".join(map(str, value)) + if isinstance(value, list): + return " ".join(map(str, value)) + return str(value) + + +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", ""), keys, choices) + except SweepConfigError as e: + sys.stderr.write(f"error: config: {e}\n") + return 1 + for key, (var, kind, _) in keys.items(): + print(f"{var}={_shell_value(kind, cfg[key])}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-disg-vs-dense/disg-vs-dense-speedup.png b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-disg-vs-dense/disg-vs-dense-speedup.png new file mode 100644 index 00000000..ec3b0ef0 Binary files /dev/null and b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-disg-vs-dense/disg-vs-dense-speedup.png differ diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-disg-vs-dense/disg-vs-dense-summary.csv b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-disg-vs-dense/disg-vs-dense-summary.csv new file mode 100644 index 00000000..ba18c142 --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-disg-vs-dense/disg-vs-dense-summary.csv @@ -0,0 +1,19 @@ +decomp,n,g,dense_mlups,disg_mlups,speedup +brick,256,8,35617.407,24248.140,0.6808 +brick,384,8,44884.536,28672.174,0.6388 +brick,512,8,48408.605,31273.917,0.6460 +pencil,256,4,30206.431,17458.764,0.5780 +pencil,256,8,50375.249,32472.333,0.6446 +pencil,384,4,32029.573,19010.249,0.5935 +pencil,384,8,61085.733,36929.974,0.6046 +pencil,512,4,32614.456,19725.893,0.6048 +pencil,512,8,63194.988,38747.500,0.6131 +slab,256,2,15697.892,9845.159,0.6272 +slab,256,4,30201.093,19039.444,0.6304 +slab,256,8,56927.116,34590.962,0.6076 +slab,384,2,16354.072,10371.083,0.6342 +slab,384,4,31878.404,20620.534,0.6468 +slab,384,8,61392.481,39422.238,0.6421 +slab,512,2,16642.525,10595.283,0.6366 +slab,512,4,32548.910,21353.558,0.6560 +slab,512,8,63975.557,41819.560,0.6537 diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-disg-vs-dense/json/failed.txt b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-disg-vs-dense/json/failed.txt new file mode 100644 index 00000000..e69de29b diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-disg-vs-dense/lbm-disg-vs-dense-sweep.yml b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-disg-vs-dense/lbm-disg-vs-dense-sweep.yml new file mode 100644 index 00000000..55722d52 --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-disg-vs-dense/lbm-disg-vs-dense-sweep.yml @@ -0,0 +1,25 @@ +# Comparison sweep: DenseDistributed vs DenseDisgDistributed. +# Same matrix as lbm-dist-sweep, both grids, hp-halo on (the fair OCC baseline). +configs: [q19:bgk] +grids: [dense_distributed, disg_distributed] +sizes: [256, 384, 512] +decompositions: [slab, pencil, brick] +gpus_slab: [2, 4, 8] +gpus_pencil: [4, 8] +gpus_brick: [8] +transports: [mpi] +hp_halo: ["on"] +overlap: standard +warmup: 400 +iters_per_rep: 400 +reps: 5 +sm_arch: "80" +image: carbon-cuda-nccl-pinned:local +build_dir: build-dist +prefix: lbm-disg-vs-dense +skip_build: true +force: true +run_timeout: 1800 +reference_dir: benchmarks/lbm_lid_driven_cavity/data/lbm-dgx-sweep/json +reference_prefix: lbm-dgx-sweep +reference_label: dense-intra diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/json/failed.txt b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/json/failed.txt new file mode 100644 index 00000000..e69de29b diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-gpus-n256.png b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-gpus-n256.png new file mode 100644 index 00000000..da080b34 Binary files /dev/null and b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-gpus-n256.png differ diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-gpus-n320.png b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-gpus-n320.png new file mode 100644 index 00000000..e16644a8 Binary files /dev/null and b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-gpus-n320.png differ diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-gpus-n384.png b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-gpus-n384.png new file mode 100644 index 00000000..27d00404 Binary files /dev/null and b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-gpus-n384.png differ diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-gpus-n448.png b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-gpus-n448.png new file mode 100644 index 00000000..7a6419a1 Binary files /dev/null and b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-gpus-n448.png differ diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-gpus-n512.png b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-gpus-n512.png new file mode 100644 index 00000000..35fa4677 Binary files /dev/null and b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-gpus-n512.png differ diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-n-g8.png b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-n-g8.png new file mode 100644 index 00000000..d3b394e7 Binary files /dev/null and b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-eff-vs-n-g8.png differ diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-hp-speedup-mpi.png b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-hp-speedup-mpi.png new file mode 100644 index 00000000..03db5beb Binary files /dev/null and b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-hp-speedup-mpi.png differ diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-mlups-vs-gpus-n256.png b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-mlups-vs-gpus-n256.png new file mode 100644 index 00000000..a47b6c5f Binary files /dev/null and b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-mlups-vs-gpus-n256.png differ diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-mlups-vs-gpus-n320.png b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-mlups-vs-gpus-n320.png new file mode 100644 index 00000000..e8541ab4 Binary files /dev/null and b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-mlups-vs-gpus-n320.png differ diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-mlups-vs-gpus-n384.png b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-mlups-vs-gpus-n384.png new file mode 100644 index 00000000..c4b30249 Binary files /dev/null and b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-mlups-vs-gpus-n384.png differ diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-mlups-vs-gpus-n448.png b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-mlups-vs-gpus-n448.png new file mode 100644 index 00000000..76b4cd2a Binary files /dev/null and b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-mlups-vs-gpus-n448.png differ diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-mlups-vs-gpus-n512.png b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-mlups-vs-gpus-n512.png new file mode 100644 index 00000000..bc09292b Binary files /dev/null and b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep-q19-bgk-fp32-mlups-vs-gpus-n512.png differ 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..eb9f9fa9 --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep.yml @@ -0,0 +1,86 @@ +# 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} + +# Process decompositions, one plot panel each: +# slab split z +# pencil split y and z +# brick split x, y and z +decompositions: [slab, pencil, brick] + +# GPU counts (= MPI ranks, all >= 2) of each decomposition. ProcessGrid +# factorises the rank count, so pencil only differs from a slab at 4 (1x2x2) +# and 8 (1x2x4), and brick only at 8 (2x2x2); the plots print the process +# grid under each GPU count. +gpus_slab: {start: 2, stop: 8, step: 1} +gpus_pencil: [4, 8] +gpus_brick: [8] + +# 1-GPU efficiency baseline: no 1-GPU run is done here. For size N the +# plotter reads +# /---fp32--n-g1.json +# (reference_dir relative to the carbon repo root), by default the Dense +# Peeraccess run of the single-process DGX sweep. +reference_dir: benchmarks/lbm_lid_driven_cavity/data/lbm-dgx-sweep/json +reference_prefix: lbm-dgx-sweep +reference_label: dense-intra + +# 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..0f13abfe --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/reproduce.sh @@ -0,0 +1,51 @@ +#!/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; one MPI rank per GPU; slab on 2..8 GPUs, pencil on +# 4 and 8, brick on 8; NCCL halos with --hp-halo off and on; +# 400 warmup steps, then 5 timed repetitions of 1000 solver steps. +# Efficiency is relative to the 1-GPU Dense Peeraccess runs of +# benchmarks/lbm_lid_driven_cavity/data/lbm-dgx-sweep/json (no 1-GPU run here). +# +# Original run: 8x A100-SXM4-40GB (NVLink), driver 535.161.08, carbon commit +# 0d504c5, image carbon-cuda-nccl-pinned:local (NCCL 2.27.7, CUDA 12.2). +# +# 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 an hour 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 new file mode 100644 index 00000000..e57d6a14 --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu @@ -0,0 +1,1172 @@ +// Carbon LBM lid-driven cavity benchmark — port of +// Neon/benchmarks/lbm-lid-driven-cavity-flow on top of carbon::Skeleton. +// +// Models a unit-cube cavity with bounce-back walls on the -x/+x, -y/+y, -z +// faces and a moving lid (u = (ulb, 0, 0)) on the +y face. Each iteration +// is wrapped in a 1-kernel carbon::Skeleton (the halo on the input +// population is auto-inserted by Skeleton::compile because the iteration +// kernel calls loader.read_stencil(fIn)). Two skeletons (one per +// ping-pong direction) are precompiled before the timing loop so the hot +// loop is a tight `sk.run(); sk.wait();` pair with no allocation / +// no recompilation. +// +// Lattice + collision are runtime-selectable via CLI: +// --lattice {q19,q27} : D3Q19 (default) or D3Q27. +// --collision {bgk,kbc} : BGK SRT (default) or KBC entropic stabilisation +// (Karlin-Bösch-Chikatamarla, 2014). KBC requires +// D3Q27 — the moment matrix and shear-decomposition +// table needed by the entropic step are only +// defined for the full 27-velocity lattice. +// +// Headline metric is MLUPS — Million Lattice Updates Per Second — computed +// over the post-warmup iterations only: +// +// MLUPS = (N^3 * iters_timed) / (1e6 * elapsed_seconds) +// +// CLI (clipp; same one-shot man page as examples/cg_poisson_unified.cu). + +#include "src/cell_type.h" +#include "src/d3q19.h" +#include "src/d3q27.h" +#include "src/lbm_kernels.h" + +#include +#include +#include +#include +#include +#include +// CARBON_BACKEND_NAME is "cuda" or "sycl" depending on which backend the +// library was configured with. Stamped into the JSON report's system block +// so a sweep that drives both backends from the same scripts/ directory +// can colour-code them without resorting to filename heuristics. +#include +#ifdef CARBON_HAVE_MPI_NCCL +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#if __has_include() +# include +# define CARBON_HALO_NVTX_PUSH(name) ::nvtxRangePushA(name) +# define CARBON_HALO_NVTX_POP() ::nvtxRangePop() +#elif __has_include() +# include +# define CARBON_HALO_NVTX_PUSH(name) ::nvtxRangePushA(name) +# define CARBON_HALO_NVTX_POP() ::nvtxRangePop() +#else +# define CARBON_HALO_NVTX_PUSH(name) ((void)0) +# define CARBON_HALO_NVTX_POP() ((void)0) +#endif + + + +namespace { + +using carbon::bench::lbm::BgkCollision; +using carbon::bench::lbm::Classification; +using carbon::bench::lbm::D3Q19; +using carbon::bench::lbm::D3Q27; +using carbon::bench::lbm::encode_cell; +using carbon::bench::lbm::KbcCollision; +using carbon::bench::lbm::LbmParameters; +using carbon::bench::lbm::make_compute_wall_mask_kernel; +using carbon::bench::lbm::make_iteration_kernel; +using carbon::bench::lbm::make_iteration_kernel_d3q19_bgk_fast; +using carbon::bench::lbm::make_macroscopic_kernel; + +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; + int64_t report_every = 100; + bool no_warmup_skip = false; + std::string lattice = "q19"; + std::string collision = "bgk"; + // Grid family the benchmark runs on. "dense" is carbon::Dense (aggregated + // Cartesian z-slabs); "disg" is carbon::DenseDisg (the disaggregated, + // five-region-per-slab lattice-Boltzmann layout); "dense_distributed" is + // carbon::DenseDistributed, which honours --decomposition and exchanges + // halos along all decomposed axes; "disg_distributed" is + // carbon::DenseDisgDistributed (disaggregated layout on a ProcessGrid; + // slab, pencil and brick). All run the identical hot kernel — the only + // differences are the per-slab storage layout and the auto-inserted halo + // family (Halo / HaloDisg / HaloDistributed / HaloDisgDistributed). + std::string grid = "dense"; + std::string decomposition = "slab"; + std::string report_path = ""; + std::string label = ""; + std::string vtk_path = ""; + // Skeleton OCC mode applied to both ping-pong skeletons. "none" (default, + // single-stream Standard launch) keeps the existing baseline behaviour; + // "standard" enables the carbon::Skeleton OCC rewrite that splits the + // stencil node into Internal + Boundary halves and overlaps the halo with + // the Internal launch on a second stream — the default-OFF state of + // OverlapMode is the dominant reason multi-GPU regresses below 1-GPU on + // PCIe-only hosts (the halo serialises behind every iteration). + // "extended" / "twoway-extended" are the more aggressive OCC modes; in + // the LBM iteration there is only one stencil node so they degenerate to + // "standard" but are exposed here for symmetry with carbon::OverlapMode. + std::string overlap = "none"; + // Create the OCC halo stream with the greatest driver priority + // (carbon::Skeleton::Options::halo_stream_priority = High). The halo's gather / + // NCCL / scatter kernels and the Boundary half inherit it, so they get SMs ahead of + // the Internal half's pending blocks. Only meaningful with --overlap != none. + bool hp_halo = false; + std::string export_dot_path = ""; + std::string export_dot_png_path = ""; + std::string export_dot_streams_path = ""; + // Opt in to carbon::Skeleton CUDA-graph capture + replay of each ping-pong + // skeleton. Engaged only for single-GPU / single-stream schedules (the + // OverlapMode::None single-GPU case); a no-op fallback otherwise. + bool cuda_graph = false; + // After the timed loop, Sum-reduce the whole final population field and print + // CHECKSUM=. Because sum_q pop_q == rho per cell, this is the total + // mass in the domain — a single scalar that is invariant across grid families + // when the streaming/collision is numerically identical. Used to verify that + // --grid dense and --grid disg produce bit-comparable physics (they run the + // same hot kernel; only the storage layout + halo family differ). + bool checksum = false; + bool show_help = false; + /** Limit to first N visible CUDA devices (-1 = all visible). Same as jacobi_nvidia -gpus. */ + int n_gpus = -1; +}; + +[[nodiscard]] auto +build_cli(Options& opts) -> clipp::group { + using clipp::integer; + using clipp::number; + using clipp::option; + using clipp::value; + return clipp::group( + (option("-h", "--help").set(opts.show_help) % "Show this help message and exit"), + (option("--n") & integer("n", opts.n)) % "Cavity edge length in cells (default 128)", + (option("--iters") & integer("iters", opts.iters)) % + "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)", + (option("--lattice") & value("q19|q27", opts.lattice)) % + "Lattice stencil: q19 (D3Q19, default) or q27 (D3Q27)", + (option("--collision") & value("bgk|kbc", opts.collision)) % + "Collision model: bgk (default) or kbc (entropic; D3Q27 only)", + (option("--grid") & value("dense|disg|dense_distributed|disg_distributed", opts.grid)) % + "Grid family: dense (carbon::Dense, default), disg (carbon::DenseDisg, " + "the disaggregated five-region LBM layout), dense_distributed " + "(carbon::DenseDistributed, honours --decomposition), or disg_distributed " + "(carbon::DenseDisgDistributed, disaggregated + ProcessGrid). " + "Same hot kernel on all.", + (option("--decomposition") & value("slab|pencil|brick", opts.decomposition)) % + "Process decomposition for --grid dense_distributed|disg_distributed " + "(default: slab). slab splits z; pencil splits y and z; brick splits all three " + "axes. Auto-factorized across ranks; ignored for dense/disg, which are slab-only.", + (option("-gpus", "--gpus") & integer("n", opts.n_gpus)) % + "Use the first N visible CUDA devices (-1 = all visible; default -1). " + "Combine with CUDA_VISIBLE_DEVICES to pick physical GPUs.", + (option("--report-every") & integer("n", opts.report_every)) % + "Log progress every N iterations (default 100; 0 silences)", + (option("--report") & value("path", opts.report_path)) % + "Write a structured JSON report to PATH on success " + "(consumed by scripts/sweep_and_plot.py)", + (option("--label") & value("string", opts.label)) % + "Free-form label written into the JSON report under config.label " + "(useful for tagging sweeps)", + (option("--vtk-out") & value("path", opts.vtk_path)) % + "After the timed loop, run the macroscopic kernel and dump rho + u " + "as a VTK legacy STRUCTURED_POINTS file at PATH (carbon::io::write_vtk; " + "appends .rankN under MPI). Off by default — adds ~one kernel + a " + "GPU->host copy of size cells*16B.", + (option("--overlap") & value("none|standard|extended|twoway-extended", opts.overlap)) % + "Skeleton OCC mode (default 'none'). 'standard' splits the stencil " + "node into Internal + Boundary so the halo overlaps with Internal on " + "a second stream — improves multi-GPU significantly on PCIe-only " + "hosts where halo otherwise blocks compute.", + option("--hp-halo").set(opts.hp_halo) % + "Create the OCC halo stream with the highest driver priority (Skeleton " + "Options::halo_stream_priority = High) so the halo gather / NCCL / scatter and " + "Boundary kernels get SMs before Internal's pending blocks. Only meaningful with " + "--overlap != none.", + (option("--export-dot") & value("path", opts.export_dot_path)) % + "Write the compiled Skeleton launch-matrix schedule (GraphViz .dot) for " + "the AB ping-pong skeleton to PATH after compile.", + (option("--export-dot-png") & value("path", opts.export_dot_png_path)) % + "Render the launch-matrix schedule to PNG via GraphViz (requires dot on " + "PATH). Also writes a sibling .dot file.", + (option("--export-dot-streams") & value("path", opts.export_dot_streams_path)) % + "Write the stream-cluster schedule graph (legacy export_dot format) to PATH.", + option("--cuda-graph").set(opts.cuda_graph) % + "Capture + replay each ping-pong skeleton as a CUDA graph (single-GPU / " + "single-stream only; transparently falls back to eager launch otherwise). " + "Collapses per-iteration host launch overhead.", + option("--checksum").set(opts.checksum) % + "After the loop, Sum-reduce the final population field and print " + "CHECKSUM=. Grid-family invariant — used to verify " + "dense, disg, and dense_distributed runs match numerically.", + option("--no-warmup-skip").set(opts.no_warmup_skip) % + "Include warmup iterations in the timing window (debug aid)"); +} + +[[nodiscard]] auto +parse_cli(int argc, + char** argv, + Options& opts) -> bool { + auto cli = build_cli(opts); + if (!clipp::parse(argc, argv, cli) || opts.show_help) { + auto fmt = clipp::doc_formatting{}.doc_column(31); + std::cout << clipp::make_man_page(cli, argv[0], fmt) << '\n'; + return opts.show_help; + } + if (opts.n < 4) { + std::cerr << "lbm_lid_driven_cavity: --n must be >= 4 (got " << opts.n << ")\n"; + return false; + } + if (opts.iters <= 0) { + std::cerr << "lbm_lid_driven_cavity: --iters must be > 0 (got " << opts.iters << ")\n"; + return false; + } + if (opts.warmup < 0 || opts.warmup >= opts.iters) { + std::cerr << "lbm_lid_driven_cavity: --warmup must be in [0, iters) (got " << opts.warmup + << " 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"; + return false; + } + if (opts.collision != "bgk" && opts.collision != "kbc") { + std::cerr << "lbm_lid_driven_cavity: --collision must be bgk or kbc (got '" << opts.collision + << "')\n"; + return false; + } + if (opts.collision == "kbc" && opts.lattice != "q27") { + std::cerr << "lbm_lid_driven_cavity: --collision kbc requires --lattice q27 " + "(KBC's moment basis is defined for D3Q27 only)\n"; + return false; + } + if (opts.grid != "dense" && opts.grid != "disg" && opts.grid != "dense_distributed" && + opts.grid != "disg_distributed") { + std::cerr << "lbm_lid_driven_cavity: --grid must be dense, disg, dense_distributed, or " + "disg_distributed (got '" + << opts.grid << "')\n"; + return false; + } + if (opts.decomposition != "slab" && opts.decomposition != "pencil" && + opts.decomposition != "brick") { + std::cerr << "lbm_lid_driven_cavity: --decomposition must be slab, pencil, or brick (got '" + << opts.decomposition << "')\n"; + return false; + } + if (opts.grid != "dense_distributed" && opts.grid != "disg_distributed" && + opts.decomposition != "slab") { + std::cerr << "lbm_lid_driven_cavity: --decomposition " << opts.decomposition + << " requires --grid dense_distributed or disg_distributed " + "(dense/disg are slab-only)\n"; + return false; + } + if (opts.overlap != "none" && opts.overlap != "standard" && opts.overlap != "extended" && + opts.overlap != "twoway-extended") { + std::cerr << "lbm_lid_driven_cavity: --overlap must be one of " + "{none, standard, extended, twoway-extended} (got '" + << opts.overlap << "')\n"; + return false; + } + return true; +} + +[[nodiscard]] auto +overlap_mode_from_string(std::string_view s) -> carbon::OverlapMode { + if (s == "standard") { + return carbon::OverlapMode::Standard; + } + if (s == "extended") { + return carbon::OverlapMode::Extended; + } + if (s == "twoway-extended") { + return carbon::OverlapMode::TwoWayExtended; + } + return carbon::OverlapMode::None; +} + +[[nodiscard]] auto +parse_decomposition_mode(std::string_view s) -> std::optional { + if (s == "slab" || s.empty()) { + return carbon::DecompositionMode::Slab; + } + if (s == "pencil") { + return carbon::DecompositionMode::Pencil; + } + if (s == "brick") { + return carbon::DecompositionMode::Brick; + } + return std::nullopt; +} + +[[nodiscard]] auto +decomposition_mode_name(carbon::DecompositionMode m) -> const char* { + switch (m) { + case carbon::DecompositionMode::Slab: + return "slab"; + case carbon::DecompositionMode::Pencil: + return "pencil"; + case carbon::DecompositionMode::Brick: + return "brick"; + case carbon::DecompositionMode::Custom: + return "custom"; + } + return "?"; +} + +// Tiny RFC-3339 / ISO-8601 timestamp helper used in the JSON report. +[[nodiscard]] auto +utc_timestamp_now() -> std::string { + const std::time_t now = std::time(nullptr); + std::tm tm_utc{}; +#if defined(_WIN32) + gmtime_s(&tm_utc, &now); +#else + gmtime_r(&now, &tm_utc); +#endif + std::ostringstream oss; + oss << std::put_time(&tm_utc, "%Y-%m-%dT%H:%M:%SZ"); + return oss.str(); +} + +// Minimal JSON string escape (handles ", \, control chars). Hand-rolled +// because a full rapidjson dependency would be overkill for the ~12 fields +// we emit. Keep this function private to the TU. +[[nodiscard]] auto +json_escape(const std::string& s) -> std::string { + std::string out; + out.reserve(s.size() + 2); + for (char c : s) { + switch (c) { + case '"': + out += "\\\""; + break; + case '\\': + out += "\\\\"; + break; + case '\b': + out += "\\b"; + break; + case '\f': + out += "\\f"; + break; + case '\n': + out += "\\n"; + break; + case '\r': + out += "\\r"; + break; + case '\t': + out += "\\t"; + break; + default: + if (static_cast(c) < 0x20) { + char buf[8]; + std::snprintf(buf, sizeof(buf), "\\u%04x", static_cast(c)); + out += buf; + } else { + out += c; + } + } + } + return out; +} + +// Equilibrium population for component q at zero velocity and rho = 1: w_q. +// The lid layer also seeds populations with the bounce-back lid-momentum +// correction (-6 * w_q * ulb * (c_q . ulid)) so the very first iteration +// sees a reasonable approximation of the steady state instead of having to +// spin up from rest. Templated on Lattice so the same init logic feeds +// either D3Q19 or D3Q27. +template +[[nodiscard]] auto +init_population_value(const carbon::int64_3d& gc, + const carbon::int64_3d& global, + int q, + double ulb) -> float { + const float w = Lattice::w(q); + const bool on_boundary = (gc.x == 0 || gc.x == global.x - 1 || gc.y == 0 || + gc.y == global.y - 1 || gc.z == 0 || gc.z == global.z - 1); + if (!on_boundary) { + return w; + } + if (gc.y == global.y - 1) { + // Moving lid. Mirrors Neon's init: -6 * w_q * ulb * (c_q . ulid), + // where ulid = (1, 0, 0). c_q.x carries the sign. + const auto cq = Lattice::c(q); + const float dot = static_cast(cq.x) * 1.0F; + return static_cast(-6.0F * w * static_cast(ulb) * dot); + } + return 0.0F; +} + +[[nodiscard]] auto +init_cell_value(const carbon::int64_3d& gc, + const carbon::int64_3d& global) -> int32_t { + const bool on_boundary = (gc.x == 0 || gc.x == global.x - 1 || gc.y == 0 || + gc.y == global.y - 1 || gc.z == 0 || gc.z == global.z - 1); + if (!on_boundary) { + return encode_cell(Classification::Bulk); + } + if (gc.y == global.y - 1) { + return encode_cell(Classification::MovingWall); + } + return encode_cell(Classification::BounceBack); +} + +// Build the carbon::Stencil for a given lattice — radius-1 stencil +// covering every non-center direction. Used to seed Span::halo_z so multi- +// GPU runs allocate the right z-halo on each slab. Both D3Q19 and D3Q27 have +// |c_q|_inf == 1 so radius is 1 either way; what changes is the count +// (18 for D3Q19, 26 for D3Q27). +template +[[nodiscard]] auto +make_lbm_stencil() -> carbon::Stencil { + std::vector stencil_points; + stencil_points.reserve(Lattice::Q - 1); + for (int q = 0; q < Lattice::Q; ++q) { + if (q == Lattice::kCenter) { + continue; + } + const auto cq = Lattice::c(q); + stencil_points.push_back({cq.x, cq.y, cq.z}); + } + return carbon::Stencil(stencil_points, /*remove_center=*/true); +} + +// One-shot benchmark body, instantiated once per (lattice, collision) pair +// from main(). The dispatch is: parse opts, switch on the (lattice, +// collision) combo, instantiate this template, run it, return its exit +// code. This keeps all the instantiation cost on configurations the user +// actually exercises (the dispatch only calls one of the three +// instantiations for a given run). +[[nodiscard]] auto +make_single_process_system(int n_gpus_limit) -> carbon::System { + std::vector devices = carbon::get_all_devices(); + if (devices.empty()) { + carbon::log::throw_with_log( + "lbm_lid_driven_cavity: no CUDA devices visible"); + } + if (n_gpus_limit > 0 && static_cast(n_gpus_limit) < devices.size()) { + devices.erase(devices.begin() + static_cast(n_gpus_limit), devices.end()); + } + if (n_gpus_limit > 0 && static_cast(n_gpus_limit) > devices.size()) { + CARBON_LOG_WARN( + "lbm_lid_driven_cavity: --gpus {} requested but only {} CUDA device(s) visible " + "(check CUDA_VISIBLE_DEVICES)", + n_gpus_limit, devices.size()); + } + return carbon::System(std::move(devices)); +} + +template +[[nodiscard]] auto +run_benchmark(const Options& opts, + const std::string& lattice_name, + const std::string& collision_name, + carbon::DecompositionMode dec_mode) -> int { + static_assert(std::is_same_v || std::is_same_v || + std::is_same_v || + std::is_same_v, + "LBM benchmark supports carbon::Dense, carbon::DenseDisg, " + "carbon::DenseDistributed, and carbon::DenseDisgDistributed only."); +#ifdef CARBON_HAVE_MPI_NCCL + // Auto-detect MPI launches: the `Distributed` ctor invokes `MPI_Init` (a + // no-op when already initialised) and bootstraps an `ncclComm_t` over every + // visible rank. Under a single-process launch (no `mpiexec` wrapping) + // `world_size() == 1` and we fall through to the local-`get_all_devices()` + // path so the existing single-host behaviour is byte-for-byte preserved. + // Under `mpiexec -n R` the constructor binds rank `r` to its local GPU via + // `pin_local_device` and `System(distributed)` carries `gpu_group.size() == + // 1` (carbon's strict one-rank-per-GPU model). + auto distributed = std::make_shared(); + const bool use_mpi = distributed->world_size() > 1; + carbon::System sys = + use_mpi ? carbon::System(distributed) : make_single_process_system(opts.n_gpus); + const int world_rank = use_mpi ? distributed->world_rank() : 0; + const int world_size = use_mpi ? distributed->world_size() : 1; +#else + carbon::System sys = make_single_process_system(opts.n_gpus); + const bool use_mpi = false; + const int world_rank = 0; + const int world_size = 1; +#endif + const size_t n_gpus = sys.gpu_group().size(); + const int local_gpu_count = static_cast(n_gpus); + const int total_gpu_count = use_mpi ? world_size : local_gpu_count; + + const carbon::Stencil stencil = make_lbm_stencil(); + const carbon::int64_3d global{opts.n, opts.n, opts.n}; + + std::optional pg; + if constexpr (std::is_same_v || + std::is_same_v) { + const int grid_world = use_mpi ? world_size : local_gpu_count; + pg.emplace(carbon::ProcessGrid::make(grid_world, dec_mode)); + if (world_rank == 0) { + const carbon::int32_3d dims = pg->dims(); + CARBON_LOG_INFO("lbm_lid_driven_cavity: process_grid={}x{}x{} (world_size={})", dims.x, + dims.y, dims.z, grid_world); + } + } + + // Construct the selected grid family. Dense/DenseDisg give a radius-1 z-halo + // (D3Q19 / D3Q27 have |c|_inf == 1); DenseDistributed / DenseDisgDistributed + // derive per-axis halos from the same stencil and honour the requested + // decomposition. Only one branch is instantiated per Grid, so the IIFE's + // return type is the concrete grid type for this instantiation. + Grid grid = [&]() -> Grid { + if constexpr (std::is_same_v) { + return carbon::Dense(sys, global, stencil); + } else if constexpr (std::is_same_v) { + return carbon::DenseDisg(sys, global, /*halo_z=*/1); + } else if constexpr (std::is_same_v) { + return carbon::DenseDisgDistributed(sys, global, *pg, stencil); + } else { + return carbon::DenseDistributed(sys, global, *pg, stencil); + } + }(); + + const double ulb = opts.ulb; + // Re = u_lb * L / nu_lb => nu_lb = u_lb * L / Re. omega is the BGK + // (or KBC, beta = omega/2) relaxation timescale tied to nu via + // nu = (1/omega - 1/2) / 3. + const double nu_lb = ulb * static_cast(opts.n - 1) / opts.re; + const double omega = 1.0 / (3.0 * nu_lb + 0.5); + const LbmParameters params{static_cast(ulb), static_cast(omega)}; + + CARBON_LOG_INFO( + "lbm_lid_driven_cavity: lattice={} collision={} N={} iters={} warmup={} " + "Re={:.3g} ulb={:.4g} omega={:.4g} GPUs={} local_gpus={} ranks={} decomposition={} Q={}", + lattice_name, collision_name, opts.n, opts.iters, opts.warmup, opts.re, ulb, omega, + total_gpu_count, local_gpu_count, world_size, decomposition_mode_name(dec_mode), Lattice::Q); + + // Two ping-pong populations + a cell-type field. HostDevice so we can + // seed them from the CPU via fill_owned_host then upload once. + auto pop_a = grid.template newField(carbon::MemorySide::HostDevice, "pop_a"); + auto pop_b = grid.template newField(carbon::MemorySide::HostDevice, "pop_b"); + auto cells = grid.template newField(carbon::MemorySide::HostDevice, "cells"); + auto cells_scratch = + grid.template newField(carbon::MemorySide::HostDevice, "cells_scratch"); + + auto pop_filler = [&global, ulb](carbon::int64_3d gc, int q) -> float { + return init_population_value(gc, global, q, ulb); + }; + pop_a.fill_owned_host(pop_filler); + pop_b.fill_owned_host(pop_filler); + cells.fill_owned_host([&global](carbon::int64_3d gc, int /*c*/) { + return init_cell_value(gc, global); + }); + cells_scratch.fill_owned_host([&global](carbon::int64_3d gc, int /*c*/) { + return init_cell_value(gc, global); + }); + + carbon::Stream upload_stream = sys.stream(); + try { + carbon::Transfer(sys, pop_a.cpu_buffers(), pop_a.gpu_buffers())(upload_stream); + carbon::Transfer(sys, pop_b.cpu_buffers(), pop_b.gpu_buffers())(upload_stream); + carbon::Transfer(sys, cells.cpu_buffers(), cells.gpu_buffers())(upload_stream); + carbon::Transfer(sys, cells_scratch.cpu_buffers(), + cells_scratch.gpu_buffers())(upload_stream); + upload_stream.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: upload failed: {}", e.what()); + return EXIT_FAILURE; + } + + // Precompute wall_neighbour_bits once into cells (reads cells, writes + // cells_scratch through the auto-halo + Stencil pattern; then a peer-copy + // publishes the result back into the canonical "cells" field). + { + carbon::Skeleton precompute(sys); + precompute.add(make_compute_wall_mask_kernel(grid, cells, cells_scratch)); + try { + precompute.compile(); + precompute.run(); + precompute.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: wall-mask compute failed: {}", e.what()); + return EXIT_FAILURE; + } + try { + carbon::Transfer(sys, cells_scratch.gpu_buffers(), + cells.gpu_buffers())(upload_stream); + upload_stream.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: wall-mask publish failed: {}", e.what()); + return EXIT_FAILURE; + } + } + + // Pick the symmetry-unrolled D3Q19+BGK fast-path when the (lattice, + // collision) combo allows it (factored macroscopic + GO/BK eqopp = eq + + // rho * w * 6 * c.u, mirroring Neon's lbm-flow-over-sphere SOTA path); + // otherwise fall through to the lattice-generic body that also covers + // (D3Q27, BGK) and (D3Q27, KBC). Selected at compile time so the two + // ping-pong skeletons each instantiate exactly one kernel. + auto build_iter = [&](typename Grid::template Field& fIn, + typename Grid::template Field& fOut, std::string name) { + if constexpr (std::is_same_v && std::is_same_v) { + return make_iteration_kernel_d3q19_bgk_fast(grid, fIn, fOut, cells, params, + std::move(name)); + } else { + return make_iteration_kernel(grid, fIn, fOut, cells, params, + std::move(name)); + } + }; + + const carbon::Skeleton::Options sk_opts( + overlap_mode_from_string(opts.overlap), + /*strict_halo=*/false, /*max_streams=*/0U, + /*log_dot_on_compile=*/false, + /*use_cuda_graph=*/opts.cuda_graph, + opts.hp_halo ? carbon::StreamPriority::High : carbon::StreamPriority::Normal); + carbon::Skeleton sk_ab(sys, sk_opts); + sk_ab.add(build_iter(pop_a, pop_b, "lbm_step_ab")); + carbon::Skeleton sk_ba(sys, sk_opts); + sk_ba.add(build_iter(pop_b, pop_a, "lbm_step_ba")); + try { + sk_ab.compile(); + sk_ba.compile(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: skeleton compile failed: {}", e.what()); + return EXIT_FAILURE; + } + CARBON_LOG_INFO( + "lbm_lid_driven_cavity: skeletons compiled — sk_ab.effective_kernels={} " + "sk_ba.effective_kernels={} (auto-halos included) streams={} overlap={} hp_halo={}", + sk_ab.effective_kernels().size(), sk_ba.effective_kernels().size(), sk_ab.num_streams(), + opts.overlap, opts.hp_halo); + + if (!opts.export_dot_path.empty()) { + if (!sk_ab.export_launch_matrix_dot_file(opts.export_dot_path, "lbm_sk_ab")) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: --export-dot failed for {}", opts.export_dot_path); + return EXIT_FAILURE; + } + CARBON_LOG_INFO("lbm_lid_driven_cavity: wrote launch-matrix DOT to {}", opts.export_dot_path); + } + if (!opts.export_dot_png_path.empty()) { + if (!sk_ab.export_launch_matrix_dot_png(opts.export_dot_png_path, "lbm_sk_ab")) { + CARBON_LOG_ERROR( + "lbm_lid_driven_cavity: --export-dot-png failed for {} (is graphviz dot on PATH?)", + opts.export_dot_png_path); + return EXIT_FAILURE; + } + CARBON_LOG_INFO("lbm_lid_driven_cavity: wrote launch-matrix PNG to {}", opts.export_dot_png_path); + } + if (!opts.export_dot_streams_path.empty()) { + if (!sk_ab.export_dot_file(opts.export_dot_streams_path, "lbm_sk_ab")) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: --export-dot-streams failed for {}", + opts.export_dot_streams_path); + return EXIT_FAILURE; + } + CARBON_LOG_INFO("lbm_lid_driven_cavity: wrote stream-cluster DOT to {}", + opts.export_dot_streams_path); + } + + 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 { + 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", + opts.warmup); + } + } + CARBON_HALO_NVTX_PUSH("Iteration step"); + carbon::Skeleton& sk = (it % 2 == 0) ? sk_ab : sk_ba; + try { + sk.run(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: iter {} failed: {}", it, e.what()); + return EXIT_FAILURE; + } + if (opts.report_every > 0 && (it + 1) % opts.report_every == 0) { + try { + sk_ab.wait(); + sk_ba.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: progress sync failed at iter {}: {}", it + 1, + e.what()); + return EXIT_FAILURE; + } + const auto now = Clock::now(); + const double elapsed_overall = Seconds(now - overall_started).count(); + if (world_rank == 0) { + CARBON_LOG_INFO("lbm_lid_driven_cavity: iter {}/{} elapsed={:.3f}s", it + 1, opts.iters,elapsed_overall); + } + } + CARBON_HALO_NVTX_POP(); + + } + + try { + drain_all_ranks(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: final sync failed: {}", e.what()); + return EXIT_FAILURE; + } + const auto timing_ended = Clock::now(); + if (!timing_running) { + CARBON_LOG_ERROR( + "lbm_lid_driven_cavity: timing window never opened (timed_start={} but the loop " + "never reached that iteration).", + timed_start); + return EXIT_FAILURE; + } + const double timing_seconds = Seconds(timing_ended - timing_started).count(); + const int64_t timed_iters = opts.iters - timed_start; + const double cells_per_iter = + static_cast(opts.n) * static_cast(opts.n) * static_cast(opts.n); + 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()); + + 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. + if (world_rank == 0) { + CARBON_LOG_INFO( + "lbm_lid_driven_cavity: DONE lattice={} collision={} timing_window={} iters in " + "{:.3f}s => {:.2f} MLUPS ({:.2f} MLUPS/GPU) overall={:.3f}s GPUs={} " + "local_gpus={} ranks={} decomposition={}", + lattice_name, collision_name, timed_iters, timing_seconds, mlups, + mlups / static_cast(total_gpu_count), overall_seconds, total_gpu_count, + local_gpu_count, world_size, decomposition_mode_name(dec_mode)); + std::cout << "MLUPS=" << mlups << " (cavity N=" << opts.n << " iters=" << timed_iters + << " gpus=" << total_gpu_count << " local_gpus=" << local_gpu_count + << " 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 + // field. sum_q pop_q == rho per cell, so this equals the total mass in the + // domain — a single scalar that must agree across dense, disg, and + // dense_distributed when the physics is numerically identical (they share the + // hot kernel; only the storage layout + auto-halo family differ). Cross-rank + // allreduce kicks in automatically under MPI via ReductionResult's stage-3 + // path. + if (opts.checksum) { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + auto& latest_pop = (opts.iters % 2 == 1) ? pop_b : pop_a; + carbon::ReductionResult mass_result(sys); + carbon::Skeleton checksum_sk(sys); + checksum_sk.add(carbon::Kernel::reduce( + grid, + [&latest_pop](carbon::KernelLoader& loader) { + const auto fin = loader.read(latest_pop); + return [fin] CARBON_HOST_DEVICE(Span s, Idx idx) -> double { + double acc = 0.0; +#pragma unroll + for (int q = 0; q < Lattice::Q; ++q) { + acc += static_cast(fin.read(s, idx, q)); + } + return acc; + }; + }, + mass_result, carbon::reduce::Sum{}, "lbm_mass_checksum", /*shared_mem=*/0U)); + try { + checksum_sk.compile(); + checksum_sk.run(); + checksum_sk.wait(); + mass_result.sync(sys.stream()); + sys.stream().wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: checksum reduction failed: {}", e.what()); + return EXIT_FAILURE; + } + const double total_mass = mass_result.host_value(); + CARBON_LOG_INFO( + "lbm_lid_driven_cavity: CHECKSUM (total mass, grid={} decomposition={}) = {:.10g}", + opts.grid, decomposition_mode_name(dec_mode), total_mass); + std::cout << "CHECKSUM=" << std::setprecision(12) << total_mass << " (grid=" << opts.grid + << " decomposition=" << decomposition_mode_name(dec_mode) << " N=" << opts.n + << " iters=" << opts.iters << ")" << '\n'; + } + + // Optional VTK dump of the final macroscopic fields (rho, u). Off the hot + // path: only triggered with --vtk-out, runs make_macroscopic_kernel against + // whichever ping-pong buffer holds the latest populations, downloads the + // host mirrors, and writes via carbon::io::write_vtk (legacy + // STRUCTURED_POINTS BINARY; one .rankN shard per rank under MPI). + if (!opts.vtk_path.empty()) { + // carbon::io::write_vtk is specialised on carbon::Dense (the legacy + // STRUCTURED_POINTS writer walks the aggregated dense row layout). + // DenseDisg and DenseDistributed have no VTK writer today, so the dump is + // Dense-only; those runs still report MLUPS, they just skip the optional + // VTK export. + + if constexpr (std::is_same_v || std::is_same_v) { + // The hot loop alternates sk_ab (reads pop_a, writes pop_b) on even iters + // with sk_ba (reads pop_b, writes pop_a) on odd. After `iters` iterations + // the freshest output buffer is therefore pop_b when iters is odd and + // pop_a otherwise. + auto& latest_pop = (opts.iters % 2 == 1) ? pop_b : pop_a; + + // The field names propagate into the VTK SCALARS labels, so name them + // "rho" and "u" — that's what shows up in ParaView's Pipeline Browser + // (rather than the legacy ordinal "field_0" / "field_1") and keeps the + // dump self-describing. + auto rho_field = grid.template newField(carbon::MemorySide::HostDevice, "rho"); + auto u_field = grid.template newField(carbon::MemorySide::HostDevice, "u"); + + carbon::Skeleton macro_sk(sys); + macro_sk.add(make_macroscopic_kernel(grid, latest_pop, cells, rho_field, + u_field, params)); + try { + macro_sk.compile(); + macro_sk.run(); + macro_sk.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: macroscopic kernel failed: {}", e.what()); + return EXIT_FAILURE; + } + + carbon::Stream dl_stream = sys.stream(); + try { + carbon::Transfer(sys, rho_field.gpu_buffers(), rho_field.cpu_buffers())(dl_stream); + carbon::Transfer(sys, u_field.gpu_buffers(), u_field.cpu_buffers())(dl_stream); + dl_stream.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: VTK download failed: {}", e.what()); + return EXIT_FAILURE; + } + + try { + carbon::io::write_vtk(opts.vtk_path, grid, rho_field, u_field); + // Drop a `.vtm` master alongside the per-rank shards so users can open + // one file in ParaView instead of N. No-op in the single-process case. + carbon::io::write_vtk_multiblock_index(opts.vtk_path, grid); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: write_vtk('{}') failed: {}", opts.vtk_path, + e.what()); + return EXIT_FAILURE; + } + CARBON_LOG_INFO("lbm_lid_driven_cavity: wrote VTK (rho + u) to {} after {} iters", + opts.vtk_path, opts.iters); + } else { + CARBON_LOG_WARN( + "lbm_lid_driven_cavity: --vtk-out is only supported for --grid dense " + "(carbon::io::write_vtk has no {} writer); skipping VTK dump.", + opts.grid); + } + } + + // Optional structured JSON report. Schema documented in + // benchmarks/lbm_lid_driven_cavity/scripts/sweep_and_plot.py — bump the + // schema string below and the parser there in lockstep when extending. + // Effective bandwidth assumes a pull-stream + ping-pong layout: each cell + // update reads Q populations from fIn and writes Q populations to fOut, + // so the dominant traffic is 2 * Q * sizeof(float) bytes per update. + // Only rank 0 writes the report: under MPI every rank runs this block, and + // if they all open the same --report path the writes interleave and produce + // corrupt JSON (e.g. a duplicated trailing brace). MLUPS is a global figure + // already reduced across ranks, so rank 0's copy is authoritative. +#ifdef CARBON_HAVE_MPI_NCCL + const int report_rank = use_mpi ? distributed->world_rank() : 0; +#else + const int report_rank = 0; +#endif + if (!opts.report_path.empty() && report_rank == 0) { + const double bytes_per_update = + 2.0 * static_cast(Lattice::Q) * static_cast(sizeof(float)); + const double effective_bandwidth_gb_s = (mlups * 1.0e6 * bytes_per_update) / 1.0e9; + std::ofstream out(opts.report_path); + if (!out.is_open()) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: failed to open --report path '{}'", + opts.report_path); + return EXIT_FAILURE; + } + out << std::setprecision(10); + out << "{\n"; + out << " \"schema\": \"carbon-lbm-report-v1\",\n"; + out << " \"benchmark\": \"lbm_lid_driven_cavity\",\n"; + out << " \"timestamp_utc\": \"" << utc_timestamp_now() << "\",\n"; + out << " \"config\": {\n"; + 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"; + out << " \"nu_lb\": " << nu_lb << ",\n"; + out << " \"omega\": " << omega << ",\n"; + out << " \"no_warmup_skip\": " << (opts.no_warmup_skip ? "true" : "false") << ",\n"; + out << " \"overlap\": \"" << json_escape(opts.overlap) << "\",\n"; + out << " \"hp_halo\": " << (opts.hp_halo ? "true" : "false") << ",\n"; + out << " \"cuda_graph\": " << (opts.cuda_graph ? "true" : "false") << ",\n"; + out << " \"label\": \"" << json_escape(opts.label) << "\"\n"; + out << " },\n"; + out << " \"system\": {\n"; + out << " \"backend\": \"" << CARBON_BACKEND_NAME << "\",\n"; + // `distributed` distinguishes the carbon transport path actually in use: + // - false : intra-process multi-GPU only (cudaMemcpyPeerAsync / + // SYCL queue-to-queue copy for halo). + // - true : MPI/NCCL build, *and* >1 rank present at runtime — halo + // flows over NCCL between adjacent ranks (one rank per GPU + // under carbon's strict model). The single-rank case still + // reports false even on an MPI build, because no NCCL ever + // gets called. +#ifdef CARBON_HAVE_MPI_NCCL + out << " \"distributed\": " << (use_mpi ? "true" : "false") << ",\n"; +#else + out << " \"distributed\": false,\n"; +#endif + out << " \"gpu_count\": " << total_gpu_count << ",\n"; + out << " \"local_gpu_count\": " << local_gpu_count << ",\n"; + out << " \"world_size\": " << world_size << ",\n"; + out << " \"rank\": " << world_rank << ",\n"; + out << " \"gpus\": [\n"; + const auto& gpu_devices = sys.gpu_group().devices(); + for (size_t i = 0; i < gpu_devices.size(); ++i) { + const auto& props = gpu_devices[i].properties(); + out << " {\n"; + out << " \"device_id\": " << gpu_devices[i].device_id() << ",\n"; + out << " \"name\": \"" << json_escape(props.name) << "\",\n"; + out << " \"compute_capability\": \"" << props.compute_major << "." + << props.compute_minor << "\",\n"; + out << " \"total_memory_bytes\": " << props.total_global_mem_bytes << ",\n"; + out << " \"multiprocessor_count\": " << props.multiprocessor_count << "\n"; + out << " }" << (i + 1 == gpu_devices.size() ? "" : ",") << "\n"; + } + out << " ]\n"; + out << " },\n"; + out << " \"results\": {\n"; + out << " \"timed_iters\": " << timed_iters << ",\n"; + out << " \"timing_seconds\": " << timing_seconds << ",\n"; + out << " \"overall_seconds\": " << overall_seconds << ",\n"; + 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 << " \"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(); + if (out.fail()) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: failed to write --report path '{}'", + opts.report_path); + return EXIT_FAILURE; + } + CARBON_LOG_INFO("lbm_lid_driven_cavity: wrote JSON report to {}", opts.report_path); + } + return EXIT_SUCCESS; +} + +} // namespace + +int +main(int argc, + char** argv) { + Options opts; + if (!parse_cli(argc, argv, opts)) { + return opts.show_help ? EXIT_SUCCESS : EXIT_FAILURE; + } + + carbon::init(); + if (carbon::device_count() <= 0) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: no CUDA devices visible"); + return EXIT_FAILURE; + } + + const auto dec_opt = parse_decomposition_mode(opts.decomposition); + if (!dec_opt) { + CARBON_LOG_ERROR( + "lbm_lid_driven_cavity: unknown --decomposition '{}' (expected slab|pencil|brick)", + opts.decomposition); + return EXIT_FAILURE; + } + const carbon::DecompositionMode dec_mode = *dec_opt; + + // Dispatch to the matching template instantiation. The runtime knobs + // --grid {dense,disg,dense_distributed} x --lattice {q19,q27} x --collision + // {bgk,kbc} select one compile-time run_benchmark. + // Three valid (lattice, collision) combos: (q19, bgk), (q27, bgk), (q27, + // kbc) — (q19, kbc) is rejected upstream in parse_cli because KBC's moment + // basis is D3Q27-specific. Each grid family runs the identical hot kernel. + auto dispatch_grid = [&](auto grid_tag) -> int { + using GridT = typename decltype(grid_tag)::type; + if (opts.lattice == "q19" && opts.collision == "bgk") { + return run_benchmark(opts, "q19", "bgk", dec_mode); + } + if (opts.lattice == "q27" && opts.collision == "bgk") { + return run_benchmark(opts, "q27", "bgk", dec_mode); + } + if (opts.lattice == "q27" && opts.collision == "kbc") { + return run_benchmark(opts, "q27", "kbc", dec_mode); + } + CARBON_LOG_ERROR( + "lbm_lid_driven_cavity: unsupported (lattice='{}', collision='{}') combination — " + "KBC requires D3Q27.", + opts.lattice, opts.collision); + return EXIT_FAILURE; + }; + + if (opts.grid == "disg") { + return dispatch_grid(std::type_identity{}); + } + if (opts.grid == "dense_distributed") { + return dispatch_grid(std::type_identity{}); + } + if (opts.grid == "disg_distributed") { + return dispatch_grid(std::type_identity{}); + } + return dispatch_grid(std::type_identity{}); +} diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-disg-vs-dense-sweep.yml b/benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-disg-vs-dense-sweep.yml new file mode 100644 index 00000000..55722d52 --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-disg-vs-dense-sweep.yml @@ -0,0 +1,25 @@ +# Comparison sweep: DenseDistributed vs DenseDisgDistributed. +# Same matrix as lbm-dist-sweep, both grids, hp-halo on (the fair OCC baseline). +configs: [q19:bgk] +grids: [dense_distributed, disg_distributed] +sizes: [256, 384, 512] +decompositions: [slab, pencil, brick] +gpus_slab: [2, 4, 8] +gpus_pencil: [4, 8] +gpus_brick: [8] +transports: [mpi] +hp_halo: ["on"] +overlap: standard +warmup: 400 +iters_per_rep: 400 +reps: 5 +sm_arch: "80" +image: carbon-cuda-nccl-pinned:local +build_dir: build-dist +prefix: lbm-disg-vs-dense +skip_build: true +force: true +run_timeout: 1800 +reference_dir: benchmarks/lbm_lid_driven_cavity/data/lbm-dgx-sweep/json +reference_prefix: lbm-dgx-sweep +reference_label: dense-intra 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..16de3368 --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep-run.sh @@ -0,0 +1,283 @@ +#!/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 decomposition x its GPU counts 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), each with its +# own GPU counts (GPUS_SLAB / GPUS_PENCIL / GPUS_BRICK, all >= 2) +# 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) +# +# No 1-GPU run is done: the efficiency baseline of size N is the 1-GPU report +# of another sweep, by default the Dense Peeraccess run of the single-process +# DGX sweep, +# /---fp32--n-g1.json +# The script warns before the runs if one of them is missing. +# +# 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---hp-n-g.json +# in benchmarks/lbm_lid_driven_cavity_distributed/data//json/. A failing +# or hung run (RUN_TIMEOUT) is logged to failed.txt there and the sweep moves on. +# +# Usage: +# ./benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep-run.sh [CONFIG.yml] +# +# CONFIG.yml (see lbm-dist-sweep.yml) sets the knobs below by their lowercase +# name. List-valued keys take a list or a space-separated string; sizes and +# gpus_* also accept {start, stop, step} (inclusive). Precedence: env var > +# CONFIG.yml > default. +# +# Knobs (env vars, all optional): +# CONFIGS="q19:bgk" lattice:collision pairs (q19:bgk q27:bgk q27:kbc) +# SIZES="256 320 384 448 512" domain edge lengths +# DECOMPOSITIONS="slab pencil brick" process decompositions +# GPUS_SLAB="2 3 4 5 6 7 8" GPU counts (= MPI ranks) of the slab runs +# GPUS_PENCIL="4 8" ... of the pencil runs +# GPUS_BRICK="8" ... of the brick runs +# REFERENCE_DIR=benchmarks/lbm_lid_driven_cavity/data/lbm-dgx-sweep/json +# 1-GPU baseline reports, relative to the repo root +# REFERENCE_PREFIX=lbm-dgx-sweep their report prefix +# REFERENCE_LABEL=dense-intra their grid-transport label +# TRANSPORTS="mpi" mpi (NCCL) and/or mpip2p +# HP_HALO="off on" halo stream priority variants +# OVERLAP=standard Skeleton OCC mode of every run +# WARMUP=400 untimed solver steps before the first repetition +# ITERS_PER_REP=400 solver steps in each timed repetition +# REPS=4 timed repetitions per run +# SM_ARCH=auto CUDA arch (A100=80, H100=90); auto = detect +# IMAGE=carbon-cuda-nccl-pinned:local image for the build and every run +# BUILD_DIR=build-dist CUDA+MPI build tree under the repo root +# PREFIX=lbm-dist-sweep report prefix and data// folder +# SKIP_BUILD=0 set 1 to reuse the existing build tree +# FORCE=0 set 1 to redo runs whose JSON exists +# RUN_TIMEOUT=1800 per-run timeout in seconds +# DRY_RUN=0 set 1 to print the resolved config and exit + +set -euo pipefail + +if [[ $# -gt 1 ]]; then + echo "usage: $0 [CONFIG.yml]" >&2 + exit 2 +fi +config_path="" +if [[ $# -eq 1 ]]; then + if [[ ! -f "$1" ]]; then + echo "error: config file not found: $1" >&2 + exit 2 + fi + config_path="$(realpath "$1")" +fi + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" +cd "${repo_root}" + +# Every knob as a validated VAR=value line, defaults filled in, from the parser +# the plotter shares (lbm_dist_sweep_config.py); an empty config yields the defaults. +config_text="" +if [[ -n "${config_path}" ]]; then + config_text="$(<"${config_path}")" +fi +config_vars="$(LBM_SWEEP_CONFIG="${config_text}" \ + python3 "${repo_root}/benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm_dist_sweep_config.py")" +while IFS='=' read -r key value; do + [[ -z "${key}" ]] && continue + if [[ -z "${!key+x}" ]]; then + export "${key}=${value}" + else + export "${key}" + echo "==> ${key} taken from the environment" + fi +done <<< "${config_vars}" + +check_words() { + local var="$1" allowed="$2" w + for w in ${!var}; do + if [[ " ${allowed} " != *" ${w} "* ]]; then + echo "error: ${var} entry '${w}' is not one of: ${allowed}" >&2 + exit 1 + fi + done +} +check_words CONFIGS "q19:bgk q27:bgk q27:kbc" +check_words GRIDS "dense_distributed disg_distributed" +check_words DECOMPOSITIONS "slab pencil brick" +check_words TRANSPORTS "mpi mpip2p" +check_words HP_HALO "off on" +check_words OVERLAP "none standard extended twoway-extended" +for v in SIZES GPUS_SLAB GPUS_PENCIL GPUS_BRICK WARMUP ITERS_PER_REP REPS RUN_TIMEOUT; do + if [[ ! "${!v}" =~ ^[0-9]+( [0-9]+)*$ ]]; then + echo "error: ${v} must be non-negative integers (got '${!v}')" >&2 + exit 1 + fi +done +for v in GPUS_SLAB GPUS_PENCIL GPUS_BRICK; do + for g in ${!v}; do + if [[ "${g}" -lt 2 ]]; then + echo "error: ${v} entries must be >= 2 (the 1-GPU point is the reference run)" >&2 + exit 1 + fi + done +done +for v in BUILD_DIR PREFIX REFERENCE_PREFIX REFERENCE_LABEL; do + if [[ ! "${!v}" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then + echo "error: ${v} must be a single path component (got '${!v}')" >&2 + exit 1 + fi +done +if [[ ! "${REFERENCE_DIR}" =~ ^[A-Za-z0-9._/-]+$ || "${REFERENCE_DIR}" == /* || + "/${REFERENCE_DIR}/" == */../* ]]; then + echo "error: REFERENCE_DIR must be a path inside the repo (got '${REFERENCE_DIR}')" >&2 + exit 1 +fi +if [[ "${SM_ARCH}" == "auto" ]]; then + SM_ARCH="$(nvidia-smi --query-gpu=compute_cap --format=csv,noheader 2>/dev/null | + tr -d '. ' | sort -u | paste -sd';' -)" || true + if [[ -z "${SM_ARCH}" ]]; then + echo "error: could not detect the GPU compute capability with nvidia-smi;" \ + "set sm_arch / SM_ARCH explicitly (A100=80, H100=90)" >&2 + exit 1 + fi +fi +if [[ ! "${SM_ARCH}" =~ ^[0-9]+(\;[0-9]+)*$ ]]; then + echo "error: SM_ARCH must be auto or numbers separated by ';' (got '${SM_ARCH}')" >&2 + exit 1 +fi + +echo "==> sweep config${config_path:+ (${config_path##*/})}:" +for v in CONFIGS GRIDS SIZES DECOMPOSITIONS GPUS_SLAB GPUS_PENCIL GPUS_BRICK REFERENCE_DIR \ + REFERENCE_PREFIX REFERENCE_LABEL TRANSPORTS HP_HALO OVERLAP WARMUP ITERS_PER_REP \ + REPS SM_ARCH IMAGE BUILD_DIR PREFIX SKIP_BUILD FORCE RUN_TIMEOUT; do + printf ' %-16s %s\n' "${v}" "${!v}" +done +for cfg in ${CONFIGS}; do + for n in ${SIZES}; do + ref="${REFERENCE_DIR}/${REFERENCE_PREFIX}-${cfg%%:*}-${cfg##*:}-fp32-${REFERENCE_LABEL}-n${n}-g1.json" + if [[ ! -f "${repo_root}/${ref}" ]]; then + echo "warning: missing 1-GPU reference ${ref}; N=${n} gets no efficiency plots" >&2 + fi + done +done +if [[ "${DRY_RUN:-0}" -eq 1 ]]; then + exit 0 +fi + +rel_data="benchmarks/lbm_lid_driven_cavity_distributed/data/${PREFIX}/json" +mkdir -p "${repo_root}/${rel_data}" + +docker_run() { + local script="$1" + shift + docker run --rm --gpus all --ipc=host --shm-size=8g \ + -v "${repo_root}:/src:rw" -w /src \ + -e CONFIGS -e GRIDS -e SIZES -e DECOMPOSITIONS -e GPUS_SLAB -e GPUS_PENCIL -e GPUS_BRICK \ + -e TRANSPORTS -e HP_HALO -e OVERLAP \ + -e WARMUP -e ITERS_PER_REP -e REPS -e BUILD_DIR \ + -e FORCE -e RUN_TIMEOUT -e PREFIX -e OUT_DIR="/src/${rel_data}" \ + "${IMAGE}" /bin/bash -lc "${script}" sweep "$@" +} + +if [[ "${SKIP_BUILD}" -eq 0 ]]; then + echo "==> building ${BUILD_DIR}/ (CUDA+MPI Release, SM_${SM_ARCH}) in ${IMAGE}" + docker_run " +set -euo pipefail +export PATH=\"/root/.local/bin:\$PATH\" +cmake -S /src -B \"/src/\${BUILD_DIR}\" -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DCARBON_BACKEND=Cuda '-DCMAKE_CUDA_ARCHITECTURES=${SM_ARCH}' -DCARBON_ENABLE_MPI=ON +cmake --build \"/src/\${BUILD_DIR}\" -j\"\$(nproc)\" \ + --target carbon_benchmark_lbm_lid_driven_cavity_distributed +echo '=== Build complete ===' +" +else + echo "==> SKIP_BUILD=1: reusing ${BUILD_DIR}/" +fi + +# Runs inside the container as `bash -lc "$sweep_body" sweep`. +read -r -d '' sweep_body <<'EOF' || true +set -uo pipefail +bin="/src/${BUILD_DIR}/benchmarks/lbm_lid_driven_cavity_distributed/carbon_benchmark_lbm_lid_driven_cavity_distributed" +if [[ ! -x "${bin}" ]]; then + echo "error: ${bin} not built (run without skip_build)" >&2 + exit 1 +fi +export OMPI_ALLOW_RUN_AS_ROOT=1 OMPI_ALLOW_RUN_AS_ROOT_CONFIRM=1 +export NCCL_IB_DISABLE=1 + +mkdir -p "${OUT_DIR}" +failed_log="${OUT_DIR}/failed.txt" +: > "${failed_log}" +iters=$((WARMUP + REPS * ITERS_PER_REP)) + +# run