diff --git a/CMakeLists.txt b/CMakeLists.txt index 9162d81a..03017cd1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -141,18 +141,20 @@ elseif(CARBON_BACKEND STREQUAL "Sycl") "AdaptiveCpp_DIR points at /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; 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}") @@ -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 @@ -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 (, ) are reached via acpp's # --acpp-rocm-path forwarding (-isystem $ROCM_PATH/include) configured above. The @@ -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") @@ -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 @@ -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) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 12f931d8..b6d1461e 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -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. diff --git a/docs/reduce-2d-stage1-yz-fix-report.md b/docs/reduce-2d-stage1-yz-fix-report.md new file mode 100644 index 00000000..85b76fec --- /dev/null +++ b/docs/reduce-2d-stage1-yz-fix-report.md @@ -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` 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. diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 533910a0..1f930cd0 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -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 diff --git a/examples/distributed/stencil_axpy.cu b/examples/distributed/stencil_axpy.cu new file mode 100644 index 00000000..d2047341 --- /dev/null +++ b/examples/distributed/stencil_axpy.cu @@ -0,0 +1,281 @@ +// stencil_axpy.cu +// +// A very small distributed example: one stencil + one axpy on carbon::DenseDistributed, with the +// 3D domain decomposition chosen on the command line (slab | pencil | brick). +// +// 1. stencil: s(c) = sum of x over the 6 in-domain face neighbours of cell c +// 2. axpy: y(c) = y(c) + alpha * s(c) +// +// Both kernels are added to one carbon::Skeleton; the Skeleton inserts the halo exchange that the +// stencil needs, so the example works unchanged for any decomposition and any number of ranks. +// +// Verification (identical on every rank, independent of the decomposition): +// x is a position-dependent integer field, so a missing or misplaced halo changes the result. +// SUM(s) and SUM(y) are compared against a serial host reference over the whole global domain. +// +// Built for CPU (SYCL backend, AdaptiveCpp `omp` target, CARBON_ENABLE_MPI=ON) this is a plain +// `mpirun` program: every rank is one OpenMP "device". +// +// mpirun -np 4 ./carbon_example_distributed_stencil_axpy pencil --n 128 --alpha 0.5 --iters 10 +// +// Exit code: 0 = PASS, 1 = FAIL (the same on every rank). + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef CARBON_HAVE_MPI_NCCL +# include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using Grid = carbon::DenseDistributed; +using Span = Grid::Span; +using Idx = Grid::Idx; + +// Position-dependent integer-valued seed. Sums of these stay exact in double. +[[nodiscard]] auto +seed(carbon::int64_3d g) -> double { + return static_cast((g.x + 2 * g.y + 3 * g.z) % 5 + 1); +} + +// Serial reference: SUM over all cells of the sum of seed() over the in-domain face neighbours. +[[nodiscard]] auto +reference_stencil_sum(int64_t n) -> double { + static constexpr int kDirs[6][3] = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, + {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}; + double total = 0.0; + for (int64_t z = 0; z < n; ++z) { + for (int64_t y = 0; y < n; ++y) { + for (int64_t x = 0; x < n; ++x) { + for (const auto& d : kDirs) { + const int64_t nx = x + d[0]; + const int64_t ny = y + d[1]; + const int64_t nz = z + d[2]; + if (nx >= 0 && nx < n && ny >= 0 && ny < n && nz >= 0 && nz < n) { + total += seed({nx, ny, nz}); + } + } + } + } + } + return total; +} + +[[nodiscard]] auto +decomposition_mode(const std::string& s) -> carbon::DecompositionMode { + if (s == "slab") { + return carbon::DecompositionMode::Slab; + } + if (s == "pencil") { + return carbon::DecompositionMode::Pencil; + } + if (s == "brick") { + return carbon::DecompositionMode::Brick; + } + std::cerr << "error: decomposition must be slab, pencil or brick (got '" << s << "')\n"; + std::exit(EXIT_FAILURE); +} + +// Global (all ranks) sum of component 0 of a field. The cross-rank allreduce is done by the +// reduction itself (MPI in a host build, NCCL in a CUDA build). +template +[[nodiscard]] auto +global_sum(carbon::System& sys, + const Grid& grid, + const FieldT& field, + const char* name) -> double { + carbon::ReductionResult result(sys); + carbon::Skeleton sk(sys); + sk.add(carbon::Kernel::reduce( + grid, + [&field](carbon::KernelLoader& loader) { + const auto p = loader.read(field); + return [p] CARBON_HOST_DEVICE(Span s, Idx idx) -> double { return p.read(s, idx, 0); }; + }, + result, carbon::reduce::Sum{}, name, /*shared_mem=*/0U)); + sk.compile(); + sk.run(); + sk.wait(); + result.sync(sys.stream()); + sys.stream().wait(); + return result.host_value(); +} + +[[nodiscard]] auto +close_enough(double got, + double expected) -> bool { + return std::abs(got - expected) <= 1e-9 * std::max(1.0, std::abs(expected)); +} + +} // namespace + +int main(int argc, char** argv) { + // ---- CLI: [--n N] [--alpha A] [--iters K] ------------------------ + std::string dec = "slab"; + int64_t n = 64; + double alpha = 0.5; // power of two => the checksums below are exact + int iters = 1; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + if (a == "--help" || a == "-h") { + std::cout << "usage: " << argv[0] + << " [--n N] [--alpha A] [--iters K]\n"; + return EXIT_SUCCESS; + } + if (a == "--n" && i + 1 < argc) { + n = std::stoll(argv[++i]); + } else if (a == "--alpha" && i + 1 < argc) { + alpha = std::stod(argv[++i]); + } else if (a == "--iters" && i + 1 < argc) { + iters = std::stoi(argv[++i]); + } else if (!a.empty() && a[0] != '-') { + dec = a; + } else { + std::cerr << "error: unknown argument '" << a << "' (try --help)\n"; + return EXIT_FAILURE; + } + } + if (n < 4 || iters < 1) { + std::cerr << "error: need --n >= 4 and --iters >= 1\n"; + return EXIT_FAILURE; + } + const carbon::DecompositionMode dec_mode = decomposition_mode(dec); + + carbon::init(); + if (carbon::device_count() <= 0) { + CARBON_LOG_ERROR("stencil_axpy: no compute device visible"); + return EXIT_FAILURE; + } + + // ---- System: one rank = one device (an OpenMP "device" in a CPU build) -------------------- +#ifdef CARBON_HAVE_MPI_NCCL + auto distributed = std::make_shared(); + const bool use_mpi = distributed->world_size() > 1; + carbon::System sys = + use_mpi ? carbon::System(distributed) : carbon::System(carbon::get_all_devices()); + const int world_rank = use_mpi ? distributed->world_rank() : 0; + const int world_size = + use_mpi ? distributed->world_size() : static_cast(sys.gpu_group().size()); +#else + carbon::System sys(carbon::get_all_devices()); + const int world_rank = 0; + const int world_size = static_cast(sys.gpu_group().size()); +#endif + + // ---- Grid: the 6-neighbour stencil sets the halo width of the decomposition --------------- + const carbon::Stencil stencil( + std::vector{{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, + {0, 0, -1}}, + /*remove_center=*/true); + const carbon::ProcessGrid pg = carbon::ProcessGrid::make(world_size, dec_mode); + Grid grid(sys, carbon::int64_3d{n, n, n}, pg, stencil); + + if (world_rank == 0) { + const auto d = pg.dims(); + std::cout << "decomposition=" << dec << " process_grid=" << d.x << "x" << d.y << "x" << d.z + << " ranks=" << world_size << " N=" << n << " iters=" << iters + << " alpha=" << alpha << '\n'; + } + + auto x = grid.newField(carbon::MemorySide::HostDevice, "x"); + auto s = grid.newField(carbon::MemorySide::HostDevice, "s"); + auto y = grid.newField(carbon::MemorySide::HostDevice, "y"); + + x.fill_owned_host([](carbon::int64_3d g, int) -> double { return seed(g); }); + y.fill_owned_host([](carbon::int64_3d, int) -> double { return 1.0; }); + { + carbon::Stream st = sys.stream(); + carbon::Transfer(sys, x.cpu_buffers(), x.gpu_buffers())(st); + carbon::Transfer(sys, y.cpu_buffers(), y.gpu_buffers())(st); + st.wait(); + } + + // ---- The two kernels, in one Skeleton (halo exchange for x is inserted automatically) ------ + carbon::Skeleton sk(sys); + sk.add(carbon::Kernel::compute( + grid, + [&x, &s](carbon::KernelLoader& loader) { + const auto px = loader.read_stencil(x); + const auto ps = loader.write(s); + return [px, ps] CARBON_HOST_DEVICE(Span sp, Idx idx) { + double acc = 0.0; + acc += px.neighbour(sp, idx, carbon::int8_3d{1, 0, 0}, 0).value_or(0.0); + acc += px.neighbour(sp, idx, carbon::int8_3d{-1, 0, 0}, 0).value_or(0.0); + acc += px.neighbour(sp, idx, carbon::int8_3d{0, 1, 0}, 0).value_or(0.0); + acc += px.neighbour(sp, idx, carbon::int8_3d{0, -1, 0}, 0).value_or(0.0); + acc += px.neighbour(sp, idx, carbon::int8_3d{0, 0, 1}, 0).value_or(0.0); + acc += px.neighbour(sp, idx, carbon::int8_3d{0, 0, -1}, 0).value_or(0.0); + ps.write(sp, idx, 0, acc); + }; + }, + "stencil_neighbour_sum")); + sk.add(carbon::Kernel::compute( + grid, + [&s, &y, alpha](carbon::KernelLoader& loader) { + const auto ps = loader.read(s); + auto py = loader.read_write(y); + return [ps, py, alpha] CARBON_HOST_DEVICE(Span sp, Idx idx) { + py.write(sp, idx, 0, py.read(sp, idx, 0) + alpha * ps.read(sp, idx, 0)); + }; + }, + "axpy")); + + double seconds = 0.0; + try { + sk.compile(); + const auto t0 = std::chrono::steady_clock::now(); + for (int it = 0; it < iters; ++it) { + sk.run(); + } + sk.wait(); + seconds = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("stencil_axpy: kernel failed: {}", e.what()); + return EXIT_FAILURE; + } + + // ---- Verification: global sums vs. a serial host reference -------------------------------- + double sum_s = 0.0; + double sum_y = 0.0; + try { + sum_s = global_sum(sys, grid, s, "sum_s"); + sum_y = global_sum(sys, grid, y, "sum_y"); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("stencil_axpy: checksum failed: {}", e.what()); + return EXIT_FAILURE; + } + + const double ref_s = reference_stencil_sum(n); + const double ref_y = static_cast(n) * n * n + iters * alpha * ref_s; + const bool ok = close_enough(sum_s, ref_s) && close_enough(sum_y, ref_y); + + if (world_rank == 0) { + std::cout.precision(15); + std::cout << "SUM(s) = " << sum_s << " expected " << ref_s << '\n' + << "SUM(y) = " << sum_y << " expected " << ref_y << '\n' + << "time = " << seconds << " s for " << iters << " iteration(s)\n" + << (ok ? "PASS" : "FAIL") << " (decomposition=" << dec << ", ranks=" << world_size + << ")\n"; + } + return ok ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/include/carbon/cpu.h b/include/carbon/cpu.h index 217c5f51..433d8deb 100644 --- a/include/carbon/cpu.h +++ b/include/carbon/cpu.h @@ -16,6 +16,18 @@ #include #endif +namespace carbon::detail { +#if CARBON_BACKEND_IS_SYCL +// Context used for pinned (USM host) allocations. AdaptiveCpp 25.02 has no +// sycl::default_context(); take the context of a default-selected queue instead. +[[nodiscard]] inline auto +pinned_host_context() -> const sycl::context& { + static const sycl::context ctx = sycl::queue{}.get_context(); + return ctx; +} +#endif +} // namespace carbon::detail + namespace carbon { /** Host-side allocator for Allocation objects (CPU memory). */ @@ -67,7 +79,7 @@ class CARBON_API Cpu { } #elif CARBON_BACKEND_IS_SYCL try { - ptr = static_cast(sycl::malloc_host(size_bytes, sycl::default_context())); + ptr = static_cast(sycl::malloc_host(size_bytes, detail::pinned_host_context())); } catch (const sycl::exception& ex) { log::throw_with_log("Cpu::pinned_buffer: sycl::malloc_host failed: {}", ex.what()); @@ -87,7 +99,7 @@ class CARBON_API Cpu { #if CARBON_BACKEND_IS_CUDALIKE (void)detail::gpu_host_free(p); #elif CARBON_BACKEND_IS_SYCL - sycl::free(p, sycl::default_context()); + sycl::free(p, detail::pinned_host_context()); #endif }; diff --git a/include/carbon/detail/backend/cudalike/atomic.h b/include/carbon/detail/backend/cudalike/atomic.h index c295ac4d..a339ef59 100644 --- a/include/carbon/detail/backend/cudalike/atomic.h +++ b/include/carbon/detail/backend/cudalike/atomic.h @@ -1,8 +1,10 @@ #pragma once #include +#include #include +#include namespace carbon { namespace detail { @@ -26,6 +28,74 @@ atomic_add(float* address, #endif } +[[nodiscard]] CARBON_HD inline auto +atomic_add(int32_t* address, + int32_t val) -> int32_t { +#if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__) + return static_cast(atomicAdd(reinterpret_cast(address), static_cast(val))); +#else + std::atomic_ref ref(*address); + return ref.fetch_add(val, std::memory_order_relaxed); +#endif +} + +[[nodiscard]] CARBON_HD inline auto +atomic_add(double* address, + double val) -> double { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 600 + return atomicAdd(address, val); +#elif defined(__CUDA_ARCH__) + // CUDA before sm_60 has no native double atomicAdd. Emulate it with a CAS loop on the + // 64-bit representation; only one thread per block reaches this helper in BlockAtomic. + auto* bits = reinterpret_cast(address); + unsigned long long old = *bits; + while (true) { + const unsigned long long assumed = old; + const double current = __longlong_as_double(static_cast(assumed)); + const unsigned long long next = + static_cast(__double_as_longlong(current + val)); + old = atomicCAS(bits, assumed, next); + if (old == assumed) { + return current; + } + } +#elif defined(__HIP_DEVICE_COMPILE__) + // HIP defines __HIP_DEVICE_COMPILE__ but not __CUDA_ARCH__ on AMD. HIP's atomicAdd + // accepts double and lowers to native atomics or a CAS loop depending on the target. + return atomicAdd(address, val); +#else + std::atomic_ref ref(*address); + return ref.fetch_add(val, std::memory_order_relaxed); +#endif +} + +[[nodiscard]] CARBON_HD inline auto +atomic_add(int64_t* address, + int64_t val) -> int64_t { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 600 + auto* bits = reinterpret_cast(address); + return static_cast(atomicAdd(bits, static_cast(val))); +#elif defined(__CUDA_ARCH__) + // CUDA before sm_60 has no native 64-bit atomicAdd. Emulate it with a CAS loop; signed + // addition is performed on the unsigned representation (two's-complement wraparound). + auto* bits = reinterpret_cast(address); + unsigned long long old = *bits; + while (true) { + const unsigned long long assumed = old; + old = atomicCAS(bits, assumed, assumed + static_cast(val)); + if (old == assumed) { + return static_cast(assumed); + } + } +#elif defined(__HIP_DEVICE_COMPILE__) + auto* bits = reinterpret_cast(address); + return static_cast(atomicAdd(bits, static_cast(val))); +#else + std::atomic_ref ref(*address); + return ref.fetch_add(val, std::memory_order_relaxed); +#endif +} + [[nodiscard]] CARBON_HD inline auto atomic_min(unsigned long long* address, unsigned long long val) -> unsigned long long { diff --git a/include/carbon/detail/backend/cudalike/block_reduce_kernel.h b/include/carbon/detail/backend/cudalike/block_reduce_kernel.h index 80b526d6..0e2bf169 100644 --- a/include/carbon/detail/backend/cudalike/block_reduce_kernel.h +++ b/include/carbon/detail/backend/cudalike/block_reduce_kernel.h @@ -24,6 +24,7 @@ #if CARBON_CUDALIKE_DEVICE_TU #include +#include #endif namespace carbon::detail::block { @@ -116,34 +117,6 @@ block_grid_reduce_kernel(Span span, } } -template -CARBON_HD inline auto -block_reduce_atomic_accumulate(T* dst, - T value) -> void { - if constexpr (std::is_same_v) { - atomicAdd(dst, value); - } else if constexpr (std::is_same_v) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 600 - atomicAdd(dst, value); -#else - (void)dst; - (void)value; -#endif - } else if constexpr (std::is_same_v) { - atomicAdd(dst, value); - } else if constexpr (std::is_same_v) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 600 - atomicAdd(reinterpret_cast(dst), static_cast(value)); -#else - (void)dst; - (void)value; -#endif - } else { - (void)dst; - (void)value; - } -} - /** * Block-grid reduce with block partials merged via atomics into @p global_out * ( @ref ReduceFinalize::BlockAtomic ), analogous to @ref dense_grid_reduce_block_atomic_kernel . @@ -180,7 +153,7 @@ block_grid_reduce_block_atomic_kernel(Span span, const T brick_val = BlockReduceT(temp_storage).Reduce(thread_val, op); if (threadIdx.x == 0U) { - block_reduce_atomic_accumulate(global_out, brick_val); + reduce_atomic_accumulate(global_out, brick_val); } } diff --git a/include/carbon/detail/backend/cudalike/dense_disg_reduce_kernel.h b/include/carbon/detail/backend/cudalike/dense_disg_reduce_kernel.h index 68afb180..296d6d7e 100644 --- a/include/carbon/detail/backend/cudalike/dense_disg_reduce_kernel.h +++ b/include/carbon/detail/backend/cudalike/dense_disg_reduce_kernel.h @@ -17,6 +17,7 @@ #if CARBON_CUDALIKE_DEVICE_TU #include +#include #endif namespace carbon::detail::dense_disg { @@ -70,34 +71,6 @@ disg_grid_reduce_kernel(Span span, } } -template -CARBON_HD inline auto -disg_reduce_atomic_accumulate(T* dst, - T value) -> void { - if constexpr (std::is_same_v) { - atomicAdd(dst, value); - } else if constexpr (std::is_same_v) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 600 - atomicAdd(dst, value); -#else - (void)dst; - (void)value; -#endif - } else if constexpr (std::is_same_v) { - atomicAdd(dst, value); - } else if constexpr (std::is_same_v) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 600 - atomicAdd(reinterpret_cast(dst), static_cast(value)); -#else - (void)dst; - (void)value; -#endif - } else { - (void)dst; - (void)value; - } -} - /** * Disg twin of @ref carbon::detail::dense::dense_grid_reduce_block_atomic_kernel . */ @@ -133,7 +106,7 @@ disg_grid_reduce_block_atomic_kernel(Span span, const T block_val = BlockReduceT(temp_storage).Reduce(thread_val, op); if (threadIdx.x == 0U) { - disg_reduce_atomic_accumulate(global_out, block_val); + reduce_atomic_accumulate(global_out, block_val); } } diff --git a/include/carbon/detail/backend/cudalike/dense_distributed_reduce_kernel.h b/include/carbon/detail/backend/cudalike/dense_distributed_reduce_kernel.h index 2e8dc285..a9b1ed7e 100644 --- a/include/carbon/detail/backend/cudalike/dense_distributed_reduce_kernel.h +++ b/include/carbon/detail/backend/cudalike/dense_distributed_reduce_kernel.h @@ -23,6 +23,7 @@ #if CARBON_CUDALIKE_DEVICE_TU #include +#include #endif namespace carbon::detail::dense_distributed { @@ -49,34 +50,6 @@ constexpr int kReduceBlockThreads = 256; #if CARBON_CUDALIKE_DEVICE_TU -template -CARBON_HD inline auto -reduce_atomic_accumulate(T* dst, - T value) -> void { - if constexpr (std::is_same_v) { - atomicAdd(dst, value); - } else if constexpr (std::is_same_v) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 600 - atomicAdd(dst, value); -#else - (void)dst; - (void)value; -#endif - } else if constexpr (std::is_same_v) { - atomicAdd(dst, value); - } else if constexpr (std::is_same_v) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 600 - atomicAdd(reinterpret_cast(dst), static_cast(value)); -#else - (void)dst; - (void)value; -#endif - } else { - (void)dst; - (void)value; - } -} - /** * Fused "map + block-reduce" kernel for a @c DenseDistributed slab under any @ref DataView . * @p BlockThreads must match the launch configuration (see @c dense_reduce_launch.h ). @@ -160,8 +133,9 @@ dense_grid_reduce_block_atomic_kernel_t(Span span, } /** - * 2D CUDA block over @c (ix, iz) — matches NVIDIA @c jacobi_kernel launch shape on Carbon - * @c DenseDistributed slabs where @c y == 1 and @c z is the second mesh axis. + * 2D CUDA block over @c (ix, flat_yz) , where @c flat_yz is the flattened @c (iy, iz) index. + * For @c y == 1 this matches the NVIDIA @c jacobi_kernel @c x/z launch shape; for @c y > 1 + * the second block dimension covers every @c (y, z) cell. */ template (blockIdx.x) * BlockDimX + static_cast(threadIdx.x); - const int64_t iz = + const int64_t flat_yz = static_cast(blockIdx.y) * BlockDimY + static_cast(threadIdx.y); T thread_val = init; - if (ix < ext.x && iz < ext.z) { - const ValidatedIdx vi = span.set_and_validate(view, ix, 0, iz); + 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); if (vi.valid) { thread_val = fn(span, vi.idx); } @@ -220,14 +197,17 @@ dense_grid_reduce_block_atomic_kernel_2d_t(Span span, __shared__ typename BlockReduceT::TempStorage temp_storage; const ::carbon::int64_3d ext = span.iter_extent(view); + const int64_t yz_extent = ext.y * ext.z; const int64_t ix = static_cast(blockIdx.x) * BlockDimX + static_cast(threadIdx.x); - const int64_t iz = + const int64_t flat_yz = static_cast(blockIdx.y) * BlockDimY + static_cast(threadIdx.y); T thread_val = init; - if (ix < ext.x && iz < ext.z) { - const ValidatedIdx vi = span.set_and_validate(view, ix, 0, iz); + 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); if (vi.valid) { thread_val = fn(span, vi.idx); } diff --git a/include/carbon/detail/backend/cudalike/dense_distributed_reduce_launch.h b/include/carbon/detail/backend/cudalike/dense_distributed_reduce_launch.h index bdb7e2cb..49815c16 100644 --- a/include/carbon/detail/backend/cudalike/dense_distributed_reduce_launch.h +++ b/include/carbon/detail/backend/cudalike/dense_distributed_reduce_launch.h @@ -123,10 +123,12 @@ launch_dense_grid_reduce_kernel_2d(int block_dim_x, int64_t total_cells) -> gpu_error_t { const ::carbon::int64_3d ext = span.iter_extent(view); const unsigned grid_x = static_cast((ext.x + block_dim_x - 1) / block_dim_x); - const unsigned grid_y = static_cast((ext.z + block_dim_y - 1) / block_dim_y); + const int64_t yz_extent = ext.y * ext.z; + const unsigned grid_y = static_cast((yz_extent + block_dim_y - 1) / block_dim_y); if (static_cast(grid_x) * static_cast(grid_y) != blocks) { log::throw_with_log( - "Kernel::reduce: 2D launch grid {}x{} != expected block count {}", grid_x, grid_y, blocks); + "Kernel::reduce: 2D launch grid {}x{} over (x, y*z) != expected block count {}", grid_x, + grid_y, blocks); } #define CARBON_LAUNCH_DENSE_REDUCE_2D(BX, BY) \ @@ -137,23 +139,8 @@ launch_dense_grid_reduce_kernel_2d(int block_dim_x, if (block_dim_x == 32 && block_dim_y == 32) { CARBON_LAUNCH_DENSE_REDUCE_2D(32, 32); } - if (block_dim_x == 16 && block_dim_y == 16) { - CARBON_LAUNCH_DENSE_REDUCE_2D(16, 16); - } - if (block_dim_x == 8 && block_dim_y == 8) { - CARBON_LAUNCH_DENSE_REDUCE_2D(8, 8); - } - if (block_dim_x == 32 && block_dim_y == 16) { - CARBON_LAUNCH_DENSE_REDUCE_2D(32, 16); - } - if (block_dim_x == 16 && block_dim_y == 32) { - CARBON_LAUNCH_DENSE_REDUCE_2D(16, 32); - } - if (block_dim_x == 64 && block_dim_y == 64) { - CARBON_LAUNCH_DENSE_REDUCE_2D(64, 64); - } log::throw_with_log( - "Kernel::reduce: unsupported 2D reduce block {}x{} (try 32x32, 16x16, …)", block_dim_x, + "Kernel::reduce: unsupported 2D reduce block {}x{} (currently only 32x32)", block_dim_x, block_dim_y); #undef CARBON_LAUNCH_DENSE_REDUCE_2D } @@ -177,10 +164,12 @@ launch_dense_grid_reduce_block_atomic_kernel_2d(int block_dim_x, int64_t total_cells) -> gpu_error_t { const ::carbon::int64_3d ext = span.iter_extent(view); const unsigned grid_x = static_cast((ext.x + block_dim_x - 1) / block_dim_x); - const unsigned grid_y = static_cast((ext.z + block_dim_y - 1) / block_dim_y); + const int64_t yz_extent = ext.y * ext.z; + const unsigned grid_y = static_cast((yz_extent + block_dim_y - 1) / block_dim_y); if (static_cast(grid_x) * static_cast(grid_y) != blocks) { log::throw_with_log( - "Kernel::reduce: 2D launch grid {}x{} != expected block count {}", grid_x, grid_y, blocks); + "Kernel::reduce: 2D launch grid {}x{} over (x, y*z) != expected block count {}", grid_x, + grid_y, blocks); } #define CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D(BX, BY) \ @@ -191,23 +180,8 @@ launch_dense_grid_reduce_block_atomic_kernel_2d(int block_dim_x, if (block_dim_x == 32 && block_dim_y == 32) { CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D(32, 32); } - if (block_dim_x == 16 && block_dim_y == 16) { - CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D(16, 16); - } - if (block_dim_x == 8 && block_dim_y == 8) { - CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D(8, 8); - } - if (block_dim_x == 32 && block_dim_y == 16) { - CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D(32, 16); - } - if (block_dim_x == 16 && block_dim_y == 32) { - CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D(16, 32); - } - if (block_dim_x == 64 && block_dim_y == 64) { - CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D(64, 64); - } log::throw_with_log( - "Kernel::reduce: unsupported 2D reduce block {}x{} (try 32x32, 16x16, …)", block_dim_x, + "Kernel::reduce: unsupported 2D reduce block {}x{} (currently only 32x32)", block_dim_x, block_dim_y); #undef CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D } diff --git a/include/carbon/detail/backend/cudalike/dense_reduce_kernel.h b/include/carbon/detail/backend/cudalike/dense_reduce_kernel.h index b0dce329..6a147984 100644 --- a/include/carbon/detail/backend/cudalike/dense_reduce_kernel.h +++ b/include/carbon/detail/backend/cudalike/dense_reduce_kernel.h @@ -23,6 +23,7 @@ #if CARBON_CUDALIKE_DEVICE_TU #include +#include #endif namespace carbon::detail::dense { @@ -49,34 +50,6 @@ constexpr int kReduceBlockThreads = 256; #if CARBON_CUDALIKE_DEVICE_TU -template -CARBON_HD inline auto -reduce_atomic_accumulate(T* dst, - T value) -> void { - if constexpr (std::is_same_v) { - atomicAdd(dst, value); - } else if constexpr (std::is_same_v) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 600 - atomicAdd(dst, value); -#else - (void)dst; - (void)value; -#endif - } else if constexpr (std::is_same_v) { - atomicAdd(dst, value); - } else if constexpr (std::is_same_v) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 600 - atomicAdd(reinterpret_cast(dst), static_cast(value)); -#else - (void)dst; - (void)value; -#endif - } else { - (void)dst; - (void)value; - } -} - /** * Fused "map + block-reduce" kernel for a @c Dense slab under any @ref DataView . * @p BlockThreads must match the launch configuration (see @c dense_reduce_launch.h ). @@ -160,8 +133,9 @@ dense_grid_reduce_block_atomic_kernel_t(Span span, } /** - * 2D CUDA block over @c (ix, iz) — matches NVIDIA @c jacobi_kernel launch shape on Carbon - * @c Dense slabs where @c y == 1 and @c z is the second mesh axis. + * 2D CUDA block over @c (ix, flat_yz) , where @c flat_yz is the flattened @c (iy, iz) index. + * For @c y == 1 this matches the NVIDIA @c jacobi_kernel @c x/z launch shape; for @c y > 1 + * the second block dimension covers every @c (y, z) cell. */ template (blockIdx.x) * BlockDimX + static_cast(threadIdx.x); - const int64_t iz = + const int64_t flat_yz = static_cast(blockIdx.y) * BlockDimY + static_cast(threadIdx.y); T thread_val = init; - if (ix < ext.x && iz < ext.z) { - const ValidatedIdx vi = span.set_and_validate(view, ix, 0, iz); + 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); if (vi.valid) { thread_val = fn(span, vi.idx); } @@ -220,14 +197,17 @@ dense_grid_reduce_block_atomic_kernel_2d_t(Span span, __shared__ typename BlockReduceT::TempStorage temp_storage; const ::carbon::int64_3d ext = span.iter_extent(view); + const int64_t yz_extent = ext.y * ext.z; const int64_t ix = static_cast(blockIdx.x) * BlockDimX + static_cast(threadIdx.x); - const int64_t iz = + const int64_t flat_yz = static_cast(blockIdx.y) * BlockDimY + static_cast(threadIdx.y); T thread_val = init; - if (ix < ext.x && iz < ext.z) { - const ValidatedIdx vi = span.set_and_validate(view, ix, 0, iz); + 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); if (vi.valid) { thread_val = fn(span, vi.idx); } diff --git a/include/carbon/detail/backend/cudalike/dense_reduce_launch.h b/include/carbon/detail/backend/cudalike/dense_reduce_launch.h index 651e7acd..e631059a 100644 --- a/include/carbon/detail/backend/cudalike/dense_reduce_launch.h +++ b/include/carbon/detail/backend/cudalike/dense_reduce_launch.h @@ -121,10 +121,12 @@ launch_dense_grid_reduce_kernel_2d(int block_dim_x, int64_t total_cells) -> gpu_error_t { const ::carbon::int64_3d ext = span.iter_extent(view); const unsigned grid_x = static_cast((ext.x + block_dim_x - 1) / block_dim_x); - const unsigned grid_y = static_cast((ext.z + block_dim_y - 1) / block_dim_y); + const int64_t yz_extent = ext.y * ext.z; + const unsigned grid_y = static_cast((yz_extent + block_dim_y - 1) / block_dim_y); if (static_cast(grid_x) * static_cast(grid_y) != blocks) { log::throw_with_log( - "Kernel::reduce: 2D launch grid {}x{} != expected block count {}", grid_x, grid_y, blocks); + "Kernel::reduce: 2D launch grid {}x{} over (x, y*z) != expected block count {}", grid_x, + grid_y, blocks); } #define CARBON_LAUNCH_DENSE_REDUCE_2D(BX, BY) \ @@ -135,23 +137,8 @@ launch_dense_grid_reduce_kernel_2d(int block_dim_x, if (block_dim_x == 32 && block_dim_y == 32) { CARBON_LAUNCH_DENSE_REDUCE_2D(32, 32); } - if (block_dim_x == 16 && block_dim_y == 16) { - CARBON_LAUNCH_DENSE_REDUCE_2D(16, 16); - } - if (block_dim_x == 8 && block_dim_y == 8) { - CARBON_LAUNCH_DENSE_REDUCE_2D(8, 8); - } - if (block_dim_x == 32 && block_dim_y == 16) { - CARBON_LAUNCH_DENSE_REDUCE_2D(32, 16); - } - if (block_dim_x == 16 && block_dim_y == 32) { - CARBON_LAUNCH_DENSE_REDUCE_2D(16, 32); - } - if (block_dim_x == 64 && block_dim_y == 64) { - CARBON_LAUNCH_DENSE_REDUCE_2D(64, 64); - } log::throw_with_log( - "Kernel::reduce: unsupported 2D reduce block {}x{} (try 32x32, 16x16, …)", block_dim_x, + "Kernel::reduce: unsupported 2D reduce block {}x{} (currently only 32x32)", block_dim_x, block_dim_y); #undef CARBON_LAUNCH_DENSE_REDUCE_2D } @@ -175,10 +162,12 @@ launch_dense_grid_reduce_block_atomic_kernel_2d(int block_dim_x, int64_t total_cells) -> gpu_error_t { const ::carbon::int64_3d ext = span.iter_extent(view); const unsigned grid_x = static_cast((ext.x + block_dim_x - 1) / block_dim_x); - const unsigned grid_y = static_cast((ext.z + block_dim_y - 1) / block_dim_y); + const int64_t yz_extent = ext.y * ext.z; + const unsigned grid_y = static_cast((yz_extent + block_dim_y - 1) / block_dim_y); if (static_cast(grid_x) * static_cast(grid_y) != blocks) { log::throw_with_log( - "Kernel::reduce: 2D launch grid {}x{} != expected block count {}", grid_x, grid_y, blocks); + "Kernel::reduce: 2D launch grid {}x{} over (x, y*z) != expected block count {}", grid_x, + grid_y, blocks); } #define CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D(BX, BY) \ @@ -189,23 +178,8 @@ launch_dense_grid_reduce_block_atomic_kernel_2d(int block_dim_x, if (block_dim_x == 32 && block_dim_y == 32) { CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D(32, 32); } - if (block_dim_x == 16 && block_dim_y == 16) { - CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D(16, 16); - } - if (block_dim_x == 8 && block_dim_y == 8) { - CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D(8, 8); - } - if (block_dim_x == 32 && block_dim_y == 16) { - CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D(32, 16); - } - if (block_dim_x == 16 && block_dim_y == 32) { - CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D(16, 32); - } - if (block_dim_x == 64 && block_dim_y == 64) { - CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D(64, 64); - } log::throw_with_log( - "Kernel::reduce: unsupported 2D reduce block {}x{} (try 32x32, 16x16, …)", block_dim_x, + "Kernel::reduce: unsupported 2D reduce block {}x{} (currently only 32x32)", block_dim_x, block_dim_y); #undef CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D } diff --git a/include/carbon/detail/backend/cudalike/reduce_atomic.h b/include/carbon/detail/backend/cudalike/reduce_atomic.h new file mode 100644 index 00000000..ab0bf197 --- /dev/null +++ b/include/carbon/detail/backend/cudalike/reduce_atomic.h @@ -0,0 +1,38 @@ +#pragma once + +/** + * Shared block-partial accumulation for the CUDA/HIP reduce kernels. + * + * The four reduce-kernel headers (Dense, DenseDistributed, DenseDisg, Block) all fold + * per-block partials into a global scalar under @ref carbon::reduce::ReduceFinalize::BlockAtomic. + * Keeping the type dispatch here ensures every backend gets the same HIP-aware atomic path + * and that an unsupported element type is a compile-time error rather than a silent no-op. + */ + +#include +#include + +#include +#include + +namespace carbon { +namespace detail { + +template +inline constexpr bool dependent_false_v = false; + +template +CARBON_HD inline auto +reduce_atomic_accumulate(T* dst, + T value) -> void { + if constexpr (std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v) { + (void)atomic_add(dst, value); + } else { + static_assert(dependent_false_v, + "reduce_atomic_accumulate: unsupported element type"); + } +} + +} // namespace detail +} // namespace carbon diff --git a/include/carbon/detail/backend/sycl/event.h b/include/carbon/detail/backend/sycl/event.h index 18268700..78fd9967 100644 --- a/include/carbon/detail/backend/sycl/event.h +++ b/include/carbon/detail/backend/sycl/event.h @@ -26,12 +26,19 @@ #include namespace carbon { + +template +class ReductionResult; + namespace detail { class Gpu; class CARBON_API Event { friend class Gpu; + // ReductionResult::record_slot_done_on_stream_ wraps a sycl::event in an Event (SYCL backend). + template + friend class ::carbon::ReductionResult; Event() = default; explicit Event(std::shared_ptr e) noexcept diff --git a/include/carbon/detail/dense_distributed/layout.h b/include/carbon/detail/dense_distributed/layout.h index b29a26da..979d1273 100644 --- a/include/carbon/detail/dense_distributed/layout.h +++ b/include/carbon/detail/dense_distributed/layout.h @@ -85,6 +85,42 @@ halo_extent(const ProcessGrid& pg, }; } +/** + * Validate that every global chunk is thick enough for its halo. Throws on the first offending + * chunk in the same deterministic order on every rank, so a bad decomposition cannot throw on + * only some ranks and leave the others waiting in the first collective. + */ +inline void +validate_global_halo_fit(const int64_3d& global, + const ProcessGrid& pg, + const int64_3d& halo, + bool legacy_slab, + const Stencil& stencil) { + const int32_3d dims = pg.dims(); + for (const size_t nx : split_extent(global.x, static_cast(dims.x))) { + for (const size_t ny : split_extent(global.y, static_cast(dims.y))) { + for (const size_t nz : split_extent(global.z, static_cast(dims.z))) { + if (legacy_slab && halo.z > 0 && nz < static_cast(2 * halo.z)) { + carbon::log::throw_with_log( + "DenseDistributed: global slab z-extent {} is smaller than 2 * halo_z = {} (stencil " + "radius {}); the Internal / Boundary DataView split would overlap. Either grow " + "the slab or shrink the stencil", + nz, 2 * halo.z, stencil.radius()); + } + if (!legacy_slab && + ((halo.x > 0 && nx < static_cast(halo.x)) || + (halo.y > 0 && ny < static_cast(halo.y)) || + (halo.z > 0 && nz < static_cast(halo.z)))) { + carbon::log::throw_with_log( + "DenseDistributed: global owned extent ({}, {}, {}) is smaller than halo ({}, {}, " + "{}) on a multi-axis decomposition; the halo would overlap the owned region", + nx, ny, nz, halo.x, halo.y, halo.z); + } + } + } + } +} + /** Geometry of the chunk owned by one process-grid coordinate. */ struct RankChunk { /** Owned (non-halo) extent. */ diff --git a/include/carbon/detail/dense_distributed/span.h b/include/carbon/detail/dense_distributed/span.h index 636006cf..ff03b55b 100644 --- a/include/carbon/detail/dense_distributed/span.h +++ b/include/carbon/detail/dense_distributed/span.h @@ -55,6 +55,7 @@ class Span { int64_3d offset_{}; int64_3d halo_{}; BoundaryModeDistributed boundary_mode_{BoundaryModeDistributed::Open}; + bool legacy_slab_{false}; float32_3d origin_{}; float spacing_{1.0F}; @@ -67,6 +68,7 @@ class Span { int64_3d offset, int64_3d halo = {}, BoundaryModeDistributed boundary_mode = BoundaryModeDistributed::Open, + bool legacy_slab = false, float32_3d origin = {}, float spacing = 1.0F) noexcept : haloed_extent_(haloed_extent), @@ -75,6 +77,7 @@ class Span { offset_(offset), halo_(halo), boundary_mode_(boundary_mode), + legacy_slab_(legacy_slab), origin_(origin), spacing_(spacing) {} @@ -93,18 +96,23 @@ class Span { * @param boundary_mode Per-axis boundary semantics propagated from the owning @c DenseDistributed; * consumed by @c Partition::neighbour and the halo exchange. * Defaults to @c BoundaryModeDistributed::Open. + * @param legacy_slab Selects the historical two-band z-only Boundary mapping. This is valid + * only when @c halo.x == halo.y == 0 and @c logic_extent().z >= + * 2 * halo.z; @c DenseDistributed passes true only for legacy slabs. + * Defaults to false, so z-only non-legacy chunks use the compact shell. * @param origin Physical-space origin of global cell @c (0,0,0)'s corner (same * convention as @c global_location on integer indices). * @param spacing Isotropic cell spacing along every axis (must be finite and > 0). */ /** Z-only convenience overload: equivalent to full @c offset={0,0,z_offset} and - * @c halo={0,0,halo_z}. */ + * @c halo={0,0,halo_z}. @p legacy_slab defaults to false; pass true for a legacy z-slab. */ CARBON_HD constexpr Span(int64_3d haloed_extent, int64_3d global_extent, int64_t xy_slab_elements, int64_t z_offset, int64_t halo_z = 0, BoundaryModeDistributed boundary_mode = BoundaryModeDistributed::Open, + bool legacy_slab = false, float32_3d origin = {}, float spacing = 1.0F) noexcept : Span(haloed_extent, @@ -117,6 +125,7 @@ class Span { 0, halo_z}, boundary_mode, + legacy_slab, origin, spacing) {} @@ -154,11 +163,12 @@ class Span { * - @c Internal: @c max(owned - 2 * halo(), 0) component-wise. Covers the inner region that * does not depend on data outside the chunk. Zero halo on an axis leaves that axis whole. * - @c Boundary: the owned cells that are not in @c Internal (the shell of thickness - * @c halo() ). Legacy z-only chunks ( @c halo.x == halo.y == 0 ) use the compact - * @c 2 * halo.z z-band domain. Multi-axis chunks (pencil / brick) use a @b compact shell - * domain: the shell is split into six non-overlapping slabs (Z faces over the full XY - * extent, then Y faces over the middle Z range, then X faces over the middle Y and Z - * ranges), and @c iter_extent is a 2-D @c (W, ceil(S / W), 1) launch box over the @c S + * @c halo() ). Legacy z-only chunks ( @c legacy_slab == true and @c halo.x == halo.y == 0 ) + * use the compact @c 2 * halo.z z-band domain. Non-legacy z-only chunks (for example a + * pencil/brick or periodic-X/Y slab with a z-only stencil) and multi-axis chunks use a + * @b compact shell domain: the shell is split into six non-overlapping slabs (Z faces over + * the full XY extent, then Y faces over the middle Z range, then X faces over the middle Y + * and Z ranges), and @c iter_extent is a 2-D @c (W, ceil(S / W), 1) launch box over the @c S * shell cells. @ref set_and_validate maps the linear thread index to its cell and returns * @c valid=false only for the padded tail ( @c < W trailing threads), so a Boundary launch * runs ~ @c S threads instead of one per owned cell. Because of that mapping, consecutive @@ -185,7 +195,7 @@ class Span { } case ::carbon::DataView::Boundary: { - if (halo_.x == 0 && halo_.y == 0) { + if (legacy_slab_ && halo_.x == 0 && halo_.y == 0) { return int64_3d{owned.x, owned.y, halo_.z > 0 ? 2 * halo_.z : 0}; } const int64_t shell = shell_bands_().total; @@ -340,9 +350,9 @@ class Span { * * - @c Standard: @c b = halo() + i. * - @c Internal: @c b = 2 * halo() + i (skip past the halo plus the boundary band). - * - @c Boundary: legacy z-only chunks use the compact lower/upper z bands; multi-axis chunks - * decode the linear shell index @c t = iy * iter_extent.x + ix into an owned cell (see - * @ref iter_extent ) and return @c valid=false for the padded tail. + * - @c Boundary: legacy z-only chunks ( @c legacy_slab == true ) use the compact lower/upper z + * bands; non-legacy chunks decode the linear shell index @c t = iy * iter_extent.x + ix into + * an owned cell (see @ref iter_extent ) and return @c valid=false for the padded tail. * * The @c valid flag in the returned @ref ValidatedIdx is @c true iff every component of * @c (ix, iy, iz) is within @c iter_extent(view); kernels should early-out on a @c false @@ -488,7 +498,7 @@ Span::set_and_validate(::carbon::DataView view, return ValidatedIdx{Idx(2 * halo_.x + ix, 2 * halo_.y + iy, 2 * halo_.z + iz), true}; case ::carbon::DataView::Boundary: { - if (halo_.x == 0 && halo_.y == 0) { + if (legacy_slab_ && halo_.x == 0 && halo_.y == 0) { const int64_t owned_z = logic_extent().z; const int64_t bz = (iz < halo_.z) ? (halo_.z + iz) : (owned_z - halo_.z + iz); return ValidatedIdx{Idx(ix, iy, bz), true}; diff --git a/include/carbon/detail/launch_traits.h b/include/carbon/detail/launch_traits.h index 7a54d3e0..a5dca73a 100644 --- a/include/carbon/detail/launch_traits.h +++ b/include/carbon/detail/launch_traits.h @@ -433,7 +433,8 @@ struct HostLaunchTraits<::carbon::Block> { * @c kDisgReduceBlockThreads ; Block: @c SBlock::VoxelCount ). * - @c stage1_unit_count(grid, g_idx, view) — number of CUDA blocks the * stage-1 launch dispatches for @p view on local GPU @p g_idx . Dense / - * DenseDisg : @c ceil_div(iter_extent.volume(), stage1_block_threads()) . + * DenseDisg 1-D : @c ceil_div(iter_extent.volume(), stage1_block_threads()) . + * Dense / DenseDisg 2-D : @c ceil(ext.x / bx) * ceil((ext.y * ext.z) / by) . * Block : @c iter_block_count(view) (one CUDA block per retained brick). * - @c is_empty_domain(grid, g_idx, view) — true iff the stage-1 launch * would have zero work. Dense / DenseDisg : @c iter_cells == 0 . Block : @@ -476,12 +477,13 @@ struct ReduceLaunchTraits { if (dense_stage1_threads_y > 0) { const int bx = dense_stage1_threads > 0 ? dense_stage1_threads : 32; const int by = dense_stage1_threads_y; - if (ext.x <= 0 || ext.z <= 0) { + const int64_t yz_extent = ext.y * ext.z; + if (ext.x <= 0 || yz_extent <= 0) { return 0; } const int64_t gx = (ext.x + bx - 1) / bx; - const int64_t gz = (ext.z + by - 1) / by; - return gx * gz; + const int64_t gyz = (yz_extent + by - 1) / by; + return gx * gyz; } } int bt = stage1_block_threads(); diff --git a/include/carbon/detail/reduce_kernel_impl.h b/include/carbon/detail/reduce_kernel_impl.h index 62329c74..e86dd64f 100644 --- a/include/carbon/detail/reduce_kernel_impl.h +++ b/include/carbon/detail/reduce_kernel_impl.h @@ -35,9 +35,10 @@ * the user side. * * Per-block scratch and CUB device-reduce temp storage are pre-allocated per @ref DataView - * per local GPU in the constructor, sized from the @c Standard -view iteration extent of - * each slab (the largest of the three views — every Internal / Boundary launch uses - * @c <= block_count_per_gpu_[g] blocks, so neither buffer ever needs to grow). + * per local GPU in the constructor, sized from the maximum stage-1 block count over + * @c Standard , @c Internal and @c Boundary . The 2-D compact-shell @c Boundary can need + * more blocks than @c Standard because its flattened @c (y, z) launch box includes row + * padding; every view's launch uses @c <= stage1_scratch_blocks_per_gpu_[g] blocks. * * Include from @c .cu translation units (or any TU compiled with nvcc) when the factory * @c carbon::Kernel::reduce / @c Dense::make_reduce_kernel is instantiated. @@ -66,6 +67,7 @@ // shape) lives in @c detail::ReduceLaunchTraits from launch_traits.h above. #include +#include #include #include #include @@ -164,7 +166,7 @@ class ReduceKernelImpl final : public KernelImpl { } #if CARBON_BACKEND_IS_SYCL log::throw_with_log( - "Kernel::reduce: ReduceFinalize::BlockAtomic is supported only on the CUDA backend"); + "Kernel::reduce: ReduceFinalize::BlockAtomic is supported only on the CUDA/HIP backend"); #endif } if (reduce_options_.host_copy == reduce::ReduceHostCopy::Deferred) { @@ -204,18 +206,27 @@ class ReduceKernelImpl final : public KernelImpl { const size_t gpu_count = grid_.gpu_count(); total_cells_per_gpu_.assign(gpu_count, 0); block_count_per_gpu_.assign(gpu_count, 0); + stage1_scratch_blocks_per_gpu_.assign(gpu_count, 0); // The trait's stage1_unit_count returns the per-GPU "CUDA-block count" // the stage-1 reduce launch dispatches: Dense / DenseDisg derive it from // @c iter_extent.volume() / kReduceBlockThreads ; Block returns - // @c iter_block_count(view) directly. Sized off Standard since that - // view dominates Internal + Boundary (whose unit counts together cover - // the same set of cells / bricks). + // @c iter_block_count(view) directly. The public block_count() accessor + // stays tied to the Standard view. Scratch buffers, however, must cover the + // largest view: the 2-D compact-shell Boundary can need more blocks than + // Standard because its flattened (y, z) launch box includes row padding. using Traits = ReduceLaunchTraits; for (size_t g_idx = 0; g_idx < gpu_count; ++g_idx) { total_cells_per_gpu_[g_idx] = Traits::iter_cell_count(grid_, g_idx, DataView::Standard); block_count_per_gpu_[g_idx] = Traits::stage1_unit_count( grid_, g_idx, DataView::Standard, dense_stage1_threads_, dense_stage1_threads_y_); + for (const DataView view : + {DataView::Standard, DataView::Internal, DataView::Boundary}) { + stage1_scratch_blocks_per_gpu_[g_idx] = + std::max(stage1_scratch_blocks_per_gpu_[g_idx], + Traits::stage1_unit_count(grid_, g_idx, view, dense_stage1_threads_, + dense_stage1_threads_y_)); + } } #if CARBON_BACKEND_IS_CUDALIKE && CARBON_CUDALIKE_DEVICE_TU @@ -230,13 +241,13 @@ class ReduceKernelImpl final : public KernelImpl { } for (size_t g_idx = 0; g_idx < gpu_count; ++g_idx) { const detail::Gpu& gpu = grid_.system().gpu_group().devices()[g_idx]; - const int64_t blocks = block_count_per_gpu_[g_idx]; + const int64_t blocks = stage1_scratch_blocks_per_gpu_[g_idx]; // Always allocate at least one element so partials_[v][g].data() is non-null and the // empty-domain branch in launch() can pass it as the d_in for cub::DeviceReduce // with num_items=0 (which writes init verbatim). Same trick the v1 code used. const size_t partial_count = static_cast(blocks > 0 ? blocks : 1); - // Size CUB temp once from the Standard-view scratch shape; every view reuses that - // byte count (Internal/Boundary launch <= Standard blocks). + // Size CUB temp once from the maximum per-view scratch shape; every view reuses that + // byte count. The 2-D compact-shell Boundary can exceed Standard's block count. { auto probe = gpu.template buffer(partial_count, /*relative_gpu_id=*/static_cast(g_idx)); @@ -383,11 +394,10 @@ class ReduceKernelImpl final : public KernelImpl { const int64_t blocks = Traits::stage1_unit_count(grid_, g_idx, view, dense_stage1_threads_, dense_stage1_threads_y_); const int64_t iter_cells = Traits::iter_cell_count(grid_, g_idx, view); - if (blocks > block_count_per_gpu_[g_idx]) { - // Sanity check: Standard-view sizing in the ctor must dominate every other view's - // launch; if this trips, the trait's @c stage1_unit_count for this view exceeds - // Standard, which would invalidate the per-GPU partial scratch shape. - outcomes[g_idx] = {gpu_success, "sizing", block_count_per_gpu_[g_idx], blocks, 0}; + if (blocks > stage1_scratch_blocks_per_gpu_[g_idx]) { + // Sanity check: the ctor sizes scratch from the maximum over all DataViews; if this + // trips, the trait's @c stage1_unit_count for this view exceeds that maximum. + outcomes[g_idx] = {gpu_success, "sizing", stage1_scratch_blocks_per_gpu_[g_idx], blocks, 0}; continue; } @@ -493,7 +503,7 @@ class ReduceKernelImpl final : public KernelImpl { log::throw_with_log( "Kernel::reduce::launch: view {} requires {} stage-1 units on local GPU {} but the " "ctor only sized {} (ReduceLaunchTraits::stage1_unit_count for this view exceeds " - "Standard?)", + "the per-view maximum?)", ::carbon::to_string(view), o.requested, g_idx, o.sized); } if (o.stage == "gpu_set_device"sv) { @@ -605,9 +615,48 @@ class ReduceKernelImpl final : public KernelImpl { dst.record_readback_done(DataView::Standard, slot, stream); dst.mark_fresh(DataView::Standard); } +#elif CARBON_BACKEND_IS_SYCL + if (stream.size() != grid_.gpu_count()) { + log::throw_with_log( + "Kernel::reduce::launch_merge: stream-group size ({}) != gpu_count ({})", + stream.size(), grid_.gpu_count()); + } + ReductionResult& dst = *dst_; + (void)dst.begin_launch_slot(DataView::Standard, stream); + const size_t root = static_cast(dst.root_local_gpu()); + sycl::queue& q = stream[root].queue(); + + T* const out = dst.device_data(DataView::Standard); + const T* const internal = dst.device_data(DataView::Internal); + const T* const boundary = dst.device_data(DataView::Boundary); + // Copy Op and the identity into locals so the device lambda captures no `this` + // pointer; the single_task folds the two already-combined Partial scalars. + const Op op = op_; + const T init = op.identity(); + try { + q.submit([&](sycl::handler& cgh) { + cgh.single_task([op, init, out, internal, boundary]() { + *out = op(op(init, *internal), *boundary); + }); + }); + } catch (const sycl::exception& ex) { + log::throw_with_log( + "Kernel::reduce::launch_merge: SYCL submission failed: {}", ex.what()); + } + + reduce_stages::run_stage3_cross_rank(grid_.system(), stream, dst, + DataView::Standard); + if (reduce_options_.host_copy == reduce::ReduceHostCopy::Inline) { + const size_t slot = dst.active_slot(); + grid_.system().async_copy(dst.device_allocation(DataView::Standard, slot), + dst.host_allocation(DataView::Standard, slot), sizeof(T), + stream); + dst.record_readback_done(DataView::Standard, slot, stream); + dst.mark_fresh(DataView::Standard); + } #else log::throw_with_log( - "Kernel::reduce::launch_merge requires a CUDA/HIP device translation unit"); + "Kernel::reduce::launch_merge requires a CUDA/HIP or SYCL backend"); #endif } @@ -671,11 +720,12 @@ class ReduceKernelImpl final : public KernelImpl { size_t shared_mem_{}; std::vector total_cells_per_gpu_{}; std::vector block_count_per_gpu_{}; + std::vector stage1_scratch_blocks_per_gpu_{}; std::vector tokens_{}; reduce::ReduceOptions reduce_options_{}; - /** Plain @c Dense CUDA stage-1 block width; @c 0 → default @c 256 (1D) or @c 32 (2D). */ + /** Plain @c Dense CUDA/HIP stage-1 block width; @c 0 → default @c 256 (1D) or @c 32 (2D). */ int dense_stage1_threads_{0}; - /** @c 0 = 1D flat tiling; @c >0 = 2D block height ( @c z axis ). */ + /** @c 0 = 1D flat tiling; @c >0 = 2D block dimension over flattened (y, z). */ int dense_stage1_threads_y_{0}; #if CARBON_BACKEND_IS_CUDALIKE && CARBON_CUDALIKE_DEVICE_TU /** Per-view per-GPU stage-1 block partials (concurrent Partial I/B safe). */ diff --git a/include/carbon/reduce.h b/include/carbon/reduce.h index 7c016027..5ab74562 100644 --- a/include/carbon/reduce.h +++ b/include/carbon/reduce.h @@ -34,9 +34,9 @@ * 1. @b Stage-1 (per-GPU map+reduce). Each local GPU runs the user's per-cell device * lambda over @c span.iter_extent(view) and collapses to one @c T into * @c gpu_partial(view, g) . The loading lambda may also perform stencil reads and field - * writes in the same launch (fused map/stencil + reduce). Backed by NVIDIA CUB - * (CUDA) or @c sycl::reduction (SYCL). With @ref ReduceFinalize::BlockAtomic , each - * CUDA block @c atomicAdd s into the per-GPU scalar and stage-1.5 @c DeviceReduce is + * writes in the same launch (fused map/stencil + reduce). Backed by CUB/hipcub + * (CUDA/HIP) or @c sycl::reduction (SYCL). With @ref ReduceFinalize::BlockAtomic , each + * CUDA/HIP block @c atomicAdd s into the per-GPU scalar and stage-1.5 @c DeviceReduce is * skipped (floating-point sums may differ run-to-run vs the default path). * 2. @b Stage-2 (intra-process combine). Per-GPU partials are peer-copied into the * rank-local root GPU's per-view stage-2 staging buffer and combined via the user's @@ -193,10 +193,10 @@ enum class ReduceFinalize : unsigned char { /** Block partials array + @c cub::DeviceReduce::Reduce (default). */ DeviceReduce = 0, /** - * Each CUDA block @c atomicAdd s its block sum into the per-GPU output scalar + * Each CUDA/HIP block @c atomicAdd s its block sum into the per-GPU output scalar * (NVIDIA @c jacobi_kernel style). Skips @c DeviceReduce on the partials buffer. * Only supported with @ref Sum and @c T in @c {float, double, int32_t, int64_t} on - * plain @c Dense CUDA grids. Floating-point sums are not bitwise-deterministic across + * plain @c Dense CUDA/HIP grids. Floating-point sums are not bitwise-deterministic across * launches (atomic add order varies). */ BlockAtomic = 1, @@ -226,14 +226,18 @@ struct ReduceOptions { ReduceFinalize finalize = ReduceFinalize::DeviceReduce; ReduceHostCopy host_copy = ReduceHostCopy::Inline; /** - * CUDA @c Dense stage-1 threads per block. @c 0 selects the library default (@c 256 for - * 1D flat tiling, or @c 32 when @c stage1_threads_y is set for 2D grid tiling). - * Supported 1D values: @c 32 … @c 1024 (powers of two). With @c stage1_threads_y @c > 0, - * @c stage1_threads is the X dimension and @c stage1_threads_y is Y (NVIDIA Jacobi-style - * @c 32x32). Ignored on SYCL; unsupported on @c DenseDisg and @c Block grids. + * CUDA/HIP @c Dense / @c DenseDistributed stage-1 threads per block. @c 0 selects the + * library default (@c 256 for 1D flat tiling, or @c 32 when @c stage1_threads_y is set for + * 2D grid tiling). Supported 1D values: @c 32 … @c 1024 (powers of two). With + * @c stage1_threads_y @c > 0, @c stage1_threads is the X dimension and + * @c stage1_threads_y is the second dimension over flattened @c (y, z); all @c y and + * @c z cells are covered. For @c y == 1 this is the NVIDIA Jacobi-style @c 32x32 @c x/z + * launch shape. Ignored on SYCL; unsupported on @c DenseDisg and @c Block grids. */ unsigned stage1_threads = 0U; - /** @c 0 = 1D flat reduce; @c >0 = 2D CUDA block (@c stage1_threads × this). */ + /** + * @c 0 = 1D flat reduce; @c >0 = 2D CUDA/HIP block over @c x and flattened @c (y, z). + */ unsigned stage1_threads_y = 0U; }; @@ -732,10 +736,25 @@ class ReductionResult { detail::gpu_error_string(err)); } #elif CARBON_BACKEND_IS_SYCL + sycl::queue& q = stream[root].queue(); + q.submit([&](sycl::handler& h) { h.depends_on(evt.event()); + h.single_task([]() {}); }); + + + // #ifdef _ACPP_ + // sycl::queue& q = stream[root].queue(); + // q.AdaptiveCpp_enqueue_custom_operation([](sycl::interop_handle& h) {},evt.event()); + // #else + // sycl::queue& q = stream[root].queue(); + // q.submit([&](sycl::handler& h) { + // h.depends_on(evt.event()); + // }); + // #endif + #else (void)view; (void)slot; @@ -762,8 +781,15 @@ class ReductionResult { } #elif CARBON_BACKEND_IS_SYCL sycl::queue& q = stream[root].queue(); - auto e = q.submit([](sycl::handler& h) { - }); + + sycl::event e = q.single_task([](){}); + + // #ifdef __ACPP__ + // auto e = q.AdaptiveCpp_enqueue_custom_operation([](sycl::interop_handle& h) {}); + // #else + // auto e = q.submit([](sycl::handler& h) {}); + // #endif + *const_cast(&evt) = detail::Event(std::make_shared(e)); #else (void)view; diff --git a/src/communicator.cpp b/src/communicator.cpp index 409df929..c20d13d7 100644 --- a/src/communicator.cpp +++ b/src/communicator.cpp @@ -15,6 +15,7 @@ namespace carbon::detail { namespace { +#ifndef CARBON_DIST_HOST_MPI [[noreturn]] auto throw_nccl_error(const char* where, ncclResult_t res) -> void { @@ -29,6 +30,7 @@ check_nccl(const char* where, throw_nccl_error(where, res); } } +#endif // !CARBON_DIST_HOST_MPI [[noreturn]] auto throw_mpi_error(const char* where, @@ -53,7 +55,9 @@ check_mpi(const char* where, } // namespace struct Communicator::Impl { +#ifndef CARBON_DIST_HOST_MPI ncclComm_t comm{nullptr}; +#endif int rank{0}; int size{1}; int device{0}; @@ -63,12 +67,14 @@ Communicator::Communicator() : impl_(std::make_unique()) {} Communicator::~Communicator() { +#ifndef CARBON_DIST_HOST_MPI if (impl_ && impl_->comm != nullptr) { ncclResult_t res = ncclCommDestroy(impl_->comm); if (res != ncclSuccess) { CARBON_LOG_ERROR("Communicator: ncclCommDestroy failed: {}", ncclGetErrorString(res)); } } +#endif } auto @@ -85,13 +91,19 @@ Communicator::from_mpi(const Distributed& distributed) -> std::shared_ptr std::shared_ptrimpl_->comm, distributed.world_size(), id, distributed.world_rank())); +#endif // CARBON_DIST_HOST_MPI CARBON_LOG_INFO("Communicator: rank={}/{} bound to device {}", comm->impl_->rank, comm->impl_->size, comm->impl_->device); @@ -122,7 +135,11 @@ Communicator::device() const noexcept -> int { auto Communicator::raw_handle() const noexcept -> void* { +#ifdef CARBON_DIST_HOST_MPI + return nullptr; +#else return reinterpret_cast(impl_->comm); +#endif } } // namespace carbon::detail diff --git a/src/communicator_internal.h b/src/communicator_internal.h index 1b0a1117..0588cd44 100644 --- a/src/communicator_internal.h +++ b/src/communicator_internal.h @@ -9,6 +9,7 @@ namespace carbon::detail { +#ifndef CARBON_DIST_HOST_MPI // Definition of the friend bridge forward-declared in . Users // cannot reach @c Communicator::raw_handle through this bridge because the definition lives in // this header, which is not installed; in-tree code that needs the raw @c ncclComm_t includes @@ -25,5 +26,6 @@ struct nccl_bridge { communicator_handle(const Communicator& comm) noexcept -> ncclComm_t { return nccl_bridge::comm(comm); } +#endif // !CARBON_DIST_HOST_MPI } // namespace carbon::detail diff --git a/src/dense.cpp b/src/dense.cpp index f1d9cd35..03fcdbec 100644 --- a/src/dense.cpp +++ b/src/dense.cpp @@ -143,13 +143,24 @@ Dense::Dense(System system, local_slab_offset_ = 0U; } + const int64_t halo_z = static_cast(stencil_.radius()); const std::vector z_counts_global = split_extent_z(global_.z, global_slab_count_); - // Validate per-slab owned-element counts up front so any overflow surfaces during Dense - // construction rather than later in a buffer allocation. The values themselves are not + // Validate per-slab owned-element counts and thickness up front so any overflow or + // too-thin chunk surfaces during Dense construction rather than later in a buffer + // allocation. These checks must run against the global decomposition on every rank: with + // one rank per GPU, validating only local spans lets a rank with a thin chunk throw while + // the others proceed to the first collective and hang. The values themselves are not // cached: linear_elements() recomputes them on demand from spans_. for (size_t g = 0; g < global_slab_count_; ++g) { (void)linear_count_for_slab(global_.x, global_.y, z_counts_global[g]); + if (halo_z > 0 && z_counts_global[g] < static_cast(2 * halo_z)) { + log::throw_with_log( + "Dense: global slab z-extent {} is smaller than 2 * halo_z = {} (stencil radius {}); " + "the Internal / Boundary DataView split would overlap. Either grow the slab or " + "shrink the stencil", + z_counts_global[g], 2 * halo_z, stencil_.radius()); + } } // Cumulative z up to (but not including) this rank's first local slab — i.e. the global z @@ -163,7 +174,6 @@ Dense::Dense(System system, // Prefix scan over the @b local subset of z_counts_global. System::make_vector invokes the // callback in ascending order 0..local_n-1; the captured accumulator continues across local // slabs without resetting. - const int64_t halo_z = static_cast(stencil_.radius()); spans_ = system_.make_vector([&](size_t i) { const int64_t owned_z = static_cast(z_counts_global[local_slab_offset_ + i]); const int64_t z_off = running_z; @@ -185,23 +195,6 @@ Dense::Dense(System system, } } - // The Internal / Boundary split partitions the owned z-extent into a lower halo-thick band, - // an interior of (Lz - 2*halo_z) layers, and an upper halo-thick band. If any local slab is - // thinner than 2*halo_z those bands would overlap, so reject the configuration up front - // rather than letting set_and_validate quietly double-write cells. - if (halo_z > 0) { - for (size_t i = 0; i < local_n; ++i) { - const int64_t lz = spans_[i].logic_extent().z; - if (lz < 2 * halo_z) { - log::throw_with_log( - "Dense: local slab z-extent {} is smaller than 2 * halo_z {} (stencil radius {}); " - "the Internal / Boundary DataView split would overlap. Either grow the slab or " - "shrink the stencil", - lz, 2 * halo_z, stencil_.radius()); - } - } - } - for (auto view : data_view_options()) { const auto vi = static_cast(view); gpu_block_per_view_[vi] = system_.make_vector([&](size_t i) { diff --git a/src/dense_disg.cpp b/src/dense_disg.cpp index 7efe1349..aa751ee4 100644 --- a/src/dense_disg.cpp +++ b/src/dense_disg.cpp @@ -123,6 +123,22 @@ DenseDisg::DenseDisg(System system, const std::vector z_counts_global = split_extent_z(global_.z, global_slab_count_); + // Reject geometries that are too thin for the Internal / Boundary split against the global + // decomposition, so every rank makes the same decision before reaching any collective. With + // halo_z = 1 the internal band has Lz - 2 layers and the boundary spans 2; a slab with + // Lz < 2 makes the boundary view's iter extent collide with the internal one. Same shape of + // check as src/dense.cpp. + if (halo_z_ > 0) { + for (size_t g = 0; g < global_slab_count_; ++g) { + if (z_counts_global[g] < static_cast(2 * halo_z_)) { + log::throw_with_log( + "DenseDisg: global slab z-extent {} is smaller than 2 * halo_z = {}; the Internal / " + "Boundary DataView split would overlap. Either grow the slab or reduce halo_z to 0", + z_counts_global[g], 2 * halo_z_); + } + } + } + // Cumulative z up to (but not including) this rank's first local slab. int64_t running_z = 0; for (size_t g = 0; g < local_slab_offset_; ++g) { @@ -140,22 +156,6 @@ DenseDisg::DenseDisg(System system, boundary_mode_, origin_, spacing_); }); - // Reject geometries that are too thin for the Internal / Boundary split. With halo_z = 1 - // the internal band has Lz - 2 layers and the boundary spans 2; a slab with Lz < 2 makes - // the boundary view's iter extent collide with the internal one. Same shape of check as - // src/dense.cpp. - if (halo_z_ > 0) { - for (size_t i = 0; i < local_n; ++i) { - const int64_t lz = spans_[i].logic_extent().z; - if (lz < 2 * halo_z_) { - log::throw_with_log( - "DenseDisg: local slab z-extent {} is smaller than 2 * halo_z {}; the Internal / " - "Boundary DataView split would overlap. Either grow the slab or reduce halo_z to 0", - lz, 2 * halo_z_); - } - } - } - for (auto view : data_view_options()) { const auto vi = static_cast(view); gpu_block_per_view_[vi] = system_.make_vector([&](size_t i) { diff --git a/src/dense_distributed.cpp b/src/dense_distributed.cpp index 61cad632..0d6683d0 100644 --- a/src/dense_distributed.cpp +++ b/src/dense_distributed.cpp @@ -170,7 +170,14 @@ DenseDistributed::init_common_(System system, global_slab_count_ = static_cast(dims.z); local_slab_offset_ = distributed ? static_cast(coords.z) : 0U; - // Validate every global chunk's owned-element count before allocating fields. + const bool legacy_slab = detail::dense_distributed::is_legacy_slab(process_grid_, boundary_mode_); + const int64_3d halo = + detail::dense_distributed::halo_extent(process_grid_, boundary_mode_, stencil_); + + // Validate every global chunk's owned-element count and halo fit before allocating fields. + // These checks must run against the global decomposition on every rank: with one rank per + // GPU, validating only local spans lets a rank with a thin chunk throw while the others + // proceed to the first collective and hang. for (const size_t nx : split_extent(global_.x, static_cast(dims.x))) { for (const size_t ny : split_extent(global_.y, static_cast(dims.y))) { for (const size_t nz : split_extent(global_.z, static_cast(dims.z))) { @@ -178,10 +185,8 @@ DenseDistributed::init_common_(System system, } } } - - const bool legacy_slab = detail::dense_distributed::is_legacy_slab(process_grid_, boundary_mode_); - const int64_3d halo = - detail::dense_distributed::halo_extent(process_grid_, boundary_mode_, stencil_); + detail::dense_distributed::validate_global_halo_fit(global_, process_grid_, halo, legacy_slab, + stencil_); spans_ = system_.make_vector([&](size_t i) { const int32_3d gpu_coords = @@ -190,40 +195,10 @@ DenseDistributed::init_common_(System system, detail::dense_distributed::rank_chunk(global_, process_grid_, gpu_coords, halo); return detail::dense_distributed::Span(chunk.haloed, global_, chunk.xy_pitch, chunk.offset, - chunk.halo, boundary_mode_, origin_, spacing_); + chunk.halo, boundary_mode_, legacy_slab, origin_, + spacing_); }); - // The legacy Slab Boundary is still two z-bands; keep its old overlap guard. - // Multi-axis Stage-A Boundary is full-owned and rejects internal cells instead. - if (legacy_slab && halo.z > 0) { - for (size_t i = 0; i < local_n; ++i) { - const int64_t lz = spans_[i].logic_extent().z; - if (lz < 2 * halo.z) { - log::throw_with_log( - "DenseDistributed: local slab z-extent {} is smaller than 2 * halo_z {} (stencil " - "radius {}); " - "the Internal / Boundary DataView split would overlap. Either grow the slab or " - "shrink the stencil", - lz, 2 * halo.z, stencil_.radius()); - } - } - } - - if (!legacy_slab) { - for (size_t i = 0; i < local_n; ++i) { - const int64_3d owned = spans_[i].logic_extent(); - const int64_3d h = spans_[i].halo(); - - if ((h.x > 0 && owned.x < h.x) || (h.y > 0 && owned.y < h.y) || (h.z > 0 && owned.z < h.z)) { - log::throw_with_log( - "DenseDistributed: local owned extent ({}, {}, {}) is smaller than halo ({}, {}, {}) " - "on a " - "multi-axis decomposition; the halo would overlap the owned region", - owned.x, owned.y, owned.z, h.x, h.y, h.z); - } - } - } - for (auto view : data_view_options()) { const auto vi = static_cast(view); gpu_block_per_view_[vi] = system_.make_vector([&](size_t i) { diff --git a/src/dist_reduce.cpp b/src/dist_reduce.cpp index d9ed377c..20b8d209 100644 --- a/src/dist_reduce.cpp +++ b/src/dist_reduce.cpp @@ -28,6 +28,7 @@ namespace carbon::reduce { namespace { +#ifndef CARBON_DIST_HOST_MPI [[noreturn]] auto throw_nccl_error(const char* where, ncclResult_t res) -> void { @@ -58,6 +59,7 @@ to_nccl_op(ReduceOpKind op) -> ncclRedOp_t { log::throw_with_log("dist_allreduce_in_place: unknown ReduceOpKind {}", static_cast(op)); } +#endif // !CARBON_DIST_HOST_MPI [[nodiscard]] auto to_mpi_op(ReduceOpKind op) -> MPI_Op { @@ -126,6 +128,7 @@ check_mpi(const char* where, } } +#ifndef CARBON_DIST_HOST_MPI [[nodiscard]] auto to_nccl_dtype(ReduceDataKind dt) -> ncclDataType_t { switch (dt) { @@ -162,6 +165,7 @@ to_nccl_dtype(ReduceDataKind dt) -> ncclDataType_t { log::throw_with_log("dist_allreduce_in_place: unknown ReduceDataKind {}", static_cast(dt)); } +#endif // !CARBON_DIST_HOST_MPI } // namespace @@ -188,6 +192,27 @@ dist_allreduce_in_place(const System& sys, stream.size()); } +#ifdef CARBON_DIST_HOST_MPI + // Host-MPI build: the reduction scalar lives in ordinary host memory, so drain the + // rank's queue and allreduce it in place with MPI. + { + stream.wait(); + const auto* dist_ptr = sys.distributed(); + if (dist_ptr == nullptr) { + log::throw_with_log( + "dist_allreduce_in_place: System has no Distributed handle"); + } + if (count > static_cast(std::numeric_limits::max())) { + log::throw_with_log( + "dist_allreduce_in_place: count={} exceeds MPI_Allreduce's int element limit", count); + } + check_mpi("MPI_Allreduce", + ::MPI_Allreduce(MPI_IN_PLACE, device_ptr, static_cast(count), + to_mpi_dtype(dtype), to_mpi_op(op), + detail::distributed_mpi_world(*dist_ptr))); + return; + } +#else ncclComm_t nccl_comm = detail::communicator_handle(*comm_ptr); const ncclRedOp_t nccl_op = to_nccl_op(op); const ncclDataType_t nccl_dtype = to_nccl_dtype(dtype); @@ -197,7 +222,7 @@ dist_allreduce_in_place(const System& sys, // in. ncclAllReduce is in-place when sendbuff == recvbuff, which is exactly the // mode the reduce KernelImpl uses (single scalar already living on the root GPU). using detail::gpu_compat::gpu_stream_t; - auto submit_allreduce = [&](gpu_stream_t cs) { + auto submit_allreduce = [=](gpu_stream_t cs) { check_nccl("ncclAllReduce", ncclAllReduce(device_ptr, device_ptr, count, nccl_dtype, nccl_op, nccl_comm, cs)); }; @@ -208,11 +233,14 @@ dist_allreduce_in_place(const System& sys, // SYCL backend mirrors dist_transfer.cpp's interop hop: AdaptiveCpp does not expose // get_native(queue) outside a command group, so we wrap the NCCL // call inside an AdaptiveCpp_enqueue_custom_operation that runs on the queue's - // current frontier. The host-side q.wait_and_throw() afterwards keeps the call shape - // synchronous-looking on the host side; the device-side allreduce remains async. + // current frontier. Capture the submission lambda by value so the custom operation + // can run after this function returns; the in-order queue orders subsequent + // submissions after the collective, so no host-side wait is needed here. As with any + // async launch, the caller must keep the System/communicator and device allocation + // alive until the queued work completes. sycl::queue& q = stream[0].queue(); - q.submit([&](sycl::handler& cgh) { - cgh.AdaptiveCpp_enqueue_custom_operation([&submit_allreduce](sycl::interop_handle ih) { + q.submit([submit_allreduce](sycl::handler& cgh) { + cgh.AdaptiveCpp_enqueue_custom_operation([submit_allreduce](sycl::interop_handle ih) { #ifdef CARBON_USE_RCCL submit_allreduce(ih.get_native_queue()); #else @@ -220,8 +248,8 @@ dist_allreduce_in_place(const System& sys, #endif }); }); - q.wait_and_throw(); #endif +#endif // !CARBON_DIST_HOST_MPI } auto diff --git a/src/dist_transfer.cpp b/src/dist_transfer.cpp index b3ef79a9..3e2b8f5c 100644 --- a/src/dist_transfer.cpp +++ b/src/dist_transfer.cpp @@ -30,6 +30,7 @@ namespace carbon::dist_transfer_detail { namespace { +#ifndef CARBON_DIST_HOST_MPI [[noreturn]] auto throw_nccl_error(const char* where, ncclResult_t res) -> void { @@ -44,6 +45,7 @@ check_nccl(const char* where, throw_nccl_error(where, res); } } +#endif // !CARBON_DIST_HOST_MPI [[noreturn]] auto throw_mpi_error(const char* where, @@ -67,16 +69,22 @@ check_mpi(const char* where, [[nodiscard]] auto dist_transport_is_mpi() noexcept -> bool { +#ifdef CARBON_DIST_HOST_MPI + return true; // the only transport in a host-MPI build +#else static const bool is_mpi = [] { const char* value = std::getenv("CARBON_DIST_TRANSPORT"); return value != nullptr && std::strcmp(value, "mpi") == 0; }(); return is_mpi; +#endif } [[nodiscard]] auto mpi_cuda_aware() noexcept -> bool { -#if defined(OMPI_MAJOR_VERSION) +#if defined(CARBON_DIST_HOST_MPI) + return true; // "device" buffers are plain host memory: MPI can use them directly, no staging +#elif defined(OMPI_MAJOR_VERSION) static const bool aware = MPIX_Query_cuda_support() != 0; return aware; #else @@ -231,6 +239,7 @@ run(const System& system, run_mpi_device(system, local_buffer, peer_ranks, ops, first_bytes, byte_counts, stream); return; } +#ifndef CARBON_DIST_HOST_MPI ncclComm_t nccl_comm = detail::communicator_handle(*comm_ptr); auto* base = static_cast(local_buffer); @@ -291,6 +300,7 @@ run(const System& system, // underlying vendor stream. q.wait_and_throw(); #endif +#endif // !CARBON_DIST_HOST_MPI } auto diff --git a/src/gpu_runtime_compat.h b/src/gpu_runtime_compat.h index c44018ba..39940ce0 100644 --- a/src/gpu_runtime_compat.h +++ b/src/gpu_runtime_compat.h @@ -14,7 +14,12 @@ #include -#ifdef CARBON_USE_RCCL +#ifdef CARBON_DIST_HOST_MPI +// Host-MPI build (CARBON_BACKEND=Sycl, omp-only target): no vendor runtime, no NCCL/RCCL. +// "Device" memory is ordinary host RAM and the single compute device is the OpenMP host. +#include +#include +#elif defined(CARBON_USE_RCCL) #include #include #else @@ -24,7 +29,40 @@ namespace carbon::detail::gpu_compat { -#ifdef CARBON_USE_RCCL +#ifdef CARBON_DIST_HOST_MPI +using gpu_stream_t = void*; +using gpu_error_t = int; +inline constexpr gpu_error_t gpu_success = 0; + +inline auto +gpu_get_device(int* dev) noexcept -> gpu_error_t { + *dev = 0; + return gpu_success; +} +inline auto +gpu_set_device(int /*dev*/) noexcept -> gpu_error_t { + return gpu_success; +} +inline auto +gpu_get_device_count(int* n) noexcept -> gpu_error_t { + *n = 1; + return gpu_success; +} +inline auto +gpu_get_error_string(gpu_error_t /*e*/) noexcept -> const char* { + return "host-mpi (no vendor runtime)"; +} +inline auto +gpu_memcpy(void* dst, + const void* src, + size_t count, + int /*kind*/) noexcept -> gpu_error_t { + std::memcpy(dst, src, count); + return gpu_success; +} +inline constexpr int gpu_memcpy_host_to_device = 0; +inline constexpr int gpu_memcpy_device_to_host = 1; +#elif defined(CARBON_USE_RCCL) using gpu_stream_t = hipStream_t; using gpu_error_t = hipError_t; inline constexpr gpu_error_t gpu_success = hipSuccess; diff --git a/src/gpu_sycl.cpp b/src/gpu_sycl.cpp index aad100ce..bb99d682 100644 --- a/src/gpu_sycl.cpp +++ b/src/gpu_sycl.cpp @@ -13,6 +13,8 @@ #include +#include "sycl_device_filter.h" + #include #include @@ -45,7 +47,7 @@ all_sycl_devices() -> const std::vector& { for (const auto& dev : platform.get_devices(sycl::info::device_type::all)) { // Skip the host CPU device exposed by SYCL — carbon's "device" concept is the // GPU/accelerator side; the host is reached via Cpu::buffer instead. - if (!dev.is_cpu()) { + if (is_compute_device(dev)) { out.push_back(dev); } } diff --git a/src/sycl_device_filter.h b/src/sycl_device_filter.h new file mode 100644 index 00000000..e1415dce --- /dev/null +++ b/src/sycl_device_filter.h @@ -0,0 +1,26 @@ +#pragma once + +// Single place that decides which sycl::device objects carbon treats as "compute devices". +// +// Default (GPU/accelerator builds): CPU devices are skipped -- carbon's "device" is the +// accelerator side and the host is reached through Cpu::buffer. +// +// CARBON_SYCL_CPU_DEVICE=1 (set by CMake for `-DCARBON_SYCL_TARGETS=omp`): the AdaptiveCpp +// OpenMP host device IS the compute device. AdaptiveCpp reports it with is_cpu() == true, so +// without this switch device_count() is 0 and every grid constructor throws. + +#include + +namespace carbon::detail { + +[[nodiscard]] inline auto +is_compute_device(const sycl::device& dev) -> bool { +#ifdef CARBON_SYCL_CPU_DEVICE + (void)dev; + return true; +#else + return !dev.is_cpu(); +#endif +} + +} // namespace carbon::detail diff --git a/src/sycl_stub.cpp b/src/sycl_stub.cpp index 9d2da52e..0a9acd5e 100644 --- a/src/sycl_stub.cpp +++ b/src/sycl_stub.cpp @@ -15,6 +15,8 @@ #include +#include "sycl_device_filter.h" + #include #include @@ -29,7 +31,7 @@ auto first_gpu_or_default() -> sycl::device { for (const auto& platform : sycl::platform::get_platforms()) { for (const auto& dev : platform.get_devices(sycl::info::device_type::all)) { - if (!dev.is_cpu()) { + if (carbon::detail::is_compute_device(dev)) { return dev; } } @@ -84,7 +86,7 @@ carbon_cuda_runtime_linked(void) { int n = 0; for (const auto& platform : sycl::platform::get_platforms()) { for (const auto& d : platform.get_devices(sycl::info::device_type::all)) { - if (!d.is_cpu()) { + if (carbon::detail::is_compute_device(d)) { ++n; } } @@ -110,7 +112,7 @@ carbon_launch_smoke_kernel(int device_id) { bool found = false; for (const auto& platform : sycl::platform::get_platforms()) { for (const auto& d : platform.get_devices(sycl::info::device_type::all)) { - if (d.is_cpu()) { + if (!carbon::detail::is_compute_device(d)) { continue; } if (idx == device_id) { diff --git a/tests/test_atomic_host.cpp b/tests/test_atomic_host.cpp index 42a0a96f..692cd90e 100644 --- a/tests/test_atomic_host.cpp +++ b/tests/test_atomic_host.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include #include @@ -25,7 +26,9 @@ * * Counts are chosen so the running float sum stays integral and exactly representable * (8 threads x 4096 increments of 1.0f peaks at 32768, well inside the 2^24 exact-integer - * range of binary32), so a mismatch means a lost update rather than rounding. + * range of binary32), so a mismatch means a lost update rather than rounding. The + * CUDA/HIP-only double and int64_t cases cover the overloads used by + * @c ReduceFinalize::BlockAtomic. */ namespace { @@ -61,6 +64,61 @@ test_atomic_add_loses_nothing() { } } +#if CARBON_BACKEND_IS_CUDALIKE +void +test_atomic_add_double_loses_nothing() { + double counter = 0.0; + + std::vector workers; + workers.reserve(kThreads); + for (int t = 0; t < kThreads; ++t) { + workers.emplace_back([&counter] { + for (int i = 0; i < kIterations; ++i) { + (void)carbon::detail::atomic_add(&counter, 1.0); + } + }); + } + for (std::thread& w : workers) { + w.join(); + } + + const double expected = static_cast(kThreads) * static_cast(kIterations); + if (counter != expected) { + std::fprintf(stderr, + "test_atomic_host: double atomic_add lost updates: got %.1f, expected %.1f\n", + counter, expected); + assert(false && "detail::atomic_add(double) host branch is not atomic"); + } +} + +void +test_atomic_add_int64_loses_nothing() { + std::int64_t counter = 0; + + std::vector workers; + workers.reserve(kThreads); + for (int t = 0; t < kThreads; ++t) { + workers.emplace_back([&counter] { + for (int i = 0; i < kIterations; ++i) { + (void)carbon::detail::atomic_add(&counter, std::int64_t{1}); + } + }); + } + for (std::thread& w : workers) { + w.join(); + } + + const std::int64_t expected = + static_cast(kThreads) * static_cast(kIterations); + if (counter != expected) { + std::fprintf(stderr, + "test_atomic_host: int64_t atomic_add lost updates: got %lld, expected %lld\n", + static_cast(counter), static_cast(expected)); + assert(false && "detail::atomic_add(int64_t) host branch is not atomic"); + } +} +#endif + void test_atomic_min_reaches_true_minimum() { // Each thread walks a descending sequence offset by its id, so the threads interleave and @@ -95,6 +153,10 @@ test_atomic_min_reaches_true_minimum() { int main() { test_atomic_add_loses_nothing(); +#if CARBON_BACKEND_IS_CUDALIKE + test_atomic_add_double_loses_nothing(); + test_atomic_add_int64_loses_nothing(); +#endif test_atomic_min_reaches_true_minimum(); std::printf("test_atomic_host: OK (%d threads x %d iterations per helper)\n", kThreads, kIterations); diff --git a/tests/test_dense_distributed_dist.cu b/tests/test_dense_distributed_dist.cu index a98a791a..1462f500 100644 --- a/tests/test_dense_distributed_dist.cu +++ b/tests/test_dense_distributed_dist.cu @@ -47,6 +47,8 @@ #include #include #include +#include +#include #include #include #include @@ -699,6 +701,97 @@ run_vtk(carbon::System& sys, return ok; } +// ------------------------------------------------------------------------------------------------ +// Check 4: opt-in 2-D stage-1 reduce over flattened (y, z). +// ------------------------------------------------------------------------------------------------ + +[[nodiscard]] auto +run_reduce_2d(carbon::System& sys, + int rank, + const ProcessGrid& pg, + BoundaryModeDistributed mode, + const char* label, + const int64_3d& global) -> bool { + try { + DenseDistributed grid(sys, global, pg, six_point(), mode); + auto field = grid.template newField(carbon::MemorySide::HostDevice); + field.fill_owned_host([](carbon::int64_3d g, int /*c*/) { + return static_cast(encode(g.x, g.y, g.z)); + }); + + carbon::Stream stream = sys.stream(); + carbon::Transfer(sys, field.cpu_buffers(), field.gpu_buffers())(stream); + stream.wait(); + + carbon::reduce::ReduceOptions opts{}; + opts.stage1_threads = 32U; + opts.stage1_threads_y = 32U; + + const auto loader = [&field](carbon::KernelLoader& kl) { + const auto in = kl.read(field); + return [in] CARBON_HOST_DEVICE(DenseDistributed::Span s, + DenseDistributed::Idx idx) -> int64_t { + return in.read(s, idx, 0); + }; + }; + + int64_t want = 0; + for (int64_t z = 0; z < global.z; ++z) { + for (int64_t y = 0; y < global.y; ++y) { + for (int64_t x = 0; x < global.x; ++x) { + want += static_cast(encode(x, y, z)); + } + } + } + + carbon::ReductionResult standard_result(sys); + auto standard_reducer = grid.template make_reduce_kernel( + loader, standard_result, carbon::reduce::Sum{}, /*shared_mem=*/0U, opts); + standard_reducer.launch(stream, carbon::DataView::Standard); + standard_result.sync(stream); + const int64_t standard = standard_result.host_value(carbon::DataView::Standard); + if (standard != want) { + CARBON_LOG_ERROR( + "test_dense_distributed_dist[{}]: rank {} 2D Standard mismatch: got {}, expected {}", + label, rank, standard, want); + return false; + } + + carbon::ReductionResult split_result(sys); + auto split_reducer = grid.template make_reduce_kernel( + loader, split_result, carbon::reduce::Sum{}, /*shared_mem=*/0U, opts); + split_reducer.launch(stream, carbon::DataView::Internal); + split_reducer.launch(stream, carbon::DataView::Boundary); + split_result.sync(stream); + + const int64_t internal = split_result.host_value(carbon::DataView::Internal); + const int64_t boundary = split_result.host_value(carbon::DataView::Boundary); + if (internal + boundary != standard) { + CARBON_LOG_ERROR( + "test_dense_distributed_dist[{}]: rank {} 2D Internal({}) + Boundary({}) = {} != " + "Standard({})", + label, rank, internal, boundary, internal + boundary, standard); + return false; + } + const int64_t combined = split_result.host_value_combined(carbon::reduce::Sum{}); + if (combined != standard) { + CARBON_LOG_ERROR( + "test_dense_distributed_dist[{}]: rank {} 2D host_value_combined({}) != Standard({})", + label, rank, combined, standard); + return false; + } + CARBON_LOG_INFO( + "test_dense_distributed_dist[{}]: rank {} 2D stage-1 Standard={} = Internal({}) + " + "Boundary({})", + label, rank, standard, internal, boundary); + return true; + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: rank {} 2D reduce failed: {}", label, rank, + e.what()); + return false; + } +} + struct Case { ProcessGrid pg; BoundaryModeDistributed mode; @@ -772,6 +865,7 @@ main() { std::string(c.label) + "/stencil", global) || !run_stencil(sys, rank, c.pg, c.mode, carbon::OverlapMode::Standard, std::string(c.label) + "/stencil-overlap", global) || + !run_reduce_2d(sys, rank, c.pg, c.mode, c.label, global) || !run_vtk(sys, rank, world, c.pg, c.mode, c.label, global)) { return 1; } diff --git a/tests/test_dense_distributed_host.cpp b/tests/test_dense_distributed_host.cpp index 60cd2183..794fb969 100644 --- a/tests/test_dense_distributed_host.cpp +++ b/tests/test_dense_distributed_host.cpp @@ -743,7 +743,8 @@ check_geometry(const GeomCase& c, {ch.owned.x + 2 * halo.x, ch.owned.y + 2 * halo.y, ch.owned.z + 2 * halo.z})); CHECK(ch.xy_pitch == ch.haloed.x * ch.haloed.y); - const dd::Span span(ch.haloed, global, ch.xy_pitch, ch.offset, ch.halo, bm); + const dd::Span span(ch.haloed, global, ch.xy_pitch, ch.offset, ch.halo, bm, + /*legacy_slab=*/legacy_slab); CHECK(eq3(span.logic_extent(), ch.owned)); CHECK(eq3(span.haloed_extent(), ch.haloed)); CHECK(eq3(span.halo(), halo)); @@ -776,6 +777,9 @@ check_geometry(const GeomCase& c, std::vector mark(static_cast(ch.owned.x * ch.owned.y * ch.owned.z), 0); for (const carbon::DataView view : {carbon::DataView::Internal, carbon::DataView::Boundary}) { const int64_3d e = span.iter_extent(view); + if (view == carbon::DataView::Boundary && legacy_slab) { + CHECK(e.z == 2 * halo.z); + } if (view == carbon::DataView::Boundary && !legacy_slab) { // Compact shell: the launch box holds the shell cells plus less than one 128-wide row // of padding (a full-owned-extent launch would fail this by a wide margin), and the @@ -881,6 +885,7 @@ part_b_geometry(size_t& cells, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}; const std::vector r2 = {{2, 0, 0}, {-2, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 2}, {0, 0, -2}}; + const std::vector zonly = {{0, 0, 1}, {0, 0, -1}}; std::vector d3q19; for (int z = -1; z <= 1; ++z) { for (int y = -1; y <= 1; ++y) { @@ -912,6 +917,12 @@ part_b_geometry(size_t& cells, {"brick/221-aniso", 2, 2, 1, kO, 8, 6, 5, aniso, {2, 1, 0}}, {"brick/221-aniso-periodicZ", 2, 2, 1, kZ, 8, 6, 5, aniso, {2, 1, 1}}, {"brick/212-d3q19-periodicXZ", 2, 1, 2, kX | kZ, 6, 5, 6, d3q19, {1, 0, 1}}, + // Non-legacy z-only stencils: halo.x == halo.y == 0, but the layout is not a legacy slab. + // The Boundary view must use the compact shell path; with owned.z == 1 the two-band path + // would visit the same cell twice. + {"pencil/zonly-thin", 1, 2, 2, kO, 4, 4, 2, zonly, {0, 0, 1}}, + {"brick/zonly-thin", 2, 2, 2, kO, 4, 4, 2, zonly, {0, 0, 1}}, + {"slab/zonly-thin-periodicX", 1, 1, 1, kX, 4, 4, 1, zonly, {0, 0, 1}}, }; for (const GeomCase& c : cases) { check_geometry(c, cells, neighbour_reads); @@ -919,6 +930,67 @@ part_b_geometry(size_t& cells, return cases.size(); } +auto +part_b_global_validation() -> size_t { + g_ctx = "part B global validation"; + const carbon::Stencil stencil(six(), /*remove_center=*/true); + const auto throws_invalid_argument = [](auto&& fn) -> bool { + try { + fn(); + } catch (const std::invalid_argument&) { + return true; + } catch (...) { + return false; + } + return false; + }; + + size_t cases = 0; + { + // z = 7 over 4 slabs -> [2,2,2,1]; the last rank is too thin for halo_z = 1. Every rank + // must reject the global decomposition, not just the rank that owns the thin chunk. + const ProcessGrid pg = ProcessGrid::custom(4, 1, 1, 4); + const int64_3d global{9, 8, 7}; + const int64_3d halo = dd::halo_extent(pg, BoundaryModeDistributed::Open, stencil); + CHECK(dd::is_legacy_slab(pg, BoundaryModeDistributed::Open)); + CHECK(throws_invalid_argument([&] { + dd::validate_global_halo_fit(global, pg, halo, /*legacy_slab=*/true, stencil); + })); + ++cases; + } + { + // x = 1 over 2 bricks -> [1,0]; a zero-owned chunk cannot host the X halo. Again the + // decision is global, so ranks with a non-thin chunk throw as well. + const ProcessGrid pg = ProcessGrid::custom(8, 2, 2, 2); + const int64_3d global{1, 5, 7}; + const int64_3d halo = dd::halo_extent(pg, BoundaryModeDistributed::Open, stencil); + CHECK(!dd::is_legacy_slab(pg, BoundaryModeDistributed::Open)); + CHECK(throws_invalid_argument([&] { + dd::validate_global_halo_fit(global, pg, halo, /*legacy_slab=*/false, stencil); + })); + ++cases; + } + { + const ProcessGrid pg = ProcessGrid::custom(4, 1, 1, 4); + const int64_3d global{9, 8, 11}; + const int64_3d halo = dd::halo_extent(pg, BoundaryModeDistributed::Open, stencil); + CHECK(!throws_invalid_argument([&] { + dd::validate_global_halo_fit(global, pg, halo, /*legacy_slab=*/true, stencil); + })); + ++cases; + } + { + const ProcessGrid pg = ProcessGrid::custom(8, 2, 2, 2); + const int64_3d global{9, 8, 11}; + const int64_3d halo = dd::halo_extent(pg, BoundaryModeDistributed::Open, stencil); + CHECK(!throws_invalid_argument([&] { + dd::validate_global_halo_fit(global, pg, halo, /*legacy_slab=*/false, stencil); + })); + ++cases; + } + return cases; +} + // ------------------------------------------------------------------------------------------------ // Part D: VTK shard I/O for DenseDistributed. // ------------------------------------------------------------------------------------------------ @@ -1268,8 +1340,10 @@ main() { size_t geom_cells = 0; size_t geom_neighbours = 0; const size_t geom_cases = part_b_geometry(geom_cells, geom_neighbours); - std::printf("geometry cases=%zu owned cells checked=%zu neighbour reads checked=%zu\n", - geom_cases, geom_cells, geom_neighbours); + const size_t validation_cases = part_b_global_validation(); + std::printf("geometry cases=%zu owned cells checked=%zu neighbour reads checked=%zu " + "global-validation cases=%zu\n", + geom_cases, geom_cells, geom_neighbours, validation_cases); size_t vtk_shards = 0; size_t vtk_empty = 0; diff --git a/tests/test_reduce_atomic.cu b/tests/test_reduce_atomic.cu index 8a4fb4d1..6803ceb9 100644 --- a/tests/test_reduce_atomic.cu +++ b/tests/test_reduce_atomic.cu @@ -1,4 +1,4 @@ -// ReduceFinalize::BlockAtomic vs default DeviceReduce on Dense sum reductions. +// ReduceFinalize::BlockAtomic vs default DeviceReduce on Dense float/int64/double sums. #include #include @@ -43,6 +43,28 @@ host_reference_sum(int64_t W, return s; } +[[nodiscard]] CARBON_HD auto +encode_double(int64_t x, + int64_t y, + int64_t z) -> double { + return 0.5 * static_cast(encode(x, y, z)) + 0.25; +} + +[[nodiscard]] auto +host_reference_sum_double(int64_t W, + int64_t H, + int64_t D) -> double { + double s = 0.0; + for (int64_t z = 0; z < D; ++z) { + for (int64_t y = 0; y < H; ++y) { + for (int64_t x = 0; x < W; ++x) { + s += encode_double(x, y, z); + } + } + } + return s; +} + } // namespace int @@ -156,6 +178,75 @@ main() { return EXIT_FAILURE; } + // Double: exercise the HIP __HIP_DEVICE_COMPILE__ atomic path as well as CUDA's sm_60+ + // native double atomicAdd. Compare against the default DeviceReduce path and the host sum. + auto d_field = dense.newField(carbon::MemorySide::HostDevice, "df"); + d_field.fill_owned_host([](carbon::int64_3d g, int) { + return encode_double(g.x, g.y, g.z); + }); + try { + carbon::Transfer(sys, d_field.cpu_buffers(), d_field.gpu_buffers())(upload); + upload.wait(); + } catch (const std::exception& ex) { + CARBON_LOG_ERROR("test_reduce_atomic: double upload failed: {}", ex.what()); + return EXIT_FAILURE; + } + + carbon::ReductionResult d_dev(sys); + carbon::ReductionResult d_atomic(sys); + auto d_loader = [&d_field](carbon::KernelLoader& kl) { + const auto in = kl.read(d_field); + return [in] CARBON_HOST_DEVICE(carbon::Dense::Span s, carbon::Dense::Idx idx) -> double { + return in.read(s, idx, 0); + }; + }; + auto d_dev_k = dense.make_reduce_kernel(d_loader, d_dev); + auto d_atomic_k = dense.make_reduce_kernel( + d_loader, d_atomic, carbon::reduce::Sum{}, 0U, atomic_opts); + try { + d_dev_k.launch(st); + d_dev.sync(st); + d_atomic_k.launch(st); + d_atomic.sync(st); + st.wait(); + } catch (const std::exception& ex) { + CARBON_LOG_ERROR("test_reduce_atomic: double launch failed: {}", ex.what()); + return EXIT_FAILURE; + } + const double expected_double = host_reference_sum_double(kWidth, kHeight, kDepth); + const double rel_dev = std::fabs(d_dev.host_value() - expected_double) / + std::fmax(1.0, std::fabs(expected_double)); + const double rel_atomic = std::fabs(d_atomic.host_value() - expected_double) / + std::fmax(1.0, std::fabs(expected_double)); + if (rel_dev > 1.0e-9 || rel_atomic > 1.0e-9) { + CARBON_LOG_ERROR("test_reduce_atomic: double mismatch dev={} atomic={} expected={} " + "(rel dev={}, atomic={})", + d_dev.host_value(), d_atomic.host_value(), expected_double, rel_dev, + rel_atomic); + return EXIT_FAILURE; + } + + // 2-D stage-1 BlockAtomic: flattening (y, z) must cover every cell, not just y == 0. + carbon::reduce::ReduceOptions atomic_2d_opts = atomic_opts; + atomic_2d_opts.stage1_threads = 32U; + atomic_2d_opts.stage1_threads_y = 32U; + carbon::ReductionResult atomic_2d_result(sys); + auto atomic_2d_kernel = dense.make_reduce_kernel( + loader, atomic_2d_result, carbon::reduce::Sum{}, /*shared_mem=*/0U, atomic_2d_opts); + try { + atomic_2d_kernel.launch(st); + atomic_2d_result.sync(st); + st.wait(); + } catch (const std::exception& ex) { + CARBON_LOG_ERROR("test_reduce_atomic: 2D atomic launch failed: {}", ex.what()); + return EXIT_FAILURE; + } + if (atomic_2d_result.host_value() != expected) { + CARBON_LOG_ERROR("test_reduce_atomic: 2D atomic path got {} expected {}", + atomic_2d_result.host_value(), expected); + return EXIT_FAILURE; + } + // Invalid: Min + BlockAtomic throws at construction. carbon::ReductionResult bad_dst(sys); bool threw = false; diff --git a/tests/test_reduce_sum.cu b/tests/test_reduce_sum.cu index 02d9a63d..263487df 100644 --- a/tests/test_reduce_sum.cu +++ b/tests/test_reduce_sum.cu @@ -376,6 +376,91 @@ main() { standard, internal, boundary, combined); } + // ---- Case 6: 2-D stage-1 covers y > 1 ---- + // The opt-in stage1_threads_y path uses a 2-D block over x and flattened (y, z). + // This geometry has kHeight == 32 and a non-empty z halo, so a regression to the old + // "only y == 0" mapping would fail both the Standard reference and the Internal + + // Boundary recombine. + { + carbon::Stencil stencil_radius1( + std::vector{ + {1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}, + /*remove_center=*/true); + carbon::Dense halo_dense(sys, global, stencil_radius1); + auto field = halo_dense.newField(carbon::MemorySide::HostDevice); + field.fill_owned_host([](carbon::int64_3d gc, int /*c*/) { + return encode(gc.x, gc.y, gc.z); + }); + + carbon::Stream stream = sys.stream(); + try { + carbon::Transfer(sys, field.cpu_buffers(), field.gpu_buffers())(stream); + stream.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_reduce_sum: 2D upload failed: {}", e.what()); + return EXIT_FAILURE; + } + + carbon::reduce::ReduceOptions opts{}; + opts.stage1_threads = 32U; + opts.stage1_threads_y = 32U; + + const auto loader = [&field](carbon::KernelLoader& kl) { + const auto in = kl.read(field); + return [in] CARBON_HOST_DEVICE(carbon::Dense::Span s, carbon::Dense::Idx idx) -> int64_t { + return in.read(s, idx, 0); + }; + }; + + carbon::ReductionResult standard_result(sys); + auto standard_reducer = halo_dense.make_reduce_kernel( + loader, standard_result, carbon::reduce::Sum{}, /*shared_mem=*/0U, opts); + try { + standard_reducer.launch(stream, carbon::DataView::Standard); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_reduce_sum: 2D Standard launch failed: {}", e.what()); + return EXIT_FAILURE; + } + standard_result.sync(stream); + + const int64_t standard = standard_result.host_value(carbon::DataView::Standard); + const int64_t want = host_reference_sum(kWidth, kHeight, kDepth); + if (standard != want) { + CARBON_LOG_ERROR("test_reduce_sum: 2D Standard mismatch: got {}, expected {}", standard, + want); + return EXIT_FAILURE; + } + + carbon::ReductionResult split_result(sys); + auto split_reducer = halo_dense.make_reduce_kernel( + loader, split_result, carbon::reduce::Sum{}, /*shared_mem=*/0U, opts); + try { + split_reducer.launch(stream, carbon::DataView::Internal); + split_reducer.launch(stream, carbon::DataView::Boundary); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_reduce_sum: 2D split launch failed: {}", e.what()); + return EXIT_FAILURE; + } + split_result.sync(stream); + + const int64_t internal = split_result.host_value(carbon::DataView::Internal); + const int64_t boundary = split_result.host_value(carbon::DataView::Boundary); + if (internal + boundary != standard) { + CARBON_LOG_ERROR("test_reduce_sum: 2D Internal({}) + Boundary({}) = {} != Standard({})", + internal, boundary, internal + boundary, standard); + return EXIT_FAILURE; + } + const int64_t combined = split_result.host_value_combined(carbon::reduce::Sum{}); + if (combined != standard) { + CARBON_LOG_ERROR("test_reduce_sum: 2D host_value_combined({}) != Standard({})", combined, + standard); + return EXIT_FAILURE; + } + CARBON_LOG_INFO( + "test_reduce_sum: 2D stage-1 Standard={} = Internal({}) + Boundary({}) (combined={})", + standard, internal, boundary, combined); + } + CARBON_LOG_INFO("test_reduce_sum: PASS"); return EXIT_SUCCESS; } diff --git a/tests/test_skeleton_reduce_split.cu b/tests/test_skeleton_reduce_split.cu index 802269b0..2a9b0ba6 100644 --- a/tests/test_skeleton_reduce_split.cu +++ b/tests/test_skeleton_reduce_split.cu @@ -147,9 +147,9 @@ main() { carbon::ReductionResult sum_ref(sys); carbon::Kernel whole = build_stencil_sum_kernel(dense, u, sum_ref, "sum_whole"); - whole.launch(sys.stream(), carbon::DataView::Standard); - sys.stream().wait(); - sum_ref.sync(sys.stream()); + whole.launch(s_up, carbon::DataView::Standard); + s_up.wait(); + sum_ref.sync(s_up); const float ref_val = sum_ref.host_value(); bool ok = true; @@ -165,7 +165,7 @@ main() { sk.compile(); sk.run(); sk.wait(); - sum.sync(sys.stream()); + sum.sync(s_up); if (!matches(sum.host_value(), ref_val)) { CARBON_LOG_ERROR("test_skeleton_reduce_split[{}]: split {} != ref {}", mode_name(mode), sum.host_value(), ref_val); @@ -181,7 +181,7 @@ main() { sk.compile(); sk.run(); sk.wait(); - sum.sync(sys.stream()); + sum.sync(s_up); if (!matches(sum.host_value(), 2.0F * ref_val)) { CARBON_LOG_ERROR("test_skeleton_reduce_split[{} + producer]: split {} != ref {}", mode_name(mode), sum.host_value(), 2.0F * ref_val); @@ -200,7 +200,7 @@ main() { sk_none.compile(); sk_none.run(); sk_none.wait(); - sum_none.sync(sys.stream()); + sum_none.sync(s_up); const float none_val = sum_none.host_value(); carbon::ReductionResult sum_ext(sys); @@ -212,7 +212,7 @@ main() { const std::string order_ext = sk_ext.export_launch_order(); sk_ext.run(); sk_ext.wait(); - sum_ext.sync(sys.stream()); + sum_ext.sync(s_up); if (!matches(sum_ext.host_value(), none_val)) { CARBON_LOG_ERROR("test_skeleton_reduce_split[Extended trailing Map reduce]: {} != None {}", sum_ext.host_value(), none_val); @@ -236,7 +236,7 @@ main() { const std::string order_tw = sk_tw.export_launch_order(); sk_tw.run(); sk_tw.wait(); - sum_tw.sync(sys.stream()); + sum_tw.sync(s_up); if (!matches(sum_tw.host_value(), none_val)) { CARBON_LOG_ERROR( "test_skeleton_reduce_split[TwoWayExtended trailing Map reduce]: {} != None {}",