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
51 changes: 39 additions & 12 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -141,18 +141,20 @@ elseif(CARBON_BACKEND STREQUAL "Sycl")
"AdaptiveCpp_DIR points at <prefix>/lib/cmake/AdaptiveCpp.")
endif()

# Host-MPI transport: with an omp-only target there is no CUDA/HIP runtime, so NCCL/RCCL
# cannot be used. Carbon's "device" memory is then plain host RAM and halo exchange /
# allreduce go straight through MPI (see CARBON_DIST_HOST_MPI in src/dist_*.cpp).
set(_carbon_dist_host_mpi OFF)
if(CARBON_ENABLE_MPI
AND NOT CARBON_SYCL_TARGETS MATCHES "cuda"
AND NOT CARBON_SYCL_TARGETS MATCHES "hip")
message(FATAL_ERROR
"CARBON_ENABLE_MPI=ON under CARBON_BACKEND=Sycl currently requires either a 'cuda:' "
"(NCCL transport) or 'hip:' (RCCL transport) target in CARBON_SYCL_TARGETS (got "
"'${CARBON_SYCL_TARGETS}'). Carbon's distributed transport calls NCCL/RCCL on the "
"underlying cudaMalloc'd / hipMalloc'd USM pointers extracted via "
"sycl::interop_handle::get_native_queue<sycl::backend::cuda|hip>; that interop only "
"exists when AdaptiveCpp's CUDA or HIP backend is in CARBON_SYCL_TARGETS. Host-MPI "
"(OMP / Apple-CPU) is a planned follow-up; until then, either add 'cuda:sm_XX' / "
"'hip:gfxXXX' to CARBON_SYCL_TARGETS or re-configure with CARBON_ENABLE_MPI=OFF.")
if(CARBON_SYCL_TARGETS MATCHES "omp")
set(_carbon_dist_host_mpi ON)
else()
message(FATAL_ERROR
"CARBON_ENABLE_MPI=ON under CARBON_BACKEND=Sycl needs a 'cuda:' (NCCL), 'hip:' (RCCL) "
"or 'omp' (host MPI) target in CARBON_SYCL_TARGETS (got '${CARBON_SYCL_TARGETS}').")
endif()
endif()

message(STATUS "carbon: SYCL backend selected (AdaptiveCpp). ACPP_TARGETS=${ACPP_TARGETS}")
Expand Down Expand Up @@ -389,6 +391,21 @@ elseif(CARBON_BACKEND STREQUAL "Sycl")
target_sources(carbon PRIVATE
src/sycl_stub.cpp
src/gpu_sycl.cpp)
# Multicore-CPU execution: with an omp-only target the AdaptiveCpp OpenMP host device is the
# only device, but it reports is_cpu() == true and the default enumeration skips CPU devices,
# so device_count() would be 0. Default ON for omp-only targets; OFF when a cuda:/hip: target
# is present (the GPU stays device 0).
if(CARBON_SYCL_TARGETS MATCHES "omp" AND NOT CARBON_SYCL_TARGETS MATCHES "cuda|hip")
set(_carbon_sycl_cpu_default ON)
else()
set(_carbon_sycl_cpu_default OFF)
endif()
option(CARBON_SYCL_CPU_DEVICE
"Treat the AdaptiveCpp OpenMP host device as a carbon compute device" ${_carbon_sycl_cpu_default})
if(CARBON_SYCL_CPU_DEVICE)
target_compile_definitions(carbon PRIVATE CARBON_SYCL_CPU_DEVICE=1)
message(STATUS "carbon: SYCL OpenMP host device enabled as compute device")
endif()
# AdaptiveCpp's add_sycl_to_target tags every TU listed in SOURCES with the SYCL
# compile/link flags. Apply it to all .cu / .cpp files participating in the carbon
# target; this is the AdaptiveCpp-recommended way to get cross-TU SYCL with the
Expand Down Expand Up @@ -469,7 +486,9 @@ if(CARBON_ENABLE_MPI)
set(_carbon_use_rccl ON)
endif()

