Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion benchmarks/cg/cg_poisson.cu
Original file line number Diff line number Diff line change
Expand Up @@ -939,7 +939,7 @@ run_cg(Grid& grid,
if (!sk.export_launch_matrix_dot_file(base + ".dot", std::string{"cg_"} + tag)) {
CARBON_LOG_ERROR("cg_poisson_unified: failed to write {}.dot", base);
}
if (!sk.export_dot_file(base + "_streams.dot", std::string{"cg_"} + tag)) {
if (!sk.export_streams_dot_file(base + "_streams.dot", std::string{"cg_"} + tag)) {
CARBON_LOG_ERROR("cg_poisson_unified: failed to write {}_streams.dot", base);
}
if (!sk.export_launch_order_file(base + ".txt")) {
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/jacobi_nvidia/jacobi_nvidia.cu
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ run_solver(DenseGrid& grid,
std::string{"jacobi"} + tag)) {
std::fprintf(stderr, "jacobi_nvidia: failed to write %s%s.dot\n", dot_prefix.c_str(), tag);
}
if (!sk->export_dot_file(dot_prefix + tag + "_streams.dot")) {
if (!sk->export_streams_dot_file(dot_prefix + tag + "_streams.dot")) {
std::fprintf(stderr, "jacobi_nvidia: failed to write %s%s_streams.dot\n",
dot_prefix.c_str(), tag);
}
Expand Down
18 changes: 18 additions & 0 deletions benchmarks/lbm_ldc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ Run every command from the carbon repository root.
| `scripts/plotting/plot_scaling.py` | plot MLUPS per GPU vs GPUs and vs N, the hp-halo speedup, and all grids on shared axes |
| `scripts/plotting/plot_disg_vs_dense.py` | plot the DenseDisg / Dense ratio |
| `scripts/plotting/plot_best_family.py` | colour an N × GPU-count map by the fastest of Dense / DenseDisg × Peeraccess / NCCL |
| `scripts/plotting/plot_transfers.py` | plot the rank × message halo transfer matrix of `--export-transfers` |

A YAML file lists *experiments*, each with a type (`strong_scaling`,
`domain_size`, `best_family`) that decides its figures, and its own run
Expand Down Expand Up @@ -140,3 +141,20 @@ python3 benchmarks/lbm_ldc/scripts/plotting/plot_scaling.py --config $cfg
[`reference/`](reference/) is a committed copy of a full DGX sweep: its YAML,
1050 JSON reports and the figures. To plot your own `data/` against the
same experiments, pass `--data-dir benchmarks/lbm_ldc/data`.

## Example 6 — halo transfers per rank, without running

`--export-transfers PATH` reads the cross-rank halo messages of one iteration
from the compiled skeleton and writes them as CSV (one line per rank ×
message: launch, NCCL group, send / receive, peer rank, bytes); rank 0 also
logs the rank × message matrix. `--compile-only` exits before the solver
loop, so no iteration runs.

```bash
mpiexec -n 8 build-mpi/benchmarks/lbm_ldc/carbon_benchmark_lbm_ldc \
--grid disg_distributed --decomposition pencil --gpus 1 --n 512 \
--export-transfers benchmarks/lbm_ldc/data/disg_distributed-pencil-mpi-g8-transfers.csv --compile-only
python3 benchmarks/lbm_ldc/scripts/plotting/plot_transfers.py \
benchmarks/lbm_ldc/data/disg_distributed-pencil-mpi-g8-transfers.csv
# -> data/disg_distributed-pencil-mpi-g8-transfers.png: rank on y, message on x, size as colour
```
46 changes: 45 additions & 1 deletion benchmarks/lbm_ldc/lbm_ldc.cu
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,11 @@ struct Options {
std::string export_dot_path = "";
std::string export_dot_png_path = "";
std::string export_dot_streams_path = "";
// CSV of every rank's cross-rank halo messages of one sk_ab iteration, read from the
// compiled skeleton.
std::string export_transfers_path = "";
// Stop after compiling the skeletons and writing the exports; no solver iterations.
bool compile_only = false;
// 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.
Expand Down Expand Up @@ -241,6 +246,15 @@ build_cli(Options& opts) -> clipp::group {
"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("--export-transfers") & value("path", opts.export_transfers_path)) %
"Write the cross-rank halo messages of one skeleton iteration as CSV to PATH, read "
"from the compiled skeleton (nothing is launched): one row per rank x message with "
"its launch, NCCL group, direction, peer rank and bytes. Rank 0 also logs the "
"rank x message matrix. Needs an mpiexec launch for cross-rank traffic. Plot with "
"scripts/plotting/plot_transfers.py.",
option("--compile-only").set(opts.compile_only) %
"Exit after compiling the skeletons and writing the --export-* files, without "
"running the solver loop.",
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). "
Expand Down Expand Up @@ -721,12 +735,42 @@ run_benchmark(const Options& opts,
CARBON_LOG_INFO("lbm_ldc: 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")) {
if (!sk_ab.export_streams_dot_file(opts.export_dot_streams_path, "lbm_sk_ab")) {
CARBON_LOG_ERROR("lbm_ldc: --export-dot-streams failed for {}", opts.export_dot_streams_path);
return EXIT_FAILURE;
}
CARBON_LOG_INFO("lbm_ldc: wrote stream-cluster DOT to {}", opts.export_dot_streams_path);
}
if (!opts.export_transfers_path.empty()) {
// Collective over all ranks: every rank's messages are read from its compiled sk_ab.
const std::string matrix = sk_ab.export_transfer_matrix_text();
std::ostringstream about;
about << "grid=" << opts.grid << "\ndecomposition=" << decomposition_mode_name(dec_mode);
if (pg) {
const carbon::int32_3d dims = pg->dims();
about << "\nprocess_grid=" << dims.x << 'x' << dims.y << 'x' << dims.z;
}
about << "\nn=" << opts.n << "\nranks=" << world_size << "\ngpus=" << total_gpu_count
<< "\nlattice=" << lattice_name << "\ncollision=" << collision_name
<< "\nprecision=" << opts.precision << "\noverlap=" << opts.overlap;
if (!sk_ab.export_transfer_matrix_csv_file(opts.export_transfers_path, about.str())) {
CARBON_LOG_ERROR("lbm_ldc: --export-transfers failed for {}", opts.export_transfers_path);
return EXIT_FAILURE;
}
if (world_rank == 0) {
CARBON_LOG_INFO(
"lbm_ldc: cross-rank halo messages of one sk_ab iteration (grid={} "
"decomposition={}):\n{}",
opts.grid, decomposition_mode_name(dec_mode), matrix);
CARBON_LOG_INFO("lbm_ldc: wrote transfer matrix CSV to {}", opts.export_transfers_path);
}
}
if (opts.compile_only) {
if (world_rank == 0) {
CARBON_LOG_INFO("lbm_ldc: --compile-only, exiting before the solver loop");
}
return EXIT_SUCCESS;
}

using Clock = std::chrono::steady_clock;
using Seconds = std::chrono::duration<double>;
Expand Down
170 changes: 170 additions & 0 deletions benchmarks/lbm_ldc/scripts/plotting/plot_transfers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
#!/usr/bin/env python3
"""Plot the rank x message transfer matrix written by ``lbm_ldc --export-transfers``.

The CSV (``rank,index,seq,kernel,group,op,peer,elements,bytes``) lists every cross-rank halo
message of one skeleton iteration, read from the compiled ``carbon::Skeleton``; the
``# key=value`` lines above its header (grid, decomposition, process grid, N, ...) make
the first line of the title. The plot
has one row per rank and one column per message in issue order; the colour is the
message size and each cell reads ``S>p`` (send to rank p) or ``R<p`` (receive from
rank p) with its size and element count. The right margin gives each rank's message count and bytes sent.

Example::

mpiexec -n 8 carbon_benchmark_lbm_ldc --grid disg_distributed --n 512 \\
--export-transfers transfers.csv --compile-only
python3 benchmarks/lbm_ldc/scripts/plotting/plot_transfers.py transfers.csv
"""

from __future__ import annotations

import argparse
import csv
import math
import sys
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(HERE.parent))
import lbm_reports as lr # noqa: E402
import lbm_sweep_config as sc # noqa: E402

COLUMNS = ("rank", "index", "seq", "kernel", "group", "op", "peer", "elements", "bytes")


def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="Plot the rank x message transfer matrix.")
p.add_argument("csv", type=Path, help="CSV written by --export-transfers")
p.add_argument("--out", type=Path, default=None,
help="output PNG (default: the CSV path with a .png suffix)")
return p.parse_args()


def checked_paths(args: argparse.Namespace) -> tuple[Path, Path]:
"""Resolve and validate the command-line paths: an existing .csv in, a .png out."""
src = args.csv.expanduser().resolve()
if src.suffix.lower() != ".csv" or not src.is_file():
raise ValueError(f"{args.csv}: not an existing .csv file")
out = (args.out.expanduser().resolve() if args.out is not None
else src.with_suffix(".png"))
if out.suffix.lower() != ".png":
raise ValueError(f"{out}: output must end in .png")
if not out.parent.is_dir():
raise ValueError(f"{out.parent}: output directory does not exist")
return src, out


def read_messages(src: Path) -> tuple[dict[str, str], list[dict]]:
"""``# key=value`` lines above the header (the run description), then the messages."""
meta: dict[str, str] = {}
body: list[str] = []
with src.open(newline="") as f:
for line in f:
if line.startswith("#"):
key, sep, value = line[1:].strip().partition("=")
if sep and key.replace("_", "").isalnum():
meta[key] = value
else:
body.append(line)
reader = csv.DictReader(body)
if tuple(reader.fieldnames or ()) != COLUMNS:
raise ValueError(f"{src}: expected header {','.join(COLUMNS)}")
rows = []
for r in reader:
if r["op"] not in ("send", "recv"):
raise ValueError(f"{src}: bad op {r['op']!r}")
rows.append({"rank": int(r["rank"]), "index": int(r["index"]),
"seq": int(r["seq"]), "kernel": r["kernel"],
"op": r["op"], "peer": int(r["peer"]), "elements": int(r["elements"]),
"bytes": int(r["bytes"])})
return meta, rows


def run_title(meta: dict[str, str]) -> str:
"""One line describing the run, e.g. ``DenseDisgDistributed, slab (z) 1x1x8, N = 512``."""
if "grid" not in meta:
return ""
parts = [lr.GRID_TITLES.get(meta["grid"], meta["grid"])]
if meta["grid"] in sc.DISTRIBUTED_GRIDS and "decomposition" in meta:
decomp = lr.DECOMP_TITLES.get(meta["decomposition"], meta["decomposition"])
parts.append(f"{decomp} {meta.get('process_grid', '')}".strip())
if "n" in meta:
parts.append(f"N = {meta['n']}")
if "ranks" in meta:
parts.append(f"{meta['ranks']} ranks")
model = " ".join(meta[k] for k in ("lattice", "collision", "precision") if k in meta)
if model:
parts.append(model)
return ", ".join(parts)


def megabytes(n: int) -> str:
return f"{n / 1e6:.2f} MB" if n >= 1_000_000 else f"{n / 1e3:.1f} KB"


def plot(rows: list[dict], title: str, out: Path) -> None:
ranks = max(r["rank"] for r in rows) + 1
cols = max(r["index"] for r in rows) + 1
grid = [[math.nan] * cols for _ in range(ranks)]
for r in rows:
grid[r["rank"]][r["index"]] = r["bytes"] / 1e6

width = max(7.0, 0.95 * cols + 4.5)
fig, ax = plt.subplots(figsize=(width, max(3.0, 0.6 * ranks + 1.8)))
cmap = plt.get_cmap("viridis").copy()
cmap.set_bad("#f2f2f2")
vmax = max(r["bytes"] for r in rows) / 1e6
im = ax.imshow(grid, cmap=cmap, aspect="auto", interpolation="nearest", vmin=0.0, vmax=vmax)
for r in rows:
mb = r["bytes"] / 1e6
arrow = f"S>{r['peer']}" if r["op"] == "send" else f"R<{r['peer']}"
ax.text(r["index"], r["rank"], f"{arrow}\n{megabytes(r['bytes'])}\n{r['elements']:,} el", ha="center",
va="center", fontsize=7, color="black" if mb > 0.6 * vmax else "white")

totals = []
for rank in range(ranks):
mine = [r for r in rows if r["rank"] == rank]
sent = sum(r["bytes"] for r in mine if r["op"] == "send")
totals.append(f"{len(mine)} msgs, {megabytes(sent)} sent")

ax.set_xticks(range(cols), [f"msg {i}" for i in range(cols)], fontsize=8)
ax.set_yticks(range(ranks), [f"rank {i}" for i in range(ranks)])
right = ax.secondary_yaxis("right")
right.set_yticks(range(ranks), totals, fontsize=8)
ax.set_xlabel("message (issue order)")
ax.set_title(title, fontsize=10)
# pad is a fraction of the axes width; keep ~1.7 in free for the right-hand totals.
fig.colorbar(im, ax=ax, label="MB", pad=1.7 / (width - 2.8))
fig.tight_layout()
fig.savefig(out, dpi=150)
plt.close(fig)


def main() -> int:
args = parse_args()
try:
src, out = checked_paths(args)
meta, rows = read_messages(src)
except (OSError, ValueError, KeyError) as e:
sys.stderr.write(f"error: {e}\n")
return 1
if not rows:
print(f"note: {src} has no cross-rank messages, nothing to plot")
return 0
kernels = sorted({(r["seq"], r["kernel"]) for r in rows})
lines = [run_title(meta), "Cross-rank halo messages per skeleton iteration",
", ".join(f"#{seq} {name}" for seq, name in kernels)]
title = "\n".join(line for line in lines if line)
plot(rows, title, out)
print(f"wrote {out}")
return 0


if __name__ == "__main__":
sys.exit(main())
21 changes: 21 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6696,3 +6696,24 @@ This unblocked the matrix on this host: the `sycl` and `hip-nvidia` images build
follow. Scripts, YAMLs, docs and the include path of the examples are updated;
the committed reference reports keep the old `benchmark` value they were written
with.
- **2026-11 — Halo transfer matrix from the Skeleton.** `DistOp` / `DistMessage` move to
the NCCL-free `<carbon/dist_message.h>`; the four dense halo descriptors gain
`dist_messages()` (this rank's cross-rank messages of one exchange with element count
and bytes, empty without MPI),
surfaced through `KernelImpl::dist_messages()` / `Kernel::dist_messages()`. `Skeleton`
gains `halo_messages()` (per halo launch, in `run()` order), the collective
`gather_halo_messages()` (count and lists broadcast from each rank) and
`export_transfer_matrix_csv[_file]()` / `export_transfer_matrix_text()`. All of it
reads the compiled halo kernels: nothing is launched. LBM adds `--export-transfers PATH`
and `--compile-only` (exit before the solver loop) plus
`scripts/plotting/plot_transfers.py` (rank × message heatmap). N=512
DenseDisgDistributed on 8 ranks: slab sends 2 × 5.24 MB per interior rank; pencil
1x2x4 sends 7 messages (2.62 MB z-faces, 3.41 MB y-faces, 26.6 KB edges) per interior
rank; brick 2x2x2 sends 6 per rank, 12.88 MB in total.
- **2026-11 — `Skeleton::export_dot` defaults to the launch matrix.** `export_dot()` /
`export_dot_file()` now return / write `export_launch_matrix_dot()`, matching
`export_dot_png()`, so `log_dot_on_compile`, the examples' `--dot` logs and dumps and the
Python `ioToDot` all produce the launch matrix. The stream-cluster graph is renamed
`export_streams_dot()` / `export_streams_dot_file()`; the `*_streams.dot` sidecars of
jacobi_nvidia, cg and LBM `--export-dot-streams`, and the tests that check its text
(stream clusters, field labels, region-mask tooltips, the copy stream) use the new names.
Loading
Loading