Skip to content

Distributed NCCL and Multi Node

Amadeus edited this page Nov 29, 2026 · 2 revisions

Distributed NCCL & Multi-Node Execution (v1.0.0)

Back to Home · Previous: Multi-Probe, Fisher & Topology · Next: Multi-GPU & Large Grids

21cmCU v1.0.0 introduces a zero-compile-dependency dynamic NCCL 2.x backend (src/py21cmfast/src/cuda/cuda_nccl.cuh) paired with the Python py21cmcu.distributed API for collective slab transposes, rank-partitioned batch sweeps, and distributed Fisher reductions.


1. Zero-Compile-Dependency Dynamic NCCL (dlopen)

Unlike C++ extensions that fail to compile if nccl.h or libnccl-dev is missing, 21cmCU resolves NCCL symbols strictly at runtime (NCCL >= 2.7) via dlopen/dlsym in cuda_nccl.cuh:

  1. $P21_NCCL_LIB (if set in the environment — useful on custom HPC module trees or non-standard Conda paths)
  2. Already loaded symbols (RTLD_DEFAULT)
  3. libnccl.so.2, then libnccl.so

Checking Runtime Status

21cmcu doctor --as-json

Or in Python:

import py21cmcu as p21

print("NCCL available:", p21.nccl_available())
print("NCCL version:", p21.nccl_version())   # e.g. (2, 28, 3) or None

Selecting the Slab Transpose Backend (P21_CUDA_MGPU_BACKEND)

cuda_mgpu.cu selects the X↔Y slab exchange path via P21_CUDA_MGPU_BACKEND:

Value Behavior
auto (default) Uses cached NCCL clique communicators when libnccl.so.2 (>= 2.7) loads; otherwise falls back seamlessly to CUDA P2P or pinned host-bounce (MgpuHostBounce).
nccl Force NCCL collective slab exchange.
p2p Force direct CUDA peer-to-peer memcpy without NCCL.
host Force pinned 64 MiB host-bounce std::thread sub-tiled transpose.

2. Python Distributed Collective API (py21cmcu.distributed)

Ten CFFI-exported primitives (p21_cuda_nccl_*, part of 93 CUDA APIs / 57 CFFI exports) back the Python helpers:

  • nccl_available() -> bool / nccl_version() -> tuple[int, int, int] | None: query runtime availability and (major, minor, patch).
  • nccl_unique_id() -> bytes & bootstrap_nccl_unique_id(path, rank=...): generate and atomically exchange a 128-byte NCCL unique communicator ID on rank 0 across ranks (shared filesystem, or MPI/torchrun).
  • detect_distributed_env(): auto-detects torchrun, slurm, openmpi, pmi, or single-process launcher variables (rank, world_size, local_rank, local_world_size, launcher).
  • NcclContext(n_ranks, rank, unique_id, device_id=None): RAII context manager binding the rank's NCCL communicator (dev = rank % cuda_device_count() if device_id=None). Exposes .alltoall(), .allreduce(), zero-copy .alltoall_device(send_view, recv_view), and .allreduce_device(send_view, recv_view=None, op="sum").
  • nccl_alltoall_f32(send_buf) / nccl_allreduce_f64(send_buf, op="sum"): host-staged collectives across ranks.
  • nccl_alltoall_device(send_buf, recv_buf) / nccl_allreduce_device(send_buf, recv_buf=None, op="sum") (Stage 1 v1.1.0-dev): zero-copy GPU device-pointer collectives accepting CudaFieldView or any __cuda_array_interface__ buffer (torch.Tensor on CUDA, CuPy arrays) with zero host bounce (float32 / float64, in-place recv_buf=None supported for allreduce).
  • Cross-Process Distributed Y-Slab 3D FFT (DistributedSlabGrid) (Stage 1 v1.1.0-dev):
    • slab_partition(n_global, rank, n_ranks): balanced (start, count) slab indexing (handles non-divisible grid dimensions).
    • distributed_rfft3d_slab(local_x_slab, grid, comm=...), distributed_irfft3d_slab(local_y_kslab, grid, comm=...), and distributed_filter_box_slab(local_x_slab, grid, filter_fn=..., comm=...): distributed X-slab ↔ Y-kslab 3D FFTs and $k$-space filtering over NcclContext or custom exchange_fn.
  • Multi-Node Inference & Batch Sharding:
    • distributed_batch_partition(tasks, rank, n_ranks): deterministic balanced contiguous sharding for BatchTask lists.
    • distributed_likelihood_eval(likelihood, theta_batch, rank=..., n_ranks=..., comm=...): shards parameter batches across ranks and reduces finite values while preserving exact -inf/NaN boundary masks.
    • reduce_fisher_results(local_result, op="sum", comm=None): aggregates local FisherForecastResult shards and/or reduces fisher_matrix and n_seeds across all active NCCL ranks.