if(_carbon_use_rccl)
if(_carbon_dist_host_mpi)
message(STATUS "carbon: distributed transport = host MPI (SYCL omp target, no NCCL/RCCL)")
elseif(_carbon_use_rccl)
find_package(RCCL REQUIRED)
# HIP headers (<hip/hip_runtime.h>, <hip/hip_fp16.h>) are reached via acpp's
# --acpp-rocm-path forwarding (-isystem $ROCM_PATH/include) configured above. The
Expand Down Expand Up @@ -517,7 +536,9 @@ if(CARBON_ENABLE_MPI)
src/communicator.cpp
src/dist_transfer.cpp
src/dist_reduce.cpp)
if(_carbon_use_rccl)
if(_carbon_dist_host_mpi)
set(_carbon_mpi_extra_includes "")
elseif(_carbon_use_rccl)
set(_carbon_mpi_extra_includes
"${RCCL_INCLUDE_DIR}"
"${CARBON_SYCL_ROCM_PATH}/include")
Expand Down Expand Up @@ -547,7 +568,10 @@ if(CARBON_ENABLE_MPI)
target_link_libraries(carbon PRIVATE MPI::MPI_CXX)
target_compile_definitions(carbon PUBLIC CARBON_HAVE_MPI_NCCL)

if(_carbon_use_rccl)
if(_carbon_dist_host_mpi)
target_compile_definitions(carbon PRIVATE CARBON_DIST_HOST_MPI=1)
set(_carbon_collective_lib_dir "")
elseif(_carbon_use_rccl)
target_link_libraries(carbon PRIVATE RCCL::rccl)
target_compile_definitions(carbon PRIVATE CARBON_USE_RCCL)
# The AMD HIP runtime headers gate the AMD-side declarations on
Expand Down Expand Up @@ -587,6 +611,9 @@ if(CARBON_ENABLE_MPI)
if(_mpi_dir)
list(APPEND CARBON_RUNTIME_SEARCH_DIRS "${_mpi_dir}")
target_link_directories(carbon INTERFACE "${_mpi_dir}")
# Consumers (examples/tests) re-resolve libcarbon.so's DT_NEEDED libmpi.so.N at link
# time; conda's ld does not search -L dirs for that, only -rpath-link.
target_link_options(carbon INTERFACE "LINKER:-rpath-link,${_mpi_dir}")
endif()
endforeach()
list(REMOVE_DUPLICATES CARBON_RUNTIME_SEARCH_DIRS)
Expand Down
53 changes: 53 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6185,3 +6185,56 @@ This unblocked the matrix on this host: the `sycl` and `hip-nvidia` images build
`OverlapMode::None`, and the distributed LBM benchmark gains `--hp-halo` (`hp_halo` in
the JSON report). `test_skeleton_halo_priority` checks the native priority of the halo
stream for Standard / Extended, a ping-pong pair, a recompile, and `None`.
- **2026-11 — Global chunk validation for `Dense` / `DenseDisg` / `DenseDistributed`.**
The thickness guards used to inspect only the local `spans_`. Under MPI (one rank per GPU)
`local_n == 1`, so a rank whose chunk was too thin threw while the other ranks continued to
the first halo collective and hung. The checks now run against the global decomposition on
every rank, in the same chunk order, before any field allocation or collective. `Dense` and
`DenseDisg` validate every `z_counts_global` slab; `DenseDistributed` uses the shared
`detail::dense_distributed::validate_global_halo_fit` helper for both the legacy-slab
`2 * halo_z` rule and the multi-axis `owned >= halo` rule. The host test adds four
global-validation cases (`z=7` over 4 slabs and `x=1` over a 2x2x2 brick must throw; the
existing valid slab/brick layouts must not).
- **2026-11 — Legacy z-band Boundary path is now opt-in.** `DenseDistributed::Span` carries a
`legacy_slab` flag; only spans marked legacy use the two-band z-only Boundary mapping.
Non-legacy z-only chunks (pencil/brick or periodic-X/Y slab with a z-only stencil) now use
the compact shell path, so `owned.z < 2 * halo.z` no longer visits Boundary cells twice.
The host test adds thin z-only pencil/brick/periodic-X cases and asserts legacy slabs still
use the `2 * halo.z` z-band extent.
- **2026-11 — HIP `BlockAtomic` double / int64 sums are no longer dropped.** The four
CUDA/HIP reduce-kernel headers duplicated a `__CUDA_ARCH__ >= 600` guard whose `#else`
silently discarded `double` and `int64_t` block partials. AMD HIP defines
`__HIP_DEVICE_COMPILE__` but not `__CUDA_ARCH__`, so `ReduceFinalize::BlockAtomic`
produced zero on that backend. The atomic dispatch now lives in `cudalike/atomic.h`
(`double`, `int32_t`, `int64_t` overloads, with a CUDA pre-sm_60 CAS fallback and the
existing host `std::atomic_ref` path), and one shared `reduce_atomic_accumulate` helper is
used by the Dense, DenseDistributed, DenseDisg and Block kernels. Unsupported element
types now fail with a dependent `static_assert` instead of compiling to a no-op. The
`test_reduce_atomic` suite adds a `double` BlockAtomic case and `test_atomic_host` covers
the new host overloads.
- **2026-11 — 2-D stage-1 reduce now covers every `(y, z)` cell.** The opt-in
`stage1_threads_y` path previously mapped a 2-D block over `(x, z)` and always called
`set_and_validate(view, ix, 0, iz)`. It was correct only when `iter_extent(view).y == 1`:
`Standard`/`Internal` reduced just the `y = 0` plane, and the DenseDistributed compact-shell
`Boundary` view reduced only its first 128 shell cells. The second block dimension is now a
flattened `(y, z)` index, decoded with `iy = flat_yz % ext.y` and `iz = flat_yz / ext.y`;
`y == 1` keeps the NVIDIA Jacobi `x/z` shape. The launch-grid and
`ReduceLaunchTraits::stage1_unit_count` formulas now use `ext.y * ext.z`, and
`ReduceKernelImpl` sizes its partials/CUB scratch from the maximum block count over
`Standard`, `Internal`, and `Boundary` because the padded compact-shell boundary can need
more blocks than Standard. Dead `16x16`, `8x8`, `32x16`, `16x32`, and `64x64` dispatch cases
were removed; only `32x32` is reachable under the current normalizer.
- **2026-11 — SYCL split-reduction Merge now runs instead of throwing.** A stencil reduction
inside an overlapped `Skeleton` is emitted as `Partial Internal + Partial Boundary + Merge`;
`ReduceKernelImpl::launch_merge_on_device` only had a CUDA/HIP body and threw
`std::logic_error` under SYCL, so every overlapped stencil reduction aborted. The SYCL branch
now folds the two already-combined per-view scalars with a one-thread `sycl::single_task`
(`*out = op(op(identity, *internal), *boundary)`), captures `Op`/identity and the pointers by
value, and reuses the existing cross-rank and inline-readback tail. The SYCL NCCL
`dist_allreduce_in_place` path now value-captures its submission lambda and drops the host
`wait_and_throw()`: the custom operation may outlive the caller's stack frame, and the
in-order queue orders later submissions after the collective. `test_skeleton_reduce_split`
now uses one stable `Stream` for the whole-reduction reference instead of minting a fresh
`System::stream()` per call (the old reference raced the inline D-to-H copy on SYCL OpenMP).
Verified with `test_skeleton_reduce_split`, `test_reduce_sum`, and `test_reduce_ops` on SYCL
OpenMP, and with `test_skeleton_reduce_split` on CUDA.
190 changes: 190 additions & 0 deletions docs/reduce-2d-stage1-yz-fix-report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
# 2-D stage-1 reduce over flattened `(y, z)` — implementation report

Date: 2026-11-07

## Problem

The opt-in 2-D stage-1 reduce path (`ReduceOptions::stage1_threads_y > 0`) mapped a
CUDA/HIP block over `(x, z)` and always called

```cpp
span.set_and_validate(view, ix, 0, iz);
```

so it reduced only the `y == 0` plane. The launch grid and
`ReduceLaunchTraits::stage1_unit_count` also used `ext.z` only, ignoring `ext.y`.

This was correct for the intended NVIDIA Jacobi-style `Dense` slab shape where
`iter_extent(view).y == 1`, but it silently under-counted any grid with `y > 1`:

- `Dense` / `DenseDistributed` `Standard` and `Internal` views reduced only `y == 0`.
- The `DenseDistributed` compact-shell `Boundary` view reduced only its first 128
shell cells, because its launch box was `(128, ceil(S / 128), 1)` and
`t = iy * ext.x + ix` with `iy == 0` covered only the first row.

## Fix

The second block dimension is now a flattened `(y, z)` index:

```cpp
const int64_t yz_extent = ext.y * ext.z;
const int64_t flat_yz = blockIdx.y * BlockDimY + threadIdx.y;
if (ix < ext.x && flat_yz < yz_extent) {
const int64_t iy = flat_yz % ext.y;
const int64_t iz = flat_yz / ext.y;
const ValidatedIdx vi = span.set_and_validate(view, ix, iy, iz);
...
}
```