3. Multi-Rank / Multi-Node Python Pattern

Each rank (launched via srun, mpirun, or torchrun) auto-detects its rank/world size via detect_distributed_env(), receives the rank-0 unique ID atomically via bootstrap_nccl_unique_id(), processes its deterministic BatchTask shard, distributed slab FFT, likelihood evaluation, or local Fisher shard, and reduces across ranks:

import py21cmcu as p21

env = p21.detect_distributed_env()
rank, world_size = int(env["rank"]), int(env["world_size"])
uid = p21.bootstrap_nccl_unique_id("nccl_uid.bin", rank=rank)

grid = p21.DistributedSlabGrid(64, 64, 64, rank=rank, n_ranks=world_size, box_length=128.0)

with p21.NcclContext(n_ranks=world_size, rank=rank, unique_id=uid) as comm:
    # 1) Cross-process distributed 3D k-space filter
    smoothed_slab = p21.distributed_filter_box_slab(
        local_x_slab, grid, filter_fn=lambda kx, ky, kz: np.exp(-0.5 * (kx**2 + ky**2 + kz**2) * 2.0**2), comm=comm
    )

    # 2) Distributed likelihood evaluation preserving -inf / NaN masks
    ll_batch = p21.distributed_likelihood_eval(likelihood, theta_batch, rank=rank, n_ranks=world_size, comm=comm)

    # 3) Zero-copy device-pointer collectives on CudaFieldView / torch.Tensor on CUDA
    with p21.to_cuda_view(arr_f32) as d_send, p21.to_cuda_view(np.zeros_like(arr_f32)) as d_recv:
        comm.alltoall_device(d_send, d_recv)
        comm.allreduce_device(d_recv, op="avg")

    # 4) Deterministic BatchTask sharding & Fisher aggregation
    local_tasks = p21.distributed_batch_partition(all_tasks, rank=rank, n_ranks=world_size)
    global_fisher = p21.reduce_fisher_results(local_fisher, op="sum", comm=comm)

See examples/11_multinode_nccl_distributed.py for a complete runnable script supporting both single-rank local execution and torchrun --standalone --nproc_per_node=2. For embarrassingly parallel multi-node parameter sweeps without GPU-to-GPU collectives, distributed_batch_partition(all_tasks, rank, world_size) and detect_distributed_env() work independently even when nccl_available() is False.


4. Virtual-Rank Validation & Current Verification Scope

  • Single-GPU virtual-rank testing: Set export P21_CUDA_MGPU_VIRTUAL_RANKS=2 (or 4) to exercise multi-GPU slab splitting and transpose indexing paths on a single workstation GPU.
  • What is verified in v1.0.0:
    • Dynamic dlopen & collective dispatch: Verified on Tesla T4 with dynamic libnccl.so.2 (2.28.3, benchmarks/results_t4_v100.json, tests/native/test_21cmcu_phase16_nccl_v100.py). Because the Colab T4 environment has 1 GPU (n_ranks=1), those microbenchmarks (1.06 ms at 4 KiB up to 9.29 ms / 1.68 GB/s at 16 MiB float32 all-to-all; 8.77 ms float64 all-reduce) measure host-staged (H2D + NCCL + D2H) intra-device dispatch, not inter-GPU interconnect bandwidth.
    • True inter-GPU slab scaling: Separately verified across 2×–3× RTX 4090 up to 2048³ (8.590 B voxels, 58.47 s native in-VRAM Zel'dovich IC); see Multi-GPU & Large Grids.

Clone this wiki locally