The launch grid and stage-1 unit count use the same flattened extent:

```cpp
grid_y = ceil_div(ext.y * ext.z, block_dim_y);
stage1_unit_count = ceil_div(ext.x, block_dim_x) * grid_y;
```

For `y == 1` this reduces to the old `(x, z)` NVIDIA Jacobi shape. For `y > 1` it
covers every `(y, z)` cell.

## Changes by file

### Kernel mapping

- `include/carbon/detail/backend/cudalike/dense_reduce_kernel.h`
- Normal and `BlockAtomic` 2-D kernels now decode `flat_yz` into `(iy, iz)` and pass
all three indices to `set_and_validate`.
- Updated the kernel comment to describe the flattened `(y, z)` second dimension.

- `include/carbon/detail/backend/cudalike/dense_distributed_reduce_kernel.h`
- Same mapping change for the `DenseDistributed` normal and `BlockAtomic` 2-D
kernels. This is the part that fixes compact-shell `Boundary` under-counting.

### Launch geometry

- `include/carbon/detail/backend/cudalike/dense_reduce_launch.h`
- `grid_y` is computed from `ext.y * ext.z` for both normal and `BlockAtomic`
launches.
- The grid/block-count consistency error now says the grid is over `(x, y*z)`.
- Removed dead dispatch branches: only `32x32` is reachable under
`normalize_dense_stage1_block_2d`. The removed `16x16`, `8x8`, `32x16`,
`16x32`, and `64x64` branches were either unreachable or invalid (`64x64` is
4096 threads, above the 1024-thread limit).

- `include/carbon/detail/backend/cudalike/dense_distributed_reduce_launch.h`
- Same launch-grid and dead-branch changes for `DenseDistributed`.

### Unit count and scratch sizing

- `include/carbon/detail/launch_traits.h`
- 2-D `stage1_unit_count` now uses
`ceil_div(ext.x, bx) * ceil_div(ext.y * ext.z, by)`.
- Updated the trait documentation to distinguish 1-D volume tiling from 2-D
flattened `(y, z)` tiling.

- `include/carbon/detail/reduce_kernel_impl.h`
- Added `stage1_scratch_blocks_per_gpu_`, sized from the maximum
`stage1_unit_count` over `Standard`, `Internal`, and `Boundary`.
- Partials and CUB temp storage now use this maximum instead of the
`Standard`-only `block_count_per_gpu_`.
- This is required because the compact-shell `Boundary` launch box can contain
more blocks than `Standard` due to flattened `(y, z)` row padding. Sizing from
`Standard` would otherwise reject or overflow the `Boundary` launch.
- Public `block_count()` remains tied to the `Standard` view.
- Updated the sanity-check and error text to refer to the per-view maximum.

### Public documentation

- `include/carbon/reduce.h`
- `ReduceOptions::stage1_threads` and `stage1_threads_y` now document CUDA/HIP,
`Dense` / `DenseDistributed`, and the flattened `(y, z)` second dimension.
- Documented that `y == 1` keeps the NVIDIA Jacobi `32x32` `x/z` shape.
- `docs/CHANGELOG.md`
- Added the 2026-11 entry describing the bug, the flattened mapping, the scratch
sizing change, and the removed dead dispatch branches.

## Regression tests

- `tests/test_reduce_sum.cu`
- New Case 6: `Dense` grid `24 x 32 x 16` (so `kHeight == 32` and the `z` halo
is non-empty) with `stage1_threads = 32`, `stage1_threads_y = 32`.
- Checks `Standard` against the host reference and checks
`Internal + Boundary == Standard` plus `host_value_combined == Standard`.
- A regression to the old `y == 0` mapping fails all three checks.

- `tests/test_reduce_atomic.cu`
- New 2-D `BlockAtomic` case with the same `32x32` options, checked against the
host reference. This exercises the atomic kernel's flattened `(y, z)` mapping.

- `tests/test_dense_distributed_dist.cu`
- Added `run_reduce_2d` and calls it for every existing `DenseDistributed` case
(slab, pencil, brick, open/compact boundary modes).
- Compares `Standard` to a global host reference and checks
`Internal + Boundary == Standard` and `host_value_combined`.
- This covers the compact-shell `Boundary` path and the new scratch-max sizing.

## Verification performed

Local CUDA build (RTX 3050 Ti, compute 8.6, CUDA 13.4, MPI + NCCL enabled):

```text
test_reduce_sum PASS (including 2D Standard = Internal + Boundary)
test_reduce_atomic PASS (expected negative BlockAtomic non-Sum log only)
test_reduce_ops PASS
```

`test_dense_distributed_dist` was built and launched with
`mpirun --oversubscribe -n 4`. It correctly skipped because this machine exposes
only one CUDA device (`needs >= 4 visible devices, have 1; skipping`), so the
multi-rank 2-D reduce regression still needs a multi-GPU run.

An ad-hoc single-GPU `DenseDistributed` smoke test (not committed; 1x1x1
`ProcessGrid`, `9 x 8 x 11`, six-point stencil, `32x32` stage-1) also passed:

```text
dd2d: PASS Standard=39880368 Internal=32629392 Boundary=7250976
```

This directly exercises the compact-shell `Boundary` mapping and the new
scratch-max sizing without MPI.

## Supported grid families and 3D stencil fields

The 2-D stage-1 option (`stage1_threads_y > 0`) is available on plain `Dense`
and `DenseDistributed`:

- **`DenseDistributed` with a true 3-D stencil** (x/y/z halo, pencil/brick, or
periodic X/Y): supported. `Standard` iterates every owned cell, and the
flattened `(y, z)` mapping covers `Internal` plus the compact-shell
`Boundary`. Use `stage1_threads = 32`, `stage1_threads_y = 32`.
- **`Dense`**: the reduce itself covers all owned x/y/z cells and the 2-D path
works, but `Dense` allocates only a z-halo (`halo_z = stencil.radius()`). It
is therefore fine for an open x/y boundary where the x/y neighbours lie in
the full owned plane, but it cannot express x/y periodic halos. Use
`DenseDistributed` for multi-axis halo/periodicity.
- **`DenseDisg` and `Block`**: the default 1-D reduce works, but
`stage1_threads_y` is rejected at construction, so the 2-D stage-1 path is
not available.
- Only the `32x32` 2-D block shape is reachable under the current
`normalize_dense_stage1_block_2d`.

## Remaining validation

- On Leonardo (AMD MI250X, HIP + MPI), rebuild and run the HIP/MPI checks:

```bash
cmake --build build-mpi-nccl --target test_reduce_sum test_reduce_atomic \
test_dense_distributed_dist -j
./build-mpi-nccl/tests/test_reduce_sum
./build-mpi-nccl/tests/test_reduce_atomic
mpirun -n 4 ./build-mpi-nccl/tests/test_dense_distributed_dist
# If 8 GPUs are available, also exercise the full brick (2,2,2):
mpirun -n 8 ./build-mpi-nccl/tests/test_dense_distributed_dist
```

`test_reduce_atomic` should exit 0 with only the expected negative
`ReduceFinalize::BlockAtomic requires reduce::Sum<T>` log.
`test_dense_distributed_dist` should run its 4- or 8-rank cases instead of
self-skipping.
- The `gridDim.y` limit is 65535; the existing 1-D flat path remains the
fallback for grids whose flattened `(y, z)` extent exceeds that limit.
6 changes: 6 additions & 0 deletions examples/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,12 @@ _carbon_example_link_viewer(carbon_example_render_wind_tunnel_live)
target_include_directories(carbon_example_render_wind_tunnel_live
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../benchmarks/lbm_lid_driven_cavity/src)

# Distributed 6-neighbour stencil + axpy with a CLI-selected slab | pencil | brick decomposition.
# Self-verifying (global sums vs. a serial host reference). With the SYCL backend, an omp-only
# target and CARBON_ENABLE_MPI=ON this is a pure-CPU `mpirun -np N` program.
_carbon_example_add(carbon_example_distributed_stencil_axpy distributed/stencil_axpy.cu)
target_link_libraries(carbon_example_distributed_stencil_axpy PRIVATE carbon::carbon)

# Multi-resolution (mGrid) worked example: cross-level restriction / prolongation, a reduction,
# and an intra-level halo'd smoothing step on carbon::MultiResBlock — every operation through the
# kernel layer (make_kernel / make_reduce_kernel / level_view / make_halo_kernel), each stage
Expand Down
Loading
Loading