From a51265a115c24abe76e5ae16517947a117a877d9 Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Mon, 2 Nov 2026 18:23:00 +0100 Subject: [PATCH 01/33] Add dense_distributed class enabling slab, pencil and brick domain decomposition --- CMakeLists.txt | 8 +- include/carbon/boundary_mode_distributed.h | 72 ++ include/carbon/carbon.h | 5 + include/carbon/dense_distributed.h | 600 +++++++++ .../cudalike/dense_distributed_kernel.h | 74 ++ .../cudalike/dense_distributed_launch.h | 124 ++ .../dense_distributed_reduce_kernel.h | 244 ++++ .../dense_distributed_reduce_launch.h | 217 ++++ .../backend/sycl/dense_distributed_kernel.h | 30 + .../backend/sycl/dense_distributed_launch.h | 109 ++ .../sycl/dense_distributed_reduce_kernel.h | 138 ++ .../dense_distributed/dense_distributed.inl | 89 ++ .../carbon/detail/dense_distributed/field.h | 513 ++++++++ .../carbon/detail/dense_distributed/kernel.h | 18 + .../carbon/detail/dense_distributed/launch.h | 17 + .../carbon/detail/dense_distributed/layout.h | 130 ++ .../detail/dense_distributed/partition.h | 302 +++++ .../detail/dense_distributed/reduce_kernel.h | 16 + .../carbon/detail/dense_distributed/span.h | 474 +++++++ .../carbon/detail/halo_distributed_build.h | 247 ++++ .../detail/halo_distributed_kernel_impl.h | 41 + include/carbon/detail/halo_pack.h | 81 ++ include/carbon/detail/halo_pack_plan.h | 517 ++++++++ .../detail/kernel_dense_distributed.inl | 95 ++ include/carbon/detail/launch_traits.h | 46 + include/carbon/halo_distributed.h | 1131 +++++++++++++++++ include/carbon/kernel.h | 27 + include/carbon/process_grid.h | 130 ++ include/carbon/stencil.h | 11 + src/dense_distributed.cpp | 393 ++++++ src/halo_pack.cu | 114 ++ src/process_grid.cpp | 168 +++ src/stencil.cpp | 19 + 33 files changed, 6199 insertions(+), 1 deletion(-) create mode 100644 include/carbon/boundary_mode_distributed.h create mode 100644 include/carbon/dense_distributed.h create mode 100644 include/carbon/detail/backend/cudalike/dense_distributed_kernel.h create mode 100644 include/carbon/detail/backend/cudalike/dense_distributed_launch.h create mode 100644 include/carbon/detail/backend/cudalike/dense_distributed_reduce_kernel.h create mode 100644 include/carbon/detail/backend/cudalike/dense_distributed_reduce_launch.h create mode 100644 include/carbon/detail/backend/sycl/dense_distributed_kernel.h create mode 100644 include/carbon/detail/backend/sycl/dense_distributed_launch.h create mode 100644 include/carbon/detail/backend/sycl/dense_distributed_reduce_kernel.h create mode 100644 include/carbon/detail/dense_distributed/dense_distributed.inl create mode 100644 include/carbon/detail/dense_distributed/field.h create mode 100644 include/carbon/detail/dense_distributed/kernel.h create mode 100644 include/carbon/detail/dense_distributed/launch.h create mode 100644 include/carbon/detail/dense_distributed/layout.h create mode 100644 include/carbon/detail/dense_distributed/partition.h create mode 100644 include/carbon/detail/dense_distributed/reduce_kernel.h create mode 100644 include/carbon/detail/dense_distributed/span.h create mode 100644 include/carbon/detail/halo_distributed_build.h create mode 100644 include/carbon/detail/halo_distributed_kernel_impl.h create mode 100644 include/carbon/detail/halo_pack.h create mode 100644 include/carbon/detail/halo_pack_plan.h create mode 100644 include/carbon/detail/kernel_dense_distributed.inl create mode 100644 include/carbon/halo_distributed.h create mode 100644 include/carbon/process_grid.h create mode 100644 src/dense_distributed.cpp create mode 100644 src/halo_pack.cu create mode 100644 src/process_grid.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index f14dd70e..00d478dc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -280,6 +280,7 @@ add_library(carbon SHARED src/data_view.cpp src/dense.cpp src/dense_disg.cpp + src/dense_distributed.cpp src/dense_launch_shape.cpp src/dist_reduce.cpp src/dist_render.cpp @@ -287,6 +288,7 @@ add_library(carbon SHARED src/io_vtk.cpp src/logging.cpp src/memory_side.cpp + src/process_grid.cpp src/report.cpp src/skeleton.cpp src/stencil.cpp @@ -297,6 +299,7 @@ target_link_libraries(carbon PUBLIC spdlog::spdlog rapidjson OpenMP::OpenMP_CXX) if(CARBON_BACKEND STREQUAL "Cuda") target_sources(carbon PRIVATE src/cuda_stub.cu + src/halo_pack.cu src/gpu.cpp) target_link_libraries(carbon PUBLIC CUDA::cudart) target_compile_definitions(carbon PUBLIC CARBON_HAVE_NVTX=1) @@ -320,11 +323,12 @@ if(CARBON_BACKEND STREQUAL "Cuda") elseif(CARBON_BACKEND STREQUAL "Hip") target_sources(carbon PRIVATE src/hip_stub.cu + src/halo_pack.cu src/gpu_hip.cpp) # The .cu stub is HIP device code; tell CMake to feed it to the HIP compiler (the .cu # suffix would otherwise be treated as CUDA). The .cpp host source stays on the C++ # compiler. Consumer .cu TUs do the same via set_source_files_properties in tests/. - set_source_files_properties(src/hip_stub.cu PROPERTIES LANGUAGE HIP) + set_source_files_properties(src/hip_stub.cu src/halo_pack.cu PROPERTIES LANGUAGE HIP) if(CARBON_HIP_NVCC) # HIP-on-NVIDIA (nvcc backs the HIP language). The HIP runtime is a thin shim over # CUDA, so host .cpp TUs that include pull in and @@ -394,11 +398,13 @@ elseif(CARBON_BACKEND STREQUAL "Sycl") src/data_view.cpp src/dense.cpp src/dense_disg.cpp + src/dense_distributed.cpp src/dist_reduce.cpp src/io.cpp src/io_vtk.cpp src/logging.cpp src/memory_side.cpp + src/process_grid.cpp src/report.cpp src/skeleton.cpp src/stencil.cpp diff --git a/include/carbon/boundary_mode_distributed.h b/include/carbon/boundary_mode_distributed.h new file mode 100644 index 00000000..55122419 --- /dev/null +++ b/include/carbon/boundary_mode_distributed.h @@ -0,0 +1,72 @@ +#pragma once + +#include +#include + +#include + +namespace carbon { + +/** + * Per-axis boundary semantics of a @ref DenseDistributed grid (propagated into every per-rank + * @c Span). + * + * The enumerators are independent bits, so axes can mix open and periodic boundaries: + * @c PeriodicX | @c PeriodicZ wraps X and Z while leaving Y open. + * + * Drives two pieces of behaviour: + * - @c Partition::neighbour : an out-of-domain read on an open axis returns @c valid = false; on a + * periodic axis the read wraps to the opposite face. + * - Halo exchange (@ref HaloDistributed): schedules the wrap pair on every periodic axis and omits + * it on an open axis. + * + * @note This is deliberately a different type from @ref BoundaryMode, which belongs to the + * Z-slab-only @ref Dense / @ref DenseDisg families and keeps its original numeric values + * (@c PeriodicZ == 1). Keeping the two apart means a per-axis mask can never be handed to a grid + * that only understands a Z wrap. + */ +enum class BoundaryModeDistributed : std::uint8_t { + /** Non-toroidal grid (default): every axis is open. */ + Open = 0, + + /** Wrap the X axis. */ + PeriodicX = 1U << 0, + + /** Wrap the Y axis. */ + PeriodicY = 1U << 1, + + /** Wrap the Z axis. */ + PeriodicZ = 1U << 2, +}; + +/** True when @p mode wraps @p axis. */ +[[nodiscard]] constexpr CARBON_HD auto +is_periodic(BoundaryModeDistributed mode, + Axis axis) noexcept -> bool { + const auto bits = static_cast(mode); + switch (axis) { + case Axis::X: + return (bits & static_cast(BoundaryModeDistributed::PeriodicX)) != 0; + case Axis::Y: + return (bits & static_cast(BoundaryModeDistributed::PeriodicY)) != 0; + case Axis::Z: + return (bits & static_cast(BoundaryModeDistributed::PeriodicZ)) != 0; + } + return false; +} + +[[nodiscard]] constexpr CARBON_HD auto +operator|(BoundaryModeDistributed a, + BoundaryModeDistributed b) noexcept -> BoundaryModeDistributed { + return static_cast(static_cast(a) | + static_cast(b)); +} + +[[nodiscard]] constexpr CARBON_HD auto +operator&(BoundaryModeDistributed a, + BoundaryModeDistributed b) noexcept -> BoundaryModeDistributed { + return static_cast(static_cast(a) & + static_cast(b)); +} + +} // namespace carbon diff --git a/include/carbon/carbon.h b/include/carbon/carbon.h index 3fd1954a..55636c2f 100644 --- a/include/carbon/carbon.h +++ b/include/carbon/carbon.h @@ -23,12 +23,15 @@ device_count() noexcept -> int; } // namespace carbon #include +#include #include #include #include +#include #include #include #include +#include #include #include #include @@ -44,6 +47,8 @@ device_count() noexcept -> int; #include #include +#include + #ifdef CARBON_HAVE_MPI_NCCL #include #include diff --git a/include/carbon/dense_distributed.h b/include/carbon/dense_distributed.h new file mode 100644 index 00000000..079cea02 --- /dev/null +++ b/include/carbon/dense_distributed.h @@ -0,0 +1,600 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace carbon { + +class Kernel; + +template +class ReductionResult; + +namespace reduce { +template +struct Sum; +} // namespace reduce + +namespace detail { +template +class DeviceKernelImpl; +} // namespace detail + +namespace detail::dense_distributed { +template +class Field; +} // namespace detail::dense_distributed + +/** + * Logical Cartesian grid over a (possibly distributed) multi-GPU System: a fixed global + * @c (x, y, z), partitioned by a @ref ProcessGrid. The local @c DenseDistributed holds one span + * per local GPU; each span is the chunk of the global domain owned by that GPU. + * + * Relationship to @ref Dense: @c Dense is the original grid and only ever splits @c z (one slab + * per GPU/rank). @c DenseDistributed is the same kind of grid -- same kernel, reduce, Skeleton and + * Field surface, selected through the same launch-traits mechanism as @ref DenseDisg -- but with a + * per-axis decomposition (slab / pencil / brick), per-axis periodicity + * (@ref BoundaryModeDistributed) and a multi-axis halo exchange (@ref HaloDistributed). Its + * @c Span exposes per-axis @c offset() / @c halo() / @c logic_extent(); the Z-only accessors + * (@c z_offset(), @c halo_z()) are kept for slab code. Slab layouts reproduce @c Dense's geometry + * exactly. + * + * Partitioning model + * ------------------ + * - @ref DecompositionMode::Slab (the default) splits only @c z, preserving the historical + * behaviour: each GPU/rank owns a z-slab with the full global @c x and @c y extent. + * - @ref DecompositionMode::Pencil splits @c y and @c z; @c x remains whole. + * - @ref DecompositionMode::Brick splits all three axes. + * - @b Single-process (no @c Distributed attached): local GPUs map to process-grid ranks in + * order. Multi-GPU Pencil/Brick is rejected; Slab remains supported with one z-slab per GPU. + * - @b Distributed (one rank per GPU, the model carbon assumes for MPI builds): this rank's + * @c gpu_group() holds exactly one device and its process-grid coordinate comes from + * @c distributed().world_rank(). Multiple GPUs per rank are rejected at construction. + * + * Extents are split as evenly as possible along each axis: earlier coordinates receive one + * extra layer when the global extent is not divisible. Local span @c i carries its own + * @c x_offset / @c y_offset / @c z_offset, which include that chunk's lower halo. + * + * Stores a shallow copy of @p system (see @ref System); all copies share the same underlying + * devices, stream/event state, and (when present) @c Distributed handle. + */ +class CARBON_API DenseDistributed { +public: + /** Per-GPU chunk layout (alias of @c detail::dense_distributed::Span). */ + using Span = detail::dense_distributed::Span; + /** Cell index for dense kernels (alias of @c detail::dense_distributed::Idx). */ + using Idx = detail::dense_distributed::Idx; + + /** + * Marker consumed by @c detail::DeviceLaunchTraits / @c detail::ReduceLaunchTraits to route + * kernel launches through the @c dense_distributed launch helpers (same mechanism as + * @c DenseDisg::DisgPolicy ). + */ + using DenseDistributedPolicy = void; + + /** + * Per-GPU device-pointer view of a slab for one @ref Field, alias of + * @c detail::dense_distributed::Partition. Kernel code reads cells via + * @c partition.read(span, idx, component_id); see @ref detail::dense_distributed::Partition for the + * SoA layout. Mirrors the @ref Field alias so users do not reach into @c detail/dense_distributed/ for + * the partition view type either. + */ + template + using Partition = detail::dense_distributed::Partition; + + /** + * @brief Builds the default Slab layout over @p system for the given @p global_extent. + * Computes per-GPU spans, linear counts, and backend launch grid/block shapes (see + * @ref gpu_grid). Throws if extents are invalid or launch-shape validation fails for any + * device. Use a @ref DecompositionMode / @ref ProcessGrid overload for Pencil/Brick. + * + * @param stencil Optional stencil describing neighbour accesses over this grid. Stored + * by value; retrievable via @ref stencil(). Defaults to an empty stencil + * (radius 0, i.e. no halo dependencies). Drives the halo thickness on + * each per-GPU @c Span. + * @param boundary_mode Per-axis boundary semantics applied to the grid (propagated into + * every per-GPU @c Span and consulted by @c Partition::neighbour and the + * halo exchange). Defaults to @ref BoundaryModeDistributed::Open (non-toroidal); + * any combination of @ref BoundaryModeDistributed::PeriodicX / @c PeriodicY / + * @c PeriodicZ is honoured end-to-end. + * @param origin Physical-space origin at global integer cell @c (0,0,0) (cell-corner + * convention with @c Span::global_location). + * @param spacing Isotropic cell spacing; must be finite and strictly positive. + * @param block_override When set, used as the CUDA/SYCL launch block for every local GPU + * instead of @c dense_make_kernel_block(). The matching launch grid + * is derived via @c compute_dense_grid for each @ref DataView. + */ + DenseDistributed(System system, + int64_3d global_extent, + Stencil stencil = Stencil{}, + BoundaryModeDistributed boundary_mode = BoundaryModeDistributed::Open, + float32_3d origin = {}, + float spacing = 1.0F, + std::optional block_override = std::nullopt); + + /** + * @brief Build a layout by auto-factorizing the world size for @p decomposition. + * + * See @ref ProcessGrid::make for the factor order. Remaining parameters match the Slab + * constructor above. + */ + DenseDistributed(System system, + int64_3d global_extent, + DecompositionMode decomposition, + Stencil stencil = Stencil{}, + BoundaryModeDistributed boundary_mode = BoundaryModeDistributed::Open, + float32_3d origin = {}, + float spacing = 1.0F, + std::optional block_override = std::nullopt); + + /** + * @brief Build a layout from an explicit @p process_grid. + * + * The grid's @c world_size must match the rank count (distributed) or the local GPU count + * (single-process). Remaining parameters match the Slab constructor above. + */ + DenseDistributed(System system, + int64_3d global_extent, + ProcessGrid process_grid, + Stencil stencil = Stencil{}, + BoundaryModeDistributed boundary_mode = BoundaryModeDistributed::Open, + float32_3d origin = {}, + float spacing = 1.0F, + std::optional block_override = std::nullopt); + + /** + * @brief Default-construct an empty grid: zero global extent, default + * @ref System (no devices), no slabs. Useful as a placeholder + * member or before an assignment from a real-args ctor; every + * accessor returns its zero value (e.g. @c global_extent() == + * @c {0, 0, 0} , @c spans().empty() ). Required to make the + * default constructor of @c detail::dense_distributed::Field well- + * formed (and through that, @c carbon::HaloDistributed as well — + * both store a @c DenseDistributed by value as the "I'm a placeholder" + * state). Trivial implementation; all data members carry + * in-class default initializers. + */ + DenseDistributed() = default; + + [[nodiscard]] auto + process_grid() const noexcept -> const ProcessGrid&; + + /** + * @brief Global @c (x,y,z) extent shared by all chunks (before decomposition). + * @return Reference to the extent stored at construction; valid for the lifetime of this @c DenseDistributed. + * @see local_extent for per-GPU subgrid extents. + */ + [[nodiscard]] auto + global_extent() const noexcept -> const int64_3d&; + + /** + * @brief Stencil this grid was constructed with (empty by default). + * @return Reference to the stored @ref Stencil; valid for the lifetime of this @c DenseDistributed. + */ + [[nodiscard]] auto + stencil() const noexcept -> const Stencil&; + + /** + * @brief Boundary mode this grid was constructed with (default @c BoundaryModeDistributed::Open). + * Propagated to every entry of @ref spans() and consulted by @c Partition::neighbour + * and the halo exchange. + */ + [[nodiscard]] auto + boundary_mode() const noexcept -> BoundaryModeDistributed; + + /** Physical-space origin at global cell @c (0,0,0); same value on every @ref spans entry. */ + [[nodiscard]] auto + origin() const noexcept -> float32_3d; + + /** Isotropic cell spacing carried on every @ref spans slab. */ + [[nodiscard]] auto + spacing() const noexcept -> float; + + /** + * @brief Mutable access to the backing @ref System (devices, streams, events). + * @return Reference to the shared @c System state; copies of @c DenseDistributed alias the same state. + * @see system() const for read-only access. + */ + [[nodiscard]] auto + system() noexcept -> System&; + + /** + * @brief Read-only access to the backing @ref System (devices, streams, events). + * @return Const reference to the shared @c System state. + * @see system() for non-const access. + */ + [[nodiscard]] auto + system() const noexcept -> const System&; + + /** + * @brief Number of @b local GPUs participating in this layout (same as + * @c system().gpu_group().size()). In distributed mode this is always @c 1 (carbon's + * one-rank-per-GPU model); in single-process mode it is the visible-GPU count. + * @return Zero if the @c System has no devices; otherwise the local-GPU count. + * @see gpu_grid and gpu_block for per-GPU launch metadata. + * @see global_slab_count for the cross-rank slab total. + */ + [[nodiscard]] auto + gpu_count() const noexcept -> size_t; + + /** + * @brief Number of z coordinates in the process grid (@c dims.z). + * - Slab single-process: equals @ref gpu_count(). + * - Slab distributed: equals @c system().distributed()->world_size(). + * - Pencil/Brick: a z coordinate contains multiple chunks; this is @b not the rank count. + */ + [[nodiscard]] auto + global_slab_count() const noexcept -> size_t; + + /** + * @brief Process-grid @c z coordinate of local span @c 0. Equals @c 0 in single-process + * mode and the rank's @c coords.z when distributed. + */ + [[nodiscard]] auto + local_slab_offset() const noexcept -> size_t; + + /** + * @brief Local @b owned @c z extent on GPU @p gpu (excludes halo layers when the grid carries a + * non-trivial @ref Stencil; equals @c spans()[gpu].logic_extent().z). + * @param gpu Must be less than @ref gpu_count(); otherwise throws. + * @return Number of owned z layers on that device after splitting the global z extent. + */ + [[nodiscard]] auto + local_z(size_t gpu) const -> int64_t; + + /** + * @brief Starting global z index of the @b owned region on GPU @p gpu (the chunk's first + * non-halo layer; equals @c spans()[gpu].z_offset() + spans()[gpu].halo().z). + * @param gpu Must be less than @ref gpu_count(); otherwise throws. + * @return Global z offset so owned cells on this GPU lie in @c [offset, offset + local_z(gpu)). + */ + [[nodiscard]] auto + z_offset_global(size_t gpu) const -> int64_t; + + /** + * @brief Subgrid @b owned extent on GPU @p gpu (excludes halos), one component per axis. + * @param gpu Must be less than @ref gpu_count(); otherwise throws. + * @return int64_3d describing the local owned Cartesian chunk for that device. + */ + [[nodiscard]] auto + local_extent(size_t gpu) const -> int64_3d; + + /** + * @brief Owned (non-haloed) element count on GPU @p gpu: + * @c local_extent(gpu).x * .y * .z. For the haloed @b storage size used by + * @ref newField, see @c spans()[gpu].linear_storage_elements(). + * @param gpu Must be less than @ref gpu_count(); otherwise throws. + * @return Number of owned scalar cells in the chunk. + */ + [[nodiscard]] auto + linear_elements(size_t gpu) const -> size_t; + + /** + * @brief One @b owned element count per GPU (computed from @ref spans). Use + * @c spans()[i].linear_storage_elements() when sizing buffers that include halos. + * @return Vector parallel to @c system().gpu_group().devices() and @ref spans(). + * @see linear_elements for a single index. + */ + [[nodiscard]] auto + linear_counts_per_gpu() const -> std::vector; + + /** + * @brief One @ref Span per GPU (same order as @ref system), each describing the @b storage + * (haloed) layout of its chunk: per-axis offsets, halo thickness derived from + * @ref stencil(), and @c xy_slab_elements for pitch. + * + * When the grid has no stencil, @c halo() is zero and @c haloed_extent() equals + * @c logic_extent(). Use @c logic_extent() to iterate only owned cells; use @c haloed_extent() + * for pointer math over the buffer. + * + * @see local_extent for the same owned-cell extents in @c int64_3d form. + */ + [[nodiscard]] auto + spans() const noexcept -> const std::vector& { + return spans_; + } + + /** + * @brief Per-GPU launch grid for @c dense_grid_kernel under @p view. + * @param view Iteration view (Standard / Internal / Boundary); see @ref DataView and + * @c Span::iter_extent. Defaults to @c DataView::Standard. + * @return Computed in the constructor from @c spans()[i].iter_extent(view), + * @c dense_make_kernel_block(), and each device's @c max_threads_per_block. + * Returned as @ref LaunchShape so the public API does not depend on any + * backend-specific 3D type (the CUDA backend converts to @c dim3 internally; + * the future SYCL backend will convert to @c sycl::range<3>). + * @see gpu_block for the matching block dimensions. + */ + [[nodiscard]] auto + gpu_grid(DataView view = DataView::Standard) const noexcept -> const std::vector& { + return gpu_grid_per_view_[static_cast(view)]; + } + + /** + * @brief Per-GPU launch block for @p view (same shape repeated for each device today). + * + * Block dimensions are independent of @p view today (every view uses + * @c dense_make_kernel_block()), but the API takes the view for symmetry with + * @ref gpu_grid and to leave room for view-specific block tuning later. + * + * @return Vector parallel to @ref gpu_grid(view); each entry matches @c dense_make_kernel_block(). + * @see carbon/detail/dense/launch_shape.h for how the default block is chosen and validated. + */ + [[nodiscard]] auto + gpu_block(DataView view = DataView::Standard) const noexcept -> const std::vector& { + return gpu_block_per_view_[static_cast(view)]; + } + + /** + * @brief Builds a deferred *device-only* compute @ref Kernel bound to every GPU in + * @ref system(). + * + * The cheapest factory profile: only the device launch path is instantiated, and + * the returned @c Kernel throws @c std::logic_error on @c launch_on_host. The + * loading lambda is invoked with a @c carbon::KernelLoader @c & whose runtime + * @c target() is @c KernelTarget::Device, so @c loader(field) returns the device + * partition. If you also need a host (OpenMP) launch path on the same handle, use + * @ref make_universal_kernel. + * + * Returns a value-typed @c Kernel handle (a thin shared_ptr wrapper around the + * polymorphic @c detail::KernelImpl base) so the result can be stored alongside + * reductions and halo exchanges in a @c std::vector. The @ref DataView is + * not stored on the kernel — it is purely a launch-time choice, picked via + * @ref Kernel::launch (defaults to @c DataView::Standard). Per-view launch shapes + * are precomputed in the @c DenseDistributed constructor (see @ref gpu_grid / @ref gpu_block). + * Definition lives in @c carbon/kernel.h. + */ + template + [[nodiscard]] auto + make_kernel(L&& loading_fn, + size_t shared_mem = 0U) const -> Kernel; + + /** + * @brief Builds a deferred *dual-target* (universal) compute @ref Kernel bound to + * every GPU in @ref system(). The returned kernel can be launched on either + * the device (CUDA / SYCL) or the host (OpenMP) from the same handle. + * + * Both launch paths are instantiated when this factory is called, so the consumer + * pays a slightly higher compile-time cost than @ref make_kernel — earn it back + * by using the same loading lambda for in-process device/host parity tests, or for + * adaptive dispatch where the runtime picks the side per call. The loading lambda + * sees a @c carbon::KernelLoader @c & on every launch (the same non-template type + * on both paths); @c loader.target() differs at runtime so @c loader(field) + * automatically routes to the device or host buffer, and the user writes one + * concrete lambda body that nvcc accepts without the generic-lambda HD-trap. + * + * @par Default launch behaviour + * @c Kernel::launch(stream) on the result dispatches to the device path so existing + * call sites that iterate a @c std::vector keep their device behaviour. + * @c Kernel::launch_on_host(stream) runs the OpenMP body on the same handle — + * useful for debugging, validation against a CPU reference, or adaptive dispatch. + * + * @par Field side selection + * The @c KernelLoader passed to the loading lambda routes @c loader(field) based on + * the active launch target: device launches see @c Field::partitions, host launches + * see @c Field::host_partitions. Fields touched by a host launch must therefore have + * been built with @c MemorySide::Host or @c MemorySide::HostDevice. + */ + template + [[nodiscard]] auto + make_universal_kernel(L&& loading_fn, + size_t shared_mem = 0U) const -> Kernel; + + /** + * @brief Builds a deferred *device-only* grid-wide reduction kernel bound to this + * @c DenseDistributed slab. + * + * The user's per-cell lambda returns @p T (instead of @c void); the launch pipeline + * reduces those contributions to a single scalar @ref ReductionResult destination. + * Multi-GPU and multi-rank are both supported through a three-stage pipeline + * (per-GPU stage 1 via CUB / @c sycl::reduction , intra-process combine on the + * root GPU as stage 2, cross-rank @c ncclAllReduce / @c MPI_Allreduce as stage 3 + * — see @c include/carbon/detail/reduce_stages.h ). Launches use + * @c DataView::Standard ; the Internal / Boundary split is the universal-reduce + * kernel's job. The loading lambda receives a @c carbon::KernelLoader @c & whose + * @c target() is @c KernelTarget::Device. For a dual-target reduction kernel, + * see @ref make_universal_reduce_kernel. + * + * The destination @ref ReductionResult is captured by reference at construction + * time so the polymorphic @c Kernel::launch signature stays uniform with every + * other kernel kind. Lifetime contract: @p dst must outlive the returned @c Kernel + * handle. + * + * Definition lives in @c carbon/kernel.h. + * + * @tparam T Reduction value type returned by the per-cell lambda. + * @tparam L Type of the loading callable (Neon-style: takes @ref KernelLoader, + * returns the per-cell lambda). + * @tparam Op Reduction operator with @c CARBON_HD @c identity() and + * @c operator()(T, T) -> T. Defaults to @c carbon::reduce::Sum. + * + * @param loading_fn Loading callable. + * @param dst Reduction destination; lifetime must extend beyond every + * @c launch on the returned @c Kernel. + * @param op Reduction operator instance (default-constructed). + * @param shared_mem Dynamic shared memory in bytes (default 0). + * @param options Optional @ref reduce::ReduceOptions . + */ + template > + [[nodiscard]] auto + make_reduce_kernel(L&& loading_fn, + ReductionResult& dst, + Op op = {}, + size_t shared_mem = 0U, + reduce::ReduceOptions options = {}) const -> Kernel; + + /** + * @brief Builds a deferred *dual-target* (universal) grid-wide reduction kernel. + * + * Same dual semantics as @ref make_universal_kernel but for a grid-wide reduction: + * @c Kernel::launch(stream) defaults to the device path (CUB / sycl::reduction + + * async D→H copy; user calls @c dst.sync(stream) before reading + * @c dst.host_value()). @c Kernel::launch_on_host(stream) runs the OpenMP per-thread + * partials path and writes directly to @c dst.host_data — no async copy, no sync + * needed. The loading lambda must be generic (see @ref make_universal_kernel). + * + * Definition lives in @c carbon/kernel.h. + */ + template > + [[nodiscard]] auto + make_universal_reduce_kernel(L&& loading_fn, + ReductionResult& dst, + Op op = {}, + size_t shared_mem = 0U) const -> Kernel; + + /** + * @brief Builds a deferred host (CPU / OpenMP) compute @ref Kernel bound to every GPU + * slab in @ref system(). + * + * Twin of @ref make_kernel that walks the iter extent through an OpenMP nested-for + * (z slowest, x fastest) instead of a CUDA / SYCL submit. The user's loading lambda + * has the same shape; the per-cell @c (Span, Idx) -> void closure can be the same + * @c CARBON_HOST_DEVICE-annotated body fed to @ref make_kernel. The loader passed in + * is @c carbon::KernelLoader @c & with @c target() == @c KernelTarget::Host, so + * @c loader(field) hands back @c Field::host_partitions instead of + * @c Field::partitions — every field touched must have been built with + * @c MemorySide::Host or @c MemorySide::HostDevice. + * + * Definition lives in @c carbon/kernel.h. + * + * @note Stream argument on @c Kernel::launch(stream) is waited-on first (so a host + * kernel sitting after a device kernel sees the device's writes flushed to the + * CPU mirror via a prior Transfer), then the OpenMP loop runs synchronously + * inline. There is no per-kernel shared-memory parameter: OpenMP has no analog. + */ + template + [[nodiscard]] auto + make_host_kernel(L&& loading_fn) const -> Kernel; + + /** + * @brief Builds a deferred host (CPU / OpenMP) grid-wide reduction kernel. + * + * Twin of @ref make_reduce_kernel; the OpenMP path uses one accumulator per thread + * (initialised to @c op.identity()) and combines the partials sequentially through + * @p op so user-defined operators (not just @c reduce::Sum) work without an explicit + * @c omp declare reduction. Result is written directly into @c dst.host_data() — + * @c dst.sync(stream) after launch is still safe but a no-op for the host path. + * + * Definition lives in @c carbon/kernel.h. + * + * @throws std::invalid_argument when @c gpu_count() == 0 (the System carries no + * GPUs / slabs to drive the OpenMP loop). Multi-GPU and multi-rank are + * both supported, mirroring the device reducer's three-stage pipeline. + */ + template > + [[nodiscard]] auto + make_host_reduce_kernel(L&& loading_fn, + ReductionResult& dst, + Op op = {}) const -> Kernel; + + /** + * @brief Per-GPU device field storage (buffers + @ref Partition views) for this layout. + * @tparam T Element type per grid cell. + * @tparam Components Number of components per cell (1 = scalar, 3 = vector, ...). Same value + * flows through to @ref detail::dense_distributed::Partition. + */ + template + using Field = detail::dense_distributed::Field; + + /** + * @brief Allocates per-slab field storage for this @c DenseDistributed layout. + * + * @p side selects which sides of the field are reserved (see @ref MemorySide): + * - @c Device : one device @ref Buffer per GPU (sized by + * @c spans()[gpu].linear_storage_elements()); host buffers are empty. + * - @c Host : one host @ref Buffer per GPU (same per-GPU sizes); device buffers are + * empty. Partitions are bound to the host pointers so callers can use + * the same @ref Partition / @ref Span APIs on the CPU side. + * - @c HostDevice : both sides are allocated; partitions are bound to the @b device side + * (matching the previous behaviour) so kernel launches keep working + * unchanged. Use @ref Transfer to move data between sides. + * + * The default is @c MemorySide::Device, matching the original device-only behaviour so + * existing callers keep working without changes. + * + * @throws std::runtime_error if @ref gpu_count() is zero (after @c CARBON_LOG_ERROR). + */ + /** + * @overload + * + * Like @ref newField above but also stamps the resulting field with a + * diagnostic @p name (forwarded to @c Field::set_name ). The name is + * optional — pass an empty string for unnamed fields. Used by the carbon + * @c Skeleton 's DAG export to label edges and node tooltips, and propagated + * through @c KernelLoader so token records carry the name to the analysis + * stage. Identity (the @c BufferGroup uid) is independent of the name — + * two fields with the same name are still distinct fields, and changing the + * name post-hoc via @c Field::set_name does not affect any already-recorded + * tokens (those carry the name they saw at @c make_kernel time). + */ + template + [[nodiscard]] auto + newField(MemorySide side = MemorySide::Device, + std::string name = {}) const -> Field; + +private: + int64_3d global_{}; + System system_; + Stencil stencil_{}; + BoundaryModeDistributed boundary_mode_{BoundaryModeDistributed::Open}; + float32_3d origin_{}; + float spacing_{1.0F}; + // Cross-rank partitioning state. See class doxygen for the model. These are z-coordinate + // values, not rank indices when a Y or X split is active. + size_t global_slab_count_{}; + size_t local_slab_offset_{}; + // spans_ is the single source of truth for per-GPU chunk geometry: owned/haloed extent, + // per-axis global origins (with halo), halo thickness, and storage pitch. Owned counts and + // offsets are derived from it on access; only the launch shapes (gpu_grid_/gpu_block_) are + // kept as separate vectors because they depend on per-device launch caps, not just layout. + std::vector spans_{}; + // Per-DataView per-GPU launch shapes. Indexed by static_cast(DataView): 0=Standard, + // 1=Internal, 2=Boundary. Each inner vector parallels @ref spans() and @ref system(). Stored + // as backend-neutral @ref LaunchShape; converted to the active backend's 3D type + // (@c dim3 / @c sycl::range<3>) at the launch site inside @c carbon::detail. + std::array, data_view_count> gpu_grid_per_view_{}; + std::array, data_view_count> gpu_block_per_view_{}; + + void + init_common_(System system, + int64_3d global_extent, + Stencil stencil, + BoundaryModeDistributed boundary_mode, + float32_3d origin, + float spacing, + ProcessGrid process_grid, + std::optional block_override); + + ProcessGrid process_grid_{}; +}; + +} // namespace carbon + +#include diff --git a/include/carbon/detail/backend/cudalike/dense_distributed_kernel.h b/include/carbon/detail/backend/cudalike/dense_distributed_kernel.h new file mode 100644 index 00000000..5595b21b --- /dev/null +++ b/include/carbon/detail/backend/cudalike/dense_distributed_kernel.h @@ -0,0 +1,74 @@ +#pragma once + +/** + * CUDA dense grid kernel. Include only from @c .cu translation units (or any TU compiled with nvcc). + * Requires C++20 and @c --extended-lambda on the CUDA compile line when using device lambdas. + */ + +#include +#include + +#include +#include + +#if CARBON_CUDALIKE_DEVICE_TU +#include +#endif + +namespace carbon::detail::dense_distributed { + +/** + * Callable type for @ref dense_grid_kernel: @c void fn(span, idx). + * + * Host-side checking requires the call to be valid on the host too, so prefer a functor with + * @c CARBON_HOST_DEVICE @c void @c operator()(Span, @c Idx) @c const (or a non-capturing + * @c CARBON_HOST_DEVICE lambda at namespace scope with @c --extended-lambda). A @c __device__-only + * callable can still be used with the kernel but may not satisfy this concept during instantiation. + */ +template +concept dense_kernel_fn = requires(F fn, Span span, Idx idx) { + {fn(span, idx)}->std::same_as; +}; + +#if CARBON_CUDALIKE_DEVICE_TU + +/** + * Maps each CUDA thread to @c (ix, iy, iz) = @c blockIdx * blockDim + threadIdx and invokes + * @p fn(span, idx) only for threads that fall inside @c span.iter_extent(view). The launch + * grid is the iteration shape for @p view (Standard / Internal / Boundary; see + * @c Span::iter_extent), so halo layers are never iterated. + * + * The @p idx handed to @p fn is buffer-relative: x and y are passed through verbatim, while + * z has been shifted by @c Span::set_and_validate so that it points at the correct cell in + * the buffer-local SoA layout for @p view. Use @c span.global_location(idx) if you need the + * grid-global coordinates. + * + * Running Internal then Boundary (in either order) covers exactly the same set of owned + * cells as a single Standard launch — the three iteration domains partition the slab. + * + * @note We deliberately do @b not annotate this kernel with @c __launch_bounds__ . The launch + * block is warp-aligned and capped at 512 threads (@c dense_make_kernel_block), and a measured + * A100 sweep of LBM D3Q19 (the register-heaviest dense consumer) showed a @c __launch_bounds__(512) + * cap to be neutral-to-slightly-negative across N=128..384 — the pull-stencil kernels are HBM- + * bandwidth bound (already near the roofline), so there is no occupancy headroom for the hint to + * recover. Left off to avoid constraining ptxas for no gain; revisit only for a compute-bound + * dense consumer. + */ +template +requires dense_kernel_fn __global__ void +dense_grid_kernel(Span span, + ::carbon::DataView view, + F fn) { + const int64_t ix = static_cast(blockIdx.x * blockDim.x + threadIdx.x); + const int64_t iy = static_cast(blockIdx.y * blockDim.y + threadIdx.y); + const int64_t iz = static_cast(blockIdx.z * blockDim.z + threadIdx.z); + const ValidatedIdx r = span.set_and_validate(view, ix, iy, iz); + if (!r.valid) { + return; + } + fn(span, r.idx); +} + +#endif + +} // namespace carbon::detail::dense_distributed diff --git a/include/carbon/detail/backend/cudalike/dense_distributed_launch.h b/include/carbon/detail/backend/cudalike/dense_distributed_launch.h new file mode 100644 index 00000000..d3fd4021 --- /dev/null +++ b/include/carbon/detail/backend/cudalike/dense_distributed_launch.h @@ -0,0 +1,124 @@ +#pragma once + +/** + * Single-GPU launch helper for @c carbon::detail::dense_distributed::dense_grid_kernel. Lives in + * @c detail/ so that the public @c carbon/dense.h does not have to mention any backend + * stream / error type. Today this is the CUDA implementation; the SYCL backend will + * provide an equivalent free function with the same name and signature inside its own + * detail subtree, selected at compile time by the future backend dispatcher. + * + * Internal API: only @c carbon::detail::DeviceKernelImpl reaches in here. User code should + * compose a @c carbon::Kernel via @c DenseDistributed::make_kernel / @c Kernel::compute and call + * @c Kernel::launch — never @c launch_dense_grid directly. + * + * @par Why a free function (rather than a @c DenseDistributed member) + * The previous @c DenseDistributed::launch_dense_grid friend method tied the public @c DenseDistributed type to + * @c dim3 and @c gpu_stream_t. With the kernel impls already gating their bodies on + * @c CARBON_CUDALIKE_DEVICE_TU, the helper does not need member access to @c DenseDistributed's privates — it can + * read @c grid.system() and @c grid.spans() through the public accessors. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +namespace carbon { + +namespace detail::dense_distributed { + +/** Convert a backend-neutral @ref LaunchShape to CUDA's @c dim3 at the launch site. */ +[[nodiscard]] inline auto +to_dim3(LaunchShape s) noexcept -> dim3 { + return dim3(s.x, s.y, s.z); +} + +// Dependent false predicate so the non-CUDA branch's static_assert below only fires when +// launch_dense_grid is actually instantiated by user code, not on plain header inclusion. +template +inline constexpr bool dense_launch_requires_cudacc_ = false; + +#if CARBON_CUDALIKE_DEVICE_TU + +/** + * @brief Launch @c dense_grid_kernel on @p relative_gpu_id with the given launch shape. + * + * @param grid The @c DenseDistributed layout this launch is bound to. + * @param grid_shape Per-axis grid extent (in blocks); produced by + * @ref compute_dense_grid in @c DenseDistributed's constructor. + * @param block_shape Per-axis block extent (in threads); the same value is used for + * every device today (see @ref dense_make_kernel_block). + * @param relative_gpu_id Index into @c grid.system().gpu_group().devices() and @c grid.spans(). + * @param shared_mem Dynamic shared memory in bytes per launch. + * @param stream CUDA stream to enqueue on; the caller has already picked the + * per-GPU handle out of the public @c Stream group. + * @param view Iteration sub-domain (Standard / Internal / Boundary). + * @param fn Per-cell device callable; must satisfy @c dense_kernel_fn. + * + * @return @c gpu_error_t result of @c gpu_runtime_launch_kernel — non-success values are surfaced + * to the user through @c DeviceKernelImpl's error path. + */ +template +requires dense_kernel_fn [[nodiscard]] inline auto +launch_dense_grid(const ::carbon::DenseDistributed& grid, + LaunchShape grid_shape, + LaunchShape block_shape, + size_t relative_gpu_id, + size_t shared_mem, + gpu_stream_t stream, + ::carbon::DataView view, + F fn) -> gpu_error_t { + if (relative_gpu_id >= grid.gpu_count()) { + ::carbon::log::throw_with_log( + "launch_dense_grid: relative_gpu_id out of range (relative_gpu_id={}, gpu_count={})", + relative_gpu_id, grid.gpu_count()); + } + if (!grid_shape.is_nonzero() || !block_shape.is_nonzero()) { + // Empty iteration — no work, so report success without touching the driver. This is + // reachable two ways: a Boundary view on a slab whose z extent is fully owned, and a slab + // that got no cells at all because the grid has fewer z planes than GPUs. Note that CUDA + // does *not* forgive a zero grid dimension: cudaLaunchKernel rejects dim3(0, 0, 0) with + // cudaErrorInvalidConfiguration, so without this guard those launches fail outright. + return gpu_success; + } + const ::carbon::detail::Gpu& gpu = grid.system().gpu_group().devices()[relative_gpu_id]; + const Span span = grid.spans()[relative_gpu_id]; + return gpu.template typed_launch<&dense_grid_kernel>(to_dim3(grid_shape), to_dim3(block_shape), + shared_mem, stream, span, view, fn); +} + +#else + +template +requires dense_kernel_fn [[nodiscard]] inline auto +launch_dense_grid(const ::carbon::DenseDistributed&, + LaunchShape, + LaunchShape, + size_t, + size_t, + gpu_stream_t, + ::carbon::DataView, + F) -> gpu_error_t { + static_assert( + dense_launch_requires_cudacc_, + "carbon::detail::dense_distributed::launch_dense_grid is only supported in translation " + "units compiled with nvcc (CARBON_CUDALIKE_DEVICE_TU). Move the call site to a .cu file (or " + "build the TU with nvcc) and include from there. Only the " + "*call site* needs to be CUDA — the rest of your project can stay on the host " + "compiler."); + return gpu_error_not_supported; +} + +#endif + +} // namespace detail::dense_distributed + +} // namespace carbon diff --git a/include/carbon/detail/backend/cudalike/dense_distributed_reduce_kernel.h b/include/carbon/detail/backend/cudalike/dense_distributed_reduce_kernel.h new file mode 100644 index 00000000..2e8dc285 --- /dev/null +++ b/include/carbon/detail/backend/cudalike/dense_distributed_reduce_kernel.h @@ -0,0 +1,244 @@ +#pragma once + +/** + * Device-side machinery for grid-wide reductions on @c DenseDistributed slabs. The fused + * "map + block-reduce" CUDA kernel that runs the user's per-cell device lambda and + * collapses each block to a single partial via @c gpucub::BlockReduce. The grid-level + * collapse (the second pass over the per-block partials) is done by + * @c gpucub::DeviceReduce::Reduce on the host side; see + * @c carbon/detail/reduce_kernel_impl.h for the orchestration (the impl behind + * @c carbon::Kernel::reduce in @c carbon/kernel.h). + * + * Include only from @c .cu translation units (or any TU compiled with nvcc): pulls in + * @c and a @c __global__ template. + */ + +#include +#include +#include + +#include +#include +#include + +#if CARBON_CUDALIKE_DEVICE_TU +#include +#endif + +namespace carbon::detail::dense_distributed { + +/** + * Concept for a reduce kernel's per-cell device lambda: callable as @c (Span, Idx) -> T, + * with @c T returned by value. Same shape as @ref dense_kernel_fn but the return type is + * the contribution to the reduction instead of @c void. + * + * No @c std::is_trivially_copyable_v check: nvcc wraps extended host-device lambdas in + * @c __nv_hdl_wrapper_t which fails the standard trait even though the closure is safe to + * pass by value into a @c __global__ kernel (CUDA's own contract is more permissive than + * the C++ trait). The existing @ref dense_kernel_fn for the void-returning compute case + * doesn't enforce trivial copyability either, and we follow the same convention here. + */ +template +concept dense_reduce_fn = std::is_invocable_r_v; + +/** + * Default block-flat thread count when @ref carbon::reduce::ReduceOptions::stage1_threads + * is zero. + */ +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 ). + */ +template +__global__ void +dense_grid_reduce_kernel_t(Span span, + ::carbon::DataView view, + F fn, + Op op, + T init, + T* partials, + int64_t total_cells) { + using BlockReduceT = gpucub::BlockReduce; + __shared__ typename BlockReduceT::TempStorage temp_storage; + + const int64_t flat = + static_cast(blockIdx.x) * BlockThreads + static_cast(threadIdx.x); + + T thread_val = init; + if (flat < total_cells) { + const ::carbon::int64_3d ext = span.iter_extent(view); + const int64_t ix = flat % ext.x; + const int64_t rest = flat / ext.x; + const int64_t iy = rest % ext.y; + const int64_t iz = rest / ext.y; + const ValidatedIdx vi = span.set_and_validate(view, ix, iy, iz); + if (vi.valid) { + thread_val = fn(span, vi.idx); + } + } + + const T block_val = BlockReduceT(temp_storage).Reduce(thread_val, op); + if (threadIdx.x == 0U) { + partials[blockIdx.x] = block_val; + } +} + +/** + * Same as @ref dense_grid_reduce_kernel_t but block sums are merged with + * @ref reduce_atomic_accumulate into @p global_out instead of a partials vector. + */ +template +__global__ void +dense_grid_reduce_block_atomic_kernel_t(Span span, + ::carbon::DataView view, + F fn, + Op op, + T init, + T* global_out, + int64_t total_cells) { + using BlockReduceT = gpucub::BlockReduce; + __shared__ typename BlockReduceT::TempStorage temp_storage; + + const int64_t flat = + static_cast(blockIdx.x) * BlockThreads + static_cast(threadIdx.x); + + T thread_val = init; + if (flat < total_cells) { + const ::carbon::int64_3d ext = span.iter_extent(view); + const int64_t ix = flat % ext.x; + const int64_t rest = flat / ext.x; + const int64_t iy = rest % ext.y; + const int64_t iz = rest / ext.y; + const ValidatedIdx vi = span.set_and_validate(view, ix, iy, iz); + if (vi.valid) { + thread_val = fn(span, vi.idx); + } + } + + const T block_val = BlockReduceT(temp_storage).Reduce(thread_val, op); + if (threadIdx.x == 0U) { + reduce_atomic_accumulate(global_out, block_val); + } +} + +/** + * 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. + */ +template +__global__ void +dense_grid_reduce_kernel_2d_t(Span span, + ::carbon::DataView view, + F fn, + Op op, + T init, + T* partials, + int64_t /*total_cells*/) { + using BlockReduceT = + gpucub::BlockReduce; + __shared__ typename BlockReduceT::TempStorage temp_storage; + + const ::carbon::int64_3d ext = span.iter_extent(view); + const int64_t ix = + static_cast(blockIdx.x) * BlockDimX + static_cast(threadIdx.x); + const int64_t iz = + 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 (vi.valid) { + thread_val = fn(span, vi.idx); + } + } + + const T block_val = BlockReduceT(temp_storage).Reduce(thread_val, op); + if (threadIdx.x == 0 && threadIdx.y == 0) { + const size_t block_linear = static_cast(blockIdx.y) * static_cast(gridDim.x) + + static_cast(blockIdx.x); + partials[block_linear] = block_val; + } +} + +template +__global__ void +dense_grid_reduce_block_atomic_kernel_2d_t(Span span, + ::carbon::DataView view, + F fn, + Op op, + T init, + T* global_out, + int64_t /*total_cells*/) { + using BlockReduceT = + gpucub::BlockReduce; + __shared__ typename BlockReduceT::TempStorage temp_storage; + + const ::carbon::int64_3d ext = span.iter_extent(view); + const int64_t ix = + static_cast(blockIdx.x) * BlockDimX + static_cast(threadIdx.x); + const int64_t iz = + 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 (vi.valid) { + thread_val = fn(span, vi.idx); + } + } + + const T block_val = BlockReduceT(temp_storage).Reduce(thread_val, op); + if (threadIdx.x == 0 && threadIdx.y == 0) { + reduce_atomic_accumulate(global_out, block_val); + } +} + +#endif // CARBON_CUDALIKE_DEVICE_TU + +} // namespace carbon::detail::dense_distributed diff --git a/include/carbon/detail/backend/cudalike/dense_distributed_reduce_launch.h b/include/carbon/detail/backend/cudalike/dense_distributed_reduce_launch.h new file mode 100644 index 00000000..bdb7e2cb --- /dev/null +++ b/include/carbon/detail/backend/cudalike/dense_distributed_reduce_launch.h @@ -0,0 +1,217 @@ +#pragma once + +/** + * Host-side launch dispatch for @c DenseDistributed grid reduce kernels at variable CUB block + * sizes (compile-time @c BlockThreads template on the device kernels). + */ + +#include +#include +#include +#include +#include + +#include +#include + +namespace carbon::detail::dense_distributed { + +#if CARBON_CUDALIKE_DEVICE_TU + +template +auto +launch_dense_grid_reduce_kernel(int block_threads, + const ::carbon::detail::Gpu& gpu, + int64_t blocks, + size_t shared_mem, + gpu_stream_t stream, + Span span, + ::carbon::DataView view, + F& fn, + Op& op, + T identity, + T* partials, + int64_t total_cells) -> gpu_error_t { +#define CARBON_LAUNCH_DENSE_REDUCE(BT) \ + return gpu.template typed_launch<&dense_grid_reduce_kernel_t>( \ + dim3(static_cast(blocks), 1U, 1U), dim3(static_cast(BT), 1U, 1U), \ + shared_mem, stream, span, view, fn, op, identity, partials, total_cells) + + switch (block_threads) { + case 32: + CARBON_LAUNCH_DENSE_REDUCE(32); + case 64: + CARBON_LAUNCH_DENSE_REDUCE(64); + case 128: + CARBON_LAUNCH_DENSE_REDUCE(128); + case 256: + CARBON_LAUNCH_DENSE_REDUCE(256); + case 512: + CARBON_LAUNCH_DENSE_REDUCE(512); + case 1024: + CARBON_LAUNCH_DENSE_REDUCE(1024); + default: + log::throw_with_log( + "Kernel::reduce: unsupported DenseDistributed stage1_threads {} (use a power-of-two " + "32–1024)", + block_threads); + } +#undef CARBON_LAUNCH_DENSE_REDUCE +} + +template +auto +launch_dense_grid_reduce_block_atomic_kernel(int block_threads, + const ::carbon::detail::Gpu& gpu, + int64_t blocks, + size_t shared_mem, + gpu_stream_t stream, + Span span, + ::carbon::DataView view, + F& fn, + Op& op, + T identity, + T* global_out, + int64_t total_cells) -> gpu_error_t { +#define CARBON_LAUNCH_DENSE_REDUCE_ATOMIC(BT) \ + return gpu.template typed_launch<&dense_grid_reduce_block_atomic_kernel_t>( \ + dim3(static_cast(blocks), 1U, 1U), dim3(static_cast(BT), 1U, 1U), \ + shared_mem, stream, span, view, fn, op, identity, global_out, total_cells) + + switch (block_threads) { + case 32: + CARBON_LAUNCH_DENSE_REDUCE_ATOMIC(32); + case 64: + CARBON_LAUNCH_DENSE_REDUCE_ATOMIC(64); + case 128: + CARBON_LAUNCH_DENSE_REDUCE_ATOMIC(128); + case 256: + CARBON_LAUNCH_DENSE_REDUCE_ATOMIC(256); + case 512: + CARBON_LAUNCH_DENSE_REDUCE_ATOMIC(512); + case 1024: + CARBON_LAUNCH_DENSE_REDUCE_ATOMIC(1024); + default: + log::throw_with_log( + "Kernel::reduce: unsupported DenseDistributed stage1_threads {} (use a power-of-two " + "32–1024)", + block_threads); + } +#undef CARBON_LAUNCH_DENSE_REDUCE_ATOMIC +} + +template +auto +launch_dense_grid_reduce_kernel_2d(int block_dim_x, + int block_dim_y, + const ::carbon::detail::Gpu& gpu, + int64_t blocks, + size_t shared_mem, + gpu_stream_t stream, + Span span, + ::carbon::DataView view, + F& fn, + Op& op, + T identity, + T* partials, + 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); + 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); + } + +#define CARBON_LAUNCH_DENSE_REDUCE_2D(BX, BY) \ + return gpu.template typed_launch<&dense_grid_reduce_kernel_2d_t>( \ + dim3(grid_x, grid_y, 1U), dim3(static_cast(BX), static_cast(BY), 1U), \ + shared_mem, stream, span, view, fn, op, identity, partials, total_cells) + + 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, + block_dim_y); +#undef CARBON_LAUNCH_DENSE_REDUCE_2D +} + +template +auto +launch_dense_grid_reduce_block_atomic_kernel_2d(int block_dim_x, + int block_dim_y, + const ::carbon::detail::Gpu& gpu, + int64_t blocks, + size_t shared_mem, + gpu_stream_t stream, + Span span, + ::carbon::DataView view, + F& fn, + Op& op, + T identity, + T* global_out, + 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); + 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); + } + +#define CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D(BX, BY) \ + return gpu.template typed_launch<&dense_grid_reduce_block_atomic_kernel_2d_t>( \ + dim3(grid_x, grid_y, 1U), dim3(static_cast(BX), static_cast(BY), 1U), \ + shared_mem, stream, span, view, fn, op, identity, global_out, total_cells) + + 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, + block_dim_y); +#undef CARBON_LAUNCH_DENSE_REDUCE_ATOMIC_2D +} + +#endif // CARBON_CUDALIKE_DEVICE_TU + +} // namespace carbon::detail::dense_distributed diff --git a/include/carbon/detail/backend/sycl/dense_distributed_kernel.h b/include/carbon/detail/backend/sycl/dense_distributed_kernel.h new file mode 100644 index 00000000..05c4a5bd --- /dev/null +++ b/include/carbon/detail/backend/sycl/dense_distributed_kernel.h @@ -0,0 +1,30 @@ +#pragma once + +/** + * SYCL twin of @c detail/backend/cudalike/dense_distributed_kernel.h. Mirrors the CUDA file's @e concept + * declaration (host-portable, used by the public @c DenseDistributed API for static-checking + * loading-lambda return types). The SYCL dense kernel launcher itself lives next door + * in @c detail/backend/sycl/dense_distributed_launch.h ; this file is the concept-only shim so + * @c carbon/dense.h 's transitive include stays cheap under SYCL — the public dense + * API only needs the concept, not the kernel template. + */ + +#include +#include + +#include +#include + +namespace carbon::detail::dense_distributed { + +/** + * Callable type for the SYCL dense grid launch (phase 2.4): @c void fn(span, idx). + * Same shape as the CUDA backend's concept so user lambdas authored against the public + * @c DenseDistributed::make_kernel API satisfy both, no per-backend authoring needed. + */ +template +concept dense_kernel_fn = requires(F fn, Span span, Idx idx) { + {fn(span, idx)}->std::same_as; +}; + +} // namespace carbon::detail::dense_distributed diff --git a/include/carbon/detail/backend/sycl/dense_distributed_launch.h b/include/carbon/detail/backend/sycl/dense_distributed_launch.h new file mode 100644 index 00000000..c27d4389 --- /dev/null +++ b/include/carbon/detail/backend/sycl/dense_distributed_launch.h @@ -0,0 +1,109 @@ +#pragma once + +/** + * SYCL twin of @c detail/backend/cudalike/dense_distributed_launch.h. Provides the same + * @c launch_dense_grid free function name (different signature: takes a + * @c sycl::queue& instead of a @c cudaStream_t, returns @c void instead of + * @c cudaError_t — SYCL surfaces failures as exceptions). Internal API; only + * @c carbon::detail::DeviceKernelImpl reaches into here. + * + * @par 3D launch mapping + * The CUDA @c dense_grid_kernel maps each thread to @c (ix, iy, iz) = + * @c blockIdx * @c blockDim + @c threadIdx, with x as @c {.x} (fastest dim) and z as + * @c {.z} (slowest). SYCL @c nd_range / @c nd_item index by dimension @b 0 (slowest + * dim) through @c d-1 (fastest), so the carbon X axis maps to SYCL dim 2, Y to dim 1, + * Z to dim 0. The @c LaunchShape coming in (built by @c compute_dense_grid) is in + * (x, y, z) order regardless of backend, so we mirror the CUDA call's per-axis values + * into the SYCL @c range<3> with that swap. + * + * @par Shared memory + * The CUDA backend supports a non-zero @p shared_mem dynamic-shared bytes argument + * on launch. SYCL exposes the same concept through @c sycl::local_accessor, but the + * existing carbon kernel signature @c fn(span, idx) does not include a local-memory + * pointer parameter — adding one is a public-API change that belongs in a later phase + * once a compute kernel actually needs it. For now, @p shared_mem != 0 throws so the + * mismatch surfaces loudly at the call site instead of silently dropping the request. + * + * @par Errors + * The implementation throws @c std::out_of_range when @p relative_gpu_id is invalid + * and @c std::runtime_error on any @c sycl::exception escaping the @c parallel_for + * submission. Callers in @c dense_kernel_impl.h forward the throw upward; carbon's + * existing test suite asserts on exception messages, not error codes, so this is + * symmetric with the CUDA path's @c throw_with_log behaviour. + */ + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +namespace carbon::detail::dense_distributed { + +template +requires dense_kernel_fn inline auto +launch_dense_grid(const ::carbon::DenseDistributed& grid, + LaunchShape grid_shape, + LaunchShape block_shape, + size_t relative_gpu_id, + size_t shared_mem, + sycl::queue& queue, + ::carbon::DataView view, + F fn) -> void { + if (relative_gpu_id >= grid.gpu_count()) { + ::carbon::log::throw_with_log( + "launch_dense_grid: relative_gpu_id out of range (relative_gpu_id={}, gpu_count={})", + relative_gpu_id, grid.gpu_count()); + } + if (shared_mem != 0U) { + ::carbon::log::throw_with_log( + "launch_dense_grid: dynamic shared memory ({} bytes) is not yet supported under " + "the SYCL backend. Phase 5 will plumb a sycl::local_accessor into the per-cell " + "callable signature.", + shared_mem); + } + if (!grid_shape.is_nonzero() || !block_shape.is_nonzero()) { + // Empty iteration. Match the CUDA backend's "non-fatal no-op" behaviour: a zero-volume + // launch is legitimate (e.g. a Boundary view on a slab whose Z extent is fully owned) + // and the CUDA driver also silently skips it. + return; + } + + const Span span = grid.spans()[relative_gpu_id]; + + // SYCL nd_range orders dimensions slowest..fastest; carbon's LaunchShape is (x, y, z) in + // the CUDA convention (x fastest). Swap when constructing the range so dim 2 maps to x, + // dim 1 to y, dim 0 to z. + const sycl::range<3> local{static_cast(block_shape.z), static_cast(block_shape.y), + static_cast(block_shape.x)}; + const sycl::range<3> global{ + static_cast(grid_shape.z) * static_cast(block_shape.z), + static_cast(grid_shape.y) * static_cast(block_shape.y), + static_cast(grid_shape.x) * static_cast(block_shape.x)}; + + try { + queue.parallel_for(sycl::nd_range<3>{global, local}, [=](sycl::nd_item<3> it) { + const int64_t ix = static_cast(it.get_global_id(2)); + const int64_t iy = static_cast(it.get_global_id(1)); + const int64_t iz = static_cast(it.get_global_id(0)); + const ValidatedIdx r = span.set_and_validate(view, ix, iy, iz); + if (!r.valid) { + return; + } + fn(span, r.idx); + }); + } catch (const sycl::exception& ex) { + ::carbon::log::throw_with_log( + "launch_dense_grid: SYCL parallel_for submission failed (relative_gpu_id={}): {}", + relative_gpu_id, ex.what()); + } +} + +} // namespace carbon::detail::dense_distributed diff --git a/include/carbon/detail/backend/sycl/dense_distributed_reduce_kernel.h b/include/carbon/detail/backend/sycl/dense_distributed_reduce_kernel.h new file mode 100644 index 00000000..8dbbd2d7 --- /dev/null +++ b/include/carbon/detail/backend/sycl/dense_distributed_reduce_kernel.h @@ -0,0 +1,138 @@ +#pragma once + +/** + * SYCL twin of @c detail/backend/cudalike/dense_distributed_reduce_kernel.h. Drives the grid-wide + * reduction through @c sycl::reduction over @c sycl::queue::parallel_for, replacing the + * CUDA backend's two-stage @c cub::BlockReduce + @c cub::DeviceReduce::Reduce pipeline + * with the single SYCL primitive — the runtime picks the appropriate per-target reduce + * tree internally (CUB on cuda, OMP on the host fallback, etc.). + * + * @par Concept + * Same @c dense_reduce_fn concept as the CUDA backend so user lambdas authored + * against the public @c DenseDistributed::make_reduce_kernel API satisfy both. The concept itself + * is host-portable (no CUDA / SYCL types) and lives at file scope. + * + * @par Why no per-block scratch + * CUDA needs a @c partials_ array (one @c T per launched block) plus a CUB temp-storage + * scratch buffer because the host orchestrates the second pass. SYCL's @c sycl::reduction + * subsumes both stages: the reduction object names the destination scalar directly and + * the runtime allocates whatever per-work-group scratch it needs internally. The + * @c reduce_kernel_impl.h SYCL branch therefore skips both allocations entirely. + */ + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +namespace carbon::detail::dense_distributed { + +/** + * Same shape as the CUDA-backend concept: callable as @c (Span, Idx) -> T returned by + * value. No @c std::is_trivially_copyable_v check, matching the CUDA side's permissive + * stance toward extended host-device lambda wrappers (clang's SYCL closures fail the + * standard trait too). + */ +template +concept dense_reduce_fn = std::is_invocable_r_v; + +/** + * Same constant the CUDA backend uses for its block size. Kept here so @c + * reduce_kernel_impl.h's ctor can publish a @c block_count() value with the same + * meaning across backends — the SYCL launch itself does NOT honour this in a literal + * sense (the runtime picks a work-group size of its own choosing inside @c parallel_for + * with @c sycl::reduction), but exposing the same constant keeps the per-test + * @c block_count assertions backend-symmetric. + */ +constexpr int kReduceBlockThreads = 256; + +/** + * @brief Launch a fused map+reduce over @c span 's iteration extent for @p view and + * write the final scalar into @p out . + * + * @tparam F Per-cell device callable returning the per-cell @c T contribution. + * @tparam T Reduction value type. + * @tparam Op Binary reduction functor; must be commutative-associative and accept + * @c op(a, b) -> T . + * + * @param queue SYCL queue to enqueue on (already pinned to the right device). + * @param span Slab geometry. + * @param view Iteration view; @c iter_extent and @c set_and_validate are both + * parameterised on this so Internal / Boundary launches index only + * their owned z-band. + * @param fn Per-cell device callable. + * @param op Reduction operator. + * @param init Identity element for @p op . + * @param out Device pointer to a single @c T receiving the final result. The + * value at @p out before the launch is ignored — + * @c sycl::property::reduction::initialize_to_identity ensures the + * reduction object writes @p init in-place before combining. + * @param total_cells Owned-cell count for @p view + * (== @c span.iter_extent(view).volume() ). + * + * @throws std::runtime_error on any @c sycl::exception escaping the @c parallel_for + * submission (signature symmetric with @c launch_dense_grid). + */ +template +inline auto +launch_dense_reduce(sycl::queue& queue, + Span span, + ::carbon::DataView view, + F fn, + Op op, + T init, + T* out, + int64_t total_cells) -> void { + if (total_cells <= 0) { + // Empty domain: write the identity directly to the output and return. Matches the + // CUDA backend's "degenerate cub::DeviceReduce::Reduce with num_items=0" branch. + try { + queue.fill(out, init, 1U); + } catch (const sycl::exception& ex) { + ::carbon::log::throw_with_log( + "launch_dense_reduce: empty-domain queue.fill failed: {}", ex.what()); + } + return; + } + + const ::carbon::int64_3d ext = span.iter_extent(view); + + try { + queue.submit([&](sycl::handler& cgh) { + auto reducer = + sycl::reduction(out, init, op, sycl::property::reduction::initialize_to_identity{}); + cgh.parallel_for(sycl::range<1>(static_cast(total_cells)), reducer, + [=](sycl::id<1> i, auto& red) { + const int64_t flat = static_cast(i[0]); + // Row-major decoding (z slowest, x fastest), same as the CUDA + // dense_grid_reduce_kernel — keeps the per-cell traversal order + // identical so any non-associative-op corner case lands on the + // same accumulation tree shape on both backends (modulo the + // runtime's own internal reduction tree, which is associative + // by contract). + const int64_t ix = flat % ext.x; + const int64_t rest = flat / ext.x; + const int64_t iy = rest % ext.y; + const int64_t iz = rest / ext.y; + const ValidatedIdx vi = span.set_and_validate(view, ix, iy, iz); + if (vi.valid) { + red.combine(fn(span, vi.idx)); + } + }); + }); + } catch (const sycl::exception& ex) { + ::carbon::log::throw_with_log( + "launch_dense_reduce: SYCL parallel_for submission failed: {}", ex.what()); + } +} + +} // namespace carbon::detail::dense_distributed diff --git a/include/carbon/detail/dense_distributed/dense_distributed.inl b/include/carbon/detail/dense_distributed/dense_distributed.inl new file mode 100644 index 00000000..6271f460 --- /dev/null +++ b/include/carbon/detail/dense_distributed/dense_distributed.inl @@ -0,0 +1,89 @@ +#pragma once + +#include +#include // brings in carbon::Buffer via system.h + +#include +#include + +#include +#include +#include + +namespace carbon { + +template +inline auto +DenseDistributed::newField(MemorySide side, + std::string name) const -> Field { + static_assert( + Components >= 1, + "DenseDistributed::newField requires Components >= 1 (1 = scalar, 3 = vector, ...). " + "The Components value sizes the per-cell SoA storage; Components == 0 would " + "allocate zero bytes per slab."); + const size_t n = gpu_count(); + if (n == 0U) { + log::throw_with_log( + "DenseDistributed::newField: gpu_count is zero; cannot allocate field buffers"); + } + // spans_[i] already carries the haloed storage layout (built in DenseDistributed's ctor from the grid's + // stencil radius), so per-component sizes and partition z-offsets come straight from it. The + // total buffer size is Components * linear_storage_elements() because Partition::linear_offset + // uses `component_id * linear_storage_elements() + ...` (SoA): a vector field with Components=3 + // needs three component planes back-to-back per slab. + const auto counts_per_gpu = system_.make_vector([&](size_t i) { + const size_t per_component = static_cast(spans_[i].linear_storage_elements()); + return per_component * static_cast(Components); + }); + + Buffer gpu_buffers{}; + if (has_device(side)) { + gpu_buffers = system_.gpu_group().buffer(counts_per_gpu); + } + + // Host mirror is allocated eagerly only for @c MemorySide::Host . For + // @c MemorySide::HostDevice the mirror is allocated lazily on first access (see + // @c Field::ensure_host_storage_ ) — the default-empty @c Buffer is passed + // through to the field's @c HostStorage where the once_flag faults it in on + // demand. For @c MemorySide::Device the mirror stays default-empty for the field's + // lifetime. + Buffer cpu_buffers{}; + if (side == MemorySide::Host) { + auto host_allocs = system_.make_vector([&](size_t i) { + return Cpu::buffer(counts_per_gpu[i]); + }); + cpu_buffers = detail::BufferGroup::from_vector(std::move(host_allocs)); + } + + // Device-bound partitions (drive Field::partitions and the device kernel launch path). + // Bind to the device buffer when present; for Host-only fields fall back to the host + // buffer so existing single-side device callers still see a non-null pointer (the + // launch will fail at the first device read of a host pointer, but that mismatch is + // covered by Field's MemorySide invariants and we do not change them here). + auto parts = system_.make_vector([&](size_t i) { + T* const ptr = has_device(side) ? gpu_buffers[i].data() : cpu_buffers[i].data(); + const auto& sp = spans_[i]; + return detail::dense_distributed::Partition(ptr, carbon::DataView::Standard, + sp.origin(), sp.spacing()); + }); + // Host-bound partitions (drive Field::host_partitions and the OpenMP host-kernel + // launch path). Populated only for @c MemorySide::Host (eager); for + // @c MemorySide::HostDevice they are built alongside the lazy @c cpu_buffers in + // @c Field::ensure_host_storage_ . Host kernels run against an unallocated mirror + // throw a clean @c std::invalid_argument at launch time with the offending side. + std::vector> host_parts; + if (side == MemorySide::Host) { + host_parts = system_.make_vector([&](size_t i) { + const auto& sp = spans_[i]; + return detail::dense_distributed::Partition( + cpu_buffers[i].data(), carbon::DataView::Standard, sp.origin(), sp.spacing()); + }); + } + return detail::dense_distributed::Field( + *this, std::move(gpu_buffers), std::move(cpu_buffers), std::move(parts), + std::move(host_parts), side, std::move(name)); +} + +} // namespace carbon diff --git a/include/carbon/detail/dense_distributed/field.h b/include/carbon/detail/dense_distributed/field.h new file mode 100644 index 00000000..64d3fbf0 --- /dev/null +++ b/include/carbon/detail/dense_distributed/field.h @@ -0,0 +1,513 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include // for carbon::Buffer + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace carbon { +class Kernel; // see +} // namespace carbon + +namespace carbon::detail::dense_distributed { + +/** + * Per-grid field storage over a @c DenseDistributed layout: owns one device @ref Buffer and one host + * @ref Buffer (either may be empty), plus one @ref Partition per GPU (pointer + slab + * offset) aligned with @ref DenseDistributed::spans. + * + * The owning @c DenseDistributed is stored @b by @b value rather than by reference: copying @c DenseDistributed is + * cheap (its @c System is a shallow handle and @c spans_ is a small vector), and storing it by + * value lets a @c Field outlive the @c DenseDistributed it was created from without dangling. Two fields + * built from the same @c DenseDistributed will see identical layouts because the underlying device/stream + * state is shared via @c System's shared-pointer based group types. + * + * A field always carries both a GPU and a CPU @ref Buffer so mirroring code has a stable + * place to write to; it is fine to leave either side default-constructed (empty) when the + * corresponding storage has not been allocated yet. @ref DenseDistributed::newField today populates the + * GPU side only and leaves the CPU side empty. + * + * @tparam T Scalar or element type stored per grid cell (same as @ref Buffer). + * @tparam Components Number of components per cell (compile-time). 1 = scalar field, + * 3 = vector field, etc. Same value carried by every @ref Partition built + * from this @c Field. + */ +template +class Field { + static_assert(Components >= 1, + "carbon::DenseDistributed::Field requires Components >= 1 " + "(1 = scalar, 3 = vector, ...). Components is the per-cell component count " + "used to size the SoA storage in DenseDistributed::newField."); + +public: + /** + * Element type stored per cell (component). Exposed so generic code (e.g. @c carbon::io) + * can recover @c T from a @c Field instance without re-deducing it. + */ + using value_type = T; + + /** + * Per-cell component count this field was instantiated with. @c 1 for scalar fields, + * @c 3 for vector fields, etc. Same role as @c value_type for the second template + * parameter. + */ + static constexpr int components = Components; + + /** + * @brief Default-construct an empty field (no grid, no buffers, no partitions). Useful as a + * placeholder before assignment from a real @ref DenseDistributed::newField. All buffer / partition + * accessors return empty containers in this state. + */ + Field() + : host_storage_(std::make_shared()) {} + + [[nodiscard]] auto + dense() const noexcept -> const DenseDistributed& { + return dense_; + } + + /** + * @brief Optional human-readable name for this field. + * + * Free-form, used purely for diagnostics: log messages, the carbon + * @c Skeleton 's DAG export ( @c Skeleton::export_dot fills node tooltips and + * edge labels with this string), and any future visualisation / reporting + * layer. Not interpreted by carbon itself — empty by default; two fields with + * the same name are not treated as the same field (identity is still the + * @c BufferGroup uid). Set at @c DenseDistributed::newField time or post-hoc via + * @ref set_name . + */ + [[nodiscard]] auto + name() const noexcept -> const std::string& { + return name_; + } + + /** + * @brief Set the field's diagnostic name. Returns @c *this so call sites can + * chain ( @c auto u = dense.newField(MemorySide::HostDevice).set_name("u"); ). + * Idempotent — overwrites the previous name. + */ + auto + set_name(std::string name) -> Field& { + name_ = std::move(name); + return *this; + } + + [[nodiscard]] auto + gpu_buffers() noexcept -> ::carbon::Buffer& { + return gpu_buffers_; + } + + [[nodiscard]] auto + gpu_buffers() const noexcept -> const ::carbon::Buffer& { + return gpu_buffers_; + } + + /** + * @brief Per-GPU host (CPU) mirror buffers. + * + * For fields built with @c MemorySide::HostDevice the host mirror is allocated @b + * lazily on first access (this method, @ref host_partitions , or + * @ref fill_owned_host ) — Neon-style "NULL_MEM until needed" so a HostDevice + * field that ends up only ever touched on the device pays no host-allocation cost, + * and a device pipeline that copies through the mirror via @ref Transfer triggers + * the host allocation exactly when it first needs it. Allocation is one-shot and + * idempotent (guarded by an internal @c std::once_flag ); all subsequent calls are + * O(1). + * + * For @c MemorySide::Host the buffers are populated eagerly in + * @c DenseDistributed::newField ; for @c MemorySide::Device this method returns the empty + * default ( @c size() == 0 ) and never allocates. + * + * @par Copy semantics + * The lazy state is held in a @c shared_ptr so all shallow copies of a + * @c Field share the same lazily-allocated host mirror — a @c HaloDistributed built from a + * @c HostDevice field, for instance, sees the same @c cpu_buffers as the field the + * user fills via @ref fill_owned_host , regardless of which copy triggers the + * first access. Same handle-sharing model as @c gpu_buffers (carbon's + * @c Buffer is itself shallow over @c BufferGroup ). + * + * @throws std::runtime_error on host-allocation failure (only fires the first time + * this is called against a @c HostDevice field). + */ + [[nodiscard]] auto + cpu_buffers() -> ::carbon::Buffer& { + ensure_host_storage_(); + return host_storage_->cpu_buffers; + } + + [[nodiscard]] auto + cpu_buffers() const -> const ::carbon::Buffer& { + ensure_host_storage_(); + return host_storage_->cpu_buffers; + } + + [[nodiscard]] auto + partitions() noexcept -> std::vector>& { + return partitions_; + } + + [[nodiscard]] auto + partitions() const noexcept -> const std::vector>& { + return partitions_; + } + + /** + * @brief Return per-GPU @ref Partition handles bound to the host (CPU) mirror. + * + * Parallel vector to @ref partitions, but every entry's pointer targets + * @c cpu_buffers()[g].data() instead of the device buffer. Empty when the field was + * built with @c MemorySide::Device (no CPU mirror was allocated). Used by the + * carbon::detail::DenseHostKernelImpl / ReduceHostKernelImpl OpenMP launch paths + * (@c DenseDistributed::make_host_kernel, @c DenseDistributed::make_host_reduce_kernel); device kernels + * keep going through @ref partitions as before. + * + * @par Lifetime + * Bound at @c Field construction (in @c DenseDistributed::newField); the partitions stay valid + * for the field's lifetime. Returning by reference avoids per-launch rebinds. + */ + [[nodiscard]] auto + host_partitions() -> std::vector>& { + ensure_host_storage_(); + return host_storage_->host_partitions; + } + + [[nodiscard]] auto + host_partitions() const -> const std::vector>& { + ensure_host_storage_(); + return host_storage_->host_partitions; + } + + /** + * Fill every owned cell on the host mirror with @p fn applied to the cell's global + * coordinates and component. Halo cells are not touched (they are filled by @c HaloDistributed at + * exchange time, or are out-of-domain in @c BoundaryModeDistributed::Open). + * + * @p fn is invoked once per (global cell, component) pair; the iteration order is the + * standard SoA traversal carbon uses elsewhere (component outermost, then z, y, x), but + * the function takes no dependency on that order so user code should treat invocations + * as independent. + * + * @tparam Fn Callable invocable as @c fn(int64_3d global, int component) returning a + * value convertible to @c T. Single-component code can simply ignore the + * second argument. + * + * @throws std::invalid_argument when the host mirror is not allocated + * (@c cpu_buffers() is empty for a field built without + * @c MemorySide::Host or @c MemorySide::HostDevice). + * + * @note This is a host-only loop; after filling, push to device via a + * @c Transfer(sys, field.cpu_buffers(), field.gpu_buffers()) on whatever stream + * you intend to launch kernels on. We do not auto-upload here so the user retains + * control over the stream and synchronisation. + */ + /** + * @brief Build a @c carbon::Kernel that runs a halo exchange for this field. + * + * Equivalent to @c Kernel::halo_distributed(HaloDistributed(*this), std::move(name)) — a + * convenience over the static factory so call sites can stay in field-land: + * + * @code + * auto pipeline = std::vector{}; + * pipeline.push_back(u.make_halo_kernel("halo_u")); + * pipeline.push_back(dense.make_kernel(jacobi_loader, 0)); // 0 bytes shared mem + * @endcode + * + * The underlying @ref HaloDistributed is constructed in place and moved into the kernel impl, so + * the returned @c Kernel keeps the field's GPU buffers alive (shallow refcount) for as + * long as it lives. + * + * Definition lives in @c carbon/kernel.h, alongside @ref DenseDistributed::make_kernel and + * @ref DenseDistributed::make_reduce_kernel. + * + * @param name Optional human-readable name (used by logs and the future skeleton's + * DAG node labels). Defaults to empty. + * + * @throws std::invalid_argument when the field has no GPU buffers and the layout + * requires inter-slab exchange (propagated from @c HaloDistributed's constructor). + */ + [[nodiscard]] auto + make_halo_kernel(std::string name = {}) const -> ::carbon::Kernel; + + /** + * @brief Build a halo @c Kernel with explicit @p stencil and @p semantic . + * + * Used by @c KernelLoader::read_stencil(field, stencil, semantic) to auto-insert + * lattice-semantic halos (e.g. LBM populations filtered by @c c_q.z sign). + */ + [[nodiscard]] auto + make_halo_kernel(std::string name, + Stencil stencil, + StencilSemantic semantic) const -> ::carbon::Kernel; + + template + void + fill_owned_host(Fn&& fn) { + static_assert(std::is_invocable_r_v, + "Field::fill_owned_host expects a callable invocable as " + "fn(carbon::int64_3d global, int component) returning T."); + + const auto& spans = dense_.spans(); + const size_t n_gpus = spans.size(); + if (n_gpus == 0U) { + return; + } + // Trigger lazy host alloc for HostDevice fields — same one-shot path + // @ref cpu_buffers / @ref host_partitions take. No-op for Host-only (already + // allocated) and Device-only (no host mirror to allocate). + ensure_host_storage_(); + auto& cpu_buffers = host_storage_->cpu_buffers; + if (cpu_buffers.size() != n_gpus) { + log::throw_with_log( + "Field::fill_owned_host: host mirror is not allocated (cpu_buffers().size()={}, " + "gpu_count={}). Construct the field with MemorySide::Host or MemorySide::HostDevice.", + cpu_buffers.size(), n_gpus); + } + + for (size_t g = 0; g < n_gpus; ++g) { + const auto& span = spans[g]; + const auto haloed = span.haloed_extent(); + const auto owned = span.logic_extent(); + const auto halo = span.halo(); + const int64_t pitch = span.xy_slab_elements(); + const int64_t x_origin = span.x_offset(); + const int64_t y_origin = span.y_offset(); + const int64_t z_origin = span.z_offset(); + const int64_t per_comp = span.linear_storage_elements(); + T* h = cpu_buffers[g].data(); + for (int c = 0; c < Components; ++c) { + const int64_t plane = static_cast(c) * per_comp; + // Owned cells live at buffer [halo, halo + owned) on every axis; the span + // offsets carry the global origin of buffer-local (0, 0, 0). + for (int64_t z = halo.z; z < halo.z + owned.z; ++z) { + const int64_t global_z = z_origin + z; + for (int64_t y = halo.y; y < halo.y + owned.y; ++y) { + const int64_t global_y = y_origin + y; + for (int64_t x = halo.x; x < halo.x + owned.x; ++x) { + const int64_t off = plane + z * pitch + y * haloed.x + x; + h[off] = static_cast(fn(::carbon::int64_3d(x_origin + x, global_y, global_z), c)); + } + } + } + } + } + } + + /** + * Like @ref fill_owned_host but also touches every local halo cell (the + * per-axis halo shell around the owned extent). Useful when a host + * pipeline wants to seed the whole storage extent — e.g. to deterministically + * zero halo bytes that the bulk @c Transfer will copy to the device, so the + * very first stencil read on the device sees defined values even before the + * first halo exchange. + * + * @c fn is invoked as @c fn(global, component) where @c global is the + * caller's global coordinate ( @c span.x_offset() + buffer_x , etc.); for halo + * cells each component is outside the slab's owned range and (under the + * corresponding open axis) outside the global grid altogether — the caller is + * responsible for deciding what value belongs there. Periodic callers should + * mirror HaloDistributed's wrap semantics by hand if they care about the values landing + * in the halo before the first exchange. + * + * @throws std::invalid_argument when the field has no host mirror + * (Device-only field, or zero GPUs). HostDevice fields trigger lazy + * host alloc on first use, same as @c fill_owned_host. + */ + template + void + fill_full_host(Fn&& fn) { + static_assert(std::is_invocable_r_v, + "Field::fill_full_host expects a callable invocable as " + "fn(carbon::int64_3d global, int component) returning T."); + + const auto& spans = dense_.spans(); + const size_t n_gpus = spans.size(); + if (n_gpus == 0U) { + return; + } + ensure_host_storage_(); + auto& cpu_buffers = host_storage_->cpu_buffers; + if (cpu_buffers.size() != n_gpus) { + log::throw_with_log( + "Field::fill_full_host: host mirror is not allocated (cpu_buffers().size()={}, " + "gpu_count={}). Construct the field with MemorySide::Host or MemorySide::HostDevice.", + cpu_buffers.size(), n_gpus); + } + + for (size_t g = 0; g < n_gpus; ++g) { + const auto& span = spans[g]; + const auto haloed = span.haloed_extent(); + const int64_t pitch = span.xy_slab_elements(); + const int64_t x_origin = span.x_offset(); + const int64_t y_origin = span.y_offset(); + const int64_t z_origin = span.z_offset(); + const int64_t per_comp = span.linear_storage_elements(); + T* h = cpu_buffers[g].data(); + for (int c = 0; c < Components; ++c) { + const int64_t plane = static_cast(c) * per_comp; + // Walk the full storage extent; each axis uses the span offset so the + // callback sees the same global-coordinate space as the device path. + for (int64_t z = 0; z < haloed.z; ++z) { + const int64_t global_z = z_origin + z; + for (int64_t y = 0; y < haloed.y; ++y) { + const int64_t global_y = y_origin + y; + for (int64_t x = 0; x < haloed.x; ++x) { + const int64_t off = plane + z * pitch + y * haloed.x + x; + h[off] = static_cast(fn(::carbon::int64_3d(x_origin + x, global_y, global_z), c)); + } + } + } + } + } + } + +private: + /** + * The only real construction path. Marked private + friended to @ref ::carbon::DenseDistributed so user + * code cannot bypass @ref DenseDistributed::newField (which is responsible for sizing buffers from + * @c spans()[i].linear_storage_elements() and binding the @ref Partition vector consistently). + * + * @p partitions must already be fully bound by the caller: each @ref Partition should carry a + * pointer into the matching buffer. @ref DenseDistributed::newField is currently the only caller. + * + * @param dense Grid layout this field is defined on (moved into the field). + * @param gpu_buffers One device buffer per GPU, typically from @ref GpuGroup::buffer. May be + * empty (default-constructed) when no device storage has been allocated. + * @param cpu_buffers One host buffer per GPU (same indexing as @p gpu_buffers). May be empty + * (default-constructed) when no host mirror has been allocated. + * @param partitions One @ref Partition per GPU, already bound by the caller against + * the side that hosts the data (device when present, otherwise + * host) — drives @ref partitions / @c loader(field) for device + * kernels. + * @param host_partitions One @ref Partition per GPU bound to the matching @c cpu_buffers + * entry, OR an empty vector when no host mirror was allocated. + * Drives @ref host_partitions / OpenMP host kernels. + */ + Field(DenseDistributed dense, + ::carbon::Buffer gpu_buffers, + ::carbon::Buffer cpu_buffers, + std::vector> partitions, + std::vector> host_partitions, + ::carbon::MemorySide side, + std::string name = {}) + : dense_(std::move(dense)), + gpu_buffers_(std::move(gpu_buffers)), + partitions_(std::move(partitions)), + side_(side), + name_(std::move(name)), + host_storage_(std::make_shared(std::move(cpu_buffers), + std::move(host_partitions))) {} + + friend class ::carbon::DenseDistributed; + + /** + * @brief Shared, lazily-initialisable container for the host (CPU) mirror. + * + * Held by @c shared_ptr from @ref Field so all shallow copies of a field point at + * the same instance — copying a @c HostDevice field into a @c HaloDistributed and triggering + * the host alloc through either copy fills the @b same @c cpu_buffers and + * @c host_partitions , and a re-trigger from another copy short-circuits through + * the shared @c init_flag . Mirrors carbon's "shared shallow handle" pattern used + * by @c BufferGroup and @c GpuGroup . + * + * For non- @c HostDevice fields the struct is still allocated (so accessors return + * a valid reference even on Device-only fields) but stays empty — the once_flag is + * never tripped because @c ensure_host_storage_ short-circuits on @c side_ . + */ + struct HostStorage { + ::carbon::Buffer cpu_buffers{}; + std::vector> host_partitions{}; + std::once_flag init_flag{}; + + HostStorage() = default; + + HostStorage(::carbon::Buffer cpu_b, + std::vector> host_p) + : cpu_buffers(std::move(cpu_b)), + host_partitions(std::move(host_p)) {} + }; + + /** + * @brief Idempotent on-demand allocation of the host mirror for + * @c MemorySide::HostDevice fields. + * + * Called from every host-side accessor ( @c cpu_buffers , @c host_partitions , + * @c fill_owned_host ) so the user does not have to remember to opt in. Guarded by + * the shared @c HostStorage::init_flag so concurrent first-accessors race safely + * and only one wins. + * + * No-op for: + * - @c MemorySide::Device — host mirror is intentionally absent (returned + * @c cpu_buffers stays empty). + * - @c MemorySide::Host — host mirror is allocated eagerly in @c DenseDistributed::newField + * and the once_flag is never tripped. + * - Default-constructed fields — @c host_storage_ is null and accessors short- + * circuit before reaching @c HostStorage . + * - Empty layouts ( @c dense_.gpu_count() == 0 ). + * + * The allocation mirrors @c DenseDistributed::newField 's host-side path verbatim: per-GPU + * @c Cpu::buffer sized from @c spans()[i].linear_storage_elements() * + * @c Components , then a parallel @c Partition vector bound to the + * matching CPU pointer. + */ + auto + ensure_host_storage_() const -> void { + if (side_ != ::carbon::MemorySide::HostDevice) { + return; + } + HostStorage& storage = *host_storage_; + std::call_once(storage.init_flag, [this, &storage]() { + const auto& spans = dense_.spans(); + const size_t n_gpus = spans.size(); + if (n_gpus == 0U) { + return; + } + auto host_allocs = dense_.system().make_vector([&](size_t i) { + const size_t per_component = static_cast(spans[i].linear_storage_elements()); + return ::carbon::Cpu::buffer(per_component * static_cast(Components)); + }); + storage.cpu_buffers = ::carbon::detail::BufferGroup::from_vector(std::move(host_allocs)); + storage.host_partitions = dense_.system().make_vector([&storage, this](size_t i) { + const auto& sp = dense_.spans()[i]; + return ::carbon::detail::dense_distributed::Partition( + storage.cpu_buffers[i].data(), ::carbon::DataView::Standard, sp.origin(), sp.spacing()); + }); + }); + } + + DenseDistributed dense_; + ::carbon::Buffer gpu_buffers_{}; + std::vector> partitions_{}; + ::carbon::MemorySide side_{::carbon::MemorySide::Device}; + // Diagnostic-only label — see @ref name / @ref set_name . Plain by-value string; + // copies/moves alongside the rest of the field, so a Field passed by value into + // a HaloDistributed or captured into a Kernel takes its name with it. + std::string name_{}; + // Shared host-mirror state — see @ref HostStorage . Always non-null (allocated by + // both the default ctor and the friended ctor) so accessors never need a null + // check; for @c MemorySide::Device it stays default-empty. + mutable std::shared_ptr host_storage_{}; +}; + +} // namespace carbon::detail::dense_distributed diff --git a/include/carbon/detail/dense_distributed/kernel.h b/include/carbon/detail/dense_distributed/kernel.h new file mode 100644 index 00000000..0456b985 --- /dev/null +++ b/include/carbon/detail/dense_distributed/kernel.h @@ -0,0 +1,18 @@ +#pragma once + +/** + * Backend-dispatching shim for the dense-grid kernel function template (the per-cell + * device callable concept @c dense_kernel_fn and the @c __global__ launcher under CUDA). + * The SYCL counterpart will provide the same concept and a SYCL-friendly callable + * structure (no @c __global__) used by @c q.parallel_for at the launch site. + */ + +#include + +#if CARBON_BACKEND_IS_CUDALIKE +#include +#elif CARBON_BACKEND_IS_SYCL +#include +#else +#error "carbon: no compute backend selected (see carbon/detail/backend/select.h)." +#endif diff --git a/include/carbon/detail/dense_distributed/launch.h b/include/carbon/detail/dense_distributed/launch.h new file mode 100644 index 00000000..feb95216 --- /dev/null +++ b/include/carbon/detail/dense_distributed/launch.h @@ -0,0 +1,17 @@ +#pragma once + +/** + * Backend-dispatching shim for the dense-grid kernel launch helper (see + * @c carbon::detail::dense_distributed::launch_dense_grid). Hides the launch-syntax difference + * between @c <<<...>>> (CUDA) and @c q.parallel_for (SYCL). + */ + +#include + +#if CARBON_BACKEND_IS_CUDALIKE +#include +#elif CARBON_BACKEND_IS_SYCL +#include +#else +#error "carbon: no compute backend selected (see carbon/detail/backend/select.h)." +#endif diff --git a/include/carbon/detail/dense_distributed/layout.h b/include/carbon/detail/dense_distributed/layout.h new file mode 100644 index 00000000..b29a26da --- /dev/null +++ b/include/carbon/detail/dense_distributed/layout.h @@ -0,0 +1,130 @@ +#pragma once + +/** + * @file layout.h + * @brief Pure host-side decomposition arithmetic for @ref DenseDistributed. + * + * Everything that decides *which cells a rank owns and how thick its halo is* lives here as plain + * functions of (global extent, @ref ProcessGrid, boundary mode, stencil). @c DenseDistributed + * builds its per-GPU @c Span from these, and the unit tests call the very same functions to check + * the slab / pencil / brick geometry without a GPU or MPI. + * + * Splitting rule: along an axis with @c P parts, the first @c n % P coordinates receive + * @c n / P + 1 layers and the rest @c n / P. + * + * Halo rule (storage thickness per side): + * - An axis carries a halo iff it is split (@c P > 1) or periodic; its thickness is the stencil + * radius along that axis (@c Stencil::radius3). + * - Slab layouts (@c Px == Py == 1) keep carbon's historical Z halo: the isotropic + * @c Stencil::radius, always present on Z, with X/Y halos only when those axes are periodic. + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace carbon::detail::dense_distributed { + +/** Split @p n layers over @p num_parts coordinates as evenly as possible (earlier ones get +1). */ +[[nodiscard]] inline auto +split_extent(int64_t n, + size_t num_parts) -> std::vector { + if (n < 0) { + carbon::log::throw_with_log( + "DenseDistributed: extent must be non-negative (n={})", n); + } + if (static_cast(n) > static_cast(std::numeric_limits::max())) { + carbon::log::throw_with_log( + "DenseDistributed: extent too large for this platform (n={})", n); + } + const size_t n_u = static_cast(n); + if (num_parts == 0U) { + return {}; + } + std::vector counts(num_parts); + const size_t base = n_u / num_parts; + const size_t rem = n_u % num_parts; + for (size_t i = 0; i < num_parts; ++i) { + counts[i] = base + (i < rem ? 1U : 0U); + } + return counts; +} + +/** True for the historical Z-slab layout: @c Px == Py == 1 and neither X nor Y is periodic. */ +[[nodiscard]] inline auto +is_legacy_slab(const ProcessGrid& pg, + BoundaryModeDistributed boundary) noexcept -> bool { + return pg.is_slab() && !is_periodic(boundary, Axis::X) && !is_periodic(boundary, Axis::Y); +} + +/** Per-side halo thickness (uniform across ranks) for @p pg / @p boundary / @p stencil. */ +[[nodiscard]] inline auto +halo_extent(const ProcessGrid& pg, + BoundaryModeDistributed boundary, + const Stencil& stencil) -> int64_3d { + const int32_3d dims = pg.dims(); + const int32_3d radius3 = stencil.radius3(); + const auto axis_halo = [&](int32_t radius, int32_t parts, Axis axis) -> int64_t { + return (parts > 1 || is_periodic(boundary, axis)) ? static_cast(radius) : 0; + }; + if (is_legacy_slab(pg, boundary)) { + return int64_3d{0, 0, static_cast(stencil.radius())}; + } + return int64_3d{ + axis_halo(radius3.x, dims.x, Axis::X), + axis_halo(radius3.y, dims.y, Axis::Y), + pg.is_slab() ? static_cast(stencil.radius()) : axis_halo(radius3.z, dims.z, Axis::Z), + }; +} + +/** Geometry of the chunk owned by one process-grid coordinate. */ +struct RankChunk { + /** Owned (non-halo) extent. */ + int64_3d owned{}; + /** Global coordinate of the first *haloed* cell (i.e. owned origin minus the halo). */ + int64_3d offset{}; + /** Halo thickness per side. */ + int64_3d halo{}; + /** Storage extent: owned + 2 * halo on each axis. */ + int64_3d haloed{}; + /** Elements per XY plane (@c haloed.x * haloed.y). */ + int64_t xy_pitch{}; +}; + +/** Chunk owned by process coordinate @p coords of @p pg over @p global, with halo @p halo. */ +[[nodiscard]] inline auto +rank_chunk(const int64_3d& global, + const ProcessGrid& pg, + int32_3d coords, + const int64_3d& halo) -> RankChunk { + const int32_3d dims = pg.dims(); + const auto locate = [](int64_t n, int32_t parts, int32_t coord) -> std::pair { + const std::vector counts = split_extent(n, static_cast(parts)); + int64_t prefix = 0; + for (int32_t i = 0; i < coord; ++i) { + prefix += static_cast(counts[static_cast(i)]); + } + return {static_cast(counts[static_cast(coord)]), prefix}; + }; + const auto [nx, ox] = locate(global.x, dims.x, coords.x); + const auto [ny, oy] = locate(global.y, dims.y, coords.y); + const auto [nz, oz] = locate(global.z, dims.z, coords.z); + + RankChunk c; + c.owned = {nx, ny, nz}; + c.halo = halo; + c.offset = {ox - halo.x, oy - halo.y, oz - halo.z}; + c.haloed = {nx + 2 * halo.x, ny + 2 * halo.y, nz + 2 * halo.z}; + c.xy_pitch = c.haloed.x * c.haloed.y; + return c; +} + +} // namespace carbon::detail::dense_distributed diff --git a/include/carbon/detail/dense_distributed/partition.h b/include/carbon/detail/dense_distributed/partition.h new file mode 100644 index 00000000..8c21e417 --- /dev/null +++ b/include/carbon/detail/dense_distributed/partition.h @@ -0,0 +1,302 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace carbon::detail::dense_distributed { + +/** + * Trusted cell accessor: one @ref Span::linear_offset for the centre, then neighbour reads via + * constant strides (same contract as @ref Partition::read_pull ). User code never constructs an + * @ref Idx for neighbours. + */ +template +class Cursor { +public: + CARBON_HD constexpr Cursor(T* base, + int32_t y_stride, + int32_t z_stride, + int64_t component_stride +#ifndef NDEBUG + , + int64_3d centre, + int64_3d haloed +#endif + ) noexcept + : base_(base), + y_stride_(y_stride), + z_stride_(z_stride), + component_stride_(component_stride) +#ifndef NDEBUG + , + centre_(centre), + haloed_(haloed) +#endif + { + } + + [[nodiscard]] CARBON_HD constexpr auto + value(int component_id = 0) const noexcept -> const T& { + return base_[component_offset_(component_id)]; + } + + CARBON_HD constexpr auto + write(T value, + int component_id = 0) const noexcept -> void { + base_[component_offset_(component_id)] = value; + } + + [[nodiscard]] CARBON_HD constexpr auto + pull(int8_3d offset, + int component_id = 0) const noexcept -> const T& { +#ifndef NDEBUG + const int64_t bx = centre_.x + static_cast(offset.x); + const int64_t by = centre_.y + static_cast(offset.y); + const int64_t bz = centre_.z + static_cast(offset.z); + assert(bx >= 0 && bx < haloed_.x && by >= 0 && by < haloed_.y && bz >= 0 && bz < haloed_.z); +#endif + const int64_t delta = static_cast(offset.x) + + static_cast(offset.y) * static_cast(y_stride_) + + static_cast(offset.z) * static_cast(z_stride_); + return base_[component_offset_(component_id) + delta]; + } + +private: + [[nodiscard]] CARBON_HD constexpr auto + component_offset_(int component_id) const noexcept -> int64_t { + if constexpr (Components == 1) { + (void)component_id; + return 0; + } + return static_cast(component_id) * component_stride_; + } + + T* base_{}; + int32_t y_stride_{}; + int32_t z_stride_{}; + int64_t component_stride_{}; +#ifndef NDEBUG + int64_3d centre_{}; + int64_3d haloed_{}; +#endif +}; + +/** + * Lightweight view of a partitioned slab: a raw pointer to elements of type @p T tagged with the + * @ref DataView region this view targets (Standard / Internal / Boundary). The non-type template + * parameter @p Components is the compile-time number of components stored per cell (1 for a + * scalar field, 3 for a vector field, etc.); use @c static_value to read it back. + * + * Global chunk metadata (per-axis origins, halo radius, owned vs. haloed extent, layout strides) + * lives on @ref Span and is shared by every field over the same grid/chunk. Each partition also + * carries a copy of the grid's physical @ref origin and @ref spacing (same values as on the + * matching @c Span) so device code can read world metadata from the partition alone. + * + * Does not own @c ptr; lifetime of the pointed-to storage must exceed use of this object. + * + * @tparam T Element or payload type referenced by @ref ptr. + * @tparam Components Number of components per cell (compile-time). Same value carried by the + * @ref Field this partition was built from. + */ +template +class Partition { + static_assert(Components >= 1, + "carbon::DenseDistributed::Partition requires Components >= 1 " + "(1 = scalar, 3 = vector, ...). Components matches the value carried by the " + "DenseDistributed::Field this partition was built from."); + +public: + /** Compile-time component count from the class template parameter (same as @p Components). */ + static constexpr int static_value = Components; + + constexpr Partition() noexcept = default; + + /** + * Binds @p ptr and the partition's @ref DataView. + * @param p Raw pointer to storage; may be null. + * @param view Region this partition targets; defaults to DataView::Standard. + * @param origin Physical-space origin (copied from the owning grid's @c Span). + * @param spacing Isotropic cell spacing (copied from the @c Span). + */ + constexpr explicit Partition(T* p, + carbon::DataView view = carbon::DataView::Standard, + float32_3d origin = {}, + float spacing = 1.0F) noexcept + : ptr_(p), + data_view_(view), + origin_(origin), + spacing_(spacing) {} + + [[nodiscard]] CARBON_HD constexpr auto + ptr() const noexcept -> T* { + return ptr_; + } + + [[nodiscard]] CARBON_HD constexpr auto + data_view() const noexcept -> carbon::DataView { + return data_view_; + } + + /** Physical-space origin at global cell @c (0,0,0) (cell-corner convention). */ + [[nodiscard]] CARBON_HD constexpr auto + origin() const noexcept -> float32_3d { + return origin_; + } + + /** Isotropic cell spacing (same convention as @ref Span::spacing). */ + [[nodiscard]] CARBON_HD constexpr auto + spacing() const noexcept -> float { + return spacing_; + } + + /** + * Read the element at cell @p idx for component @p component_id using the layout + * described by @p span (SoA dense, matching Neon's @c dPartition::operator()). Offset math + * lives on @ref Span::linear_offset so all fields over the same slab share it. + * + * Callable from host and device. No bounds checking (matches Neon's operator() for + * performance); caller is responsible for ensuring the indices are valid. + */ + [[nodiscard]] CARBON_HD constexpr auto + read(const Span& span, + const Idx& idx, + int component_id) const noexcept -> const T& { + return ptr_[span.linear_offset(idx, component_id)]; + } + + /** + * Counterpart to @ref read: stores @p value at cell @p idx for component @p component_id. + * Same SoA layout (offset math via @ref Span::linear_offset) so a kernel that reads via + * @ref read writes back through the same coordinate system. + * + * Marked @c const because @c Partition is conceptually a non-owning view onto the buffer + * (parallel to @c std::span::operator[] being @c const): it is the @b view that is + * unchanged by the call, while the pointed-to storage is mutated. Callable from host and + * device. No bounds checking; caller ensures the indices are valid. + */ + CARBON_HD constexpr auto + write(const Span& span, + const Idx& idx, + int component_id, + T value) const noexcept -> void { + ptr_[span.linear_offset(idx, component_id)] = value; + } + + /** + * Read the cell at @p idx + @p offset for component @p component_id, returning + * @ref NeighbourValue so the caller can distinguish in-domain reads from out-of-domain + * accesses without dropping into manual boundary checks. + * + * @c valid is @c true iff the neighbour lies inside the @b global Cartesian grid @b and is + * reachable from this chunk's storage. Two checks combine: + * + * - @b Buffer (storage) bounds: @c (cell + offset) must be inside + * @c span.haloed_extent() on every axis, which bounds the offset to the per-axis halo. + * - @b Global-domain bounds: even in-buffer halo cells may live outside the global grid on an + * open face. Such reads return @c valid = false even though the storage exists. On a + * periodic axis the wrapped halo was filled by @c HaloDistributed, so the read is valid. + * + * Interior chunk boundaries alias the neighbour's first owned layer; once halos are + * exchanged the read returns @c valid = true. + * + * Same SoA layout as @ref read; offset math via @ref Span::linear_offset. Mirrors Neon's + * @c dPartition::getNghData; the offset type is @c int8_3d (radius up to ±127, common + * stencil sizes) which is small enough to keep stencil parameters in registers. + * + * The shape-and-bounds half of the work lives in @c detail::dense_distributed::neighbour_idx (internal, + * not user-facing); this member is purely the data-access half on top of it. That split + * keeps @c Partition grid-family agnostic — the same template will work for sparse / block + * grids, with each family providing its own @c neighbour_idx overload. + * + * Callable from host and device. @c CARBON_HD + @c constexpr so the compiler can inline + * neighbour reads inside a stencil kernel without indirection. + */ + [[nodiscard]] CARBON_HD constexpr auto + neighbour(const Span& span, + const Idx& idx, + int8_3d offset, + int component_id) const noexcept -> NeighbourValue { + const NeighbourIdx r = neighbour_idx(span, idx, offset); + if (!r.valid) { + return {}; + } + return NeighbourValue{ptr_[span.linear_offset(r.idx, component_id)], true}; + } + + /** + * @b Trusted neighbour read: return the element at @p idx + @p offset for component + * @p component_id with @b no validity branch. The caller guarantees the neighbour is + * in-buffer (e.g. it precomputed a wall / active mask so the non-boundary branch can + * never address out-of-buffer storage). Mirrors Neon's @c dPartition::pull, which + * likewise reads through raw offset arithmetic once the kernel has proven the source + * index is in-buffer; skipping the per-neighbour bounds check is what lets a pull-stream + * LBM kernel hit the same bandwidth as a hand-rolled kernel. + * + * For the aggregated dense grid the neighbour @ref Idx is just the cell shifted by + * @p offset (all buffer metadata lives on @ref Span), so this is a single + * @ref Span::linear_offset. The @c dense_disg twin does the same call shape but recomputes + * its per-region pitch fields for the shifted cell — that is exactly why this member is + * the grid-generic pull primitive: a kernel written against @c read_pull runs unchanged on + * either dense family. No bounds checking; the result is defined only when the neighbour + * is in-buffer. + */ + [[nodiscard]] CARBON_HD constexpr auto + read_pull(const Span& span, + const Idx& idx, + int8_3d offset, + int component_id) const noexcept -> const T& { + const int64_3d cell = idx.cell(); + const Idx shifted(cell.x + static_cast(offset.x), + cell.y + static_cast(offset.y), + cell.z + static_cast(offset.z)); + return ptr_[span.linear_offset(shifted, component_id)]; + } + + /** + * @brief Trusted cell cursor at @p idx : one linear_offset for the centre, then @ref Cursor::pull + * for neighbours. Same in-buffer contract as @ref read_pull . + */ + [[nodiscard]] CARBON_HD constexpr auto + cursor(const Span& span, + const Idx& idx) const noexcept -> Cursor { +#ifndef NDEBUG + return Cursor{ptr_ + span.linear_offset(idx, 0), + static_cast(span.haloed_extent().x), + static_cast(span.xy_slab_elements()), + span.linear_storage_elements(), + idx.cell(), + span.haloed_extent()}; +#else + return Cursor{ + ptr_ + span.linear_offset(idx, 0), static_cast(span.haloed_extent().x), + static_cast(span.xy_slab_elements()), span.linear_storage_elements()}; +#endif + } + + constexpr void + reset(T* p = nullptr, + carbon::DataView view = carbon::DataView::Standard, + float32_3d origin = {}, + float spacing = 1.0F) noexcept { + ptr_ = p; + data_view_ = view; + origin_ = origin; + spacing_ = spacing; + } + +private: + T* ptr_{}; + carbon::DataView data_view_{carbon::DataView::Standard}; + float32_3d origin_{}; + float spacing_{1.0F}; +}; + +} // namespace carbon::detail::dense_distributed diff --git a/include/carbon/detail/dense_distributed/reduce_kernel.h b/include/carbon/detail/dense_distributed/reduce_kernel.h new file mode 100644 index 00000000..fc20fec6 --- /dev/null +++ b/include/carbon/detail/dense_distributed/reduce_kernel.h @@ -0,0 +1,16 @@ +#pragma once + +/** + * Backend-dispatching shim for the dense-grid reduction kernel (block-reduction primitive + * + CUB-side glue under CUDA; @c sycl::reduction equivalent under SYCL). + */ + +#include + +#if CARBON_BACKEND_IS_CUDALIKE +#include +#elif CARBON_BACKEND_IS_SYCL +#include +#else +#error "carbon: no compute backend selected (see carbon/detail/backend/select.h)." +#endif diff --git a/include/carbon/detail/dense_distributed/span.h b/include/carbon/detail/dense_distributed/span.h new file mode 100644 index 00000000..d886bc31 --- /dev/null +++ b/include/carbon/detail/dense_distributed/span.h @@ -0,0 +1,474 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include + +namespace carbon::detail::dense_distributed { + +/** + * Cell index shared with the Z-slab @c Dense family: @c Idx carries only the buffer-relative cell + * coordinates, so it has no per-family state and a second copy of the type would add nothing. + */ +using Idx = ::carbon::detail::dense::Idx; + +/** + * Result of @ref Span::set_and_validate: the buffer-relative @ref Idx and a flag indicating + * whether the originating launch-grid thread fell inside @c iter_extent(view). Aliased to the + * cross-family @c carbon::detail::Validated template (see + * @c include/carbon/detail/validated_idx.h ) so every grid family's + * value-returning @c set_and_validate shares the same return carrier shape; + * the local @c ValidatedIdx spelling is preserved as a source-compat alias. + */ +using ValidatedIdx = ::carbon::detail::Validated; + +/** + * Layout of one GPU's dense subvolume expressed in @b storage (haloed) terms: per-axis haloed + * extent, elements per XY plane (pitch in elements), global coordinate where the chunk's storage + * starts, and the halo thickness on each axis. + * + * Convention: + * - @c haloed_extent() is the full storage extent, equal to + * @c owned + 2 * halo() component-wise. When the grid has no stencil, @c halo() is zero and + * @c haloed_extent() equals @ref logic_extent(). + * - @c offset() is the @b buffer origin: buffer-local @c (0,0,0) maps to global + * @c offset(); the lower halo on each axis occupies @c [offset(), offset() + halo()), owned + * cells follow, and the upper halo the remaining @c halo() layers. + * - @c xy_slab_elements() is the number of T-sized elements between two adjacent z planes in + * the haloed buffer. It is at least @c haloed_extent().x * haloed_extent().y ; halos are + * included in the extent rather than encoded as pitch padding. + * - @c global_extent() is the full Cartesian grid extent shared by every chunk. It is needed to + * distinguish, in @c Partition::neighbour, an in-buffer halo cell that maps to a real global + * cell (interior chunk boundary) from one that lies outside the global domain (an open face). + * + * Kernels that iterate owned cells should drive their loop bounds from @ref logic_extent(). + * Pointer math (@ref linear_offset, @ref linear_storage_elements) uses the haloed view. + */ +class Span { + int64_3d haloed_extent_{}; + int64_3d global_extent_{}; + int64_t xy_slab_elements_{}; + int64_3d offset_{}; + int64_3d halo_{}; + BoundaryModeDistributed boundary_mode_{BoundaryModeDistributed::Open}; + float32_3d origin_{}; + float spacing_{1.0F}; + +public: + CARBON_HD constexpr Span() noexcept = default; + + CARBON_HD constexpr Span(int64_3d haloed_extent, + int64_3d global_extent, + int64_t xy_slab_elements, + int64_3d offset, + int64_3d halo = {}, + BoundaryModeDistributed boundary_mode = BoundaryModeDistributed::Open, + float32_3d origin = {}, + float spacing = 1.0F) noexcept + : haloed_extent_(haloed_extent), + global_extent_(global_extent), + xy_slab_elements_(xy_slab_elements), + offset_(offset), + halo_(halo), + boundary_mode_(boundary_mode), + origin_(origin), + spacing_(spacing) {} + + /** + * Construct a span over its @b storage (haloed) extent. + * + * @param haloed_extent Storage extent: @c owned + 2 * halo(), component-wise. When + * @p halo is zero this equals @ref logic_extent(). + * @param global_extent Full Cartesian grid extent shared by every chunk. Used by + * @c Partition::neighbour to distinguish in-domain reads from + * out-of-domain halo cells on an open face. + * @param xy_slab_elements Elements per XY plane (pitch, in elements). + * @param offset Global coordinate of buffer-local @c (0,0,0). + * @param halo Halo thickness on each axis; must satisfy + * @c logic_extent() >= 0. Default 0 (no halo). + * @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 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}. */ + 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, + float32_3d origin = {}, + float spacing = 1.0F) noexcept + : Span(haloed_extent, + global_extent, + xy_slab_elements, + int64_3d{0, + 0, + z_offset}, + int64_3d{0, + 0, + halo_z}, + boundary_mode, + origin, + spacing) {} + + /** Storage extent (includes halo layers on every axis where @ref halo() is non-zero). */ + [[nodiscard]] CARBON_HD constexpr auto + haloed_extent() const noexcept -> int64_3d { + return haloed_extent_; + } + + /** Full Cartesian grid extent shared by every slab. */ + [[nodiscard]] CARBON_HD constexpr auto + global_extent() const noexcept -> int64_3d { + return global_extent_; + } + + /** + * Owned-cell extent: @c haloed_extent() - 2 * halo(), component-wise. Independent of + * @ref DataView — this is the storage-side owned region and is the same for every view. + * Use @ref iter_extent if you need the iteration shape for a specific @ref DataView. + */ + [[nodiscard]] CARBON_HD constexpr auto + logic_extent() const noexcept -> int64_3d { + return int64_3d{haloed_extent_.x - 2 * halo_.x, haloed_extent_.y - 2 * halo_.y, + haloed_extent_.z - 2 * halo_.z}; + } + + /** + * Iteration extent for @p view, i.e. the shape of the launch grid the user should iterate + * over (paired with @ref set_and_validate to translate a thread (ix, iy, iz) into a + * buffer-relative @ref Idx). The split is purely geometric — there is no special-casing on + * the GPU/rank count, so @c "Internal + Boundary == Standard" holds in single- and multi-GPU + * runs alike. + * + * - @c Standard: @c logic_extent(). Covers every owned cell exactly once. + * - @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: legacy z-only chunks ( @c halo.x == halo.y == 0 ) use the compact + * @c 2 * halo.z z-band domain; multi-axis chunks iterate the full owned extent and + * @ref set_and_validate rejects interior cells. + * + * The ranges are non-overlapping, so dispatching Internal and Boundary back-to-back + * (in any order) writes every owned cell exactly once — same coverage as a single + * Standard launch. + */ + [[nodiscard]] CARBON_HD constexpr auto + iter_extent(::carbon::DataView view) const noexcept -> int64_3d { + const int64_3d owned = logic_extent(); + switch (view) { + case ::carbon::DataView::Standard: + return owned; + + case ::carbon::DataView::Internal: { + const int64_t ix = owned.x - 2 * halo_.x; + const int64_t iy = owned.y - 2 * halo_.y; + const int64_t iz = owned.z - 2 * halo_.z; + return int64_3d{ix > 0 ? ix : 0, iy > 0 ? iy : 0, iz > 0 ? iz : 0}; + } + + case ::carbon::DataView::Boundary: + if (halo_.x == 0 && halo_.y == 0) { + return int64_3d{owned.x, owned.y, halo_.z > 0 ? 2 * halo_.z : 0}; + } + return owned; + } + return owned; + } + + /** Elements per XY plane (pitch in elements), same for halo and owned layers. */ + [[nodiscard]] CARBON_HD constexpr auto + xy_slab_elements() const noexcept -> int64_t { + return xy_slab_elements_; + } + + [[nodiscard]] CARBON_HD constexpr auto + offset() const noexcept -> int64_3d { + return offset_; + } + + [[nodiscard]] CARBON_HD constexpr auto + x_offset() const noexcept -> int64_t { + return offset_.x; + } + + [[nodiscard]] CARBON_HD constexpr auto + y_offset() const noexcept -> int64_t { + return offset_.y; + } + + [[nodiscard]] CARBON_HD constexpr auto + z_offset() const noexcept -> int64_t { + return offset_.z; + } + + [[nodiscard]] CARBON_HD constexpr auto + halo() const noexcept -> int64_3d { + return halo_; + } + + [[nodiscard]] CARBON_HD constexpr auto + halo_x() const noexcept -> int64_t { + return halo_.x; + } + + [[nodiscard]] CARBON_HD constexpr auto + halo_y() const noexcept -> int64_t { + return halo_.y; + } + + [[nodiscard]] CARBON_HD constexpr auto + halo_z() const noexcept -> int64_t { + return halo_.z; + } + + /** Boundary semantics this span was built with (propagated from the owning @c DenseDistributed). */ + [[nodiscard]] CARBON_HD constexpr auto + boundary_mode() const noexcept -> BoundaryModeDistributed { + return boundary_mode_; + } + + /** Physical-space origin at global integer cell @c (0,0,0) (cell-corner convention). */ + [[nodiscard]] CARBON_HD constexpr auto + origin() const noexcept -> float32_3d { + return origin_; + } + + /** Isotropic spacing between adjacent cell corners along @c x, @c y, and @c z. */ + [[nodiscard]] CARBON_HD constexpr auto + spacing() const noexcept -> float { + return spacing_; + } + + /** + * Contiguous element count for this slab's storage: @c haloed_extent().z layers times + * @c xy_slab_elements() per layer. Matches the buffer sizing used by + * @c DenseDistributed::newField (lower halo + owned + upper halo). + */ + [[nodiscard]] CARBON_HD constexpr auto + linear_storage_elements() const noexcept -> int64_t { + return haloed_extent_.z * xy_slab_elements_; + } + + /** + * Canonical (cross-family) spelling for the per-component buffer pitch: + * same value as the no-arg @ref linear_storage_elements above, named to + * match @c block::Span::per_card_elements (carbon's "per cardinality + * plane" terminology) and @c dense_disg::Span::per_card_elements . New + * cross-grid code should prefer this spelling; the historical no-arg + * @c linear_storage_elements stays as a source-compat alias. + */ + [[nodiscard]] CARBON_HD constexpr auto + per_card_elements() const noexcept -> int64_t { + return linear_storage_elements(); + } + + /** + * Total per-slab buffer elements for @p components cardinality planes — + * @c per_card_elements() * components . Mirrors the @c (int) -arity overload + * on @c block::Span and @c dense_disg::Span so a generic kernel impl that + * wants the full per-slab allocation size can spell it the same way across + * grid families. + */ + [[nodiscard]] CARBON_HD constexpr auto + linear_storage_elements(int components) const noexcept -> int64_t { + return per_card_elements() * static_cast(components); + } + + /** + * Build an @ref Idx for local coordinates @p (ix, iy, iz). Typical use: pass indices derived + * from @c blockIdx / @c threadIdx. The slab's z-origin is not carried on @ref Idx; use + * @ref global_location on this span when global coordinates are needed. + */ + [[nodiscard]] CARBON_HD constexpr auto + make_idx(int64_t ix, + int64_t iy, + int64_t iz) const noexcept -> Idx; + + /** Same as @ref make_idx(cell.x, cell.y, cell.z). */ + [[nodiscard]] CARBON_HD constexpr auto + make_idx(int64_3d cell) const noexcept -> Idx; + + /** + * Global location of @p idx within the grid: @c cell + offset(), component-wise. + */ + [[nodiscard]] CARBON_HD constexpr auto + global_location(const Idx& idx) const noexcept -> int64_3d; + + /** + * Element offset (in units of @c T) from the start of a partition buffer to the cell at @p idx + * for component @p component_id, using this span's SoA dense layout: + * @c component_id * linear_storage_elements() + iz * xy_slab_elements() + iy * haloed_extent().x + ix. + * + * Matches Neon's @c dPartition::getPitch with its default pitch. No bounds checking. + */ + [[nodiscard]] CARBON_HD constexpr auto + linear_offset(const Idx& idx, + int component_id = 0) const noexcept -> int64_t; + + /** + * Translate a launch-grid thread @p (ix, iy, iz) into a buffer-relative @ref Idx for @p view + * and report whether the thread falls inside @c iter_extent(view). Mirrors Neon's + * @c dSpan::setAndValidate. + * + * The returned @c Idx is in the same buffer-relative coordinate system as + * @ref linear_offset / @ref global_location: every axis is shifted into the owned / halo + * buffer layout for @p view. + * + * - @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 + * pass the owned index through and return @c valid=false for interior cells. + * + * 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 + * return. + */ + [[nodiscard]] CARBON_HD constexpr auto + set_and_validate(::carbon::DataView view, + int64_t ix, + int64_t iy, + int64_t iz) const noexcept -> ValidatedIdx; +}; + +[[nodiscard]] CARBON_HD constexpr auto +Span::make_idx(int64_t ix, + int64_t iy, + int64_t iz) const noexcept -> Idx { + return Idx(ix, iy, iz); +} + +[[nodiscard]] CARBON_HD constexpr auto +Span::make_idx(int64_3d cell) const noexcept -> Idx { + return Idx(cell); +} + +[[nodiscard]] CARBON_HD constexpr auto +Span::global_location(const Idx& idx) const noexcept -> int64_3d { + const int64_3d cell = idx.cell(); + return {cell.x + offset_.x, cell.y + offset_.y, cell.z + offset_.z}; +} + +[[nodiscard]] CARBON_HD constexpr auto +Span::linear_offset(const Idx& idx, + int component_id) const noexcept -> int64_t { + const int64_3d cell = idx.cell(); + return static_cast(component_id) * linear_storage_elements() + + cell.z * xy_slab_elements_ + cell.y * haloed_extent_.x + cell.x; +} + +[[nodiscard]] CARBON_HD constexpr auto +Span::set_and_validate(::carbon::DataView view, + int64_t ix, + int64_t iy, + int64_t iz) const noexcept -> ValidatedIdx { + const int64_3d ext = iter_extent(view); + if (ix < 0 || iy < 0 || iz < 0 || ix >= ext.x || iy >= ext.y || iz >= ext.z) { + return ValidatedIdx{Idx{}, false}; + } + + switch (view) { + case ::carbon::DataView::Standard: + return ValidatedIdx{Idx(halo_.x + ix, halo_.y + iy, halo_.z + iz), true}; + + case ::carbon::DataView::Internal: + 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) { + 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}; + } + + const int64_3d owned = logic_extent(); + const bool internal = ix >= halo_.x && ix < owned.x - halo_.x && iy >= halo_.y && + iy < owned.y - halo_.y && iz >= halo_.z && iz < owned.z - halo_.z; + if (internal) { + return ValidatedIdx{Idx{}, false}; + } + return ValidatedIdx{Idx(halo_.x + ix, halo_.y + iy, halo_.z + iz), true}; + } + } + return ValidatedIdx{Idx{}, false}; +} + +/** + * Result of resolving a neighbour offset against a @c Span: the neighbour's @c Idx and a + * @c valid flag indicating whether the neighbour is reachable (in-buffer @b and inside the + * global Cartesian grid). Internal helper struct for @ref neighbour_idx; not part of the + * user-facing API. + */ +struct NeighbourIdx { + Idx idx{}; + bool valid{false}; +}; + +/** + * Internal helper: resolve @p (idx + offset) against @p span and report whether the result is + * reachable. The shape-and-bounds half of @c Partition::neighbour, factored out so the + * partition's @c neighbour() member is purely the data-access half (pointer dereference + + * SoA stride math via @c Span::linear_offset). + * + * Two checks combine: + * - @b Buffer (storage) bounds: @c (cell + offset) must be inside @c span.haloed_extent() on + * every axis. This also bounds the offset to @c [-halo(), +halo()]. + * - @b Global-domain bounds: @c cell + offset + span.offset() must lie in + * @c [0, span.global_extent()) on every axis — rejecting halo cells that map outside the + * global grid on an open face. + * + * Lives at namespace scope (not on @c Span) so the Span class's public surface stays minimal; + * grid families that need different resolution semantics (block grids, sparse grids) provide + * their own @c neighbour_idx overload taking their own @c Span and @c Idx types and ADL picks + * the right one inside their family's @c Partition. + * + * Boundary modes: + * - @c BoundaryModeDistributed::Open: out-of-domain reads return @c valid = false (no neighbour). + * - @c BoundaryModeDistributed::PeriodicX / @c PeriodicY / @c PeriodicZ: the corresponding axis wraps. A + * halo cell whose global coordinate lies outside @c [0, global_extent) is still reachable + * because the halo exchange has filled it with the wrapped data; the buffer-local index is + * accepted and @c valid = true is returned. + */ +[[nodiscard]] CARBON_HD constexpr auto +neighbour_idx(const Span& span, + const Idx& idx, + ::carbon::int8_3d offset) noexcept -> NeighbourIdx { + const int64_3d cell = idx.cell(); + const int64_3d haloed = span.haloed_extent(); + const int64_t bx = cell.x + static_cast(offset.x); + const int64_t by = cell.y + static_cast(offset.y); + const int64_t bz = cell.z + static_cast(offset.z); + if (bx < 0 || bx >= haloed.x || by < 0 || by >= haloed.y || bz < 0 || bz >= haloed.z) { + return {}; + } + const int64_3d global_extent = span.global_extent(); + const int64_3d off = span.offset(); + const BoundaryModeDistributed mode = span.boundary_mode(); + + const int64_t gx = bx + off.x; + if ((gx < 0 || gx >= global_extent.x) && !is_periodic(mode, Axis::X)) { + return {}; + } + + const int64_t gy = by + off.y; + if ((gy < 0 || gy >= global_extent.y) && !is_periodic(mode, Axis::Y)) { + return {}; + } + + const int64_t gz = bz + off.z; + if ((gz < 0 || gz >= global_extent.z) && !is_periodic(mode, Axis::Z)) { + return {}; + } + + return NeighbourIdx{Idx(bx, by, bz), true}; +} + +} // namespace carbon::detail::dense_distributed diff --git a/include/carbon/detail/halo_distributed_build.h b/include/carbon/detail/halo_distributed_build.h new file mode 100644 index 00000000..b29d2e02 --- /dev/null +++ b/include/carbon/detail/halo_distributed_build.h @@ -0,0 +1,247 @@ +#pragma once + +/** + * @file halo_distributed_build.h + * @brief Per-axis geometry helpers for @ref HaloDistributed. + * + * A distributed rank exchanges halo faces with up to two neighbours on each of the three axes. The + * helpers here describe, for one rank's storage geometry, which contiguous runs of the field make + * up the halo face and the owned face on a given axis and side, and who the neighbouring rank is + * (with periodic wrap). They are pure host-side index arithmetic: no device state, no MPI. + * + * Storage addressing (matches @c DenseDistributed::Span): element @c (x, y, z) of one component + * lives at @c z * pitch + y * haloed.x + x, where @c pitch is the number of elements per XY plane. + * + * Kept apart from @c halo_build.h so the Z-slab @ref Halo keeps its original helper set untouched. + */ + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace carbon::detail::halo_distributed_build { + +enum class AxisSide : std::uint8_t { + Lower = 0, + Upper = 1, +}; + +struct AxisNeighbour { + bool present{false}; + bool self{false}; + int32_3d coords{}; + int32_t rank{-1}; +}; + +struct AxisGeometry { + int64_3d owned{}; + int64_3d halo{}; + int64_3d haloed{}; + int64_t pitch{}; +}; + +struct AxisRun { + size_t offset{}; + size_t count{}; +}; + +template +[[nodiscard]] constexpr auto +axis_value(V v, + Axis axis) noexcept -> int64_t { + switch (axis) { + case Axis::X: + return static_cast(v.x); + case Axis::Y: + return static_cast(v.y); + case Axis::Z: + return static_cast(v.z); + } + return 0; +} + +[[nodiscard]] inline auto +axis_neighbour(const ProcessGrid& grid, + int32_3d coords, + Axis axis, + BoundaryModeDistributed boundary, + AxisSide side) -> AxisNeighbour { + const int32_t n = static_cast(axis_value(grid.dims(), axis)); + if (n <= 0) { + return {}; + } + + const int32_t current = static_cast(axis_value(coords, axis)); + int32_t next = current + (side == AxisSide::Lower ? -1 : 1); + + if (next < 0 || next >= n) { + if (!is_periodic(boundary, axis)) { + return {}; + } + next = (next + n) % n; + } + + int32_3d nb = coords; + switch (axis) { + case Axis::X: + nb.x = next; + break; + case Axis::Y: + nb.y = next; + break; + case Axis::Z: + nb.z = next; + break; + } + + return AxisNeighbour{ + true, + next == current, + nb, + grid.rank_of(nb), + }; +} + +[[nodiscard]] inline auto +axis_halo_runs(const AxisGeometry& g, + Axis axis, + AxisSide side) -> std::vector { + std::vector runs; + + const int64_t owned = axis_value(g.owned, axis); + const int64_t halo = axis_value(g.halo, axis); + if (halo <= 0) { + return runs; + } + if (owned < halo) { + log::throw_with_log( + "axis_halo_runs: owned extent {} is smaller than halo {} on axis {}", owned, halo, + static_cast(axis)); + } + + switch (axis) { + case Axis::X: { + const int64_t start = side == AxisSide::Lower ? 0 : g.halo.x + g.owned.x; + const size_t count = static_cast(g.halo.x); + runs.reserve(static_cast(g.haloed.y * g.haloed.z)); + for (int64_t z = 0; z < g.haloed.z; ++z) { + for (int64_t y = 0; y < g.haloed.y; ++y) { + runs.push_back({ + static_cast(z * g.pitch + y * g.haloed.x) + static_cast(start), + count, + }); + } + } + break; + } + + case Axis::Y: { + const int64_t start = (side == AxisSide::Lower ? 0 : g.halo.y + g.owned.y) * g.haloed.x; + const size_t count = static_cast(g.halo.y * g.haloed.x); + runs.reserve(static_cast(g.haloed.z)); + for (int64_t z = 0; z < g.haloed.z; ++z) { + runs.push_back({ + static_cast(z * g.pitch) + static_cast(start), + count, + }); + } + break; + } + + case Axis::Z: { + const int64_t start = (side == AxisSide::Lower ? 0 : g.halo.z + g.owned.z) * g.pitch; + const size_t count = static_cast(g.halo.z * g.pitch); + runs.push_back({ + static_cast(start), + count, + }); + break; + } + } + + return runs; +} + +[[nodiscard]] inline auto +axis_owned_face_runs(const AxisGeometry& g, + Axis axis, + AxisSide side) -> std::vector { + std::vector runs; + + const int64_t owned = axis_value(g.owned, axis); + const int64_t halo = axis_value(g.halo, axis); + if (halo <= 0) { + return runs; + } + if (owned < halo) { + log::throw_with_log( + "axis_owned_face_runs: owned extent {} is smaller than halo {} on axis {}", owned, halo, + static_cast(axis)); + } + + switch (axis) { + case Axis::X: { + const int64_t start = side == AxisSide::Lower ? g.halo.x : g.owned.x; + const size_t count = static_cast(g.halo.x); + runs.reserve(static_cast(g.haloed.y * g.haloed.z)); + for (int64_t z = 0; z < g.haloed.z; ++z) { + for (int64_t y = 0; y < g.haloed.y; ++y) { + runs.push_back({ + static_cast(z * g.pitch + y * g.haloed.x) + static_cast(start), + count, + }); + } + } + break; + } + + case Axis::Y: { + const int64_t start = (side == AxisSide::Lower ? g.halo.y : g.owned.y) * g.haloed.x; + const size_t count = static_cast(g.halo.y * g.haloed.x); + runs.reserve(static_cast(g.haloed.z)); + for (int64_t z = 0; z < g.haloed.z; ++z) { + runs.push_back({ + static_cast(z * g.pitch) + static_cast(start), + count, + }); + } + break; + } + + case Axis::Z: { + const int64_t start = (side == AxisSide::Lower ? g.halo.z : g.owned.z) * g.pitch; + const size_t count = static_cast(g.halo.z * g.pitch); + runs.push_back({ + static_cast(start), + count, + }); + break; + } + } + + return runs; +} + +inline auto +validate_boundary_mode_bits(BoundaryModeDistributed boundary, + const char* family_tag) -> void { + const auto bits = static_cast(boundary); + const auto known = + static_cast(static_cast(BoundaryModeDistributed::PeriodicX) | + static_cast(BoundaryModeDistributed::PeriodicY) | + static_cast(BoundaryModeDistributed::PeriodicZ)); + + if ((bits & static_cast(~known)) != 0U) { + log::throw_with_log( + "{}: unrecognised BoundaryModeDistributed bits (got {})", family_tag, + static_cast(bits)); + } +} + +} // namespace carbon::detail::halo_distributed_build diff --git a/include/carbon/detail/halo_distributed_kernel_impl.h b/include/carbon/detail/halo_distributed_kernel_impl.h new file mode 100644 index 00000000..3ce96211 --- /dev/null +++ b/include/carbon/detail/halo_distributed_kernel_impl.h @@ -0,0 +1,41 @@ +#pragma once + +/** + * @file halo_distributed_kernel_impl.h + * @brief @c Kernel adapter for @ref HaloDistributed. + * + * Identical in shape to @c HaloKernelImpl (the Z-slab @ref Halo adapter): all launch/ordering + * logic lives in @c HaloKernelImplBase, and only the two field-identity accessors differ per halo + * type. + */ + +#include +#include + +#include +#include + +namespace carbon::detail { + +template +struct halo_kernel_impl_traits<::carbon::HaloDistributed> { + static auto + field_uid(const ::carbon::HaloDistributed& h) noexcept -> std::uint64_t { + return h.field().gpu_buffers().get_uid(); + } + static auto + field_name(const ::carbon::HaloDistributed& h) noexcept -> const std::string& { + return h.field().name(); + } +}; + +template +class HaloDistributedKernelImpl final + : public HaloKernelImplBase<::carbon::HaloDistributed> { +public: + using HaloKernelImplBase<::carbon::HaloDistributed>::HaloKernelImplBase; +}; + +} // namespace carbon::detail diff --git a/include/carbon/detail/halo_pack.h b/include/carbon/detail/halo_pack.h new file mode 100644 index 00000000..a1c7fcab --- /dev/null +++ b/include/carbon/detail/halo_pack.h @@ -0,0 +1,81 @@ +#pragma once + +/** + * @file halo_pack.h + * @brief Launchers for the packed halo gather/scatter kernels (CUDA / HIP backends only). + * + * The kernels live in @c src/halo_pack.cu and are compiled once into libcarbon, so a host-only + * translation unit that merely includes @c halo_distributed.h can run a packed @c HaloDistributed without a device + * toolchain, and there is no per-TU template instantiation (no ODR hazard between a @c .cpp and a + * @c .cu that both construct @c HaloDistributed). The launchers are type-erased: a pack/unpack is a pure + * copy, so only @c sizeof(T) matters. + * + * Planning (extents, component lists, messages) and the per-thread index math are backend-neutral + * and live in @c halo_pack_plan.h. Under the SYCL backend nothing here is declared and @c HaloDistributed + * silently keeps using the run-based path. + */ + +#include +#include + +#include +#include +#include + +namespace carbon::detail::halo_pack { + +/** + * Boolean environment switch. Unset -> @p fallback; "0", "off", "false", "no" -> false; + * anything else -> true. Read once per @c HaloDistributed construction (not per exchange). + */ +[[nodiscard]] inline auto +env_flag(const char* name, + bool fallback) -> bool { + const char* v = std::getenv(name); + if (v == nullptr || *v == '\0') { + return fallback; + } + return !(std::strcmp(v, "0") == 0 || std::strcmp(v, "off") == 0 || + std::strcmp(v, "false") == 0 || std::strcmp(v, "no") == 0); +} + +/** Element widths the type-erased kernels are instantiated for. */ +[[nodiscard]] constexpr auto +element_size_supported(std::size_t bytes) noexcept -> bool { + return bytes == 1U || bytes == 2U || bytes == 4U || bytes == 8U || bytes == 16U; +} + +} // namespace carbon::detail::halo_pack + +#if CARBON_BACKEND_IS_CUDALIKE + +#include +#include +#include + +namespace carbon::detail::halo_pack { + +/** + * Gather @p a 's box of the field (@p field_base, all components addressed through @p a) into the + * contiguous staging region @p stage_region. Asynchronous on @p stream. Returns the launch error. + */ +[[nodiscard]] CARBON_API auto +launch_gather(const Gpu& gpu, + gpu_stream_t stream, + std::size_t elem_bytes, + const void* field_base, + void* stage_region, + const PackKernelArgs& a) -> gpu_error_t; + +/** Inverse of @ref launch_gather: scatter the staging region into the field's box. */ +[[nodiscard]] CARBON_API auto +launch_scatter(const Gpu& gpu, + gpu_stream_t stream, + std::size_t elem_bytes, + const void* stage_region, + void* field_base, + const PackKernelArgs& a) -> gpu_error_t; + +} // namespace carbon::detail::halo_pack + +#endif // CARBON_BACKEND_IS_CUDALIKE diff --git a/include/carbon/detail/halo_pack_plan.h b/include/carbon/detail/halo_pack_plan.h new file mode 100644 index 00000000..4e667ab9 --- /dev/null +++ b/include/carbon/detail/halo_pack_plan.h @@ -0,0 +1,517 @@ +#pragma once + +/** + * @file halo_pack_plan.h + * @brief Host-side planning and shared index math for the *packed* multi-axis halo exchange. + * + * Why this exists + * --------------- + * The run-based multi-axis builder in @c halo_distributed_build.h describes every halo face as a list of + * contiguous runs. In the x-fastest layout that is one run per (y, z) row for an X face + * (@c haloed.y * @c haloed.z runs of @c halo.x elements) and one run per z-plane for a Y face. + * Each run becomes one @c ncclSend / @c ncclRecv (cross-rank) or one async copy (intra). At a + * 256^3 local block that is ~66k transfers per face per component: the exchange is dominated by + * per-message overhead, not bandwidth. + * + * The packed path instead gathers a face into one contiguous staging region, moves it with ONE + * message per (axis, side), and scatters it into the halo on the other side: + * + * gather (kernel) -> [intra copies] -> NCCL group (1 Send + 1 Recv per side) -> scatter (kernel) + * + * X and Y faces are always packed. A Z face is one contiguous run PER COMPONENT, so it only needs + * packing when it carries several components (a D3Q19 population field moves 5 populations per + * face with the lattice filter, 19 without): without packing that is one NCCL message per + * component per direction, and the messages that cross a node boundary are issued back to back + * through the network proxy. The caller decides (see HaloDistributed::build_multi_axis_); the plan builder + * handles Z like any other axis. + * + * This header is host-only and has no backend dependency, so the whole plan (extents, component + * lists, peers, message ordering) and the per-thread index math are unit-testable with a plain + * C++ compiler (see tests/test_halo_pack_plan.cpp). The CUDA/HIP kernels in src/halo_pack.cu are + * thin wrappers that forward their launch coordinates to @ref pack_gather_thread / + * @ref pack_scatter_thread, so the tested code IS the device code. + * + * Face extents (design: staged X -> Y -> Z) + * ----------------------------------------- + * - X pass : halo.x x OWNED y x OWNED z + * - Y pass : filled-x x halo.y x OWNED z ("filled-x" = x range already written by the + * X pass; exterior x halos on open axes are + * excluded, so they are never overwritten) + * - Z pass : filled-x x filled-y x halo.z (same rule for y: the X and Y passes have + * already filled every halo cell that has a + * neighbour, corners included) + * The run-based path sends the full haloed y/z (resp. z) range instead; those extra rows carry + * not-yet-filled halo cells (wasted bandwidth) and can overwrite exterior halo cells on end ranks + * of open axes. + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#if defined(__GNUC__) || defined(__CUDACC__) || defined(__HIPCC__) +#define CARBON_PACK_RESTRICT __restrict__ +#else +#define CARBON_PACK_RESTRICT +#endif + +namespace carbon::detail::halo_pack { + +using halo_distributed_build::AxisGeometry; +using halo_distributed_build::AxisSide; + +/** Maximum components packed by one kernel launch (kernel argument struct is fixed-size). */ +inline constexpr uint32_t kMaxPackComps = 32U; +/** Threads per block along x for pack/unpack kernels. */ +inline constexpr uint32_t kPackBlockX = 256U; + +/** Axis-aligned box in *field buffer* coordinates (x fastest, includes halos). */ +struct PackBox { + int64_t lo_x{}; + int64_t lo_y{}; + int64_t lo_z{}; + int64_t ext_x{}; + int64_t ext_y{}; + int64_t ext_z{}; + + [[nodiscard]] constexpr auto + volume() const noexcept -> size_t { + return static_cast(ext_x) * static_cast(ext_y) * static_cast(ext_z); + } +}; + +/** + * Everything a pack/unpack kernel needs, as a POD passed by value. + * + * Field addressing (matches DenseDistributed): element (c, x, y, z) lives at + * c * comp_stride + z * pitch + y * haloed_x + x. + * Staging addressing: plane k (= the k-th packed component) is contiguous and x-fastest: + * k * stage_comp_stride + (iz * ext_y + iy) * ext_x + ix, stage_comp_stride = ext_x*ext_y*ext_z. + */ +struct PackKernelArgs { + int64_t lo_x{}; + int64_t lo_y{}; + int64_t lo_z{}; + int64_t haloed_x{}; + int64_t pitch{}; + int64_t comp_stride{}; + int64_t stage_comp_stride{}; + uint32_t ext_x{}; + uint32_t ext_y{}; + uint32_t ext_z{}; + uint32_t row{}; ///< ext_x * ext_y (threads along the flattened x/y plane of the box) + uint32_t num_comps{}; + int32_t comps[kMaxPackComps]{}; +}; + +struct PackLaunchShape { + uint32_t grid_x{}; + uint32_t grid_y{}; + uint32_t grid_z{}; + uint32_t block_x{}; +}; + +/** Launch geometry: x = flattened (x,y) row, y = grid-stride over z, z = packed component. */ +[[nodiscard]] inline auto +pack_launch_shape(const PackKernelArgs& a) noexcept -> PackLaunchShape { + PackLaunchShape s; + s.block_x = kPackBlockX; + s.grid_x = (a.row + kPackBlockX - 1U) / kPackBlockX; + s.grid_y = std::min(a.ext_z, 65535U); + s.grid_z = a.num_comps; + return s; +} + +/** + * One device thread of the gather kernel (field -> staging). Host+device so the same code runs + * in the CUDA/HIP kernel and in the host unit test. + */ +template +CARBON_HD inline void +pack_gather_thread(const W* CARBON_PACK_RESTRICT field, + W* CARBON_PACK_RESTRICT stage, + const PackKernelArgs& a, + uint32_t bx, + uint32_t by, + uint32_t bz, + uint32_t tx, + uint32_t bdx, + uint32_t gdy) { + const uint32_t j = bx * bdx + tx; + if (j >= a.row || bz >= a.num_comps) { + return; + } + const uint32_t iy = j / a.ext_x; + const uint32_t ix = j - iy * a.ext_x; + const int64_t fbase = static_cast(a.comps[bz]) * a.comp_stride + + (a.lo_y + static_cast(iy)) * a.haloed_x + a.lo_x + + static_cast(ix); + const int64_t sbase = static_cast(bz) * a.stage_comp_stride + static_cast(j); + for (uint32_t iz = by; iz < a.ext_z; iz += gdy) { + stage[sbase + static_cast(iz) * static_cast(a.row)] = + field[fbase + (a.lo_z + static_cast(iz)) * a.pitch]; + } +} + +/** One device thread of the scatter kernel (staging -> field). */ +template +CARBON_HD inline void +pack_scatter_thread(const W* CARBON_PACK_RESTRICT stage, + W* CARBON_PACK_RESTRICT field, + const PackKernelArgs& a, + uint32_t bx, + uint32_t by, + uint32_t bz, + uint32_t tx, + uint32_t bdx, + uint32_t gdy) { + const uint32_t j = bx * bdx + tx; + if (j >= a.row || bz >= a.num_comps) { + return; + } + const uint32_t iy = j / a.ext_x; + const uint32_t ix = j - iy * a.ext_x; + const int64_t fbase = static_cast(a.comps[bz]) * a.comp_stride + + (a.lo_y + static_cast(iy)) * a.haloed_x + a.lo_x + + static_cast(ix); + const int64_t sbase = static_cast(bz) * a.stage_comp_stride + static_cast(j); + for (uint32_t iz = by; iz < a.ext_z; iz += gdy) { + field[fbase + (a.lo_z + static_cast(iz)) * a.pitch] = + stage[sbase + static_cast(iz) * static_cast(a.row)]; + } +} + +/** Host reference of a full gather launch (used by tests and as executable documentation). */ +template +inline auto +host_gather(const W* field, + W* stage, + const PackKernelArgs& a) -> void { + const PackLaunchShape s = pack_launch_shape(a); + for (uint32_t bz = 0; bz < s.grid_z; ++bz) { + for (uint32_t by = 0; by < s.grid_y; ++by) { + for (uint32_t bx = 0; bx < s.grid_x; ++bx) { + for (uint32_t tx = 0; tx < s.block_x; ++tx) { + pack_gather_thread(field, stage, a, bx, by, bz, tx, s.block_x, s.grid_y); + } + } + } + } +} + +/** Host reference of a full scatter launch. */ +template +inline auto +host_scatter(const W* stage, + W* field, + const PackKernelArgs& a) -> void { + const PackLaunchShape s = pack_launch_shape(a); + for (uint32_t bz = 0; bz < s.grid_z; ++bz) { + for (uint32_t by = 0; by < s.grid_y; ++by) { + for (uint32_t bx = 0; bx < s.grid_x; ++bx) { + for (uint32_t tx = 0; tx < s.block_x; ++tx) { + pack_scatter_thread(stage, field, a, bx, by, bz, tx, s.block_x, s.grid_y); + } + } + } + } +} + +// --------------------------------------------------------------------------- +// Plan +// --------------------------------------------------------------------------- + +enum class MsgOp : std::uint8_t { + Send = 0, + Recv = 1, +}; + +/** One kernel launch (<= kMaxPackComps components) plus where its staging region starts. */ +struct PackStep { + PackKernelArgs args{}; + size_t stage_offset{}; ///< element offset into the HaloDistributed's staging buffer +}; + +/** One cross-rank message over a contiguous staging region. */ +struct PackMsg { + int peer{}; + MsgOp op{MsgOp::Send}; + size_t first{}; ///< element offset into the staging buffer + size_t count{}; ///< elements + /// (axis, src_rank, src_side, dst_rank, dst_side): identical on both ends of a message. + std::tuple key{}; +}; + +struct AxisPackPlan { + std::vector gathers{}; ///< run BEFORE the exchange (cross-rank sends + self wraps) + std::vector scatters{}; ///< run AFTER the exchange (cross-rank recvs + self wraps) + std::vector msgs{}; ///< cross-rank messages (sort with @ref sort_msgs first) + size_t stage_elems{}; ///< staging elements consumed by this plan +}; + +/** + * NCCL point-to-point has no tags, so both ends of every peer pair must issue their operations in + * the same order: all sends before all recvs per peer, ordered by a key identical on both ends. + * With only two ranks along a periodic axis the same peer appears on both sides, which is exactly + * why the key (not insertion order) must decide. + */ +inline auto +sort_msgs(std::vector& msgs) -> void { + std::sort(msgs.begin(), msgs.end(), [](const PackMsg& a, const PackMsg& b) { + return std::tie(a.peer, a.op, a.key) < std::tie(b.peer, b.op, b.key); + }); +} + +/** + * x and y ranges (buffer coordinates) already filled by earlier passes, i.e. the part of a face + * that carries valid data. Exterior halos on open axes are excluded so user boundary data there + * is never overwritten. Both ends of a message compute the same range because their neighbours + * along the passed axis share the other two process coordinates. + */ +struct FilledRange { + int64_t x_lo{}; + int64_t x_hi{}; + int64_t y_lo{}; + int64_t y_hi{}; +}; + +/** Owned face of @p side: the cells this rank sends to its neighbour on @p side. */ +[[nodiscard]] inline auto +pack_face_box(const AxisGeometry& g, + Axis axis, + AxisSide side, + const FilledRange& r) -> PackBox { + const bool lower = side == AxisSide::Lower; + switch (axis) { + case Axis::X: + return PackBox{lower ? g.halo.x : g.owned.x, g.halo.y, g.halo.z, + g.halo.x, g.owned.y, g.owned.z}; + case Axis::Y: + return PackBox{r.x_lo, lower ? g.halo.y : g.owned.y, g.halo.z, + r.x_hi - r.x_lo, g.halo.y, g.owned.z}; + case Axis::Z: + return PackBox{r.x_lo, r.y_lo, lower ? g.halo.z : g.owned.z, + r.x_hi - r.x_lo, r.y_hi - r.y_lo, g.halo.z}; + } + throw std::invalid_argument("pack_face_box: unknown axis"); +} + +/** Halo region of @p side: the cells this rank receives from its neighbour on @p side. */ +[[nodiscard]] inline auto +pack_halo_box(const AxisGeometry& g, + Axis axis, + AxisSide side, + const FilledRange& r) -> PackBox { + const bool lower = side == AxisSide::Lower; + switch (axis) { + case Axis::X: + return PackBox{lower ? 0 : g.halo.x + g.owned.x, g.halo.y, g.halo.z, + g.halo.x, g.owned.y, g.owned.z}; + case Axis::Y: + return PackBox{r.x_lo, lower ? 0 : g.halo.y + g.owned.y, g.halo.z, + r.x_hi - r.x_lo, g.halo.y, g.owned.z}; + case Axis::Z: + return PackBox{r.x_lo, r.y_lo, lower ? 0 : g.halo.z + g.owned.z, + r.x_hi - r.x_lo, r.y_hi - r.y_lo, g.halo.z}; + } + throw std::invalid_argument("pack_halo_box: unknown axis"); +} + +/** Convenience overloads keeping the X/Y-only call shape (y range = whole haloed y). */ +[[nodiscard]] inline auto +pack_face_box(const AxisGeometry& g, + Axis axis, + AxisSide side, + int64_t x_lo, + int64_t x_hi) -> PackBox { + return pack_face_box(g, axis, side, FilledRange{x_lo, x_hi, 0, g.haloed.y}); +} + +[[nodiscard]] inline auto +pack_halo_box(const AxisGeometry& g, + Axis axis, + AxisSide side, + int64_t x_lo, + int64_t x_hi) -> PackBox { + return pack_halo_box(g, axis, side, FilledRange{x_lo, x_hi, 0, g.haloed.y}); +} + +namespace detail_plan { + +/** Append one launch per chunk of <= kMaxPackComps components for @p box / @p comps. */ +inline auto +append_steps(std::vector& out, + const PackBox& box, + const std::vector& comps, + const AxisGeometry& g, + int64_t comp_stride, + size_t region_offset) -> void { + if (box.volume() == 0U || comps.empty()) { + return; + } + if (box.ext_x * box.ext_y > static_cast(UINT32_MAX) || + box.ext_z > static_cast(UINT32_MAX)) { + throw std::invalid_argument("halo pack: face extent exceeds 32-bit launch range"); + } + const int64_t per_comp = static_cast(box.volume()); + for (size_t first = 0; first < comps.size(); first += kMaxPackComps) { + const size_t n = std::min(kMaxPackComps, comps.size() - first); + PackStep step; + PackKernelArgs& a = step.args; + a.lo_x = box.lo_x; + a.lo_y = box.lo_y; + a.lo_z = box.lo_z; + a.haloed_x = g.haloed.x; + a.pitch = g.pitch; + a.comp_stride = comp_stride; + a.stage_comp_stride = per_comp; + a.ext_x = static_cast(box.ext_x); + a.ext_y = static_cast(box.ext_y); + a.ext_z = static_cast(box.ext_z); + a.row = a.ext_x * a.ext_y; + a.num_comps = static_cast(n); + for (size_t k = 0; k < n; ++k) { + a.comps[k] = comps[first + k]; + } + step.stage_offset = region_offset + first * static_cast(per_comp); + out.push_back(step); + } +} + +} // namespace detail_plan + +/** + * Build the packed exchange plan for one X or Y pass of one rank. + * + * @param stage_base element offset at which this plan's staging regions start (so several passes + * can share one staging buffer) + * @param active_send / active_recv (component, axis, side) -> bool; same predicates the + * run-based builder uses, so lattice direction filtering carries over. + * + * Semantics per side, identical to the run-based builder: + * - cross-rank: send OUR owned face at `side` to the neighbour on `side`; receive INTO OUR halo at + * `side` from that neighbour's opposite face. + * - self wrap (periodic axis owned by a single rank): halo at `side` <- OUR owned face on the + * opposite side, staged through the same buffer (no message). + */ +template +[[nodiscard]] inline auto +build_axis_pack_plan(const ProcessGrid& pg, + BoundaryModeDistributed boundary, + int32_3d coords, + int32_t local_rank, + const AxisGeometry& g, + Axis axis, + int components, + int64_t comp_stride, + SendActive&& active_send, + RecvActive&& active_recv, + size_t stage_base) -> AxisPackPlan { + AxisPackPlan plan; + const int64_t owned = axis == Axis::X ? g.owned.x : (axis == Axis::Y ? g.owned.y : g.owned.z); + const int64_t halo = axis == Axis::X ? g.halo.x : (axis == Axis::Y ? g.halo.y : g.halo.z); + if (halo <= 0) { + return plan; + } + if (owned < halo) { + throw std::invalid_argument("halo pack: owned extent is smaller than the halo"); + } + + // Ranges already filled when this pass starts (see file comment). Neighbours along this axis + // share our other two coordinates, so both ends of a message compute the same ranges. + FilledRange fill{0, g.haloed.x, 0, g.haloed.y}; + if (axis != Axis::X && g.halo.x > 0) { + const bool has_lo = + halo_distributed_build::axis_neighbour(pg, coords, Axis::X, boundary, AxisSide::Lower).present; + const bool has_hi = + halo_distributed_build::axis_neighbour(pg, coords, Axis::X, boundary, AxisSide::Upper).present; + fill.x_lo = has_lo ? 0 : g.halo.x; + fill.x_hi = g.haloed.x - (has_hi ? 0 : g.halo.x); + } + if (axis == Axis::Z && g.halo.y > 0) { + const bool has_lo = + halo_distributed_build::axis_neighbour(pg, coords, Axis::Y, boundary, AxisSide::Lower).present; + const bool has_hi = + halo_distributed_build::axis_neighbour(pg, coords, Axis::Y, boundary, AxisSide::Upper).present; + fill.y_lo = has_lo ? 0 : g.halo.y; + fill.y_hi = g.haloed.y - (has_hi ? 0 : g.halo.y); + } + + size_t cursor = stage_base; + const int axis_id = static_cast(axis); + + for (const AxisSide side : {AxisSide::Lower, AxisSide::Upper}) { + const auto nb = halo_distributed_build::axis_neighbour(pg, coords, axis, boundary, side); + if (!nb.present) { + continue; + } + const AxisSide opposite = side == AxisSide::Lower ? AxisSide::Upper : AxisSide::Lower; + const int local_side = static_cast(side); + const int peer_side = 1 - local_side; + + std::vector send_comps; + std::vector recv_comps; + for (int c = 0; c < components; ++c) { + if (active_send(c, axis, side)) { + send_comps.push_back(c); + } + if (active_recv(c, axis, side)) { + recv_comps.push_back(c); + } + } + + const PackBox halo_box = pack_halo_box(g, axis, side, fill); + + if (nb.rank == local_rank) { + // Self wrap: gather our `opposite` owned face, scatter into our `side` halo. + const PackBox src_box = pack_face_box(g, axis, opposite, fill); + const size_t region = cursor; + detail_plan::append_steps(plan.gathers, src_box, recv_comps, g, comp_stride, region); + detail_plan::append_steps(plan.scatters, halo_box, recv_comps, g, comp_stride, region); + cursor += recv_comps.size() * halo_box.volume(); + continue; + } + + // Cross-rank: one send region + one recv region per side. + const PackBox send_box = pack_face_box(g, axis, side, fill); + if (!send_comps.empty() && send_box.volume() > 0U) { + const size_t region = cursor; + detail_plan::append_steps(plan.gathers, send_box, send_comps, g, comp_stride, region); + const size_t count = send_comps.size() * send_box.volume(); + plan.msgs.push_back({nb.rank, + MsgOp::Send, + region, + count, + {axis_id, static_cast(local_rank), local_side, + static_cast(nb.rank), peer_side}}); + cursor += count; + } + if (!recv_comps.empty() && halo_box.volume() > 0U) { + const size_t region = cursor; + detail_plan::append_steps(plan.scatters, halo_box, recv_comps, g, comp_stride, region); + const size_t count = recv_comps.size() * halo_box.volume(); + plan.msgs.push_back({nb.rank, + MsgOp::Recv, + region, + count, + {axis_id, static_cast(nb.rank), peer_side, + static_cast(local_rank), local_side}}); + cursor += count; + } + } + + plan.stage_elems = cursor - stage_base; + return plan; +} + +} // namespace carbon::detail::halo_pack diff --git a/include/carbon/detail/kernel_dense_distributed.inl b/include/carbon/detail/kernel_dense_distributed.inl new file mode 100644 index 00000000..3bfce093 --- /dev/null +++ b/include/carbon/detail/kernel_dense_distributed.inl @@ -0,0 +1,95 @@ +// kernel_dense_distributed.inl — DenseDistributed + DenseDistributed::Field convenience members. +// Included from exactly once, after Kernel's static factories are defined and +// after the dense impl detail headers have brought DeviceKernelImpl / ReduceKernelImpl etc. into +// scope. Not a standalone header (same contract as kernel_dense.inl). + +// ----- DenseDistributed convenience members ----- +// +// Forward to the static factories on @c Kernel; same naming convention as @c Dense: +// make_kernel -> device-only compute +// make_universal_kernel -> dual-target compute (device + host) +// make_host_kernel -> host-only compute +// Same applies to the reduce twins. + +template +[[nodiscard]] inline auto +DenseDistributed::make_kernel(L&& loading_fn, + size_t shared_mem) const -> Kernel { + return Kernel::compute(*this, std::forward(loading_fn), /*name=*/{}, shared_mem); +} + +template +[[nodiscard]] inline auto +DenseDistributed::make_universal_kernel(L&& loading_fn, + size_t shared_mem) const -> Kernel { + return Kernel::compute_universal(*this, std::forward(loading_fn), /*name=*/{}, shared_mem); +} + +template +[[nodiscard]] inline auto +DenseDistributed::make_reduce_kernel(L&& loading_fn, + ReductionResult& dst, + Op op, + size_t shared_mem, + reduce::ReduceOptions options) const -> Kernel { + return Kernel::reduce(*this, std::forward(loading_fn), dst, std::move(op), /*name=*/{}, + shared_mem, options); +} + +template +[[nodiscard]] inline auto +DenseDistributed::make_universal_reduce_kernel(L&& loading_fn, + ReductionResult& dst, + Op op, + size_t shared_mem) const -> Kernel { + return Kernel::reduce_universal(*this, std::forward(loading_fn), dst, std::move(op), + /*name=*/{}, shared_mem); +} + +template +[[nodiscard]] inline auto +DenseDistributed::make_host_kernel(L&& loading_fn) const -> Kernel { + return Kernel::host_compute(*this, std::forward(loading_fn), /*name=*/{}); +} + +template +[[nodiscard]] inline auto +DenseDistributed::make_host_reduce_kernel(L&& loading_fn, + ReductionResult& dst, + Op op) const -> Kernel { + return Kernel::host_reduce(*this, std::forward(loading_fn), dst, std::move(op), + /*name=*/{}); +} + +// ----- DenseDistributed::Field convenience member ----- +// +// Declared in against a forward-declared Kernel; +// defined here once HaloDistributed and Kernel are fully visible. +template +inline auto +detail::dense_distributed::Field::make_halo_kernel(std::string name) const + -> ::carbon::Kernel { + return ::carbon::Kernel::halo_distributed(::carbon::HaloDistributed(*this), + std::move(name)); +} + +template +inline auto +detail::dense_distributed::Field::make_halo_kernel(std::string name, + Stencil stencil, + StencilSemantic semantic) const + -> ::carbon::Kernel { + return ::carbon::Kernel::halo_distributed( + ::carbon::HaloDistributed(*this, std::move(stencil), semantic), + std::move(name)); +} diff --git a/include/carbon/detail/launch_traits.h b/include/carbon/detail/launch_traits.h index 1b98ab5e..7a54d3e0 100644 --- a/include/carbon/detail/launch_traits.h +++ b/include/carbon/detail/launch_traits.h @@ -41,6 +41,8 @@ #include #include #include +#include +#include #include #include #include @@ -49,6 +51,7 @@ #include #if CARBON_CUDALIKE_DEVICE_TU #include +#include #endif #elif CARBON_BACKEND_IS_SYCL #include @@ -116,6 +119,9 @@ struct DeviceLaunchTraits { if constexpr (requires { typename Grid::DisgPolicy; }) { return ::carbon::detail::dense_disg::launch_disg_grid(grid, gpu_grid[i], gpu_block[i], i, shared_mem, stream, view, fn); + } else if constexpr (requires { typename Grid::DenseDistributedPolicy; }) { + return ::carbon::detail::dense_distributed::launch_dense_grid( + grid, gpu_grid[i], gpu_block[i], i, shared_mem, stream, view, fn); } else { return ::carbon::detail::dense::launch_dense_grid(grid, gpu_grid[i], gpu_block[i], i, shared_mem, stream, view, fn); @@ -138,6 +144,9 @@ struct DeviceLaunchTraits { if constexpr (requires { typename Grid::DisgPolicy; }) { ::carbon::detail::dense_disg::launch_disg_grid(grid, gpu_grid[i], gpu_block[i], i, shared_mem, q, view, fn); + } else if constexpr (requires { typename Grid::DenseDistributedPolicy; }) { + ::carbon::detail::dense_distributed::launch_dense_grid(grid, gpu_grid[i], gpu_block[i], i, + shared_mem, q, view, fn); } else { ::carbon::detail::dense::launch_dense_grid(grid, gpu_grid[i], gpu_block[i], i, shared_mem, q, view, fn); @@ -446,6 +455,8 @@ struct ReduceLaunchTraits { stage1_block_threads() noexcept -> int { if constexpr (requires { typename Grid::DisgPolicy; }) { return ::carbon::detail::dense_disg::kDisgReduceBlockThreads; + } else if constexpr (requires { typename Grid::DenseDistributedPolicy; }) { + return ::carbon::detail::dense_distributed::kReduceBlockThreads; } else { return ::carbon::detail::dense::kReduceBlockThreads; } @@ -507,6 +518,11 @@ struct ReduceLaunchTraits { static_assert(::carbon::detail::dense_disg::disg_reduce_fn, "Kernel::reduce::launch (DenseDisg): the device callable returned by the " "loading function must be invocable as fn(DisgSpan, DisgIdx) -> T."); + } else if constexpr (requires { typename Grid::DenseDistributedPolicy; }) { + static_assert(::carbon::detail::dense_distributed::dense_reduce_fn, + "Kernel::reduce::launch (DenseDistributed): the device callable returned by " + "the loading function must be invocable as fn(Span, Idx) -> T and trivially " + "copyable."); } else { static_assert(::carbon::detail::dense::dense_reduce_fn, "Kernel::reduce::launch (Dense): the device callable returned by the loading " @@ -537,6 +553,18 @@ struct ReduceLaunchTraits { dim3(static_cast(blocks), 1U, 1U), dim3(static_cast(stage1_block_threads()), 1U, 1U), shared_mem, stream, span, view, fn, op, identity, partials, iter_cells); + } else if constexpr (requires { typename Grid::DenseDistributedPolicy; }) { + if (dense_stage1_threads_y > 0) { + const int bx = dense_stage1_threads > 0 ? dense_stage1_threads : 32; + const int by = dense_stage1_threads_y; + return ::carbon::detail::dense_distributed::launch_dense_grid_reduce_kernel_2d( + bx, by, gpu, blocks, shared_mem, stream, span, view, fn, op, identity, partials, + iter_cells); + } + const int bt = dense_stage1_threads > 0 ? dense_stage1_threads + : ::carbon::detail::dense_distributed::kReduceBlockThreads; + return ::carbon::detail::dense_distributed::launch_dense_grid_reduce_kernel( + bt, gpu, blocks, shared_mem, stream, span, view, fn, op, identity, partials, iter_cells); } else { if (dense_stage1_threads_y > 0) { const int bx = dense_stage1_threads > 0 ? dense_stage1_threads : 32; @@ -575,6 +603,21 @@ struct ReduceLaunchTraits { dim3(static_cast(blocks), 1U, 1U), dim3(static_cast(stage1_block_threads()), 1U, 1U), shared_mem, stream, span, view, fn, op, identity, global_out, iter_cells); + } else if constexpr (requires { typename Grid::DenseDistributedPolicy; }) { + if (dense_stage1_threads_y > 0) { + const int bx = dense_stage1_threads > 0 ? dense_stage1_threads : 32; + const int by = dense_stage1_threads_y; + return ::carbon::detail::dense_distributed:: + launch_dense_grid_reduce_block_atomic_kernel_2d( + bx, by, gpu, blocks, shared_mem, stream, span, view, fn, op, identity, global_out, + iter_cells); + } + const int bt = dense_stage1_threads > 0 ? dense_stage1_threads + : ::carbon::detail::dense_distributed::kReduceBlockThreads; + return ::carbon::detail::dense_distributed::launch_dense_grid_reduce_block_atomic_kernel( + bt, gpu, blocks, shared_mem, stream, span, view, fn, op, identity, global_out, + iter_cells); } else { if (dense_stage1_threads_y > 0) { const int bx = dense_stage1_threads > 0 ? dense_stage1_threads : 32; @@ -608,6 +651,9 @@ struct ReduceLaunchTraits { if constexpr (requires { typename Grid::DisgPolicy; }) { ::carbon::detail::dense_disg::launch_disg_reduce(q, span, view, fn, op, identity, out, iter_cells); + } else if constexpr (requires { typename Grid::DenseDistributedPolicy; }) { + ::carbon::detail::dense_distributed::launch_dense_reduce(q, span, view, fn, op, + identity, out, iter_cells); } else { ::carbon::detail::dense::launch_dense_reduce(q, span, view, fn, op, identity, out, iter_cells); diff --git a/include/carbon/halo_distributed.h b/include/carbon/halo_distributed.h new file mode 100644 index 00000000..98973ee6 --- /dev/null +++ b/include/carbon/halo_distributed.h @@ -0,0 +1,1131 @@ +#pragma once + +#include +#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 + +namespace carbon { + +/** + * Halo-exchange descriptor for a single @ref DenseDistributed::Field. + * + * @par What it does + * Every @ref DenseDistributed chunk carries a per-axis halo (driven by the grid's @ref Stencil and + * @ref ProcessGrid). Before any kernel that reads neighbours can run, those halo cells must be + * filled from the adjacent chunk's owned cells. For a Slab this is one Z pass; Pencil adds Y; + * Brick adds X. Multi-axis layouts run staged @c X -> @c Y -> @c Z passes so edge and corner + * halos propagate. @c HaloDistributed precomputes the full per-pass pair set at construction and turns it + * into: + * - an intra-process @ref Transfer covering every adjacent @b local chunk pair (carbon's + * single-process multi-GPU case, plus self-wrap pairs on a periodic axis); + * - and, when @c CARBON_HAVE_MPI_NCCL is set and @c system.distributed() is non-null, a + * cross-rank @ref DistTransfer covering every pair whose neighbour lives on a different + * rank (carbon's distributed one-rank-per-GPU case, plus wrap-around peers on a periodic + * axis). + * + * @ref operator() issues both on the user's stream — async, single-shot, same call ergonomics + * as @c Transfer / @c DistTransfer. + * + * @par Host (CPU) variant + * @ref launch_on_host runs the same exchange against the field's @c cpu_buffers via + * synchronous @c std::memcpy and (when distributed) @c MPI_Sendrecv on host pointers + * — the natural pair to @c DenseDistributed::make_host_kernel for fully-host pipelines. The host + * variant lazily forces the field's host mirror to be allocated for + * @c MemorySide::HostDevice fields (the device path keeps using @c gpu_buffers + * unchanged). The @c HaloDistributedKernelImpl that backs @c Field::make_halo_kernel exposes + * @c launch_on_host as well, so a heterogeneous pipeline that mixes host and device + * kernels around a halo can call @c kernel.launch_on_host(stream) on the halo node + * and have it Just Work without rebuilding the descriptor. + * + * @par Pair model + * The legacy Slab path is built around an @b adjacency list of global z-slab index pairs + * @c (g_lo, g_up). For every @c g in @c [0, global_slab_count - 1) it adds @c (g, g+1), plus + * the wrap pair under @c PeriodicZ. The multi-axis path uses @ref ProcessGrid to find the + * neighbour rank/coordinate on each axis and emits per-axis send/receive runs. + * + * Each pair is then dispatched based on which rank owns each end: + * - @b Both local: emit two intra-process @c Transfer entries (one upward, one downward), + * each entry contributing one copy per component plane. Self-pairs (one chunk wrapping to + * itself on a periodic axis) copy between non-overlapping offsets in the same buffer. + * - @b One local, one remote: emit NCCL group entries per component run ( @c Send / @c Recv ) + * to the peer rank. + * - @b Both remote: skipped on this rank. + * + * Per-component planes are non-contiguous in carbon's SoA layout (separated by + * @c span.linear_storage_elements()), so each @c Components plane contributes its own entry + * on both the intra and dist sides. + * + * @par NCCL pairing order + * Within each direction @c Send precedes @c Recv, and cross-rank entries are sorted + * deterministically by @c (peer, op, (axis, source_rank, source_side, dest_rank, dest_side, + * component, run_index)) so both ends of a same-peer connection, including the two directions + * of a periodic @c dims == 2 axis, enqueue operations in a matching order. The run index is + * required because one X/Y halo face fans out into multiple runs that share the same axis, + * ranks, and component; without it @c std::sort could permute those runs differently on the + * two ranks. + * + * @par BoundaryModeDistributed + * - @ref BoundaryModeDistributed::Open: out-of-domain reads return @c valid = false; no wrap pair is + * added on that axis. + * - @ref BoundaryModeDistributed::PeriodicX / @c PeriodicY / @c PeriodicZ: the corresponding axis wraps. + * On an axis with exactly one process-grid coordinate the wrap pair is a self-pair handled + * intra. Periodicity is independent per axis. + * + * @par Synchronisation contract + * @c HaloDistributed issues async copies (intra) and grouped @c ncclSend / @c ncclRecv (dist) on the + * user's stream. The caller must: + * - ensure any kernel writing the @b source cells (own owned cells, both directions) has + * completed before @c operator() is called (e.g. by sharing the same stream or by event + * sync); + * - and wait for the stream before any kernel that reads the halo cells (the natural + * ordering on the same stream is enough). + * + * Multi-axis layouts fence each staged pass before starting the next one (and synchronise the + * distributed communicator between passes under MPI/NCCL), so the X result is visible to the Y + * pass and Y to Z. Closing the last pass therefore covers the whole exchange. + * + * @note On multi-GPU layouts the "same stream is enough" rule does @b not by itself order a + * peer copy against the @b source GPU's compute: a cross-device copy is enqueued on the + * @b destination GPU's stream and carries no implicit ordering against pending writes on the + * source GPU's stream (see @c StreamGroup::wait_for_all ). @c operator() therefore opens with + * an internal cross-GPU producer fence — it records every per-GPU stream's tail and fan-in- + * waits — so the copies are sequenced behind every GPU's prior compute, and the same fence on + * the next call covers the copy-vs-next-overwrite WAR. Callers driving @c HaloDistributed on a single + * stream get correct multi-GPU results without any extra event juggling; the fence collapses + * to a no-op on single-GPU / no-halo layouts. + * + * @tparam T Element type of the field (matches @c DenseDistributed::Field). + * @tparam Components Per-cell component count (matches @c DenseDistributed::Field). + */ +template +class HaloDistributed { +public: + /** Empty descriptor; @ref operator() is a no-op (zero entries). */ + HaloDistributed() = default; + + /** + * Build a @c StencilSemantic::Standard halo-exchange descriptor for @p field — every + * component plane of every adjacency pair is moved as its own + * @c cudaMemcpyAsync entry per direction (the aggregated layout has no cross-component + * fusion, since cardinality planes sit @c linear_storage_elements apart). + * + * @throws std::invalid_argument when the field has no GPU buffers and the layout requires + * inter-slab exchange, or when the field's @ref BoundaryModeDistributed is unrecognised. + */ + explicit HaloDistributed(DenseDistributed::Field field) + : HaloDistributed(std::move(field), + Stencil{}, + StencilSemantic::Standard) {} + + /** + * Build a halo-exchange descriptor with explicit @p semantic . + * + * @c StencilSemantic::Standard ignores @p stencil and is equivalent to the no-stencil + * constructor. @c StencilSemantic::Lattice interprets @p stencil 's points as the discrete + * velocities @c c_q of the field's @c Components populations and only sends populations + * whose @c c_q component on the current axis matches the transfer direction. The aggregated + * layout has no cross-cardinality fusion, so each axis pass moves the populations selected + * by that axis (see @ref Stencil::lattice_profile ). + * + * @par Lattice pre-conditions (validated at construction) + * + * - @c stencil.size() must equal @c Components . + * - @c stencil.radius() must be @c <= the corresponding per-axis halo thickness. + * - @p semantic must be one of @c Standard / @c Lattice . + * + * @throws std::invalid_argument on any of the above failing. + */ + HaloDistributed(DenseDistributed::Field field, + Stencil stencil, + StencilSemantic semantic = StencilSemantic::Lattice); + + /** Field this descriptor is bound to. */ + [[nodiscard]] auto + field() const noexcept -> const DenseDistributed::Field& { + return field_; + } + + /** Boundary mode driving the exchange (read off the field's @c DenseDistributed at construction). */ + [[nodiscard]] auto + boundary_mode() const noexcept -> BoundaryModeDistributed { + return field_.dense().boundary_mode(); + } + + [[nodiscard]] auto + stencil_semantic() const noexcept -> StencilSemantic { + return semantic_; + } + + [[nodiscard]] auto + stencil() const noexcept -> const Stencil& { + return stencil_; + } + + /** + * Number of intra-process transfer entries the exchange will issue across all staged axis + * passes. Zero for a single GPU, an empty layout, no halo, or a distributed + * one-rank-per-GPU layout where every adjacent pair is cross-rank. + */ + [[nodiscard]] auto + pair_count() const noexcept -> size_t { + if (!axis_passes_.empty()) { + size_t n = 0; + for (const AxisPass& pass : axis_passes_) { + n += pass.intra.src_counts().size(); + } + return n; + } + return intra_.src_counts().size(); + } + + /** + * Number of cross-rank @c Send / @c Recv NCCL group entries the exchange will issue. Equals + * @c 2 * Components * peer_count (with @c peer_count in @c {0, 1, 2}) per active axis when + * MPI is enabled and the field's @c System carries a @c Distributed handle; @c 0 in non-MPI + * builds, in single-process layouts, or when no axis needs halo exchange. + */ + [[nodiscard]] auto + dist_entry_count() const noexcept -> size_t { +#ifdef CARBON_HAVE_MPI_NCCL + if (!axis_passes_.empty()) { + size_t n = 0; + for (const AxisPass& pass : axis_passes_) { + n += pass.dist.entry_count(); +#if CARBON_BACKEND_IS_CUDALIKE + n += pass.dist_staged.entry_count(); +#endif + } + return n; + } + return dist_.entry_count(); +#else + return 0U; +#endif + } + + /** + * Issue the halo updates on @p stream. Dispatches the precomputed intra-process + * @c Transfer followed by the cross-rank @c DistTransfer (the latter only in MPI + * builds). Both are no-ops when their respective entry counts are zero, so this is safe to + * call regardless of the layout. + */ + auto + operator()(const Stream& stream) const -> void { + // Cross-GPU producer fence (see @c StreamGroup::wait_for_all). The intra peer + // copies read each pair's SOURCE-GPU owned cells — written by prior compute on + // the source GPU's stream — but @c cudaMemcpyPeerAsync enqueued on the + // DESTINATION GPU's stream carries no implicit ordering against that source-side + // compute. Record every per-GPU stream's current tail and fan-in-wait so each + // copy is sequenced behind every GPU's prior writes; the same fence on the next + // halo call transitively covers the copy-vs-next-overwrite WAR. Without this the + // halo silently reads transient source bytes under cross-GPU timing pressure (a + // genuine but contention-masked numerical drift, not just harness contention). + // @c fence_event_ is empty for single-GPU / no-halo layouts, where the whole + // block is skipped. + if (!fence_event_.empty()) { + fence_event_.record(stream); + stream.wait_for_all(fence_event_); + } + if (!axis_passes_.empty()) { + for (size_t i = 0; i < axis_passes_.size(); ++i) { + const AxisPass& pass = axis_passes_[i]; + + // Packed X/Y faces: gather -> [intra] -> one NCCL message per side -> scatter, all on + // `stream`, so ordinary stream order (not a host barrier) sequences gather < comm < scatter + // and this pass < the next pass. Empty for Z passes and for run-based fallbacks. +#if CARBON_BACKEND_IS_CUDALIKE + run_pack_steps_(pass.gathers, stream, /*gather=*/true); +#endif + pass.intra(stream); +#ifdef CARBON_HAVE_MPI_NCCL + pass.dist(stream); +#if CARBON_BACKEND_IS_CUDALIKE + pass.dist_staged(stream); +#endif +#endif +#if CARBON_BACKEND_IS_CUDALIKE + run_pack_steps_(pass.scatters, stream, /*gather=*/false); +#endif + + if (i + 1U < axis_passes_.size()) { + if (!pass.fence_event.empty()) { + pass.fence_event.record(stream); + stream.wait_for_all(pass.fence_event); + } + +#ifdef CARBON_HAVE_MPI_NCCL + // Host-blocking barrier between axis passes. Kept ON by default (historical + // behaviour); CARBON_HALO_PASS_BARRIER=0 removes it. It should not be needed for + // correctness (every pass is ordered on `stream`; intra copies are fenced above) and it + // serialises the host against the GPU, which defeats overlap with interior compute. + if (pass_barrier_) { + if (const Distributed* distributed = field_.dense().system().distributed(); + distributed != nullptr) { + stream.wait(); + distributed->barrier(); + } + } +#endif + } + } + return; + } + + intra_(stream); +#ifdef CARBON_HAVE_MPI_NCCL + dist_(stream); +#endif + } + + /** + * @brief Issue the halo updates on the field's @b host (CPU) mirror. + * + * Twin of @ref operator() for fully-host pipelines: + * - Intra-process: @c std::memcpy between adjacent slabs' @c cpu_buffers using the + * same offset arithmetic as the device path (storage layout is identical + * between the two sides — the host mirror is always sized from the same + * @c span.linear_storage_elements() ). + * - Cross-rank: @b currently @b unsupported. Calling @ref launch_on_host on a + * distributed @c HaloDistributed whose adjacency includes a non-local pair throws + * @c std::runtime_error . The MPI host @c Sendrecv path is a follow-up; the + * AGENTS.md memory bullet calls this out and tracks it. + * + * Synchronous: returns when every memcpy has completed (no async work is queued). + * @p stream is waited on first so any prior device kernel writing to the field + * has flushed to the CPU mirror via a preceding @c Transfer ; mirroring the + * @ref carbon::detail::DenseHostKernelImpl stream contract. + * + * Triggers the lazy host-mirror allocation on @c MemorySide::HostDevice fields + * via @c Field::cpu_buffers() — so a halo built ahead of any host-side touch + * still finds the buffers populated when the user finally calls + * @ref launch_on_host . + * + * @throws std::invalid_argument when the field has no host mirror to write into + * (built with @c MemorySide::Device with no lazy fault-in path because + * the side is not @c HostDevice ). + * @throws std::runtime_error when @c host_dist_pending_ is non-zero — i.e. there + * is at least one cross-rank halo entry and the host MPI_Sendrecv + * fallback has not been wired in yet. + */ + auto + launch_on_host(const Stream& stream) const -> void { + stream.wait(); + if (host_dist_pending_ > 0U) { + log::throw_with_log( + "HaloDistributed::launch_on_host: cross-rank host halo is not yet supported (this halo " + "has {} " + "cross-rank slab entries). The host MPI_Sendrecv fallback is a follow-up tracked in " + "AGENTS.md (\"HaloDistributed on host\" memory bullet); for now use launch (device) on a " + "halo " + "whose pairs cross ranks, or restrict the layout to one rank.", + host_dist_pending_); + } + const bool multi_axis = !axis_passes_.empty(); + size_t host_entries = host_intra_.size(); + if (multi_axis) { + host_entries = 0; + for (const AxisPass& pass : axis_passes_) { + host_entries += pass.host_intra.size(); + } + } + if (host_entries == 0U) { + return; + } + + auto& cpu = field_.cpu_buffers(); + if (cpu.size() == 0U) { + log::throw_with_log( + "HaloDistributed::launch_on_host: field has no host mirror (cpu_buffers().size() == 0); " + "construct the field with MemorySide::Host or MemorySide::HostDevice"); + } + + const auto copy = [&](const HostIntraEntry& e) { + T* const dst_ptr = cpu[e.dst_slab].data() + e.dst_offset; + const T* const src_ptr = cpu[e.src_slab].data() + e.src_offset; + std::memcpy(static_cast(dst_ptr), static_cast(src_ptr), + e.count * sizeof(T)); + }; + + if (multi_axis) { + for (const AxisPass& pass : axis_passes_) { + for (const HostIntraEntry& e : pass.host_intra) { + copy(e); + } + } + } else { + for (const HostIntraEntry& e : host_intra_) { + copy(e); + } + } + } + + /** + * @brief Number of intra-process @c std::memcpy entries the host launch will issue. + * + * Same shape as @ref pair_count but measured against the host pipeline. Equals + * @ref pair_count today (the pair set is independent of which buffer side + * receives the writes); kept as its own accessor so future asymmetric host / + * device pair sets (e.g. when the host path lifts to @c MPI_Sendrecv ) have a + * dedicated query. + */ + [[nodiscard]] auto + host_intra_count() const noexcept -> size_t { + if (!axis_passes_.empty()) { + size_t n = 0; + for (const AxisPass& pass : axis_passes_) { + n += pass.host_intra.size(); + } + return n; + } + return host_intra_.size(); + } + +private: + /** + * Per-direction intra-process host halo entry: a single @c std::memcpy of @c count + * elements of @p T from @c src_slab 's buffer at @c src_offset (in elements) into + * @c dst_slab 's buffer at @c dst_offset . + * + * Per-component planes contribute their own entry, same as the device intra + * path. Storage layout matches between gpu and cpu buffers (both sized from + * @c span.linear_storage_elements() ), so @c src_offset / @c dst_offset / @c count + * are computed once at @c HaloDistributed construction and reused at every host launch. + */ + struct HostIntraEntry { + size_t src_slab{}; + size_t dst_slab{}; + size_t src_offset{}; + size_t dst_offset{}; + size_t count{}; + }; + + struct AxisPass { + Axis axis{Axis::X}; + Transfer intra{}; +#ifdef CARBON_HAVE_MPI_NCCL + DistTransfer dist{}; +#endif + std::vector host_intra{}; + mutable Event fence_event{}; +#if CARBON_BACKEND_IS_CUDALIKE + // Packed X/Y exchange (see detail/halo_pack_plan.h). Empty unless this pass was packed. + std::vector gathers{}; + std::vector scatters{}; + std::vector staged_msgs{}; +#ifdef CARBON_HAVE_MPI_NCCL + DistTransfer dist_staged{}; ///< bound to HaloDistributed::stage_, not to the field buffer +#endif +#endif + }; + + auto + build_multi_axis_() -> void; + +#if CARBON_BACKEND_IS_CUDALIKE + /** Launch every gather (or scatter) kernel of one pass on @p stream. */ + auto + run_pack_steps_(const std::vector& steps, + const Stream& stream, + bool gather) const -> void { + if (steps.empty()) { + return; + } + const detail::Gpu& gpu = field_.dense().system().gpu_group().devices()[0]; + const detail::gpu_stream_t native = stream.native_at(0); + T* field_base = field_.gpu_buffers()[0].data(); + T* stage_base = stage_[0].data(); + for (const detail::halo_pack::PackStep& step : steps) { + const detail::gpu_error_t err = + gather + ? detail::halo_pack::launch_gather(gpu, native, sizeof(T), field_base, + stage_base + step.stage_offset, step.args) + : detail::halo_pack::launch_scatter( + gpu, native, sizeof(T), stage_base + step.stage_offset, field_base, step.args); + if (err != detail::gpu_success) { + log::throw_with_log( + "HaloDistributed packed {} kernel launch failed: {}", gather ? "gather" : "scatter", + detail::gpu_error_string(err)); + } + } + } +#endif + + DenseDistributed::Field field_{}; + Transfer intra_{}; +#ifdef CARBON_HAVE_MPI_NCCL + DistTransfer dist_{}; +#endif + // Per-GPU event group backing the cross-GPU producer fence in @ref operator(). + // Allocated only when the layout has intra-process peer pairs (multi-local-GPU); + // stays empty (so the fence is skipped) for single-GPU / no-halo layouts. Mutable + // because the fence records into it from the const @ref operator() — the group is a + // shallow shared handle, so recording mutates the underlying events in place. + mutable Event fence_event_{}; + std::vector host_intra_{}; + std::vector axis_passes_{}; +#if CARBON_BACKEND_IS_CUDALIKE + // One contiguous staging buffer shared by every packed pass (single local GPU only). Allocated + // in the constructor so no allocation can land inside graph capture or a timed region. + Buffer stage_{}; +#endif + // See operator(): host barrier between axis passes. CARBON_HALO_PASS_BARRIER=0 disables it. + bool pass_barrier_{true}; + Stencil stencil_{}; + StencilSemantic semantic_{StencilSemantic::Standard}; + // Number of cross-rank slab pairs that the host pipeline would need to handle. + // Non-zero in distributed runs; consulted by @ref launch_on_host so we throw a + // clean diagnostic instead of silently dropping the cross-rank halo on the + // floor. Once the @c MPI_Sendrecv fallback lands this becomes the count of + // host-MPI entries instead of a "todo" sentinel. + size_t host_dist_pending_{}; +}; + +// --------------------------------------------------------------------------- +// HaloDistributed::HaloDistributed — descriptor builder. +// +// Behaviour-preserving split of the original ~262 LOC ctor body into a thin +// orchestrator that delegates to phase helpers in `detail/halo_build.h` and +// keeps only the DenseDistributed-specific per-pair offset arithmetic inline. See the +// fourth-pass audit's P1.α resolution narrative for the design rationale and +// the symmetric `HaloDisg` ctor refactor. +// --------------------------------------------------------------------------- +template +HaloDistributed::HaloDistributed(DenseDistributed::Field field, + Stencil stencil, + StencilSemantic semantic) + : field_(std::move(field)), + stencil_(std::move(stencil)), + semantic_(semantic) { + // ---------- Phase 1: validate semantic + boundary + lattice radius ---------- + detail::halo_build::validate_stencil_semantic(semantic_, "HaloDistributed"); + + const DenseDistributed& dense = field_.dense(); + const auto& spans = dense.spans(); + const auto& gpu_buffers = field_.gpu_buffers(); + const size_t n_gpus = spans.size(); + + // ---------- Phase 2: short-circuit on empty / no-halo layouts ---------- + if (n_gpus == 0U) { + // Empty layout: no slabs to exchange. intra_/dist_ stay default-constructed. + return; + } + + const bool legacy_slab = dense.process_grid().is_slab() && + !is_periodic(dense.boundary_mode(), Axis::X) && + !is_periodic(dense.boundary_mode(), Axis::Y); + + // The legacy slab builder emits one cross-rank message per component per direction. For a + // distributed Z-slab with several components per face, hand the layout to the axis builder + // instead: it packs each face into one message per side (a single Z pass). Single-process + // multi-GPU slabs keep the legacy peer-copy path. +#if CARBON_BACKEND_IS_CUDALIKE + const bool slab_via_axis_builder = legacy_slab && Components > 1 && n_gpus == 1U && + dense.system().distributed() != nullptr && + spans[0].halo().z > 0 && gpu_buffers.size() == n_gpus && + detail::halo_pack::env_flag("CARBON_HALO_PACK", true) && + detail::halo_pack::env_flag("CARBON_HALO_PACK_Z", true) && + detail::halo_pack::element_size_supported(sizeof(T)) && + dense.system().gpu_group().size() == 1U; +#else + constexpr bool slab_via_axis_builder = false; +#endif + + if (!legacy_slab || slab_via_axis_builder) { + detail::halo_distributed_build::validate_boundary_mode_bits(dense.boundary_mode(), + "HaloDistributed"); + + const int64_3d halo = spans[0].halo(); + + if (semantic_ == StencilSemantic::Lattice) { + if (stencil_.size() != static_cast(Components)) { + log::throw_with_log( + "HaloDistributed(lattice): stencil.size() = {} but Components = {}; the lattice halo " + "pairs " + "population q with stencil.points()[q] and requires equal counts", + stencil_.size(), Components); + } + + const int32_3d r = stencil_.radius3(); + if ((halo.x > 0 && static_cast(r.x) > halo.x) || + (halo.y > 0 && static_cast(r.y) > halo.y) || + (halo.z > 0 && static_cast(r.z) > halo.z)) { + log::throw_with_log( + "HaloDistributed(lattice): stencil radius3 ({}, {}, {}) exceeds halo ({}, {}, {})", r.x, + r.y, r.z, halo.x, halo.y, halo.z); + } + } + + if (halo.x > 0 || halo.y > 0 || halo.z > 0) { + build_multi_axis_(); + } + return; + } + + // Reaching the legacy branch means X and Y are open; reject stray mask bits, then read Z. + detail::halo_distributed_build::validate_boundary_mode_bits(dense.boundary_mode(), + "HaloDistributed"); + const bool periodic_z = is_periodic(dense.boundary_mode(), Axis::Z); + + const int64_t halo_z = spans[0].halo_z(); + if (halo_z <= 0) { + // Stencil radius 0: there is no halo region in storage to exchange. + return; + } + + if (semantic_ == StencilSemantic::Lattice) { + if (stencil_.size() != static_cast(Components)) { + log::throw_with_log( + "HaloDistributed(lattice): stencil.size() = {} but Components = {}; the lattice halo " + "pairs " + "population q with stencil.points()[q] and requires equal counts", + stencil_.size(), Components); + } + if (stencil_.radius() > static_cast(halo_z)) { + log::throw_with_log( + "HaloDistributed(lattice): stencil radius {} > halo_z {} (each lattice halo entry copies " + "halo_z xy-planes; the field's halo is too thin for this stencil)", + stencil_.radius(), halo_z); + } + } + + // Cardinality activity filter: the only direction-relevant axis on a z-partitioned grid + // is z (mirroring Neon's lattice halo). Standard semantic keeps every cardinality. + auto active_up = [&](int c) noexcept -> bool { + if (semantic_ == StencilSemantic::Standard) { + return true; + } + return stencil_.points()[static_cast(c)].z > 0; + }; + auto active_down = [&](int c) noexcept -> bool { + if (semantic_ == StencilSemantic::Standard) { + return true; + } + return stencil_.points()[static_cast(c)].z < 0; + }; + + // Host-only fields (MemorySide::Host) carry no GPU buffers; the host_intra_ + // metadata is still populated and @ref launch_on_host works. The device path + // (operator() / launch_on_device) checks for a populated intra_/dist_ at call + // time, so the only failure mode is "user constructed a host-only field but + // tried to launch the halo on a device kernel" — which trips the empty-Transfer + // path naturally. We only reject the cross-rank case below where gpu_buffers + // are required for NCCL. + const bool has_gpu_buffers = (gpu_buffers.size() == n_gpus); + + // ---------- Phase 3: build adjacency list ---------- + const size_t global_n = dense.global_slab_count(); + const size_t local_offset = dense.local_slab_offset(); + const auto adjacency = detail::halo_build::adjacency_pairs(global_n, periodic_z); + + // Legacy Slab path: every local span shares the full x/y extent and pitch. Cache common + // values off the local span (used for both intra and dist offset arithmetic). + const int64_t pitch = spans[0].xy_slab_elements(); + const size_t halo_count = static_cast(halo_z * pitch); + + auto is_local = [&](size_t g) noexcept -> bool { + return g >= local_offset && g < local_offset + n_gpus; + }; + + // ---------- Phase 4: walk adjacency, classify pairs, accumulate entries ---------- + // + // Intra-process entries cover every adjacency pair where both endpoints are local + // (single-process multi-GPU + PeriodicZ self-wrap on a single-slab layout). + // Cross-rank entries cover pairs with exactly one local endpoint; one Send + one + // Recv per component plane per pair. Send/Recv FIFO ordering is preserved by + // issuing Send before Recv within each direction and iterating components in + // ascending order on every rank, so NCCL's per-peer FIFO matches automatically. + detail::halo_build::IntraTransferBuilder intra; +#ifdef CARBON_HAVE_MPI_NCCL + detail::halo_build::DistTransferBuilder dist; +#endif + + for (const auto& [g_lo, g_up] : adjacency) { + const bool lo_local = is_local(g_lo); + const bool up_local = is_local(g_up); + if (!lo_local && !up_local) { + continue; // Foreign pair; another rank handles it (or no one in non-MPI builds). + } + + if (lo_local && up_local) { + // Both endpoints local: emit two intra entries per component (upward + downward). + const size_t i_lo = g_lo - local_offset; + const size_t i_up = g_up - local_offset; + const auto& span_lo = spans[i_lo]; + const auto& span_up = spans[i_up]; + const int64_t lim_z_lo = span_lo.logic_extent().z; + const int64_t per_comp_lo = span_lo.linear_storage_elements(); + const int64_t per_comp_up = span_up.linear_storage_elements(); + + for (int c = 0; c < Components; ++c) { + const size_t cc = static_cast(c); + // Upward: slab g_lo's last halo_z owned -> slab g_up's lower halo. Skipped under + // lattice semantic when stencil[c].z <= 0. + if (active_up(c)) { + const size_t up_src_off = + cc * static_cast(per_comp_lo) + static_cast(lim_z_lo * pitch); + const size_t up_dst_off = cc * static_cast(per_comp_up); + if (has_gpu_buffers) { + intra.push(gpu_buffers[i_lo], gpu_buffers[i_up], up_src_off, up_dst_off, halo_count); + } + host_intra_.push_back({i_lo, i_up, up_src_off, up_dst_off, halo_count}); + } + + // Downward: slab g_up's first halo_z owned -> slab g_lo's upper halo. Skipped under + // lattice semantic when stencil[c].z >= 0. + if (active_down(c)) { + const size_t dn_src_off = + cc * static_cast(per_comp_up) + static_cast(halo_z * pitch); + const size_t dn_dst_off = cc * static_cast(per_comp_lo) + + static_cast((halo_z + lim_z_lo) * pitch); + if (has_gpu_buffers) { + intra.push(gpu_buffers[i_up], gpu_buffers[i_lo], dn_src_off, dn_dst_off, halo_count); + } + host_intra_.push_back({i_up, i_lo, dn_src_off, dn_dst_off, halo_count}); + } + } + continue; + } + + // Adjacency pair has exactly one local endpoint — handled by the dist branch + // below (under MPI). Track for the host launch so we can throw a pointed + // "host MPI halo not implemented" diagnostic on launch_on_host instead of + // silently dropping the cross-rank update on the floor. + ++host_dist_pending_; + +#ifdef CARBON_HAVE_MPI_NCCL + // The cross-rank branch routes through NCCL on the device buffers; host-only + // fields can't take this path today (the host MPI_Sendrecv fallback is the + // tracked follow-up). + if (!has_gpu_buffers) { + log::throw_with_log( + "HaloDistributed: cross-rank halo on a host-only field (MemorySide::Host) is not yet " + "supported; " + "use MemorySide::HostDevice (or single-rank layout)"); + } + // Exactly one endpoint is local: the other is on a peer rank. Under carbon's + // one-rank-per-GPU model peer rank == peer global slab index. + const size_t local_g = lo_local ? g_lo : g_up; + const size_t peer_g = lo_local ? g_up : g_lo; + const int peer = static_cast(peer_g); + const size_t i_local = local_g - local_offset; + const auto& span = spans[i_local]; + const int64_t lim_z = span.logic_extent().z; + const int64_t per_comp = span.linear_storage_elements(); + + // lo_local: we are the LOWER of the pair, peer is above us. Send our last halo_z owned, + // Recv into our upper halo. + // up_local: we are the UPPER of the pair, peer is below us. Send our first halo_z owned, + // Recv into our lower halo. + const size_t send_offset_base = + lo_local ? static_cast(lim_z * pitch) : static_cast(halo_z * pitch); + const size_t recv_offset_base = + lo_local ? static_cast((halo_z + lim_z) * pitch) : static_cast(0); + + // Lattice activity. lo_local sends "upward" populations (c.z > 0) and receives + // "downward" populations (c.z < 0); up_local is the mirror. + for (int c = 0; c < Components; ++c) { + const bool send_active = lo_local ? active_up(c) : active_down(c); + const bool recv_active = lo_local ? active_down(c) : active_up(c); + if (!send_active && !recv_active) { + continue; + } + const size_t plane = static_cast(c) * static_cast(per_comp); + if (send_active) { + dist.push(peer, DistOp::Send, plane + send_offset_base, halo_count); + } + if (recv_active) { + dist.push(peer, DistOp::Recv, plane + recv_offset_base, halo_count); + } + } +#else + // Adjacency pair has exactly one local endpoint, but Carbon was built without MPI -- a + // distributed DenseDistributed should have been rejected earlier; reaching here means a misconfigured + // layout. + log::throw_with_log( + "HaloDistributed: adjacency pair (g_lo={}, g_up={}) has a foreign endpoint, but Carbon was " + "built " + "without CARBON_ENABLE_MPI=ON; build with MPI to enable cross-rank halo exchange", + g_lo, g_up); +#endif + } + + // ---------- Phase 5: finalise the accumulated entries into Transfer / DistTransfer ---------- + intra_ = intra.finalise(dense.system()); +#ifdef CARBON_HAVE_MPI_NCCL + dist_ = dist.finalise(dense.system(), gpu_buffers); +#endif + + // ---------- Phase 6: allocate the cross-GPU producer fence ---------- + // Only multi-local-GPU layouts have intra peer copies that can race the source + // GPU's prior compute; single-GPU / no-halo layouts leave fence_event_ empty so + // operator() skips the fence entirely. System::event() is non-const (it appends to + // the System's event history), and dense.system() is a const ref, so take a shallow + // System copy to allocate from. + if (intra_.src_counts().size() > 0U) { + System sys = dense.system(); + fence_event_ = sys.event(); + } +} + +template +auto +HaloDistributed::build_multi_axis_() -> void { + using detail::halo_distributed_build::axis_halo_runs; + using detail::halo_distributed_build::axis_neighbour; + using detail::halo_distributed_build::axis_owned_face_runs; + using detail::halo_distributed_build::axis_value; + using detail::halo_distributed_build::AxisGeometry; + using detail::halo_distributed_build::AxisSide; + + const DenseDistributed& dense = field_.dense(); + const ProcessGrid& pg = dense.process_grid(); + const auto& spans = dense.spans(); + const auto& gpu_buffers = field_.gpu_buffers(); + const bool has_gpu_buffers = gpu_buffers.size() == spans.size(); + +#ifdef CARBON_HAVE_MPI_NCCL + const Distributed* distributed_handle = dense.system().distributed(); + const bool distributed = distributed_handle != nullptr; + const int world_rank = distributed ? distributed_handle->world_rank() : 0; +#else + const bool distributed = false; + const int world_rank = 0; +#endif + + const auto geom_of = [](const DenseDistributed::Span& s) -> AxisGeometry { + return AxisGeometry{ + s.logic_extent(), + s.halo(), + s.haloed_extent(), + s.xy_slab_elements(), + }; + }; + + const auto velocity = [&](int c, Axis axis) -> int64_t { + return axis_value(stencil_.points()[static_cast(c)], axis); + }; + + const auto active_send = [&](int c, Axis axis, AxisSide side) -> bool { + if (semantic_ == StencilSemantic::Standard) { + return true; + } + const int64_t v = velocity(c, axis); + return side == AxisSide::Upper ? v > 0 : v < 0; + }; + + const auto active_recv = [&](int c, Axis axis, AxisSide side) -> bool { + if (semantic_ == StencilSemantic::Standard) { + return true; + } + const int64_t v = velocity(c, axis); + return side == AxisSide::Upper ? v < 0 : v > 0; + }; + + pass_barrier_ = detail::halo_pack::env_flag("CARBON_HALO_PASS_BARRIER", true); + +#if CARBON_BACKEND_IS_CUDALIKE + // Packed X/Y faces: one message per side instead of one per contiguous row. Needs exactly one + // local GPU (every distributed rank, or a single-GPU process) and a plain 1/2/4/8/16-byte T. + // CARBON_HALO_PACK=0 forces the run-based path (A/B testing, debugging). + const bool pack_ok = detail::halo_pack::env_flag("CARBON_HALO_PACK", true) && + detail::halo_pack::element_size_supported(sizeof(T)) && has_gpu_buffers && + spans.size() == 1U && dense.system().gpu_group().size() == 1U; + // A Z face is already contiguous PER COMPONENT, so packing only pays when a face carries + // several components: otherwise it costs one NCCL message per component per direction (76 per + // rank per exchange for D3Q19 Standard), and the ones crossing a node boundary go through the + // network proxy back to back. CARBON_HALO_PACK_Z=0 restores the per-component Z path. + const bool pack_z = + pack_ok && Components > 1 && detail::halo_pack::env_flag("CARBON_HALO_PACK_Z", true); + size_t stage_total = 0; +#endif + +#ifdef CARBON_HAVE_MPI_NCCL + struct DistEntry { + int peer; + DistOp op; + size_t first; + size_t count; + std::tuple key; + }; +#endif + + for (const Axis axis : {Axis::X, Axis::Y, Axis::Z}) { + if (axis_value(spans[0].halo(), axis) <= 0) { + continue; + } + + AxisPass pass; + pass.axis = axis; + + // X/Y faces are strided, so they are always packed. A Z face is one contiguous run per + // component: it is packed only when it carries several components (see pack_z above). + bool pack_axis = false; +#if CARBON_BACKEND_IS_CUDALIKE + detail::halo_pack::AxisPackPlan pack_plan; + if (pack_ok && (axis == Axis::X || axis == Axis::Y || (axis == Axis::Z && pack_z))) { + pack_axis = true; + const int32_3d pcoords = distributed ? pg.coords_of(world_rank) : pg.coords_of(0); + const int32_t prank = distributed ? world_rank : 0; + pack_plan = detail::halo_pack::build_axis_pack_plan( + pg, dense.boundary_mode(), pcoords, prank, geom_of(spans[0]), axis, Components, + static_cast(spans[0].linear_storage_elements()), active_send, active_recv, + stage_total); + stage_total += pack_plan.stage_elems; + } +#endif + + detail::halo_build::IntraTransferBuilder intra; +#ifdef CARBON_HAVE_MPI_NCCL + detail::halo_build::DistTransferBuilder dist; + std::vector dist_entries; +#endif + + for (size_t i = 0; i < spans.size(); ++i) { + const DenseDistributed::Span& dst_span = spans[i]; + const int32_3d coords = + distributed ? pg.coords_of(world_rank) : pg.coords_of(static_cast(i)); + const int32_t local_rank = distributed ? world_rank : static_cast(i); + + const AxisGeometry dst_geom = geom_of(dst_span); + const int64_t dst_per_card = dst_span.linear_storage_elements(); + + for (const AxisSide side : {AxisSide::Lower, AxisSide::Upper}) { + const auto nb = axis_neighbour(pg, coords, axis, dense.boundary_mode(), side); + if (!nb.present) { + continue; + } + + const auto dst_runs = axis_halo_runs(dst_geom, axis, side); + const AxisSide src_side = side == AxisSide::Lower ? AxisSide::Upper : AxisSide::Lower; + + if (!distributed || nb.rank == local_rank) { + const size_t src_slab = distributed ? i : static_cast(nb.rank); + const AxisGeometry src_geom = geom_of(spans[src_slab]); + const auto src_runs = axis_owned_face_runs(src_geom, axis, src_side); + + if (src_runs.size() != dst_runs.size()) { + log::throw_with_log( + "HaloDistributed: axis run cardinality mismatch ({} vs {})", src_runs.size(), + dst_runs.size()); + } + + const int64_t src_per_card = spans[src_slab].linear_storage_elements(); + + for (size_t r = 0; r < dst_runs.size(); ++r) { + if (src_runs[r].count != dst_runs[r].count) { + log::throw_with_log( + "HaloDistributed: axis run count mismatch ({} vs {})", src_runs[r].count, + dst_runs[r].count); + } + + for (int c = 0; c < Components; ++c) { + if (!active_recv(c, axis, side)) { + continue; + } + + const size_t src_off = + static_cast(c) * static_cast(src_per_card) + src_runs[r].offset; + const size_t dst_off = + static_cast(c) * static_cast(dst_per_card) + dst_runs[r].offset; + + if (has_gpu_buffers && !pack_axis) { + intra.push(gpu_buffers[src_slab], gpu_buffers[i], src_off, dst_off, + dst_runs[r].count); + } + + pass.host_intra.push_back({ + src_slab, + i, + src_off, + dst_off, + dst_runs[r].count, + }); + } + } + continue; + } + +#ifdef CARBON_HAVE_MPI_NCCL + ++host_dist_pending_; + + if (!has_gpu_buffers) { + log::throw_with_log( + "HaloDistributed: cross-rank halo on a host-only field is not supported"); + } + + if (pack_axis) { + continue; // this side is carried by the packed messages in pack_plan + } + + const auto src_runs = axis_owned_face_runs(dst_geom, axis, side); + if (src_runs.size() != dst_runs.size()) { + log::throw_with_log( + "HaloDistributed: axis run cardinality mismatch ({} vs {})", src_runs.size(), + dst_runs.size()); + } + + for (size_t r = 0; r < dst_runs.size(); ++r) { + if (src_runs[r].count != dst_runs[r].count) { + log::throw_with_log( + "HaloDistributed: axis run count mismatch ({} vs {})", src_runs[r].count, + dst_runs[r].count); + } + + const int axis_id = static_cast(axis); + const int local_side = static_cast(side); + const int peer_side = 1 - local_side; + + for (int c = 0; c < Components; ++c) { + const size_t plane = static_cast(c) * static_cast(dst_per_card); + + if (active_send(c, axis, side)) { + dist_entries.push_back({ + static_cast(nb.rank), + DistOp::Send, + plane + src_runs[r].offset, + src_runs[r].count, + { + axis_id, + static_cast(local_rank), + local_side, + static_cast(nb.rank), + peer_side, + c, + r, + }, + }); + } + if (active_recv(c, axis, side)) { + dist_entries.push_back({ + static_cast(nb.rank), + DistOp::Recv, + plane + dst_runs[r].offset, + dst_runs[r].count, + { + axis_id, + static_cast(nb.rank), + peer_side, + static_cast(local_rank), + local_side, + c, + r, + }, + }); + } + } + } +#else + log::throw_with_log( + "HaloDistributed: multi-axis cross-rank exchange requires CARBON_ENABLE_MPI=ON"); +#endif + } + } + + pass.intra = intra.finalise(dense.system()); +#ifdef CARBON_HAVE_MPI_NCCL + // NCCL P2P has no tags: keep both sides' per-peer operation order identical. + std::sort(dist_entries.begin(), dist_entries.end(), [](const DistEntry& a, const DistEntry& b) { + return std::tie(a.peer, a.op, a.key) < std::tie(b.peer, b.op, b.key); + }); + for (const DistEntry& entry : dist_entries) { + dist.push(entry.peer, entry.op, entry.first, entry.count); + } + pass.dist = dist.finalise(dense.system(), gpu_buffers); +#endif + + if (!pass.intra.src_counts().empty()) { + System sys = dense.system(); + pass.fence_event = sys.event(); + } + +#if CARBON_BACKEND_IS_CUDALIKE + if (pack_axis) { + pass.gathers = std::move(pack_plan.gathers); + pass.scatters = std::move(pack_plan.scatters); + pass.staged_msgs = std::move(pack_plan.msgs); + } +#endif + + axis_passes_.push_back(std::move(pass)); + } + + for (const AxisPass& pass : axis_passes_) { + if (!pass.intra.src_counts().empty()) { + System sys = dense.system(); + fence_event_ = sys.event(); + break; + } + } + +#if CARBON_BACKEND_IS_CUDALIKE + if (stage_total > 0U) { + stage_ = dense.system().template buffer(std::vector{stage_total}); +#ifdef CARBON_HAVE_MPI_NCCL + for (AxisPass& pass : axis_passes_) { + if (pass.staged_msgs.empty()) { + continue; + } + // Same rule as the run-based path: NCCL P2P has no tags, so both ends of every peer pair must + // issue operations in the same order (all sends before recvs, ordered by a symmetric key). + detail::halo_pack::sort_msgs(pass.staged_msgs); + detail::halo_build::DistTransferBuilder staged; + for (const detail::halo_pack::PackMsg& m : pass.staged_msgs) { + staged.push(m.peer, m.op == detail::halo_pack::MsgOp::Send ? DistOp::Send : DistOp::Recv, + m.first, m.count); + } + pass.dist_staged = staged.finalise(dense.system(), stage_); + } +#endif + } +#endif +} + +/** + * CTAD guide: @c HaloDistributed(field) deduces @c HaloDistributed from a @c DenseDistributed::Field. + */ +template +HaloDistributed(DenseDistributed::Field) -> HaloDistributed; + +template +HaloDistributed(DenseDistributed::Field, + Stencil, + StencilSemantic) -> HaloDistributed; + +} // namespace carbon diff --git a/include/carbon/kernel.h b/include/carbon/kernel.h index 3338d6b7..d681f489 100644 --- a/include/carbon/kernel.h +++ b/include/carbon/kernel.h @@ -46,11 +46,13 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -670,6 +672,19 @@ class Kernel { Components> h, std::string name = {}) -> Kernel; + /** + * @brief Wrap a @c HaloDistributed into a @c Kernel . The multi-axis + * (slab / pencil / brick) twin of @ref halo above: forwards @ref launch to the halo's + * @c operator()(stream) ; the @c DataView argument is ignored. Used by + * @c DenseDistributed::Field::make_halo_kernel . + */ + template + [[nodiscard]] static auto + halo_distributed(HaloDistributed h, + std::string name = {}) -> Kernel; + /** * @brief Build a dual-target (universal) compute kernel. * @@ -831,6 +846,7 @@ class Kernel { #include #include #include +#include #include #include #include @@ -927,6 +943,16 @@ Kernel::halo_disg(HaloDisg(std::move(h), std::move(name))); } +template +auto +Kernel::halo_distributed(HaloDistributed h, + std::string name) -> Kernel { + using Impl = detail::HaloDistributedKernelImpl; + return Kernel(std::make_shared(std::move(h), std::move(name))); +} + inline auto Kernel::anchor(std::string name) -> Kernel { return Kernel(std::make_shared(std::move(name))); @@ -1012,6 +1038,7 @@ Kernel::host_reduce(const Grid& grid, #include #include #include +#include #include // ----- HaloFactoryBase + TypedHaloFactory ----- diff --git a/include/carbon/process_grid.h b/include/carbon/process_grid.h new file mode 100644 index 00000000..86b2d734 --- /dev/null +++ b/include/carbon/process_grid.h @@ -0,0 +1,130 @@ +#pragma once + +#include +#include + +#include + +namespace carbon { + +/** + * Axis index used by per-axis process-grid and boundary queries. + */ +enum class Axis : std::uint8_t { + X = 0, + Y = 1, + Z = 2, +}; + +/** + * How the global domain is split across ranks. + * + * @c Slab reproduces carbon's historical Z-only layout: @c (Px,Py,Pz)=(1,1,P). + * @c Pencil and @c Brick expose Y and X as additional split axes. + */ +enum class DecompositionMode : std::uint8_t { + Slab = 0, + Pencil = 1, + Brick = 2, + Custom = 3, +}; + +/** + * Rank <-> process-coordinate mapping for a 3D decomposition. + * + * Coordinates are stored as @c (px,py,pz) and ranks are assigned in row-major order with + * Z fastest: + * @code + * rank = px * (Py * Pz) + py * Pz + pz + * @endcode + * Consequently @c Slab (Px=Py=1) has @c rank == pz, matching carbon's existing Z-only + * partitioning. + * + * @par Auto-factorization + * @ref make splits @p world_size across the axes that are free for the requested mode. Prime + * factors are assigned largest-first to the currently smallest free axis, considering Z before Y + * before X. This keeps the grid balanced while keeping Z as the fastest-varying axis. Call + * @ref custom when an exact grid is required. + * + * @par Host-only + * This type is a host-side layout description; it is not copied into device memory. It performs + * bounds checks and throws rather than returning sentinels. + */ +class CARBON_API ProcessGrid { +public: + /** Default: a one-rank slab, @c (1,1,1). */ + ProcessGrid() noexcept = default; + + /** + * Auto-factorize @p world_size into a grid matching @p mode. + * + * @throws std::invalid_argument if @p world_size <= 0, or if @p mode is @c Custom (use + * @ref custom instead). + */ + [[nodiscard]] static auto + make(int32_t world_size, + DecompositionMode mode) -> ProcessGrid; + + /** + * Build an exact @c (Px,Py,Pz) grid. + * + * @throws std::invalid_argument if @p world_size <= 0, any dimension is <= 0, or + * @c px*py*pz != world_size. + */ + [[nodiscard]] static auto + custom(int32_t world_size, + int32_t px, + int32_t py, + int32_t pz) -> ProcessGrid; + + /** Process-grid dimensions as @c (Px,Py,Pz). */ + [[nodiscard]] auto + dims() const noexcept -> int32_3d { + return dims_; + } + + /** Decomposition mode supplied at construction (@c Custom for @ref custom). */ + [[nodiscard]] auto + mode() const noexcept -> DecompositionMode { + return mode_; + } + + /** Total number of ranks, @c Px*Py*Pz. */ + [[nodiscard]] auto + world_size() const noexcept -> int32_t { + return static_cast(dims_.volume()); + } + + /** True when @c Px == Py == 1, i.e. the historical Z-slab layout. */ + [[nodiscard]] auto + is_slab() const noexcept -> bool { + return dims_.x == 1 && dims_.y == 1; + } + + /** + * Map a global rank to process coordinates. + * + * @throws std::out_of_range if @p rank is outside @c [0,world_size()). + */ + [[nodiscard]] auto + coords_of(int32_t rank) const -> int32_3d; + + /** + * Map process coordinates back to the global rank. + * + * @throws std::out_of_range if any coordinate is outside its axis' grid extent. + */ + [[nodiscard]] auto + rank_of(int32_3d coords) const -> int32_t; + +private: + ProcessGrid(int32_3d dims, + DecompositionMode mode) noexcept + : dims_(dims), + mode_(mode) {} + + int32_3d dims_{1, 1, 1}; + DecompositionMode mode_{DecompositionMode::Slab}; +}; + +} // namespace carbon \ No newline at end of file diff --git a/include/carbon/stencil.h b/include/carbon/stencil.h index 56c89cf8..0369b823 100644 --- a/include/carbon/stencil.h +++ b/include/carbon/stencil.h @@ -121,6 +121,13 @@ class CARBON_API Stencil { [[nodiscard]] auto radius() const noexcept -> std::int32_t; + /** + * Per-axis Chebyshev radius: max(|p.x|), max(|p.y|), max(|p.z|). + * Cached at construction. Empty stencil returns {0,0,0}. + */ + [[nodiscard]] auto + radius3() const noexcept -> int32_3d; + /** * Bucket the stored points by @c c.z sign and report run-length statistics — the * input the lattice-halo descriptor uses to count fused transfers (one per maximal @@ -187,8 +194,12 @@ class CARBON_API Stencil { static auto compute_radius_(const std::vector& points) noexcept -> std::int32_t; + static auto + compute_radius3_(const std::vector& points) noexcept -> int32_3d; + std::vector points_{}; std::int32_t radius_{0}; + int32_3d radius3_{}; }; } // namespace carbon diff --git a/src/dense_distributed.cpp b/src/dense_distributed.cpp new file mode 100644 index 00000000..61cad632 --- /dev/null +++ b/src/dense_distributed.cpp @@ -0,0 +1,393 @@ +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +namespace { + +using carbon::detail::dense_distributed::split_extent; + +[[nodiscard]] auto +resolve_world_size(const carbon::System& system) -> int { +#ifdef CARBON_HAVE_MPI_NCCL + if (const carbon::Distributed* dist = system.distributed(); dist != nullptr) { + return dist->world_size(); + } +#endif + return static_cast(system.gpu_group().size()); +} + +[[nodiscard]] auto +resolve_world_rank(const carbon::System& system) -> int { +#ifdef CARBON_HAVE_MPI_NCCL + if (const carbon::Distributed* dist = system.distributed(); dist != nullptr) { + return dist->world_rank(); + } +#endif + return 0; +} + +[[nodiscard]] auto +linear_count_for_slab(int64_t nx, + int64_t ny, + size_t nz_slab) -> size_t { + if (nx < 0 || ny < 0) { + carbon::log::throw_with_log( + "DenseDistributed: global x and y extents must be non-negative (nx={}, ny={})", nx, ny); + } + const int64_t nx64 = nx; + const int64_t ny64 = ny; + const int64_t nz64 = static_cast(nz_slab); + if (nz_slab > static_cast(std::numeric_limits::max())) { + carbon::log::throw_with_log( + "DenseDistributed: per-GPU z slab too large (nz_slab={})", nz_slab); + } + const int64_t prod = nx64 * ny64; + if (nx64 != 0 && prod / nx64 != ny64) { + carbon::log::throw_with_log( + "DenseDistributed: x*y overflow (nx={}, ny={})", nx64, ny64); + } + const int64_t line = prod * nz64; + if (prod != 0 && line / prod != nz64) { + carbon::log::throw_with_log( + "DenseDistributed: linear element count overflow (nx={}, ny={}, nz_slab={})", nx64, ny64, + nz_slab); + } + if (line < 0) { + carbon::log::throw_with_log( + "DenseDistributed: negative linear element count (nx={}, ny={}, nz_slab={})", nx64, ny64, + nz_slab); + } + if (static_cast(line) > static_cast(std::numeric_limits::max())) { + carbon::log::throw_with_log( + "DenseDistributed: linear element count too large for size_t (line={})", line); + } + return static_cast(line); +} + +} // namespace + +namespace carbon { +void +DenseDistributed::init_common_(System system, + int64_3d global_extent, + Stencil stencil, + BoundaryModeDistributed boundary_mode, + float32_3d origin, + float spacing, + ProcessGrid process_grid, + std::optional block_override) { + if (!std::isfinite(spacing) || spacing <= 0.0F) { + log::throw_with_log( + "DenseDistributed: spacing must be finite and strictly positive (spacing={})", spacing); + } + if (!std::isfinite(origin.x) || !std::isfinite(origin.y) || !std::isfinite(origin.z)) { + log::throw_with_log( + "DenseDistributed: origin components must be finite (origin=({}, {}, {}))", origin.x, + origin.y, origin.z); + } + if (system.gpu_group().size() == 0U) { + log::throw_with_log( + "DenseDistributed: System has zero GPUs; cannot build a grid (matches the Block / " + "DenseDisg " + "policy -- empty systems fail at the grid ctor rather than at the first newField " + "call, so the diagnostic points at the actual misconfiguration)"); + } + if (global_extent.x < 0 || global_extent.y < 0 || global_extent.z < 0) { + log::throw_with_log( + "DenseDistributed: global x, y, z extents must be non-negative (x={}, y={}, z={})", + global_extent.x, global_extent.y, global_extent.z); + } + + global_ = global_extent; + system_ = std::move(system); + stencil_ = std::move(stencil); + boundary_mode_ = boundary_mode; + origin_ = origin; + spacing_ = spacing; + process_grid_ = std::move(process_grid); + + const size_t local_n = system_.gpu_group().size(); + const int world_size = resolve_world_size(system_); + const int world_rank = resolve_world_rank(system_); + bool distributed = false; + +#ifdef CARBON_HAVE_MPI_NCCL + const Distributed* dist = system_.distributed(); + distributed = dist != nullptr; + if (dist != nullptr) { + if (local_n != 1U) { + log::throw_with_log( + "DenseDistributed: distributed System must own exactly one local GPU per rank (got {}); " + "carbon's " + "distributed model is one rank per GPU", + local_n); + } + if (world_size <= 0 || world_rank < 0 || world_rank >= world_size) { + log::throw_with_log( + "DenseDistributed: invalid Distributed state (world_size={}, world_rank={})", world_size, + world_rank); + } + if (process_grid_.world_size() != world_size) { + log::throw_with_log( + "DenseDistributed: ProcessGrid world_size ({}) does not match Distributed world_size " + "({})", + process_grid_.world_size(), world_size); + } + } else +#endif + { + if (process_grid_.world_size() != static_cast(local_n)) { + log::throw_with_log( + "DenseDistributed: ProcessGrid world_size ({}) does not match local GPU count ({})", + process_grid_.world_size(), local_n); + } + } + + const int32_3d dims = process_grid_.dims(); + if (dims.x <= 0 || dims.y <= 0 || dims.z <= 0) { + log::throw_with_log( + "DenseDistributed: ProcessGrid dimensions must be positive (dims=({}, {}, {}))", dims.x, + dims.y, dims.z); + } + if (local_n > 1U && (dims.x > 1 || dims.y > 1)) { + log::throw_with_log( + "DenseDistributed: single-process Pencil/Brick with multiple local GPUs is not supported; " + "use MPI with one rank per GPU (local GPUs={}, dims=({}, {}, {}))", + local_n, dims.x, dims.y, dims.z); + } + const int32_3d coords = process_grid_.coords_of(world_rank); + 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. + 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))) { + (void)linear_count_for_slab(static_cast(nx), static_cast(ny), nz); + } + } + } + + 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_); + + spans_ = system_.make_vector([&](size_t i) { + const int32_3d gpu_coords = + distributed ? coords : process_grid_.coords_of(static_cast(i)); + const detail::dense_distributed::RankChunk chunk = + 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_); + }); + + // 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) { + if (block_override.has_value()) { + return *block_override; + } + return dense_make_kernel_block(system_.gpu_group().devices()[i]); + }); + gpu_grid_per_view_[vi] = system_.make_vector([&](size_t i) { + const detail::Gpu& gpu = system_.gpu_group().devices()[i]; + LaunchShape grid; + detail::compute_dense_grid(spans_[i].iter_extent(view), gpu_block_per_view_[vi][i], + gpu.properties().max_threads_per_block, grid); + return grid; + }); + } +} + +DenseDistributed::DenseDistributed(System system, + int64_3d global_extent, + Stencil stencil, + BoundaryModeDistributed boundary_mode, + float32_3d origin, + float spacing, + std::optional block_override) + : DenseDistributed() { + const int world_size = resolve_world_size(system); + const ProcessGrid pg = + world_size > 0 ? ProcessGrid::make(world_size, DecompositionMode::Slab) : ProcessGrid{}; + init_common_(std::move(system), global_extent, std::move(stencil), boundary_mode, origin, spacing, + pg, block_override); +} + +DenseDistributed::DenseDistributed(System system, + int64_3d global_extent, + DecompositionMode decomposition, + Stencil stencil, + BoundaryModeDistributed boundary_mode, + float32_3d origin, + float spacing, + std::optional block_override) + : DenseDistributed() { + const int world_size = resolve_world_size(system); + const ProcessGrid pg = + world_size > 0 ? ProcessGrid::make(world_size, decomposition) : ProcessGrid{}; + init_common_(std::move(system), global_extent, std::move(stencil), boundary_mode, origin, spacing, + pg, block_override); +} + +DenseDistributed::DenseDistributed(System system, + int64_3d global_extent, + ProcessGrid process_grid, + Stencil stencil, + BoundaryModeDistributed boundary_mode, + float32_3d origin, + float spacing, + std::optional block_override) + : DenseDistributed() { + init_common_(std::move(system), global_extent, std::move(stencil), boundary_mode, origin, spacing, + std::move(process_grid), block_override); +} + +auto +DenseDistributed::process_grid() const noexcept -> const ProcessGrid& { + return process_grid_; +} + +auto +DenseDistributed::local_extent(size_t gpu) const -> int64_3d { + if (gpu >= gpu_count()) { + log::throw_with_log( + "DenseDistributed::local_extent: gpu index out of range (gpu={}, gpu_count={})", gpu, + gpu_count()); + } + return spans_[gpu].logic_extent(); +} + +auto +DenseDistributed::linear_elements(size_t gpu) const -> size_t { + if (gpu >= gpu_count()) { + log::throw_with_log( + "DenseDistributed::linear_elements: gpu index out of range (gpu={}, gpu_count={})", gpu, + gpu_count()); + } + const int64_3d owned = spans_[gpu].logic_extent(); + return linear_count_for_slab(owned.x, owned.y, static_cast(owned.z)); +} + +auto +DenseDistributed::global_extent() const noexcept -> const int64_3d& { + return global_; +} + +auto +DenseDistributed::stencil() const noexcept -> const Stencil& { + return stencil_; +} + +auto +DenseDistributed::boundary_mode() const noexcept -> BoundaryModeDistributed { + return boundary_mode_; +} + +auto +DenseDistributed::origin() const noexcept -> float32_3d { + return origin_; +} + +auto +DenseDistributed::spacing() const noexcept -> float { + return spacing_; +} + +auto +DenseDistributed::system() noexcept -> System& { + return system_; +} + +auto +DenseDistributed::system() const noexcept -> const System& { + return system_; +} + +auto +DenseDistributed::gpu_count() const noexcept -> size_t { + return system_.gpu_group().size(); +} + +auto +DenseDistributed::global_slab_count() const noexcept -> size_t { + return global_slab_count_; +} + +auto +DenseDistributed::local_slab_offset() const noexcept -> size_t { + return local_slab_offset_; +} + +auto +DenseDistributed::local_z(size_t gpu) const -> int64_t { + if (gpu >= gpu_count()) { + log::throw_with_log( + "DenseDistributed::local_z: gpu index out of range (gpu={}, gpu_count={})", gpu, + gpu_count()); + } + return spans_[gpu].logic_extent().z; +} + +auto +DenseDistributed::z_offset_global(size_t gpu) const -> int64_t { + if (gpu >= gpu_count()) { + log::throw_with_log( + "DenseDistributed::z_offset_global: gpu index out of range (gpu={}, gpu_count={})", gpu, + gpu_count()); + } + // Span::z_offset() is the start of the lower halo; the first owned layer is halo_z above it. + return spans_[gpu].z_offset() + spans_[gpu].halo_z(); +} + +auto +DenseDistributed::linear_counts_per_gpu() const -> std::vector { + return system_.make_vector([&](size_t i) { + return linear_elements(i); + }); +} + +} // namespace carbon diff --git a/src/halo_pack.cu b/src/halo_pack.cu new file mode 100644 index 00000000..2074f7eb --- /dev/null +++ b/src/halo_pack.cu @@ -0,0 +1,114 @@ +// Packed halo gather/scatter kernels (CUDA and HIP backends). See include/carbon/detail/halo_pack.h. +// +// Each __global__ is a one-line forwarder to the host+device functions in halo_pack_plan.h, which +// tests/test_halo_pack_plan.cpp exercises on the host with the same arguments. Keep the kernels +// trivial: any logic added here is NOT covered by that test. + +#include +#include +#include + +#include +#include + +namespace carbon::detail::halo_pack { +namespace { + +struct alignas(16) Word16 { + std::uint64_t lo; + std::uint64_t hi; +}; + +template +__global__ void +gather_kernel(const W* __restrict__ field, + W* __restrict__ stage, + PackKernelArgs a) { + pack_gather_thread(field, stage, a, blockIdx.x, blockIdx.y, blockIdx.z, threadIdx.x, + blockDim.x, gridDim.y); +} + +template +__global__ void +scatter_kernel(const W* __restrict__ stage, + W* __restrict__ field, + PackKernelArgs a) { + pack_scatter_thread(stage, field, a, blockIdx.x, blockIdx.y, blockIdx.z, threadIdx.x, + blockDim.x, gridDim.y); +} + +template +auto +gather_as(const Gpu& gpu, + gpu_stream_t stream, + const void* field, + void* stage, + const PackKernelArgs& a) -> gpu_error_t { + const PackLaunchShape s = pack_launch_shape(a); + return gpu.template typed_launch<&gather_kernel>( + dim3(s.grid_x, s.grid_y, s.grid_z), dim3(s.block_x, 1U, 1U), 0U, stream, + static_cast(field), static_cast(stage), a); +} + +template +auto +scatter_as(const Gpu& gpu, + gpu_stream_t stream, + const void* stage, + void* field, + const PackKernelArgs& a) -> gpu_error_t { + const PackLaunchShape s = pack_launch_shape(a); + return gpu.template typed_launch<&scatter_kernel>( + dim3(s.grid_x, s.grid_y, s.grid_z), dim3(s.block_x, 1U, 1U), 0U, stream, + static_cast(stage), static_cast(field), a); +} + +} // namespace + +auto +launch_gather(const Gpu& gpu, + gpu_stream_t stream, + std::size_t elem_bytes, + const void* field_base, + void* stage_region, + const PackKernelArgs& a) -> gpu_error_t { + switch (elem_bytes) { + case 1U: + return gather_as(gpu, stream, field_base, stage_region, a); + case 2U: + return gather_as(gpu, stream, field_base, stage_region, a); + case 4U: + return gather_as(gpu, stream, field_base, stage_region, a); + case 8U: + return gather_as(gpu, stream, field_base, stage_region, a); + case 16U: + return gather_as(gpu, stream, field_base, stage_region, a); + default: + return gpu_error_invalid_value; + } +} + +auto +launch_scatter(const Gpu& gpu, + gpu_stream_t stream, + std::size_t elem_bytes, + const void* stage_region, + void* field_base, + const PackKernelArgs& a) -> gpu_error_t { + switch (elem_bytes) { + case 1U: + return scatter_as(gpu, stream, stage_region, field_base, a); + case 2U: + return scatter_as(gpu, stream, stage_region, field_base, a); + case 4U: + return scatter_as(gpu, stream, stage_region, field_base, a); + case 8U: + return scatter_as(gpu, stream, stage_region, field_base, a); + case 16U: + return scatter_as(gpu, stream, stage_region, field_base, a); + default: + return gpu_error_invalid_value; + } +} + +} // namespace carbon::detail::halo_pack diff --git a/src/process_grid.cpp b/src/process_grid.cpp new file mode 100644 index 00000000..f9d184ef --- /dev/null +++ b/src/process_grid.cpp @@ -0,0 +1,168 @@ +#include + +#include + +#include +#include +#include +#include +#include + +namespace carbon { + +namespace { + +constexpr std::array kAxisOrderZYX{2, 1, 0}; + +[[nodiscard]] auto +prime_factors_descending(int32_t n) -> std::vector { + std::vector factors; + for (int32_t p = 2; static_cast(p) * p <= n; ++p) { + while (n % p == 0) { + factors.push_back(p); + n /= p; + } + } + if (n > 1) { + factors.push_back(n); + } + std::sort(factors.begin(), factors.end(), [](int32_t a, int32_t b) { + return a > b; + }); + return factors; +} + +[[nodiscard]] auto +factorized_dims(int32_t world_size, + DecompositionMode mode) -> int32_3d { + std::array dims{1, 1, 1}; + std::array free_axis{false, false, false}; + + switch (mode) { + case DecompositionMode::Slab: + free_axis[2] = true; + break; + case DecompositionMode::Pencil: + free_axis[1] = true; + free_axis[2] = true; + break; + case DecompositionMode::Brick: + free_axis[0] = true; + free_axis[1] = true; + free_axis[2] = true; + break; + case DecompositionMode::Custom: + log::throw_with_log( + "carbon::ProcessGrid::make: Custom mode requires ProcessGrid::custom()"); + return {1, 1, 1}; + } + + for (const int32_t factor : prime_factors_descending(world_size)) { + int best_axis = -1; + for (const int axis : kAxisOrderZYX) { + if (!free_axis[axis]) { + continue; + } + if (best_axis < 0 || dims[axis] < dims[best_axis]) { + best_axis = axis; + } + } + if (best_axis < 0) { + log::throw_with_log( + "carbon::ProcessGrid::make: decomposition mode {} has no free axis", + static_cast(mode)); + return {1, 1, 1}; + } + dims[best_axis] *= factor; + } + + return {dims[0], dims[1], dims[2]}; +} + +} // namespace + +auto +ProcessGrid::make(int32_t world_size, + DecompositionMode mode) -> ProcessGrid { + if (world_size <= 0) { + log::throw_with_log( + "carbon::ProcessGrid::make: world_size must be > 0 (got {})", world_size); + return ProcessGrid{}; + } + if (mode == DecompositionMode::Custom) { + log::throw_with_log( + "carbon::ProcessGrid::make: Custom mode requires ProcessGrid::custom()"); + return ProcessGrid{}; + } + return ProcessGrid{factorized_dims(world_size, mode), mode}; +} + +auto +ProcessGrid::custom(int32_t world_size, + int32_t px, + int32_t py, + int32_t pz) -> ProcessGrid { + if (world_size <= 0) { + log::throw_with_log( + "carbon::ProcessGrid::custom: world_size must be > 0 (got {})", world_size); + return ProcessGrid{}; + } + if (px <= 0 || py <= 0 || pz <= 0) { + log::throw_with_log( + "carbon::ProcessGrid::custom: all dimensions must be > 0 (got px={}, py={}, pz={})", + px, + py, + pz); + return ProcessGrid{}; + } + + const int64_t xy = static_cast(px) * py; + if (xy > world_size) { + log::throw_with_log( + "carbon::ProcessGrid::custom: px*py ({}) exceeds world_size ({})", xy, world_size); + return ProcessGrid{}; + } + const int64_t xyz = xy * pz; + if (xyz != world_size) { + log::throw_with_log( + "carbon::ProcessGrid::custom: px*py*pz ({}) != world_size ({})", xyz, world_size); + return ProcessGrid{}; + } + + return ProcessGrid{int32_3d{px, py, pz}, DecompositionMode::Custom}; +} + +auto +ProcessGrid::coords_of(int32_t rank) const -> int32_3d { + if (rank < 0 || rank >= world_size()) { + log::throw_with_log( + "carbon::ProcessGrid::coords_of: rank {} out of range [0, {})", rank, world_size()); + return {-1, -1, -1}; + } + + const int32_t pz = rank % dims_.z; + const int32_t py = (rank / dims_.z) % dims_.y; + const int32_t px = rank / (dims_.y * dims_.z); + return {px, py, pz}; +} + +auto +ProcessGrid::rank_of(int32_3d coords) const -> int32_t { + if (coords.x < 0 || coords.x >= dims_.x || coords.y < 0 || coords.y >= dims_.y || + coords.z < 0 || coords.z >= dims_.z) { + log::throw_with_log( + "carbon::ProcessGrid::rank_of: coords ({}, {}, {}) outside grid ({}, {}, {})", + coords.x, + coords.y, + coords.z, + dims_.x, + dims_.y, + dims_.z); + return -1; + } + + return static_cast((static_cast(coords.x) * dims_.y + coords.y) * dims_.z + + coords.z); +} + +} // namespace carbon \ No newline at end of file diff --git a/src/stencil.cpp b/src/stencil.cpp index 1f388bda..f40aeade 100644 --- a/src/stencil.cpp +++ b/src/stencil.cpp @@ -40,6 +40,7 @@ Stencil::Stencil(const std::vector& points, points_.end()); } radius_ = compute_radius_(points_); + radius3_ = compute_radius3_(points_); } auto @@ -62,6 +63,11 @@ Stencil::radius() const noexcept -> std::int32_t { return radius_; } +auto +Stencil::radius3() const noexcept -> int32_3d { + return radius3_; +} + auto Stencil::lattice_profile() const noexcept -> LatticeProfile { LatticeProfile p{}; @@ -155,4 +161,17 @@ Stencil::compute_radius_(const std::vector& points) noexcept -> std::in return r; } +auto +Stencil::compute_radius3_(const std::vector& points) noexcept -> int32_3d { + std::int32_t rx = 0; + std::int32_t ry = 0; + std::int32_t rz = 0; + for (const int8_3d& p : points) { + rx = std::max(rx, std::abs(static_cast(p.x))); + ry = std::max(ry, std::abs(static_cast(p.y))); + rz = std::max(rz, std::abs(static_cast(p.z))); + } + return int32_3d{rx, ry, rz}; +} + } // namespace carbon From c00c0b8ce679ee601a8d1cd44b51a0856fa178ce Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Mon, 2 Nov 2026 18:27:05 +0100 Subject: [PATCH 02/33] Add test distributed domain --- tests/CMakeLists.txt | 10 + tests/test_dense_distributed_dist.cu | 551 +++++++++++++++ tests/test_dense_distributed_host.cpp | 956 ++++++++++++++++++++++++++ tests/test_process_grid.cpp | 163 +++++ 4 files changed, 1680 insertions(+) create mode 100644 tests/test_dense_distributed_dist.cu create mode 100644 tests/test_dense_distributed_host.cpp create mode 100644 tests/test_process_grid.cpp diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index faceb003..a536bcbf 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -140,6 +140,7 @@ carbon_add_unit_test(logging) carbon_add_unit_test(gpu) carbon_add_unit_test(gpu_group_all_devices) carbon_add_unit_test(data_view) +carbon_add_unit_test(process_grid) carbon_add_unit_test(dense) carbon_add_unit_test(dense_disg) carbon_add_unit_test(block_static) @@ -152,6 +153,10 @@ carbon_add_unit_test(stencil) carbon_add_unit_test(system_default_stream) carbon_add_unit_test(transfer) carbon_add_unit_test(halo_coalesce) +# DenseDistributed (slab / pencil / brick), host half: decomposition geometry for every rank, +# Span views and neighbour resolution (open + periodic), and the packed X->Y->Z halo exchange on an +# emulated multi-rank world. No GPU and no MPI, so it stays on the cpu lane. +carbon_add_unit_test(dense_distributed_host) # Environment gate for the needs_multi_device class — see tests/test_multi_gpu_gate.cpp. # Labelled cpu because it only reads the device count (never launches), so it runs on # every lane and reports honestly on each. @@ -442,6 +447,11 @@ if(CARBON_ENABLE_MPI AND MPI_FOUND) carbon_add_mpi_cuda_test(dense_dist 2) carbon_add_mpi_cuda_test(halo_dist 2) carbon_add_mpi_cuda_test(halo_dist_periodic_z 2) + # DenseDistributed (slab / pencil / brick), device half: the real HaloDistributed exchange and a + # Skeleton stencil kernel on 4 ranks (one GPU each). Covers slab (1,1,4), pencil (1,2,2) and the + # pairwise bricks (2,2,1) / (2,1,2), open and periodic, single- and multi-component. Launched + # with 8 ranks it additionally covers the full brick (2,2,2); it self-skips for other sizes. + carbon_add_mpi_cuda_test(dense_distributed_dist 4) carbon_add_mpi_cuda_test(halo_block_dist 2) # Host-side cross-rank HaloBlock::launch_on_host (MPI_Isend/Irecv via run_host). carbon_add_mpi_cuda_test(halo_block_host_dist 2) diff --git a/tests/test_dense_distributed_dist.cu b/tests/test_dense_distributed_dist.cu new file mode 100644 index 00000000..ddb48a03 --- /dev/null +++ b/tests/test_dense_distributed_dist.cu @@ -0,0 +1,551 @@ +// DenseDistributed on real GPUs: slab, pencil and brick decompositions, end to end. +// +// Launched under `mpiexec -n 4 ./test_dense_distributed_dist` (one rank per GPU). With 8 ranks it +// runs the full brick (2,2,2) instead; any other world size skips (returns 0), as does a node with +// fewer visible devices than ranks. +// +// Process grids (Px, Py, Pz) per world size, each in Open and periodic variants: +// 4 ranks : slab (1,1,4) | pencil (1,2,2) | brick (2,2,1) and (2,1,2) +// 8 ranks : brick (2,2,2) +// +// Two checks per case, both against ground truth computed on the host: +// +// 1. Raw HaloDistributed exchange. Owned cells hold encode(global cell), every halo cell holds a +// sentinel; after one exchange every cell of every rank's buffer is compared: +// - owned cells unchanged, +// - interior halos == encode(the global cell they mirror), +// - exterior halos on an Open axis still the sentinel (never clobbered), +// - exterior halos on a periodic axis == encode(the wrapped global cell). +// It also checks the per-rank layout (owned extent, offset, halo, haloed extent) against an +// independent computation. Scalar and 3-component fields are run, each with the packed +// X/Y/Z exchange (CARBON_HALO_PACK=1) and the run-based path (=0), so packed == run-based +// follows from both matching ground truth. +// +// 2. Skeleton + Kernel path. A 6-point stencil kernel (sum of the six neighbours, 0 where a +// neighbour is outside an open boundary) is compiled into a Skeleton, so the halo kernel is +// auto-inserted from read_stencil and DenseDistributed::Span / Partition run on the device. +// Run once without overlap and once with OverlapMode::Standard, which splits the kernel into +// Internal + Boundary launches and therefore exercises those Span views for real. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using carbon::Axis; +using carbon::BoundaryModeDistributed; +using carbon::DenseDistributed; +using carbon::int32_3d; +using carbon::int64_3d; +using carbon::ProcessGrid; + +constexpr int kSentinel = -7777; + +[[nodiscard]] auto +encode(int64_t x, + int64_t y, + int64_t z, + int comp = 0) noexcept -> int { + return static_cast(z * 10000 + y * 100 + x) + comp * 1'000'000; +} + +[[nodiscard]] auto +split_extent(int64_t n, + int32_t parts) -> std::vector { + std::vector counts(static_cast(parts), 0); + for (int32_t i = 0; i < parts; ++i) { + counts[static_cast(i)] = n / parts + (static_cast(i) < n % parts ? 1 : 0); + } + return counts; +} + +[[nodiscard]] auto +prefix_sum(const std::vector& counts) -> std::vector { + std::vector prefix(counts.size() + 1U, 0); + for (size_t i = 0; i < counts.size(); ++i) { + prefix[i + 1U] = prefix[i] + counts[i]; + } + return prefix; +} + +[[nodiscard]] auto +sync_all(const carbon::Stream& stream, + const char* tag) -> bool { + try { + stream.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_dense_distributed_dist: sync after {} failed: {}", tag, e.what()); + return false; + } + return true; +} + +[[nodiscard]] auto +six_point() -> carbon::Stencil { + return carbon::Stencil( + std::vector{{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}, + /*remove_center=*/true); +} + +/** Wrap @p v into [0, n) if @p periodic; return false when it is outside an open axis. */ +[[nodiscard]] auto +wrap_axis(int64_t v, + int64_t n, + bool periodic, + int64_t& out) noexcept -> bool { + if (v >= 0 && v < n) { + out = v; + return true; + } + if (!periodic) { + return false; + } + out = ((v % n) + n) % n; + return true; +} + +// ------------------------------------------------------------------------------------------------ +// Check 1: raw HaloDistributed exchange, every buffer cell compared with ground truth. +// ------------------------------------------------------------------------------------------------ + +template +[[nodiscard]] auto +run_halo_once(carbon::System& sys, + int rank, + const ProcessGrid& pg, + BoundaryModeDistributed mode, + const char* label, + const int64_3d& global) -> bool { + const int32_3d dims = pg.dims(); + const int32_3d coords = pg.coords_of(rank); + const carbon::Stencil stencil = six_point(); + + // Expected geometry, derived independently of the library. + const bool slab_shape = dims.x == 1 && dims.y == 1; + const bool legacy_slab = + slab_shape && !carbon::is_periodic(mode, Axis::X) && !carbon::is_periodic(mode, Axis::Y); + const auto axis_halo = [&](int32_t parts, Axis axis) -> int64_t { + return (parts > 1 || carbon::is_periodic(mode, axis)) ? 1 : 0; + }; + const int64_3d expected_halo = + legacy_slab ? int64_3d{0, 0, 1} + : int64_3d{axis_halo(dims.x, Axis::X), axis_halo(dims.y, Axis::Y), + slab_shape ? 1 : axis_halo(dims.z, Axis::Z)}; + const auto xs = split_extent(global.x, dims.x); + const auto ys = split_extent(global.y, dims.y); + const auto zs = split_extent(global.z, dims.z); + const auto xp = prefix_sum(xs); + const auto yp = prefix_sum(ys); + const auto zp = prefix_sum(zs); + const int64_3d expected_owned{xs[static_cast(coords.x)], + ys[static_cast(coords.y)], + zs[static_cast(coords.z)]}; + const int64_3d expected_offset{xp[static_cast(coords.x)] - expected_halo.x, + yp[static_cast(coords.y)] - expected_halo.y, + zp[static_cast(coords.z)] - expected_halo.z}; + + DenseDistributed grid(sys, global, pg, stencil, mode); + const auto& span = grid.spans()[0]; + const int64_3d halo = span.halo(); + const int64_3d owned = span.logic_extent(); + const int64_3d haloed = span.haloed_extent(); + const int64_3d offset = span.offset(); + + const auto same = [](const int64_3d& a, const int64_3d& b) -> bool { + return a.x == b.x && a.y == b.y && a.z == b.z; + }; + if (grid.gpu_count() != 1U || grid.global_slab_count() != static_cast(dims.z) || + grid.local_slab_offset() != static_cast(coords.z) || !same(halo, expected_halo) || + !same(owned, expected_owned) || !same(offset, expected_offset) || + haloed.x != owned.x + 2 * halo.x || haloed.y != owned.y + 2 * halo.y || + haloed.z != owned.z + 2 * halo.z) { + CARBON_LOG_ERROR( + "test_dense_distributed_dist[{}]: rank {} layout mismatch: halo=({},{},{}) want ({},{},{}) " + "owned=({},{},{}) want ({},{},{}) offset=({},{},{}) want ({},{},{})", + label, rank, halo.x, halo.y, halo.z, expected_halo.x, expected_halo.y, expected_halo.z, + owned.x, owned.y, owned.z, expected_owned.x, expected_owned.y, expected_owned.z, offset.x, + offset.y, offset.z, expected_offset.x, expected_offset.y, expected_offset.z); + return false; + } + + auto field = grid.template newField(carbon::MemorySide::HostDevice); + const int64_t pitch = span.xy_slab_elements(); + const int64_t per_comp = span.linear_storage_elements(); + const auto is_owned_cell = [&](int64_t x, int64_t y, int64_t z) -> bool { + return x >= halo.x && x < halo.x + owned.x && y >= halo.y && y < halo.y + owned.y && + z >= halo.z && z < halo.z + owned.z; + }; + { + int* h = field.cpu_buffers()[0].data(); + for (int64_t z = 0; z < haloed.z; ++z) { + for (int64_t y = 0; y < haloed.y; ++y) { + for (int64_t x = 0; x < haloed.x; ++x) { + const int64_3d g = span.global_location(span.make_idx(x, y, z)); + const int64_t off = z * pitch + y * haloed.x + x; + for (int c = 0; c < Components; ++c) { + h[c * per_comp + off] = is_owned_cell(x, y, z) ? encode(g.x, g.y, g.z, c) : kSentinel; + } + } + } + } + } + + carbon::Stream stream = sys.stream(); + try { + carbon::Transfer upload(sys, field.cpu_buffers(), field.gpu_buffers()); + upload(stream); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: upload failed: {}", label, e.what()); + return false; + } + if (!sync_all(stream, "upload")) { + return false; + } + + carbon::HaloDistributed exchange(field); + // A multi-rank layout always needs cross-rank transfers (X/Y faces fan out into several runs, so + // the exact count is geometry dependent; correctness is enforced by the cell comparison below). + if (exchange.pair_count() != 0U || exchange.dist_entry_count() == 0U || + (exchange.dist_entry_count() % 2U) != 0U) { + CARBON_LOG_ERROR( + "test_dense_distributed_dist[{}]: pair_count={} dist_entry_count={} (want 0 and a " + "non-zero even count)", + label, exchange.pair_count(), exchange.dist_entry_count()); + return false; + } + try { + exchange(stream); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: halo exchange failed: {}", label, e.what()); + return false; + } + if (!sync_all(stream, "halo")) { + return false; + } + + { + int* h = field.cpu_buffers()[0].data(); + for (size_t i = 0; i < field.cpu_buffers()[0].size(); ++i) { + h[i] = kSentinel - 1; + } + } + try { + carbon::Transfer download(sys, field.gpu_buffers(), field.cpu_buffers()); + download(stream); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: download failed: {}", label, e.what()); + return false; + } + if (!sync_all(stream, "download")) { + return false; + } + + size_t mismatches = 0; + const int* h = field.cpu_buffers()[0].data(); + for (int64_t z = 0; z < haloed.z; ++z) { + for (int64_t y = 0; y < haloed.y; ++y) { + for (int64_t x = 0; x < haloed.x; ++x) { + const int64_3d g = span.global_location(span.make_idx(x, y, z)); + int64_t wx = 0; + int64_t wy = 0; + int64_t wz = 0; + const bool inside = wrap_axis(g.x, global.x, carbon::is_periodic(mode, Axis::X), wx) && + wrap_axis(g.y, global.y, carbon::is_periodic(mode, Axis::Y), wy) && + wrap_axis(g.z, global.z, carbon::is_periodic(mode, Axis::Z), wz); + const bool owned_cell = is_owned_cell(x, y, z); + const int64_t off = z * pitch + y * haloed.x + x; + for (int c = 0; c < Components; ++c) { + const int want = + owned_cell ? encode(g.x, g.y, g.z, c) : (inside ? encode(wx, wy, wz, c) : kSentinel); + const int got = h[c * per_comp + off]; + if (got != want) { + if (mismatches < 4U) { + CARBON_LOG_ERROR( + "test_dense_distributed_dist[{}]: rank {} comp {} buffer ({},{},{}) global " + "({},{},{}) got {} want {}", + label, rank, c, x, y, z, g.x, g.y, g.z, got, want); + } + ++mismatches; + } + } + } + } + } + if (mismatches != 0U) { + CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: rank {} has {} wrong cells", label, rank, + mismatches); + return false; + } + return true; +} + +/** + * Runs @ref run_halo_once with the packed exchange and with the run-based path. + * CARBON_HALO_PACK is read when a HaloDistributed is constructed; each variant is verified against + * ground truth, so packed == run-based follows. The environment is restored afterwards. + */ +template +[[nodiscard]] auto +run_halo(carbon::System& sys, + int rank, + const ProcessGrid& pg, + BoundaryModeDistributed mode, + const std::string& label, + const int64_3d& global) -> bool { + const char* saved = std::getenv("CARBON_HALO_PACK"); + const bool had = saved != nullptr; + const std::string previous = had ? saved : ""; + bool ok = true; + for (const bool pack : {true, false}) { + ::setenv("CARBON_HALO_PACK", pack ? "1" : "0", 1); + const std::string tagged = + label + "/c" + std::to_string(Components) + (pack ? "/packed" : "/runs"); + ok = run_halo_once(sys, rank, pg, mode, tagged.c_str(), global); + if (!ok) { + break; + } + } + if (had) { + ::setenv("CARBON_HALO_PACK", previous.c_str(), 1); + } else { + ::unsetenv("CARBON_HALO_PACK"); + } + return ok; +} + +// ------------------------------------------------------------------------------------------------ +// Check 2: Skeleton + stencil kernel (auto-inserted halo, optional compute/communication overlap). +// ------------------------------------------------------------------------------------------------ + +[[nodiscard]] auto +run_stencil(carbon::System& sys, + int rank, + const ProcessGrid& pg, + BoundaryModeDistributed mode, + carbon::OverlapMode overlap, + const std::string& label, + const int64_3d& global) -> bool { + DenseDistributed grid(sys, global, pg, six_point(), mode); + const auto& span = grid.spans()[0]; + const int64_3d halo = span.halo(); + const int64_3d owned = span.logic_extent(); + const int64_3d haloed = span.haloed_extent(); + const int64_t pitch = span.xy_slab_elements(); + + auto in = grid.newField(carbon::MemorySide::HostDevice, "in"); + auto out = grid.newField(carbon::MemorySide::HostDevice, "out"); + const auto is_owned_cell = [&](int64_t x, int64_t y, int64_t z) -> bool { + return x >= halo.x && x < halo.x + owned.x && y >= halo.y && y < halo.y + owned.y && + z >= halo.z && z < halo.z + owned.z; + }; + { + int* hi = in.cpu_buffers()[0].data(); + int* ho = out.cpu_buffers()[0].data(); + for (int64_t z = 0; z < haloed.z; ++z) { + for (int64_t y = 0; y < haloed.y; ++y) { + for (int64_t x = 0; x < haloed.x; ++x) { + const int64_3d g = span.global_location(span.make_idx(x, y, z)); + const int64_t off = z * pitch + y * haloed.x + x; + hi[off] = is_owned_cell(x, y, z) ? encode(g.x, g.y, g.z) : kSentinel; + ho[off] = kSentinel; + } + } + } + } + carbon::Stream stream = sys.stream(); + try { + carbon::Transfer(sys, in.cpu_buffers(), in.gpu_buffers())(stream); + carbon::Transfer(sys, out.cpu_buffers(), out.gpu_buffers())(stream); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: upload failed: {}", label, e.what()); + return false; + } + if (!sync_all(stream, "stencil upload")) { + return false; + } + + using Span = DenseDistributed::Span; + using Idx = DenseDistributed::Idx; + carbon::Skeleton sk(sys, carbon::Skeleton::Options(overlap)); + sk.add(carbon::Kernel::compute( + grid, + [in, out](carbon::KernelLoader& loader) { + const auto pin = loader.read_stencil(in); + const auto pout = loader.write(out); + return [pin, pout] CARBON_HOST_DEVICE(Span s, Idx idx) { + int acc = 0; + acc += pin.neighbour(s, idx, carbon::int8_3d{1, 0, 0}, 0).value_or(0); + acc += pin.neighbour(s, idx, carbon::int8_3d{-1, 0, 0}, 0).value_or(0); + acc += pin.neighbour(s, idx, carbon::int8_3d{0, 1, 0}, 0).value_or(0); + acc += pin.neighbour(s, idx, carbon::int8_3d{0, -1, 0}, 0).value_or(0); + acc += pin.neighbour(s, idx, carbon::int8_3d{0, 0, 1}, 0).value_or(0); + acc += pin.neighbour(s, idx, carbon::int8_3d{0, 0, -1}, 0).value_or(0); + pout.write(s, idx, 0, acc); + }; + }, + "neighbour_sum")); + try { + sk.compile(); + sk.run(); + sk.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: skeleton failed: {}", label, e.what()); + return false; + } + + { + int* ho = out.cpu_buffers()[0].data(); + for (size_t i = 0; i < out.cpu_buffers()[0].size(); ++i) { + ho[i] = kSentinel - 1; + } + } + try { + carbon::Transfer(sys, out.gpu_buffers(), out.cpu_buffers())(stream); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: download failed: {}", label, e.what()); + return false; + } + if (!sync_all(stream, "stencil download")) { + return false; + } + + static constexpr int kDirs[6][3] = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, + {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}; + size_t mismatches = 0; + const int* ho = out.cpu_buffers()[0].data(); + for (int64_t z = 0; z < owned.z; ++z) { + for (int64_t y = 0; y < owned.y; ++y) { + for (int64_t x = 0; x < owned.x; ++x) { + const int64_3d g = span.global_location(span.make_idx(halo.x + x, halo.y + y, halo.z + z)); + int want = 0; + for (const auto& d : kDirs) { + int64_t wx = 0; + int64_t wy = 0; + int64_t wz = 0; + if (wrap_axis(g.x + d[0], global.x, carbon::is_periodic(mode, Axis::X), wx) && + wrap_axis(g.y + d[1], global.y, carbon::is_periodic(mode, Axis::Y), wy) && + wrap_axis(g.z + d[2], global.z, carbon::is_periodic(mode, Axis::Z), wz)) { + want += encode(wx, wy, wz); + } + } + const int got = ho[(halo.z + z) * pitch + (halo.y + y) * haloed.x + (halo.x + x)]; + if (got != want) { + if (mismatches < 4U) { + CARBON_LOG_ERROR( + "test_dense_distributed_dist[{}]: rank {} global ({},{},{}) got {} want {}", label, + rank, g.x, g.y, g.z, got, want); + } + ++mismatches; + } + } + } + } + if (mismatches != 0U) { + CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: rank {} has {} wrong cells", label, rank, + mismatches); + return false; + } + return true; +} + +struct Case { + ProcessGrid pg; + BoundaryModeDistributed mode; + const char* label; + bool multi_component; // also run the 3-component (packed-Z) exchange +}; + +} // namespace + +int +main() { + carbon::init(); + + auto distributed = std::make_shared(); + const int world = distributed->world_size(); + if (world != 4 && world != 8) { + CARBON_LOG_INFO("test_dense_distributed_dist: world_size={} not in {{4, 8}}, skipping", world); + return 0; + } + if (carbon::device_count() < world) { + CARBON_LOG_INFO("test_dense_distributed_dist: needs >= {} visible devices, have {}; skipping", + world, carbon::device_count()); + return 0; + } + const int rank = distributed->world_rank(); + carbon::System sys(distributed); + if (sys.gpu_group().size() != 1U) { + CARBON_LOG_ERROR("test_dense_distributed_dist: expected one GPU per rank, got {}", + sys.gpu_group().size()); + return 1; + } + + constexpr auto kO = BoundaryModeDistributed::Open; + constexpr auto kX = BoundaryModeDistributed::PeriodicX; + constexpr auto kY = BoundaryModeDistributed::PeriodicY; + constexpr auto kZ = BoundaryModeDistributed::PeriodicZ; + const auto custom = [world](int x, int y, int z) { + return ProcessGrid::custom(world, x, y, z); + }; + + std::vector cases; + if (world == 4) { + cases = { + {custom(1, 1, 4), kO, "slab-open", true}, + {custom(1, 1, 4), kZ, "slab-periodicZ", false}, + {custom(1, 1, 4), kX, "slab-periodicX", false}, + {custom(1, 2, 2), kO, "pencil-open", true}, + {custom(1, 2, 2), kY | kZ, "pencil-periodicYZ", false}, + {custom(1, 2, 2), kX, "pencil-periodicX", false}, + {custom(2, 2, 1), kO, "brickXY-open", false}, + {custom(2, 2, 1), kX | kY, "brickXY-periodicXY", true}, + {custom(2, 1, 2), kO, "brickXZ-open", false}, + {custom(2, 1, 2), kX | kZ, "brickXZ-periodicXZ", false}, + }; + } else { + cases = { + {custom(2, 2, 2), kO, "brick-open", true}, + {custom(2, 2, 2), kX, "brick-periodicX", false}, + {custom(2, 2, 2), kX | kY | kZ, "brick-periodicXYZ", true}, + }; + } + + // Deliberately uneven extents so chunks differ in size across ranks. + const int64_3d global{9, 8, 11}; + for (const Case& c : cases) { + if (!run_halo<1>(sys, rank, c.pg, c.mode, c.label, global) || + (c.multi_component && !run_halo<3>(sys, rank, c.pg, c.mode, c.label, global)) || + !run_stencil(sys, rank, c.pg, c.mode, carbon::OverlapMode::None, + std::string(c.label) + "/stencil", global) || + !run_stencil(sys, rank, c.pg, c.mode, carbon::OverlapMode::Standard, + std::string(c.label) + "/stencil-overlap", global)) { + return 1; + } + } + + CARBON_LOG_INFO("test_dense_distributed_dist: rank {} of {} ok ({} cases)", rank, world, + cases.size()); + return 0; +} diff --git a/tests/test_dense_distributed_host.cpp b/tests/test_dense_distributed_host.cpp new file mode 100644 index 00000000..079dcd68 --- /dev/null +++ b/tests/test_dense_distributed_host.cpp @@ -0,0 +1,956 @@ +// Host-only verification of DenseDistributed's decomposition and its packed halo exchange. +// No GPU, no MPI. +// +// Part A per-thread pack/unpack index math (the exact code the CUDA/HIP kernels run). +// Part B slab / pencil / brick geometry: for every rank of several process grids, the +// production layout functions (detail/dense_distributed/layout.h) are compared with +// hand-written expectations, the owned boxes must tile the global domain exactly once, and +// the resulting Span must iterate (Standard, Internal + Boundary) and resolve +// neighbours (open vs periodic) correctly. +// Part C correctness of the full X -> Y -> Z staged halo exchange on an emulated multi-rank world +// (corners/edges, periodic wraps, uneven splits, self-wrap), driven by the production +// plan builder and checked against the run-based builder (kept as the oracle) and against +// ground truth. +// +// What it does NOT cover: stream ordering, NCCL/MPI transport and real kernel launches. That is the +// job of the dense_distributed_dist test, which runs the real exchange on GPUs. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using carbon::Axis; +using carbon::BoundaryModeDistributed; +using carbon::int32_3d; +using carbon::int64_3d; +using carbon::int8_3d; +using carbon::ProcessGrid; +namespace hb = carbon::detail::halo_distributed_build; +namespace dd = carbon::detail::dense_distributed; +namespace hp = carbon::detail::halo_pack; +using hb::AxisGeometry; +using hb::AxisSide; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "CHECK failed: %s (%s:%d)\n context: %s\n", #cond, __FILE__, \ + __LINE__, g_ctx.c_str()); \ + std::exit(1); \ + } \ + } while (0) + +std::string g_ctx; + +constexpr uint64_t kSentinel = 0xDEADBEEFDEADBEEFULL; +constexpr uint64_t kMarker = 0xB0C0000000000000ULL; + +struct Vel { + int x, y, z; +}; + +auto +lattice(int q) -> std::vector { + std::vector v; + for (int z = -1; z <= 1; ++z) { + for (int y = -1; y <= 1; ++y) { + for (int x = -1; x <= 1; ++x) { + const int nz = (x != 0) + (y != 0) + (z != 0); + if (q == 27 || (q == 19 && nz <= 2)) { + v.push_back({x, y, z}); + } + } + } + } + return v; +} + +auto +axis_of(const Vel& v, + Axis a) -> int { + return a == Axis::X ? v.x : (a == Axis::Y ? v.y : v.z); +} + +auto +axis_len(const int64_3d& v, + Axis a) -> int64_t { + return a == Axis::X ? v.x : (a == Axis::Y ? v.y : v.z); +} + +auto +split(int64_t n, + int parts, + int idx) -> std::pair { // (size, offset) + const int64_t base = n / parts; + const int64_t rem = n % parts; + return {base + (idx < rem ? 1 : 0), idx * base + std::min(idx, rem)}; +} + +struct Rank { + int32_3d coords{}; + int64_3d offset{}; // global index of local owned cell (0,0,0) + AxisGeometry g{}; + int64_t comp_stride{}; + std::vector buf; + std::vector stage; +}; + +struct World { + ProcessGrid pg = ProcessGrid::custom(1, 1, 1, 1); + BoundaryModeDistributed bm{BoundaryModeDistributed::Open}; + int64_3d global{}; + int64_3d halo{}; + int comps{1}; + bool lat{false}; + std::vector vel; + std::vector ranks; + + [[nodiscard]] auto + active_send(int c, + Axis axis, + AxisSide side) const -> bool { + if (!lat) { + return true; + } + const int v = axis_of(vel[static_cast(c)], axis); + return side == AxisSide::Upper ? v > 0 : v < 0; + } + + [[nodiscard]] auto + active_recv(int c, + Axis axis, + AxisSide side) const -> bool { + if (!lat) { + return true; + } + const int v = axis_of(vel[static_cast(c)], axis); + return side == AxisSide::Upper ? v < 0 : v > 0; + } +}; + +auto +encode(int64_t gx, + int64_t gy, + int64_t gz, + int c) -> uint64_t { + return ((static_cast(c) * 1009U + static_cast(gz)) * 997U + + static_cast(gy)) * + 991U + + static_cast(gx) + 1U; +} + +// A stencil whose per-axis radius is exactly @p halo (axes with 0 get no point). +auto +stencil_from_halo(const int64_3d& halo) -> carbon::Stencil { + std::vector pts; + const auto add = [&](int64_t r, int32_3d unit) { + if (r > 0) { + const auto k = static_cast(r); + pts.push_back({unit.x * k, unit.y * k, unit.z * k}); + pts.push_back({-unit.x * k, -unit.y * k, -unit.z * k}); + } + }; + add(halo.x, {1, 0, 0}); + add(halo.y, {0, 1, 0}); + add(halo.z, {0, 0, 1}); + return carbon::Stencil(std::move(pts), /*remove_center=*/true); +} + +auto +make_world(const ProcessGrid& pg, + BoundaryModeDistributed bm, + int64_3d global, + int64_3d halo, + int comps, + int lattice_q, + int64_t pitch_pad) -> World { + World w; + w.pg = pg; + w.bm = bm; + w.global = global; + w.halo = halo; + w.lat = lattice_q != 0; + w.vel = lattice(lattice_q); + w.comps = w.lat ? static_cast(w.vel.size()) : comps; + const int64_3d hh = dd::halo_extent(pg, bm, stencil_from_halo(halo)); + for (int32_t r = 0; r < pg.world_size(); ++r) { + Rank rk; + rk.coords = pg.coords_of(r); + // Geometry comes from the production layout functions, so Part C exercises the real + // decomposition (not a second copy of it). + const dd::RankChunk chunk = dd::rank_chunk(global, pg, rk.coords, hh); + rk.offset = {chunk.offset.x + hh.x, chunk.offset.y + hh.y, chunk.offset.z + hh.z}; + const auto sx = std::pair{chunk.owned.x, rk.offset.x}; + const auto sy = std::pair{chunk.owned.y, rk.offset.y}; + const auto sz = std::pair{chunk.owned.z, rk.offset.z}; + rk.g.owned = chunk.owned; + rk.g.halo = hh; + rk.g.haloed = chunk.haloed; + rk.g.pitch = rk.g.haloed.x * rk.g.haloed.y + pitch_pad; + rk.comp_stride = rk.g.pitch * rk.g.haloed.z; + rk.buf.assign(static_cast(rk.comp_stride) * static_cast(w.comps), kSentinel); + // Stand-in for user boundary-condition data living in exterior halo cells: a value unique to + // (rank, cell) so any stray overwrite is visible. Cells that a correct exchange fills get + // overwritten anyway; cells outside an open axis must keep it. + for (size_t k = 0; k < rk.buf.size(); ++k) { + rk.buf[k] = kMarker ^ (static_cast(r + 1) << 40) ^ static_cast(k); + } + for (int c = 0; c < w.comps; ++c) { + for (int64_t z = 0; z < sz.first; ++z) { + for (int64_t y = 0; y < sy.first; ++y) { + for (int64_t x = 0; x < sx.first; ++x) { + const size_t idx = static_cast(c * rk.comp_stride + (z + hh.z) * rk.g.pitch + + (y + hh.y) * rk.g.haloed.x + (x + hh.x)); + rk.buf[idx] = encode(rk.offset.x + x, rk.offset.y + y, rk.offset.z + z, c); + } + } + } + } + w.ranks.push_back(std::move(rk)); + } + return w; +} + +// ---- the existing run-based exchange, used as oracle (and for the Z pass) ------------------- +auto +exchange_runs(World& w, + Axis axis) -> void { + // Snapshot sources first so every rank reads pre-pass data, like concurrent streams would. + const std::vector snap = w.ranks; + for (size_t i = 0; i < w.ranks.size(); ++i) { + Rank& dst = w.ranks[i]; + if (axis_len(dst.g.halo, axis) <= 0) { + continue; + } + for (const AxisSide side : {AxisSide::Lower, AxisSide::Upper}) { + const auto nb = hb::axis_neighbour(w.pg, dst.coords, axis, w.bm, side); + if (!nb.present) { + continue; + } + const Rank& src = snap[static_cast(nb.rank)]; + const AxisSide src_side = side == AxisSide::Lower ? AxisSide::Upper : AxisSide::Lower; + const auto dst_runs = hb::axis_halo_runs(dst.g, axis, side); + const auto src_runs = hb::axis_owned_face_runs(src.g, axis, src_side); + CHECK(dst_runs.size() == src_runs.size()); + for (int c = 0; c < w.comps; ++c) { + if (!w.active_recv(c, axis, side)) { + continue; + } + for (size_t r = 0; r < dst_runs.size(); ++r) { + CHECK(dst_runs[r].count == src_runs[r].count); + for (size_t k = 0; k < dst_runs[r].count; ++k) { + dst.buf[static_cast(c * dst.comp_stride) + dst_runs[r].offset + k] = + src.buf[static_cast(c * src.comp_stride) + src_runs[r].offset + k]; + } + } + } + } + } +} + +struct PassStats { + size_t msgs{}; + size_t kernels{}; +}; + +// ---- the packed exchange, driven by the real plan builder + the real per-thread code -------- +auto +exchange_packed(World& w, + Axis axis, + std::vector& stage_cursor) -> PassStats { + PassStats stats; + std::vector plans(w.ranks.size()); + for (size_t i = 0; i < w.ranks.size(); ++i) { + Rank& rk = w.ranks[i]; + plans[i] = hp::build_axis_pack_plan( + w.pg, w.bm, rk.coords, static_cast(i), rk.g, axis, w.comps, rk.comp_stride, + [&](int c, Axis a, AxisSide s) { + return w.active_send(c, a, s); + }, + [&](int c, Axis a, AxisSide s) { + return w.active_recv(c, a, s); + }, + stage_cursor[i]); + hp::sort_msgs(plans[i].msgs); + stage_cursor[i] += plans[i].stage_elems; + rk.stage.resize(std::max(rk.stage.size(), stage_cursor[i]), kSentinel); + } + + // 1) gather everywhere (before any message is delivered or scattered). + for (size_t i = 0; i < w.ranks.size(); ++i) { + for (const hp::PackStep& s : plans[i].gathers) { + hp::host_gather(w.ranks[i].buf.data(), w.ranks[i].stage.data() + s.stage_offset, + s.args); + ++stats.kernels; + } + } + + // 2) deliver messages the way per-peer-ordered NCCL send/recv would. + std::map, std::vector> sends; // (src,dst) + std::map, std::vector> recvs; // (src,dst) + for (size_t i = 0; i < w.ranks.size(); ++i) { + for (const hp::PackMsg& m : plans[i].msgs) { + ++stats.msgs; + if (m.op == hp::MsgOp::Send) { + sends[{static_cast(i), m.peer}].push_back(&m); + } else { + recvs[{m.peer, static_cast(i)}].push_back(&m); + } + } + } + CHECK(sends.size() == recvs.size()); + for (const auto& [pair, slist] : sends) { + const auto it = recvs.find(pair); + CHECK(it != recvs.end()); + const auto& rlist = it->second; + CHECK(slist.size() == rlist.size()); + for (size_t k = 0; k < slist.size(); ++k) { + CHECK(slist[k]->count == rlist[k]->count); // same position => same size AND same key + CHECK(slist[k]->key == rlist[k]->key); + const Rank& s = w.ranks[static_cast(pair.first)]; + Rank& d = w.ranks[static_cast(pair.second)]; + std::copy_n(s.stage.begin() + static_cast(slist[k]->first), + static_cast(slist[k]->count), + d.stage.begin() + static_cast(rlist[k]->first)); + } + } + + // 3) scatter everywhere. + for (size_t i = 0; i < w.ranks.size(); ++i) { + for (const hp::PackStep& s : plans[i].scatters) { + hp::host_scatter(w.ranks[i].stage.data() + s.stage_offset, w.ranks[i].buf.data(), + s.args); + ++stats.kernels; + } + } + return stats; +} + +// ---- ground truth ------------------------------------------------------------------------- +// Returns true and the wrapped global coordinate if the cell exists in the global domain. +auto +wrap_global(const World& w, + int64_t gx, + int64_t gy, + int64_t gz, + std::array& out) -> bool { + const std::array g{gx, gy, gz}; + const std::array n{w.global.x, w.global.y, w.global.z}; + const std::array ax{Axis::X, Axis::Y, Axis::Z}; + for (size_t a = 0; a < 3; ++a) { + int64_t v = g[a]; + if (v < 0 || v >= n[a]) { + if (!carbon::is_periodic(w.bm, ax[a])) { + return false; + } + v = ((v % n[a]) + n[a]) % n[a]; + } + out[a] = v; + } + return true; +} + +// Is population c at local cell (lx,ly,lz) [buffer coords] ever read by an owned cell? +auto +needed(const World& w, + const Rank& rk, + int c, + int64_t lx, + int64_t ly, + int64_t lz) -> bool { + if (!w.lat) { + return true; + } + const Vel& v = w.vel[static_cast(c)]; + const int64_t px = lx + v.x; + const int64_t py = ly + v.y; + const int64_t pz = lz + v.z; + return px >= rk.g.halo.x && px < rk.g.halo.x + rk.g.owned.x && py >= rk.g.halo.y && + py < rk.g.halo.y + rk.g.owned.y && pz >= rk.g.halo.z && pz < rk.g.halo.z + rk.g.owned.z; +} + +// Verify one world against ground truth; optionally against another (old-path) world on every +// cell that matters. Returns the number of halo cells that were checked against ground truth. +auto +verify(const World& w, + const World* other, + bool check_exterior = true, + bool z_packed = false) -> size_t { + size_t checked = 0; + // A run-based Z pass copies whole planes (including exterior x/y halos), so exterior cells may + // only be demanded intact when no such pass exists: no Z halo at all, or Z is packed. + bool no_z_pass = z_packed; + if (!no_z_pass) { + no_z_pass = true; + for (const Rank& r : w.ranks) { + no_z_pass = no_z_pass && r.g.halo.z == 0; + } + } + for (size_t i = 0; i < w.ranks.size(); ++i) { + const Rank& rk = w.ranks[i]; + for (int c = 0; c < w.comps; ++c) { + for (int64_t z = 0; z < rk.g.haloed.z; ++z) { + for (int64_t y = 0; y < rk.g.haloed.y; ++y) { + for (int64_t x = 0; x < rk.g.haloed.x; ++x) { + const size_t idx = + static_cast(c * rk.comp_stride + z * rk.g.pitch + y * rk.g.haloed.x + x); + const uint64_t got = rk.buf[idx]; + const bool owned = x >= rk.g.halo.x && x < rk.g.halo.x + rk.g.owned.x && + y >= rk.g.halo.y && y < rk.g.halo.y + rk.g.owned.y && + z >= rk.g.halo.z && z < rk.g.halo.z + rk.g.owned.z; + std::array gw{}; + const bool valid = + wrap_global(w, rk.offset.x + x - rk.g.halo.x, rk.offset.y + y - rk.g.halo.y, + rk.offset.z + z - rk.g.halo.z, gw); + if (owned) { + CHECK(got == encode(gw[0], gw[1], gw[2], c)); + continue; + } + if (!valid) { + // Outside an open axis. With no Z pass, nothing may touch these cells: this is what + // the exterior-x clipping in the Y pass (and the owned-only X extents) guarantee. + if (no_z_pass && check_exterior) { + CHECK(got == (kMarker ^ (static_cast(i + 1) << 40) ^ + static_cast(idx))); + } + continue; + } + if (!needed(w, rk, c, x, y, z)) { + continue; // lattice: this population is never read at this halo cell + } + CHECK(got == encode(gw[0], gw[1], gw[2], c)); + if (other != nullptr) { + CHECK(other->ranks[i].buf[idx] == got); // packed == run-based, bit for bit + } + ++checked; + } + } + } + } + } + return checked; +} + +// ---- Part A: kernel index math in isolation, all element widths --------------------------- +struct Wide16 { + uint64_t a, b; + bool + operator==(const Wide16& o) const { + return a == o.a && b == o.b; + } +}; + +template +auto +make_elem(uint64_t v) -> W { + if constexpr (sizeof(W) == 16) { + return W{v, ~v}; + } else { + return static_cast(v); + } +} + +template +auto +part_a_roundtrip() -> void { + g_ctx = std::string("part A width=") + std::to_string(sizeof(W)); + AxisGeometry g; + g.owned = {5, 6, 7}; + g.halo = {2, 1, 2}; + g.haloed = {9, 8, 11}; + g.pitch = g.haloed.x * g.haloed.y + 3; // padded pitch: must not be assumed == x*y + const int comps = 70; // ~47 listed comps > kMaxPackComps: forces chunking + const int64_t cs = g.pitch * g.haloed.z; + std::vector field(static_cast(cs) * comps); + for (size_t i = 0; i < field.size(); ++i) { + field[i] = make_elem(i * 2654435761ULL + 17U); + } + for (const Axis axis : {Axis::X, Axis::Y}) { + for (const AxisSide side : {AxisSide::Lower, AxisSide::Upper}) { + std::vector cl; + for (int c = 0; c < comps; ++c) { + if (c % 3 != 1) { + cl.push_back(c); + } + } + const hp::PackBox box = hp::pack_face_box(g, axis, side, axis == Axis::Y ? 1 : 0, + axis == Axis::Y ? g.haloed.x - 2 : 0); + std::vector steps; + hp::detail_plan::append_steps(steps, box, cl, g, cs, 0); + CHECK(cl.size() > hp::kMaxPackComps); // the case must really exercise chunking + CHECK(steps.size() == (cl.size() + hp::kMaxPackComps - 1) / hp::kMaxPackComps); + CHECK(steps.size() >= 2U); + std::vector stage(cl.size() * box.volume(), make_elem(0)); + for (const auto& s : steps) { + hp::host_gather(field.data(), stage.data() + s.stage_offset, s.args); + } + // Against an explicit triple loop. + size_t n = 0; + for (const int c : cl) { + for (int64_t z = 0; z < box.ext_z; ++z) { + for (int64_t y = 0; y < box.ext_y; ++y) { + for (int64_t x = 0; x < box.ext_x; ++x) { + const W expect = field[static_cast( + c * cs + (box.lo_z + z) * g.pitch + (box.lo_y + y) * g.haloed.x + box.lo_x + x)]; + CHECK(stage[n] == expect); + ++n; + } + } + } + } + CHECK(n == stage.size()); + // Scatter into a clean field: writes exactly the box cells of exactly the listed comps. + std::vector out(field.size(), make_elem(0)); + for (const auto& s : steps) { + hp::host_scatter(stage.data() + s.stage_offset, out.data(), s.args); + } + size_t written = 0; + for (size_t i = 0; i < out.size(); ++i) { + if (!(out[i] == make_elem(0))) { + CHECK(out[i] == field[i]); + ++written; + } + } + CHECK(written <= stage.size()); // (<: a source element may legitimately equal 0) + } + } +} + +// ---- Part A2: launch-shape corner cases (rows > one block, z beyond the 65535 grid cap) ------ +auto +part_a_launch_shapes() -> void { + struct Shape { + int64_t ox, oy, oz; + int comps; + }; + // X face: row = owned.y; Y face: row = haloed.x. The last shape needs ext_z > 65535 so that + // grid_y is capped and the grid-stride loop must wrap. + const Shape shapes[] = {{4, 300, 3, 2}, {300, 4, 5, 3}, {2, 3, 70000, 2}, {37, 41, 9, 1}}; + for (const Shape& sh : shapes) { + g_ctx = "part A2 shape " + std::to_string(sh.ox) + "x" + std::to_string(sh.oy) + "x" + + std::to_string(sh.oz); + AxisGeometry g; + g.owned = {sh.ox, sh.oy, sh.oz}; + g.halo = {1, 1, 1}; + g.haloed = {sh.ox + 2, sh.oy + 2, sh.oz + 2}; + g.pitch = g.haloed.x * g.haloed.y; + const int64_t cs = g.pitch * g.haloed.z; + std::vector field(static_cast(cs) * static_cast(sh.comps)); + for (size_t i = 0; i < field.size(); ++i) { + field[i] = static_cast(i * 2654435761ULL + 5U); + } + std::vector cl; + for (int c = 0; c < sh.comps; ++c) { + cl.push_back(c); + } + for (const Axis axis : {Axis::X, Axis::Y}) { + const hp::PackBox box = hp::pack_face_box(g, axis, AxisSide::Upper, 0, g.haloed.x); + std::vector steps; + hp::detail_plan::append_steps(steps, box, cl, g, cs, 0); + CHECK(steps.size() == 1U); + const hp::PackLaunchShape ls = hp::pack_launch_shape(steps[0].args); + if (axis == Axis::X && sh.oy == 300) { + CHECK(ls.grid_x == 2U); // 300 rows over 256-thread blocks + } + if (sh.oz == 70000) { + CHECK(ls.grid_y == 65535U); // capped: the grid-stride loop must cover the rest + } + std::vector stage(cl.size() * box.volume(), 0U); + hp::host_gather(field.data(), stage.data(), steps[0].args); + size_t n = 0; + for (const int c : cl) { + for (int64_t z = 0; z < box.ext_z; ++z) { + for (int64_t y = 0; y < box.ext_y; ++y) { + for (int64_t x = 0; x < box.ext_x; ++x) { + CHECK(stage[n] == + field[static_cast(c * cs + (box.lo_z + z) * g.pitch + + (box.lo_y + y) * g.haloed.x + box.lo_x + x)]); + ++n; + } + } + } + } + CHECK(n == stage.size()); + } + } +} + +// ---- Part B: whole-world scenarios -------------------------------------------------------- +// ------------------------------------------------------------------------------------------------ +// Part B: slab / pencil / brick geometry. +// ------------------------------------------------------------------------------------------------ + +struct GeomCase { + const char* name; + int px, py, pz; + BoundaryModeDistributed bm; + int64_t gx, gy, gz; + std::vector pts; // stencil points (centre excluded) + int64_3d want_halo; // hand-written expectation (per side, uniform across ranks) +}; + +auto +six() -> std::vector { + return {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}; +} + +auto +eq3(const int64_3d& a, + const int64_3d& b) -> bool { + return a.x == b.x && a.y == b.y && a.z == b.z; +} + +auto +wrap_axis(int64_t v, + int64_t n, + bool periodic, + int64_t& out) -> bool { + if (v >= 0 && v < n) { + out = v; + return true; + } + if (!periodic) { + return false; + } + out = ((v % n) + n) % n; + return true; +} + +auto +check_geometry(const GeomCase& c, + size_t& cells, + size_t& neighbour_reads) -> void { + g_ctx = std::string("part B ") + c.name; + const ProcessGrid pg = ProcessGrid::custom(c.px * c.py * c.pz, c.px, c.py, c.pz); + const carbon::Stencil stencil(c.pts, /*remove_center=*/true); + const int64_3d global{c.gx, c.gy, c.gz}; + const BoundaryModeDistributed bm = c.bm; + + const int64_3d halo = dd::halo_extent(pg, bm, stencil); + CHECK(eq3(halo, c.want_halo)); + + const bool legacy_slab = dd::is_legacy_slab(pg, bm); + CHECK(legacy_slab == (c.px == 1 && c.py == 1 && !carbon::is_periodic(bm, Axis::X) && + !carbon::is_periodic(bm, Axis::Y))); + + std::vector cover(static_cast(c.gx * c.gy * c.gz), 0); + const auto cover_at = [&](int64_t x, int64_t y, int64_t z) -> int& { + return cover[static_cast((z * c.gy + y) * c.gx + x)]; + }; + + for (int32_t r = 0; r < pg.world_size(); ++r) { + const int32_3d co = pg.coords_of(r); + const dd::RankChunk ch = dd::rank_chunk(global, pg, co, halo); + + // Independent expectation of the split (the documented "first n % P get one extra layer"). + const auto sx = split(c.gx, c.px, co.x); + const auto sy = split(c.gy, c.py, co.y); + const auto sz = split(c.gz, c.pz, co.z); + CHECK(eq3(ch.owned, {sx.first, sy.first, sz.first})); + CHECK(eq3(ch.offset, {sx.second - halo.x, sy.second - halo.y, sz.second - halo.z})); + CHECK(eq3(ch.halo, halo)); + CHECK(eq3(ch.haloed, + {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); + CHECK(eq3(span.logic_extent(), ch.owned)); + CHECK(eq3(span.haloed_extent(), ch.haloed)); + CHECK(eq3(span.halo(), halo)); + CHECK(eq3(span.offset(), ch.offset)); + CHECK(eq3(span.global_extent(), global)); + CHECK(span.xy_slab_elements() == ch.xy_pitch); + CHECK(span.linear_storage_elements() == ch.xy_pitch * ch.haloed.z); + + // Standard view: every owned cell once, mapped to the right global coordinate. + const int64_3d own0{sx.second, sy.second, sz.second}; // global coordinate of owned cell 0 + CHECK(eq3(span.iter_extent(carbon::DataView::Standard), ch.owned)); + for (int64_t iz = 0; iz < ch.owned.z; ++iz) { + for (int64_t iy = 0; iy < ch.owned.y; ++iy) { + for (int64_t ix = 0; ix < ch.owned.x; ++ix) { + const auto v = span.set_and_validate(carbon::DataView::Standard, ix, iy, iz); + CHECK(v.valid); + CHECK(eq3(v.idx.cell(), {halo.x + ix, halo.y + iy, halo.z + iz})); + const int64_3d g = span.global_location(v.idx); + CHECK(eq3(g, {own0.x + ix, own0.y + iy, own0.z + iz})); + cover_at(g.x, g.y, g.z) += 1; + ++cells; + } + } + } + CHECK(!span.set_and_validate(carbon::DataView::Standard, ch.owned.x, 0, 0).valid); + + // Internal + Boundary must tile the owned cells exactly once. (A legacy Z slab thinner than + // 2 * halo.z has overlapping Boundary bands by construction; that degenerate shape is skipped.) + if (!(legacy_slab && ch.owned.z < 2 * halo.z)) { + 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); + for (int64_t iz = 0; iz < e.z; ++iz) { + for (int64_t iy = 0; iy < e.y; ++iy) { + for (int64_t ix = 0; ix < e.x; ++ix) { + const auto v = span.set_and_validate(view, ix, iy, iz); + if (!v.valid) { + continue; + } + const int64_3d cell = v.idx.cell(); + const int64_t lx = cell.x - halo.x; + const int64_t ly = cell.y - halo.y; + const int64_t lz = cell.z - halo.z; + CHECK(lx >= 0 && lx < ch.owned.x && ly >= 0 && ly < ch.owned.y && lz >= 0 && + lz < ch.owned.z); + mark[static_cast((lz * ch.owned.y + ly) * ch.owned.x + lx)] += 1; + } + } + } + } + for (const int m : mark) { + CHECK(m == 1); + } + } + + // Neighbour resolution for every stencil point of every owned cell. + for (int64_t iz = 0; iz < ch.owned.z; ++iz) { + for (int64_t iy = 0; iy < ch.owned.y; ++iy) { + for (int64_t ix = 0; ix < ch.owned.x; ++ix) { + const dd::Idx idx = span.make_idx(halo.x + ix, halo.y + iy, halo.z + iz); + const int64_3d g{own0.x + ix, own0.y + iy, own0.z + iz}; + for (const int32_3d& p : c.pts) { + const dd::NeighbourIdx nb = + dd::neighbour_idx(span, idx, + int8_3d{static_cast(p.x), static_cast(p.y), + static_cast(p.z)}); + int64_t wx = 0; + int64_t wy = 0; + int64_t wz = 0; + const bool want = wrap_axis(g.x + p.x, c.gx, carbon::is_periodic(bm, Axis::X), wx) && + wrap_axis(g.y + p.y, c.gy, carbon::is_periodic(bm, Axis::Y), wy) && + wrap_axis(g.z + p.z, c.gz, carbon::is_periodic(bm, Axis::Z), wz); + CHECK(nb.valid == want); + ++neighbour_reads; + if (!want) { + continue; + } + const int64_3d cell = nb.idx.cell(); + CHECK(cell.x >= 0 && cell.x < ch.haloed.x && cell.y >= 0 && cell.y < ch.haloed.y && + cell.z >= 0 && cell.z < ch.haloed.z); + // The addressed cell is the (possibly halo) copy of the wrapped global cell. + const int64_3d ng = span.global_location(nb.idx); + int64_t ax = 0; + int64_t ay = 0; + int64_t az = 0; + CHECK(wrap_axis(ng.x, c.gx, true, ax) && wrap_axis(ng.y, c.gy, true, ay) && + wrap_axis(ng.z, c.gz, true, az)); + CHECK(ax == wx && ay == wy && az == wz); + } + } + } + } + } + + for (const int m : cover) { + CHECK(m == 1); // owned boxes tile the global domain exactly once + } +} + +auto +part_b_geometry(size_t& cells, + size_t& neighbour_reads) -> size_t { + constexpr auto kO = BoundaryModeDistributed::Open; + constexpr auto kX = BoundaryModeDistributed::PeriodicX; + constexpr auto kY = BoundaryModeDistributed::PeriodicY; + constexpr auto kZ = BoundaryModeDistributed::PeriodicZ; + const std::vector aniso = {{2, 0, 0}, {-2, 0, 0}, {0, 1, 0}, + {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}}; + std::vector d3q19; + for (int z = -1; z <= 1; ++z) { + for (int y = -1; y <= 1; ++y) { + for (int x = -1; x <= 1; ++x) { + const int nz = (x != 0) + (y != 0) + (z != 0); + if (nz >= 1 && nz <= 2) { + d3q19.push_back({x, y, z}); + } + } + } + } + const std::vector cases = { + // Slab (Px == Py == 1): historical Z halo, X/Y halos only when periodic. + {"slab/single-open", 1, 1, 1, kO, 6, 5, 7, six(), {0, 0, 1}}, + {"slab/z3-open", 1, 1, 3, kO, 6, 5, 9, six(), {0, 0, 1}}, + {"slab/z3-radius2", 1, 1, 3, kO, 6, 5, 12, r2, {0, 0, 2}}, + {"slab/z2-periodicZ", 1, 1, 2, kZ, 6, 5, 8, six(), {0, 0, 1}}, + {"slab/z2-periodicX", 1, 1, 2, kX, 6, 5, 8, six(), {1, 0, 1}}, + {"slab/single-periodicXYZ", 1, 1, 1, kX | kY | kZ, 5, 5, 5, six(), {1, 1, 1}}, + // Pencil: two split axes. + {"pencil/yz-open", 1, 2, 2, kO, 6, 7, 8, six(), {0, 1, 1}}, + {"pencil/yz-periodicZ", 1, 2, 2, kZ, 6, 7, 8, six(), {0, 1, 1}}, + {"pencil/yz-periodicX", 1, 2, 2, kX, 6, 7, 8, six(), {1, 1, 1}}, + {"pencil/yz-d3q19", 1, 2, 2, kO, 6, 7, 8, d3q19, {0, 1, 1}}, + // Brick: three split axes, uneven and thin chunks. + {"brick/222-open", 2, 2, 2, kO, 7, 6, 5, six(), {1, 1, 1}}, + {"brick/322-uneven", 3, 2, 2, kO, 8, 5, 6, six(), {1, 1, 1}}, + {"brick/222-thin-periodicXYZ", 2, 2, 2, kX | kY | kZ, 3, 3, 3, six(), {1, 1, 1}}, + {"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}}, + }; + for (const GeomCase& c : cases) { + check_geometry(c, cells, neighbour_reads); + } + return cases.size(); +} + +struct Scenario { + const char* name; + int px, py, pz; + BoundaryModeDistributed bm; + int64_t gx, gy, gz; + int64_t hx, hy, hz; + int comps; + int lattice_q; + int64_t pad; +}; + +constexpr BoundaryModeDistributed kOpen = BoundaryModeDistributed::Open; +constexpr BoundaryModeDistributed kPX = BoundaryModeDistributed::PeriodicX; +constexpr BoundaryModeDistributed kPY = BoundaryModeDistributed::PeriodicY; +constexpr BoundaryModeDistributed kPZ = BoundaryModeDistributed::PeriodicZ; + +auto +bm_or(BoundaryModeDistributed a, + BoundaryModeDistributed b) -> BoundaryModeDistributed { + return static_cast(static_cast(a) | static_cast(b)); +} + +auto +run_scenario(const Scenario& s, + size_t& total_checked, + size_t& total_msgs, + size_t& z_msgs) -> void { + g_ctx = std::string(s.name) + " grid=" + std::to_string(s.px) + "x" + std::to_string(s.py) + "x" + + std::to_string(s.pz) + " bm=" + std::to_string(static_cast(s.bm)) + + " lat=" + std::to_string(s.lattice_q) + " pad=" + std::to_string(s.pad); + const ProcessGrid pg = ProcessGrid::custom(s.px * s.py * s.pz, s.px, s.py, s.pz); + World packed = + make_world(pg, s.bm, {s.gx, s.gy, s.gz}, {s.hx, s.hy, s.hz}, s.comps, s.lattice_q, s.pad); + World oracle = packed; // identical start state + + // Old path: run-based X, Y, Z. + for (const Axis a : {Axis::X, Axis::Y, Axis::Z}) { + exchange_runs(oracle, a); + } + + // New path: packed X, Y; Z is packed iff it carries several components (Halo's rule), else it + // stays on the run-based path (a single contiguous run per side). + const bool pack_z = packed.comps > 1; + std::vector cursor(packed.ranks.size(), 0); + for (const Axis a : {Axis::X, Axis::Y}) { + const PassStats st = exchange_packed(packed, a, cursor); + total_msgs += st.msgs; + } + if (pack_z) { + const PassStats st = exchange_packed(packed, Axis::Z, cursor); + total_msgs += st.msgs; + z_msgs += st.msgs; + } else { + exchange_runs(packed, Axis::Z); + } + + total_checked += + verify(oracle, nullptr, /*check_exterior=*/ + false); // oracle: right on needed cells (it clobbers exterior halos, by design)... + total_checked += + verify(packed, &oracle, true, pack_z); // ...and the packed result must match it bit for bit +} + +} // namespace + +int +main() { + part_a_roundtrip(); + part_a_roundtrip(); + part_a_roundtrip(); + part_a_roundtrip(); + part_a_roundtrip(); + part_a_launch_shapes(); + + 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); + + std::vector sc; + const BoundaryModeDistributed modes[] = { + kOpen, kPX, kPY, kPZ, bm_or(kPX, kPZ), bm_or(bm_or(kPX, kPY), kPZ)}; + struct G { + const char* n; + int x, y, z; + }; + const G grids[] = {{"single", 1, 1, 1}, {"x2", 2, 1, 1}, {"x3", 3, 1, 1}, + {"y2", 1, 2, 1}, {"slab4", 1, 1, 4}, {"pencil", 1, 2, 2}, + {"brick", 2, 2, 2}, {"brick-uneven", 2, 3, 2}, {"brick3", 3, 2, 2}}; + for (const BoundaryModeDistributed bm : modes) { + for (const G& g : grids) { + // Standard semantics, 3 components, halo (1,1,1), padded and unpadded pitch. + sc.push_back({"std-c1-runsZ", g.x, g.y, g.z, bm, 11, 9, 10, 1, 1, 1, 1, 0, 0}); + sc.push_back({"std-h111", g.x, g.y, g.z, bm, 11, 9, 10, 1, 1, 1, 3, 0, 0}); + sc.push_back({"std-h111-pad", g.x, g.y, g.z, bm, 11, 9, 10, 1, 1, 1, 3, 0, 7}); + // Wider, anisotropic halo (radius 2 on X and Z). + sc.push_back({"std-h212", g.x, g.y, g.z, bm, 13, 9, 14, 2, 1, 2, 2, 0, 3}); + // Lattice direction filtering (per-axis send/recv component lists). + sc.push_back({"d3q19", g.x, g.y, g.z, bm, 11, 9, 10, 1, 1, 1, 0, 19, 0}); + sc.push_back({"d3q27", g.x, g.y, g.z, bm, 11, 9, 10, 1, 1, 1, 0, 27, 5}); + } + } + + size_t checked = 0; + size_t msgs = 0; + size_t z_msgs = 0; + for (const Scenario& s : sc) { + run_scenario(s, checked, msgs, z_msgs); + } + std::printf("scenarios=%zu halo-cells-verified=%zu packed messages=%zu (of which Z=%zu)\n", + sc.size(), checked, msgs, z_msgs); + CHECK(z_msgs > 0U); // packed Z must actually be exercised + + // Transfer-count comparison for a realistic block (printed as evidence, asserted as a bound). + g_ctx = "transfer-count comparison"; + AxisGeometry g; + g.owned = {256, 256, 256}; + g.halo = {1, 1, 1}; + g.haloed = {258, 258, 258}; + g.pitch = 258 * 258; + const size_t old_x = hb::axis_halo_runs(g, Axis::X, AxisSide::Lower).size(); + const size_t old_y = hb::axis_halo_runs(g, Axis::Y, AxisSide::Lower).size(); + const size_t old_z = hb::axis_halo_runs(g, Axis::Z, AxisSide::Lower).size(); + std::printf( + "256^3 local block, halo 1, 1 component, per side: run-based transfers X=%zu Y=%zu Z=%zu" + " | packed X=1 Y=1 Z=%zu\n", + old_x, old_y, old_z, old_z); + CHECK(old_x == 258U * 258U); + CHECK(old_y == 258U); + + std::puts("OK"); + return 0; +} diff --git a/tests/test_process_grid.cpp b/tests/test_process_grid.cpp new file mode 100644 index 00000000..5cc10774 --- /dev/null +++ b/tests/test_process_grid.cpp @@ -0,0 +1,163 @@ +#include + +#include +#include +#include + +namespace { + +using carbon::DecompositionMode; +using carbon::int32_3d; +using carbon::ProcessGrid; + +template +void +expect_invalid_argument(Fn fn) { + bool threw = false; + try { + fn(); + } catch (const std::invalid_argument&) { + threw = true; + } + assert(threw); +} + +template +void +expect_out_of_range(Fn fn) { + bool threw = false; + try { + fn(); + } catch (const std::out_of_range&) { + threw = true; + } + assert(threw); +} + +void +expect_round_trip(const ProcessGrid& grid) { + for (int32_t rank = 0; rank < grid.world_size(); ++rank) { + const int32_3d coords = grid.coords_of(rank); + assert(grid.rank_of(coords) == rank); + } +} + +void +test_slab() { + const int32_t sizes[]{1, 2, 3, 4, 6, 12}; + for (const int32_t n : sizes) { + const ProcessGrid grid = ProcessGrid::make(n, DecompositionMode::Slab); + const int32_3d expected_dims{1, 1, n}; + assert(grid.mode() == DecompositionMode::Slab); + assert(grid.world_size() == n); + assert(grid.dims() == expected_dims); + assert(grid.is_slab()); + + for (int32_t rank = 0; rank < n; ++rank) { + const int32_3d coords = grid.coords_of(rank); + assert(coords.x == 0); + assert(coords.y == 0); + assert(coords.z == rank); + } + expect_round_trip(grid); + } +} + +void +test_pencil() { + const ProcessGrid six = ProcessGrid::make(6, DecompositionMode::Pencil); + const int32_3d expected_six{1, 2, 3}; + assert(six.mode() == DecompositionMode::Pencil); + assert(six.dims() == expected_six); + assert(!six.is_slab()); + expect_round_trip(six); + + const ProcessGrid twelve = ProcessGrid::make(12, DecompositionMode::Pencil); + const int32_3d expected_twelve{1, 4, 3}; + assert(twelve.world_size() == 12); + assert(twelve.dims() == expected_twelve); + assert(twelve.dims().x == 1); + assert(twelve.dims().y > 1); + assert(twelve.dims().z > 1); + expect_round_trip(twelve); +} + +void +test_brick() { + const ProcessGrid eight = ProcessGrid::make(8, DecompositionMode::Brick); + const int32_3d expected_eight{2, 2, 2}; + assert(eight.mode() == DecompositionMode::Brick); + assert(eight.dims() == expected_eight); + assert(!eight.is_slab()); + expect_round_trip(eight); + + const ProcessGrid twelve = ProcessGrid::make(12, DecompositionMode::Brick); + const int32_3d expected_twelve{2, 2, 3}; + assert(twelve.world_size() == 12); + assert(twelve.dims() == expected_twelve); + assert(twelve.dims().x > 1); + assert(twelve.dims().y > 1); + assert(twelve.dims().z > 1); + expect_round_trip(twelve); +} + +void +test_custom() { + const ProcessGrid grid = ProcessGrid::custom(24, 2, 3, 4); + const int32_3d expected_dims{2, 3, 4}; + assert(grid.mode() == DecompositionMode::Custom); + assert(grid.world_size() == 24); + assert(grid.dims() == expected_dims); + assert(!grid.is_slab()); + + const int32_3d origin{0, 0, 0}; + const int32_3d z1{0, 0, 1}; + const int32_3d y1{0, 1, 0}; + const int32_3d x1{1, 0, 0}; + assert(grid.rank_of(origin) == 0); + assert(grid.rank_of(z1) == 1); + assert(grid.rank_of(y1) == 4); + assert(grid.rank_of(x1) == 12); + expect_round_trip(grid); +} + +void +test_invalid() { + expect_invalid_argument([] { static_cast(ProcessGrid::make(0, DecompositionMode::Slab)); }); + expect_invalid_argument( + [] { static_cast(ProcessGrid::make(-4, DecompositionMode::Brick)); }); + expect_invalid_argument( + [] { static_cast(ProcessGrid::make(8, DecompositionMode::Custom)); }); + + expect_invalid_argument([] { static_cast(ProcessGrid::custom(0, 1, 1, 1)); }); + expect_invalid_argument([] { static_cast(ProcessGrid::custom(8, 0, 2, 4)); }); + expect_invalid_argument([] { static_cast(ProcessGrid::custom(8, -1, 2, 4)); }); + expect_invalid_argument([] { static_cast(ProcessGrid::custom(8, 2, 2, 3)); }); + + const ProcessGrid grid = ProcessGrid::custom(8, 2, 2, 2); + expect_out_of_range([&] { static_cast(grid.coords_of(-1)); }); + expect_out_of_range([&] { static_cast(grid.coords_of(8)); }); + + const int32_3d negative_x{-1, 0, 0}; + const int32_3d past_x{2, 0, 0}; + const int32_3d negative_y{0, -1, 0}; + const int32_3d past_y{0, 2, 0}; + const int32_3d negative_z{0, 0, -1}; + const int32_3d past_z{0, 0, 2}; + expect_out_of_range([&] { static_cast(grid.rank_of(negative_x)); }); + expect_out_of_range([&] { static_cast(grid.rank_of(past_x)); }); + expect_out_of_range([&] { static_cast(grid.rank_of(negative_y)); }); + expect_out_of_range([&] { static_cast(grid.rank_of(past_y)); }); + expect_out_of_range([&] { static_cast(grid.rank_of(negative_z)); }); + expect_out_of_range([&] { static_cast(grid.rank_of(past_z)); }); +} + +} // namespace + +int main() { + test_slab(); + test_pencil(); + test_brick(); + test_custom(); + test_invalid(); +} \ No newline at end of file From 5115d5fd60661f0325e36908e28909b2b0e72ea4 Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Mon, 2 Nov 2026 18:47:44 +0100 Subject: [PATCH 03/33] Diseable barrier in halo_distributed.h file and update CHANGELOG.md --- docs/CHANGELOG.md | 25 +++++++++++++++++++++++++ include/carbon/halo_distributed.h | 10 +++++----- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 1127d29c..1f384e78 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6046,6 +6046,31 @@ This unblocked the matrix on this host: the `sycl` and `hip-nvidia` images build (and DenseDisg forwarding) compute one centre offset then constant-strided `pull()` neighbours; Jacobi uses it instead of `neighbour()` + a redundant `read()` partition. `Dense` rejects layouts whose `xy_slab_elements` or haloed x extent exceed `int32_t`. New test `test_partition_cursor`. +- **2026-10 — `DenseDistributed`: slab / pencil / brick split out of `Dense`.** `Dense` is back to + its original Z-slab-only implementation (`dense.h`, `dense.cpp`, `detail/dense/{span,field, + partition}.h`, `halo.h`, `detail/halo_build.h` and `boundary_mode.h` are unchanged from before + the decomposition work; `BoundaryMode::PeriodicZ` is `1` again, so `DenseDisg`, `libcarbonpy` + and the Python bindings are untouched). The process-grid decomposition now lives in a sibling + grid family: `carbon::DenseDistributed` (+ `HaloDistributed`, and the per-axis + `BoundaryModeDistributed`, whose `PeriodicX | PeriodicY | PeriodicZ` bits are independent; it + is a separate type so a per-axis mask can never reach a grid that only understands a Z wrap). + It takes a `ProcessGrid` / `DecompositionMode` (default slab) and exposes the same `Span` / + `Partition` / `Field` / kernel / reduce surface as `Dense`, wired through a + `DenseDistributedPolicy` marker in `launch_traits.h` (same mechanism as `DisgPolicy`) and + `Kernel::halo_distributed`; `Idx` is shared with `Dense`. The split / halo-thickness / per-rank + chunk arithmetic is a pure host function set in `detail/dense_distributed/layout.h`, so tests + can exercise the production decomposition without a GPU. The cross-rank NCCL pairing key still + ends with the run index: X/Y halo faces are non-contiguous in the x-fastest buffer, so one face + fans out into many runs sharing the same `(axis, source, dest, side, component)` key, and an + unordered sort could permute them differently on the two ranks. Tests: the nine multi-axis + tests and `test_halo_decomp_common.h` are replaced by `dense_distributed_host` (host-only: + geometry of every rank for slab / pencil / brick, Span views, open vs periodic neighbours, and + the packed X→Y→Z exchange on an emulated world) and `dense_distributed_dist` (4 ranks: raw halo + exchange byte-checked on slab `(1,1,4)`, pencil `(1,2,2)` and bricks `(2,2,1)` / `(2,1,2)`, + packed and run-based, plus a Skeleton stencil kernel with and without overlap; launched with + `mpiexec -n 8` it covers the full `(2,2,2)` brick, so `CARBON_TEST_BRICK_8GPU` is gone). + `benchmarks_giulio`: CG gains `--grid dense_distributed` (`--grid dense` is the original + slab-only grid and rejects pencil / brick); LDC and Jacobi run on `DenseDistributed`. - **2026-10 — Extended / TwoWayExtended on the step graph.** Every `OverlapMode` now lowers through `compile_step_graph_and_lower_`; the legacy in-place `apply_occ_` rewrite and `compile_assign_streams_and_events_` are gone. `compile_step_graph_occ_` applies the Standard diff --git a/include/carbon/halo_distributed.h b/include/carbon/halo_distributed.h index 98973ee6..a6017c05 100644 --- a/include/carbon/halo_distributed.h +++ b/include/carbon/halo_distributed.h @@ -280,8 +280,8 @@ class HaloDistributed { } #ifdef CARBON_HAVE_MPI_NCCL - // Host-blocking barrier between axis passes. Kept ON by default (historical - // behaviour); CARBON_HALO_PASS_BARRIER=0 removes it. It should not be needed for + // Host-blocking barrier between axis passes. OFF by default; set + // CARBON_HALO_PASS_BARRIER=1 to enable it. It should not be needed for // correctness (every pass is ordered on `stream`; intra copies are fenced above) and it // serialises the host against the GPU, which defeats overlap with interior compute. if (pass_barrier_) { @@ -494,8 +494,8 @@ class HaloDistributed { // in the constructor so no allocation can land inside graph capture or a timed region. Buffer stage_{}; #endif - // See operator(): host barrier between axis passes. CARBON_HALO_PASS_BARRIER=0 disables it. - bool pass_barrier_{true}; + // See operator(): host barrier between axis passes. CARBON_HALO_PASS_BARRIER=1 enables it. + bool pass_barrier_{false}; Stencil stencil_{}; StencilSemantic semantic_{StencilSemantic::Standard}; // Number of cross-rank slab pairs that the host pipeline would need to handle. @@ -852,7 +852,7 @@ HaloDistributed 0; }; - pass_barrier_ = detail::halo_pack::env_flag("CARBON_HALO_PASS_BARRIER", true); + pass_barrier_ = detail::halo_pack::env_flag("CARBON_HALO_PASS_BARRIER", false); #if CARBON_BACKEND_IS_CUDALIKE // Packed X/Y faces: one message per side instead of one per contiguous row. Needs exactly one From 97cad1e8fc8ea09d47917f735987671cd823529f Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Mon, 2 Nov 2026 21:32:37 +0100 Subject: [PATCH 04/33] Add cg benchmark --- benchmarks/CMakeLists.txt | 2 + benchmarks/cg/CMakeLists.txt | 2 + benchmarks/cg/cg_poisson.cu | 1029 ++++++++++++++++++++++++++++++++++ 3 files changed, 1033 insertions(+) create mode 100644 benchmarks/cg/CMakeLists.txt create mode 100644 benchmarks/cg/cg_poisson.cu diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index c01ada84..02b016ad 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -53,3 +53,5 @@ add_subdirectory(reduce_throughput) add_subdirectory(skeleton_overlap) add_subdirectory(block_sparse) add_subdirectory(jacobi_nvidia) +add_subdirectory(cg) + diff --git a/benchmarks/cg/CMakeLists.txt b/benchmarks/cg/CMakeLists.txt new file mode 100644 index 00000000..7d655e69 --- /dev/null +++ b/benchmarks/cg/CMakeLists.txt @@ -0,0 +1,2 @@ +_carbon_benchmark_add(carbon_benchmark_cg_poisson cg_poisson.cu) +target_link_libraries(carbon_benchmark_cg_poisson PRIVATE carbon::carbon carbon_benchmark_common) diff --git a/benchmarks/cg/cg_poisson.cu b/benchmarks/cg/cg_poisson.cu new file mode 100644 index 00000000..b20bfbdd --- /dev/null +++ b/benchmarks/cg/cg_poisson.cu @@ -0,0 +1,1029 @@ +// Unified Conjugate-Gradient 3D Poisson solver across every carbon grid + +// every transport. Companion to @c jacobi_unified.cu : same Skeleton-only main +// loop, same per-cell device lambdas reused verbatim across: +// +// - Grids: carbon::Dense (original, Z-slab only) +// carbon::DenseDistributed (slab / pencil / brick decomposition) +// carbon::DenseDisg +// carbon::Block +// - Backends: CUDA (default, nvcc) +// SYCL (AdaptiveCpp -DCARBON_BACKEND=Sycl) +// - Transports: single-GPU, multi-GPU same node, cross-rank NCCL/RCCL/oneCCL +// (the latter with -DCARBON_ENABLE_MPI=ON + mpiexec) +// +// PDE +// --- +// -Laplacian(u) = 0 on a 3D Cartesian box (Dense / DenseDistributed / DenseDisg) or on the +// retained sphere of the @c Block predicate. +// +// Boundary conditions are encoded topologically: +// - cells whose @c (0,0,-1) neighbour is invalid (south cap / lower z-face) +// are Dirichlet at @c bd_min ; +// - cells whose @c (0,0,+1) neighbour is invalid (north cap / upper z-face) +// are Dirichlet at @c bd_max ; +// - cells with a missing x/y face neighbour drop that term from the +// Laplacian sum (the same implicit Neumann handling Neon uses). +// +// On Dense / DenseDistributed / DenseDisg with open boundaries the south + north faces +// collapse to the global @c z=0 and @c z=Nz-1 planes, so the analytical +// solution is the linear-z ramp +// @c u(x, y, z) = bd_min + (bd_max - bd_min) * z / (Nz - 1) . +// On Block with the bundled sphere predicate the "south cap" is the lower +// hemisphere shell and the "north cap" is the upper hemisphere shell, so the +// analytical solution is no longer linear-z; the example still reports the +// final residual norm and the RMS deviation against the linear-z reference +// purely as a sanity-of-convergence check (smaller after CG than before, +// *not* a correctness claim). +// +// Discretization (matches Neon's @c LaplacianMatVec): +// free cell: @c (A x)[c] = (n_valid * x[c] - sum_valid_nghs(x)) / h^2 +// Dirichlet cell: @c (A x)[c] = x[c] (identity row) +// Solver: standard CG with Dirichlet BCs folded into the iterate +// ( @c b == 0 , @c r = (Free) ? b : x , then @c r -= A x ). +// +// What Skeleton buys +// ------------------ +// The three CG phases ("init", "iter_pre" = update_p + matvec + dot pAp, +// "iter_post" = update_x_r + dot rTr) are each a @c carbon::Skeleton . The +// @c loader.read_stencil(in) annotation on @c matvec triggers an auto-inserted +// halo for the stencil read on every cycle, so the same source line exchanges: +// - nothing on single-GPU, +// - cross-GPU intra-process via @c Transfer on multi-GPU same node, +// - cross-rank via NCCL / RCCL / oneCCL when @c sys.distributed() is set. +// +// Overlap mode +// ------------ +// Same four modes as @c jacobi_unified.cu , selected via @c --overlap : +// - @c none (default): halos run serially before each stencil step. +// - @c standard : Internal+Boundary split, halo concurrent with Internal. +// - @c extended : Standard plus one step of propagation. +// - @c two-way-extended: Extended in both directions. +// +// CLI +// --- +// --grid {dense|dense_distributed|disg|block} +// Grid family (default: dense). dense is the +// original Z-slab-only grid; dense_distributed +// honours --decomposition. +// --nx N --ny N --nz N Grid extents (default 16 16 32; nz >= 2) +// --max_iter N Hard cap on CG iterations (default 4 * nz) +// --tol_rel R Relative tolerance ||r||/||r0|| (default 1e-10) +// --tol_abs R Absolute tolerance ||r|| (default 1e-12) +// --bd_min R --bd_max R Dirichlet z-face values (default +1, -1) +// --report_every N Log every N iterations (default 25) +// --warmup N Iterations excluded from timing (default 10) +// --overlap {none|standard|extended|two-way-extended} +// Skeleton::Options::overlap_mode for the +// in-iteration pipelines (default: none). +// --decomposition {slab|pencil|brick} +// MPI process decomposition (default: slab, +// only relevant for distributed runs; pencil and +// brick need --grid dense_distributed): slab +// splits z as 1x1xP, pencil splits the two +// most-square factors, brick picks the factor +// triple of P with the smallest max/min ratio. +// --dot Dump the inferred main-loop DAGs as GraphViz +// DOT on stdout (one block per Skeleton). +// --dot-out prefix Write GraphViz DOT + launch-order listings +// for init / iter_pre / iter_post as +// prefix_.dot and prefix_.txt. +// --dot-matrix With --dot-out, also write launch-matrix and +// kernel-list DOT +// (prefix__matrix.dot / _kernels.dot). +// --help Print this help and exit. +// +// Build + run +// ----------- +// ./carbon_example_cg_poisson_unified # default: dense, 1 GPU +// ./carbon_example_cg_poisson_unified --grid disg --nx 32 --ny 32 --nz 64 +// ./carbon_example_cg_poisson_unified --grid block --nx 32 --ny 32 --nz 32 +// ./carbon_example_cg_poisson_unified --grid dense --overlap standard +// mpiexec -n 2 ./carbon_example_cg_poisson_unified --grid dense --nz 64 +// mpiexec -n 8 ./carbon_example_cg_poisson_unified --grid dense_distributed --nx 32 --ny 32 --nz 32 --decomposition brick +// +// Block + MPI cross-rank stencil parity is covered by +// tests/test_block_dist_stencil_parity.cu (see jacobi_unified.cu header). + +#include +#include +#include +#include +#include +#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 +#include +#include +#include +#include +#include +#include +#include + +#if __has_include() +# include +# define CARBON_HALO_NVTX_PUSH(name) ::nvtxRangePushA(name) +# define CARBON_HALO_NVTX_POP() ::nvtxRangePop() +#elif __has_include() +# include +# define CARBON_HALO_NVTX_PUSH(name) ::nvtxRangePushA(name) +# define CARBON_HALO_NVTX_POP() ::nvtxRangePop() +#else +# define CARBON_HALO_NVTX_PUSH(name) ((void)0) +# define CARBON_HALO_NVTX_POP() ((void)0) +#endif + + +namespace { + +using SB = carbon::detail::block::DefaultStaticBlock; + +struct SampleStats { + size_t n = 0; + double min = 0.0; + double max = 0.0; + double mean = 0.0; + double stddev = 0.0; + double median = 0.0; +}; + +[[nodiscard]] auto +compute_sample_stats(std::vector values) -> SampleStats { + SampleStats stats; + stats.n = values.size(); + if (values.empty()) { + return stats; + } + + std::sort(values.begin(), values.end()); + stats.min = values.front(); + stats.max = values.back(); + stats.mean = + std::accumulate(values.begin(), values.end(), 0.0) / static_cast(stats.n); + + if (stats.n > 1U) { + double sum_sq = 0.0; + for (double value : values) { + const double delta = value - stats.mean; + sum_sq += delta * delta; + } + stats.stddev = std::sqrt(sum_sq / static_cast(stats.n - 1U)); + } + + const size_t mid = stats.n / 2U; + stats.median = (stats.n % 2U == 0U) + ? 0.5 * (values[mid - 1U] + values[mid]) + : values[mid]; + return stats; +} + +struct Options { + std::string grid_kind = "dense"; + int64_t nx = 16; + int64_t ny = 16; + int64_t nz = 32; + size_t max_iter = 0; // 0 = auto -> 4 * nz + double tol_rel = 1e-10; + double tol_abs = 1e-12; + double bd_min = 1.0; + double bd_max = -1.0; + int report_every = 25; + size_t warmup = 10; + std::string overlap_raw; + bool dump_dot = false; + bool show_help = false; + std::string dec; + std::string dot_out_prefix; + bool dot_matrix = false; +}; + +// Build a clipp parser bound directly to @p opts. Mirrors the structure of the +// pre-unified single-GPU example. +[[nodiscard]] auto +build_cli(Options& opts) -> clipp::group { + using clipp::integer; + using clipp::number; + using clipp::option; + using clipp::value; + + return clipp::group( + (option("-h", "--help").set(opts.show_help) % "Show this help message and exit"), + (option("--grid") & value("kind", opts.grid_kind)) % + "Grid family: dense | disg | block (default: dense)", + (option("--nx") & integer("nx", opts.nx)) % "Grid x extent (default 16)", + (option("--ny") & integer("ny", opts.ny)) % "Grid y extent (default 16)", + (option("--nz") & integer("nz", opts.nz)) % "Grid z extent (default 32, must be >= 2)", + (option("--max_iter") & integer("max_iter", opts.max_iter)) % + "Maximum CG iterations (default 4 * nz)", + (option("--tol_rel") & number("tol_rel", opts.tol_rel)) % + "Relative tolerance ||r||/||r0|| (default 1e-10)", + (option("--tol_abs") & number("tol_abs", opts.tol_abs)) % + "Absolute tolerance ||r|| (default 1e-12)", + (option("--bd_min") & number("bd_min", opts.bd_min)) % + "Dirichlet value at z=0 face / lower cap (default +1.0)", + (option("--bd_max") & number("bd_max", opts.bd_max)) % + "Dirichlet value at z=Nz-1 face / upper cap (default -1.0)", + (option("--report_every") & integer("n", opts.report_every)) % + "Log every N iterations (default 25)", + (option("--warmup") & integer("n", opts.warmup)) % + "Iterations excluded from timing statistics (default 10)", + (option("--overlap") & value("mode", opts.overlap_raw)) % + "Skeleton overlap mode: none | standard | extended | two-way-extended (default: none)", + (option("--dot").set(opts.dump_dot) % + "Dump inferred main-loop Skeleton DAGs as GraphViz DOT on stdout")), + (option("--dot-out") & value("prefix", opts.dot_out_prefix)) % + "Write DOT + launch-order files as prefix_.dot / .txt " + "(tag = init | iter_pre | iter_post)", + (option("--dot-matrix").set(opts.dot_matrix)) % + "With --dot-out, also write launch-matrix and kernel-list DOT files", + (option("--decomposition") & value("mode", opts.dec)) % + "MPI decomposition: slab | pencil | brick (default: slab, only relevant for distributed runs)"; + +} + +[[nodiscard]] auto +parse_cli(int argc, + char** argv, + Options& opts) -> bool { + auto cli = build_cli(opts); + if (!clipp::parse(argc, argv, cli)) { + auto fmt = clipp::doc_formatting{}.doc_column(31); + std::cout << clipp::make_man_page(cli, argv[0], fmt) << '\n'; + return false; + } + if (opts.show_help) { + auto fmt = clipp::doc_formatting{}.doc_column(31); + std::cout << clipp::make_man_page(cli, argv[0], fmt) << '\n'; + return false; + } + if (opts.nx <= 0 || opts.ny <= 0 || opts.nz < 2) { + std::cerr << "cg_poisson_unified: nx, ny must be > 0 and nz must be >= 2\n"; + return false; + } + if (opts.max_iter == 0U) { + opts.max_iter = static_cast(opts.nz) * 4U; + } + if (opts.report_every <= 0) { + opts.report_every = 1; + } + if (opts.warmup > opts.max_iter) { + opts.warmup = opts.max_iter; + } + return true; +} + +[[nodiscard]] auto +parse_overlap_mode(std::string_view s) -> std::optional { + if (s == "none" || s.empty()) { + return carbon::OverlapMode::None; + } + if (s == "standard") { + return carbon::OverlapMode::Standard; + } + if (s == "extended") { + return carbon::OverlapMode::Extended; + } + if (s == "two-way-extended" || s == "two_way_extended" || s == "twoway") { + return carbon::OverlapMode::TwoWayExtended; + } + return std::nullopt; +} + +[[nodiscard]] auto +parse_decomposition_mode(std::string_view s) -> std::optional { + if (s == "slab" || s.empty()) { + return carbon::DecompositionMode::Slab; + } + if (s == "pencil") { + return carbon::DecompositionMode::Pencil; + } + if (s == "brick") { + return carbon::DecompositionMode::Brick; + } + return std::nullopt; +} + +[[nodiscard]] auto +overlap_mode_name(carbon::OverlapMode m) -> const char* { + switch (m) { + case carbon::OverlapMode::None: + return "none"; + case carbon::OverlapMode::Standard: + return "standard"; + case carbon::OverlapMode::Extended: + return "extended"; + case carbon::OverlapMode::TwoWayExtended: + return "two-way-extended"; + } + return "?"; +} + +[[nodiscard]] auto +decomposition_mode_name(carbon::DecompositionMode m) -> const char* { + switch (m) { + case carbon::DecompositionMode::Slab: + return "slab"; + case carbon::DecompositionMode::Pencil: + return "pencil"; + case carbon::DecompositionMode::Brick: + return "brick"; + } + return "?"; +} + +// Sphere predicate for Block, mirroring jacobi_unified.cu. Retained cells form +// an inscribed sphere of radius 0.42 * max(nx, ny, nz). The CG solver then +// sees Dirichlet on the lower / upper polar caps and Neumann on the +// equatorial belt. +[[nodiscard]] auto +sphere_predicate(int64_t nmax, + const carbon::int64_3d& gc) -> bool { + const double cx = (static_cast(nmax) - 1.0) * 0.5; + const double cy = (static_cast(nmax) - 1.0) * 0.5; + const double cz = (static_cast(nmax) - 1.0) * 0.5; + const double r = static_cast(nmax) * 0.42; + const double dx = static_cast(gc.x) - cx; + const double dy = static_cast(gc.y) - cy; + const double dz = static_cast(gc.z) - cz; + return (dx * dx + dy * dy + dz * dz) <= (r * r); +} + + +// ---- Kernel builders (grid-agnostic via Kernel::compute / Kernel::reduce) ---- + +// Initialise @c u with the BC values: +// south face (!zm.valid) -> bd_min +// north face (!zp.valid) -> bd_max +// everything else -> 0 +// Topology probes through @c loader.write(u) -> @c partition.neighbour are +// safe even before any write: @c .valid is determined by Span+offset only, not +// by the buffer's contents. +template +[[nodiscard]] auto +build_init_u(const Grid& grid, + typename Grid::template Field& u, + double bd_min, + double bd_max, + std::string name) -> carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return carbon::Kernel::compute( + grid, + [&u, bd_min, bd_max](carbon::KernelLoader& loader) { + auto u_p = loader.write(u); + return [u_p, bd_min, bd_max] CARBON_HOST_DEVICE(Span s, Idx idx) -> void { + const auto zm = u_p.neighbour(s, idx, carbon::int8_3d{0, 0, -1}, 0); + if (!zm.valid) { + u_p.write(s, idx, 0, bd_min); + return; + } + const auto zp = u_p.neighbour(s, idx, carbon::int8_3d{0, 0, 1}, 0); + if (!zp.valid) { + u_p.write(s, idx, 0, bd_max); + return; + } + u_p.write(s, idx, 0, 0.0); + }; + }, + std::move(name)); +} + +// Set @p field to @p value on every owned (and active, for Block) cell. +template +[[nodiscard]] auto +build_set_const(const Grid& grid, + typename Grid::template Field& field, + T value, + std::string name) -> carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return carbon::Kernel::compute( + grid, + [&field, value](carbon::KernelLoader& loader) { + auto out = loader.write(field); + return [out, value] CARBON_HOST_DEVICE(Span s, Idx idx) -> void { + out.write(s, idx, 0, value); + }; + }, + std::move(name)); +} + +// Discrete Laplacian: out = A * in. Halo on @c in auto-inserted by Skeleton +// via @c read_stencil. Topological BC handling (south / north face = identity +// row) lets the same kernel work on Dense, DenseDistributed, DenseDisg, and Block without an +// explicit boundary-mask field. +template +[[nodiscard]] auto +build_matvec(const Grid& grid, + typename Grid::template Field& in, + typename Grid::template Field& out, + double invh2, + std::string name) -> carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return carbon::Kernel::compute( + grid, + [&in, &out, invh2](carbon::KernelLoader& loader) { + const auto in_p = loader.read_stencil(in); + auto out_p = loader.write(out); + return [in_p, out_p, invh2] CARBON_HOST_DEVICE(Span s, Idx idx) -> void { + const double center = in_p.read(s, idx, 0); + const auto zm = in_p.neighbour(s, idx, carbon::int8_3d{0, 0, -1}, 0); + const auto zp = in_p.neighbour(s, idx, carbon::int8_3d{0, 0, 1}, 0); + if (!zm.valid || !zp.valid) { + out_p.write(s, idx, 0, center); + return; + } + const auto xp = in_p.neighbour(s, idx, carbon::int8_3d{1, 0, 0}, 0); + const auto xm = in_p.neighbour(s, idx, carbon::int8_3d{-1, 0, 0}, 0); + const auto yp = in_p.neighbour(s, idx, carbon::int8_3d{0, 1, 0}, 0); + const auto ym = in_p.neighbour(s, idx, carbon::int8_3d{0, -1, 0}, 0); + double sum = 0.0; + int n_valid = 0; + if (xp.valid) { + sum += xp.value; + ++n_valid; + } + if (xm.valid) { + sum += xm.value; + ++n_valid; + } + if (yp.valid) { + sum += yp.value; + ++n_valid; + } + if (ym.valid) { + sum += ym.value; + ++n_valid; + } + sum += zp.value; + ++n_valid; + sum += zm.value; + ++n_valid; + out_p.write(s, idx, 0, (static_cast(n_valid) * center - sum) * invh2); + }; + }, + std::move(name)); +} + +// r := (Dirichlet) ? u : b — Dirichlet detected topologically. +template +[[nodiscard]] auto +build_init_r(const Grid& grid, + typename Grid::template Field& r, + typename Grid::template Field& u, + typename Grid::template Field& b, + std::string name) -> carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return carbon::Kernel::compute( + grid, + [&r, &u, &b](carbon::KernelLoader& loader) { + auto r_p = loader.write(r); + const auto u_p = loader.read(u); + const auto b_p = loader.read(b); + return [r_p, u_p, b_p] CARBON_HOST_DEVICE(Span s, Idx idx) -> void { + const auto zm = u_p.neighbour(s, idx, carbon::int8_3d{0, 0, -1}, 0); + const auto zp = u_p.neighbour(s, idx, carbon::int8_3d{0, 0, 1}, 0); + const bool is_dirichlet = (!zm.valid || !zp.valid); + const double v = is_dirichlet ? u_p.read(s, idx, 0) : b_p.read(s, idx, 0); + r_p.write(s, idx, 0, v); + }; + }, + std::move(name)); +} + +// r := r - s. +template +[[nodiscard]] auto +build_axpy_minus(const Grid& grid, + typename Grid::template Field& r, + typename Grid::template Field& s_field, + std::string name) -> carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return carbon::Kernel::compute( + grid, + [&r, &s_field](carbon::KernelLoader& loader) { + auto r_p = loader.read_write(r); + const auto s_p = loader.read(s_field); + return [r_p, s_p] CARBON_HOST_DEVICE(Span s, Idx idx) -> void { + r_p.write(s, idx, 0, r_p.read(s, idx, 0) - s_p.read(s, idx, 0)); + }; + }, + std::move(name)); +} + +// p := r (one-shot, right before the iteration loop). +template +[[nodiscard]] auto +build_copy_p_from_r(const Grid& grid, + typename Grid::template Field& p, + typename Grid::template Field& r, + std::string name) -> carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return carbon::Kernel::compute( + grid, + [&p, &r](carbon::KernelLoader& loader) { + auto p_p = loader.write(p); + const auto r_p = loader.read(r); + return [p_p, r_p] CARBON_HOST_DEVICE(Span s, Idx idx) -> void { + p_p.write(s, idx, 0, r_p.read(s, idx, 0)); + }; + }, + std::move(name)); +} + +// p := r + beta * p ; @c beta_host captured @b by reference so the device +// closure picks up the latest host value at every launch. +template +[[nodiscard]] auto +build_update_p(const Grid& grid, + typename Grid::template Field& p, + typename Grid::template Field& r, + double& beta_host, + std::string name) -> carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return carbon::Kernel::compute( + grid, + [&p, &r, &beta_host](carbon::KernelLoader& loader) { + auto p_p = loader.read_write(p); + const auto r_p = loader.read(r); + const double beta = beta_host; + return [p_p, r_p, beta] CARBON_HOST_DEVICE(Span s, Idx idx) -> void { + p_p.write(s, idx, 0, r_p.read(s, idx, 0) + beta * p_p.read(s, idx, 0)); + }; + }, + std::move(name)); +} + +// x := x + alpha * p ; r := r - alpha * s ; same alpha-by-reference trick. +template +[[nodiscard]] auto +build_update_x_r(const Grid& grid, + typename Grid::template Field& u, + typename Grid::template Field& r, + typename Grid::template Field& p, + typename Grid::template Field& s_field, + double& alpha_host, + std::string name) -> carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return carbon::Kernel::compute( + grid, + [&u, &r, &p, &s_field, &alpha_host](carbon::KernelLoader& loader) { + auto x_p = loader.read_write(u); + auto r_p = loader.read_write(r); + const auto p_p = loader.read(p); + const auto s_p = loader.read(s_field); + const double alpha = alpha_host; + return [x_p, r_p, p_p, s_p, alpha] CARBON_HOST_DEVICE(Span s, Idx idx) -> void { + x_p.write(s, idx, 0, x_p.read(s, idx, 0) + alpha * p_p.read(s, idx, 0)); + r_p.write(s, idx, 0, r_p.read(s, idx, 0) - alpha * s_p.read(s, idx, 0)); + }; + }, + std::move(name)); +} + +// +template +[[nodiscard]] auto +build_reduce_rTr(const Grid& grid, + typename Grid::template Field& r, + carbon::ReductionResult& dst, + std::string name) -> carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return carbon::Kernel::reduce( + grid, + [&r](carbon::KernelLoader& loader) { + const auto r_p = loader.read(r); + return [r_p] CARBON_HOST_DEVICE(Span s, Idx idx) -> double { + const double v = r_p.read(s, idx, 0); + return v * v; + }; + }, + dst, carbon::reduce::Sum{}, std::move(name), /*shared_mem=*/0U); +} + +// +template +[[nodiscard]] auto +build_reduce_pAp(const Grid& grid, + typename Grid::template Field& p, + typename Grid::template Field& s_field, + carbon::ReductionResult& dst, + std::string name) -> carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return carbon::Kernel::reduce( + grid, + [&p, &s_field](carbon::KernelLoader& loader) { + const auto p_p = loader.read(p); + const auto s_p = loader.read(s_field); + return [p_p, s_p] CARBON_HOST_DEVICE(Span s, Idx idx) -> double { + return p_p.read(s, idx, 0) * s_p.read(s, idx, 0); + }; + }, + dst, carbon::reduce::Sum{}, std::move(name), /*shared_mem=*/0U); +} + +// ---- Solver ---- + +template +auto +run_cg(Grid& grid, + carbon::System& sys, + const Options& opts, + std::string_view grid_tag, + int world_rank) -> int { + using Field = typename Grid::template Field; + + Field u = grid.template newField(carbon::MemorySide::Device, "u"); + Field b = grid.template newField(carbon::MemorySide::Device, "b"); + Field p = grid.template newField(carbon::MemorySide::Device, "p"); + Field r = grid.template newField(carbon::MemorySide::Device, "r"); + Field s_field = grid.template newField(carbon::MemorySide::Device, "s"); + + // h = 1, so invh2 = 1. Matches the upstream Neon LaplacianMatVec scaling. + constexpr double invh2 = 1.0; + + double alpha_host = 0.0; + double beta_host = 0.0; + + carbon::ReductionResult delta_new(sys); + carbon::ReductionResult pAp(sys); + + carbon::Stream stream = sys.stream(); + + // Initialisation skeleton: + // zero b/p/r/s ; init u with topological BCs ; r := (Dir) ? u : b ; + // matvec(u -> s) ; r -= s ; reduce ; p := r . + // The matvec inserts an auto-halo on u because @c init_u writes u and + // @c matvec read_stencil-s it. Single-GPU runs collapse the halo to a no-op. + carbon::Skeleton init(sys); + init.add(build_set_const(grid, b, 0.0, "set_b=0")); + init.add(build_set_const(grid, p, 0.0, "set_p=0")); + init.add(build_set_const(grid, r, 0.0, "set_r=0")); + init.add(build_set_const(grid, s_field, 0.0, "set_s=0")); + init.add(build_init_u(grid, u, opts.bd_min, opts.bd_max, "init_u")); + init.add(build_init_r(grid, r, u, b, "init_r")); + init.add(build_matvec(grid, u, s_field, invh2, "s:=Ax")); + init.add(build_axpy_minus(grid, r, s_field, "r-=s")); + init.add(build_reduce_rTr(grid, r, delta_new, "delta:=")); + init.add(build_copy_p_from_r(grid, p, r, "p:=r")); + init.compile(); + + // iter_pre : update_p (uses beta_host) ; matvec(p -> s) ; reduce . + // iter_post : update_x_r (uses alpha_host) ; reduce . + const auto overlap_opt = parse_overlap_mode(opts.overlap_raw); + if (!overlap_opt) { + CARBON_LOG_ERROR( + "cg_poisson_unified: unknown --overlap '{}' (expected " + "none|standard|extended|two-way-extended)", + opts.overlap_raw); + return EXIT_FAILURE; + } + const carbon::OverlapMode overlap_mode = *overlap_opt; + + carbon::Skeleton iter_pre(sys, carbon::Skeleton::Options{overlap_mode}); + iter_pre.add(build_update_p(grid, p, r, beta_host, "p:=r+beta*p")); + iter_pre.add(build_matvec(grid, p, s_field, invh2, "s:=Ap")); + iter_pre.add(build_reduce_pAp(grid, p, s_field, pAp, "pAp:=")); + iter_pre.compile(); + + carbon::Skeleton iter_post(sys, carbon::Skeleton::Options{overlap_mode}); + iter_post.add(build_update_x_r(grid, u, r, p, s_field, alpha_host, "x+=ap;r-=as")); + iter_post.add(build_reduce_rTr(grid, r, delta_new, "delta:=")); + iter_post.compile(); + + if (world_rank == 0) { + CARBON_LOG_INFO( + "cg_poisson_unified[{}]: init.kernels={}/{} iter_pre.kernels={}/{} iter_post.kernels={}/{} " + "overlap={}", + grid_tag, init.size(), init.effective_kernels().size(), iter_pre.size(), + iter_pre.effective_kernels().size(), iter_post.size(), iter_post.effective_kernels().size(), + overlap_mode_name(overlap_mode)); + if (opts.dump_dot) { + CARBON_LOG_INFO("cg_poisson_unified[{}]: --- init DAG ---\n{}", grid_tag, + init.export_dot("cg_init")); + CARBON_LOG_INFO("cg_poisson_unified[{}]: --- iter_pre DAG ---\n{}", grid_tag, + iter_pre.export_dot("cg_iter_pre")); + CARBON_LOG_INFO("cg_poisson_unified[{}]: --- iter_post DAG ---\n{}", grid_tag, + iter_post.export_dot("cg_iter_post")); + } + if (!opts.dot_out_prefix.empty()) { + const auto export_one = [&](carbon::Skeleton& sk, const char* tag) { + const std::string base = opts.dot_out_prefix + "_" + tag; + if (!sk.export_dot_file(base + ".dot", std::string{"cg_"} + tag)) { + CARBON_LOG_ERROR("cg_poisson_unified: failed to write {}.dot", base); + } + if (!sk.export_launch_order_file(base + ".txt")) { + CARBON_LOG_ERROR("cg_poisson_unified: failed to write {}.txt", base); + } + if (opts.dot_matrix) { + if (!sk.export_launch_matrix_dot_file(base + "_matrix.dot", std::string{"cg_"} + tag)) { + CARBON_LOG_ERROR("cg_poisson_unified: failed to write {}_matrix.dot", base); + } + if (!sk.export_kernel_list_dot_file(base + "_kernels.dot", std::string{"cg_"} + tag)) { + CARBON_LOG_ERROR("cg_poisson_unified: failed to write {}_kernels.dot", base); + } + } + }; + export_one(init, "init"); + export_one(iter_pre, "iter_pre"); + export_one(iter_post, "iter_post"); + CARBON_LOG_INFO("cg_poisson_unified[{}]: wrote Skeleton exports under prefix '{}'", grid_tag, + opts.dot_out_prefix); + } + } + + init.run(); + init.wait(); + delta_new.sync(stream); + stream.wait(); + + const double delta_init = delta_new.host_value(); + const double r0_norm = std::sqrt(std::max(0.0, delta_init)); + const double abs_target = std::max(opts.tol_abs, opts.tol_rel * r0_norm); + if (world_rank == 0) { + CARBON_LOG_INFO("cg_poisson_unified[{}]: ||r_0|| = {:.6e}, target ||r|| = {:.6e}", grid_tag, + r0_norm, abs_target); + } + + double delta_new_h = delta_init; + double delta_old_h = 0.0; + size_t iter = 0; + bool converged = (r0_norm <= abs_target); + std::vector iteration_ms; + + for (; iter < opts.max_iter && !converged; ++iter) { + + nvtxRangePushA("cg_iter"); + const auto iter_t0 = std::chrono::steady_clock::now(); + + beta_host = (delta_old_h > 0.0) ? (delta_new_h / delta_old_h) : 0.0; + + iter_pre.run(); + iter_pre.wait(); + pAp.sync(stream); + stream.wait(); + const double pAp_h = pAp.host_value(); + if (!(pAp_h > 0.0)) { + if (world_rank == 0) { + CARBON_LOG_ERROR( + "cg_poisson_unified[{}]: numerical issue at iter {}: ={:.6e} (not > 0)", grid_tag, + iter, pAp_h); + } + return EXIT_FAILURE; + } + alpha_host = delta_new_h / pAp_h; + + iter_post.run(); + iter_post.wait(); + delta_new.sync(stream); + stream.wait(); + + delta_old_h = delta_new_h; + delta_new_h = delta_new.host_value(); + const auto iter_t1 = std::chrono::steady_clock::now(); + if (iter >= opts.warmup) { + iteration_ms.push_back(std::chrono::duration(iter_t1 - iter_t0).count()); + } + const double r_norm = std::sqrt(std::max(0.0, delta_new_h)); + + if (world_rank == 0 && + ((iter + 1) % static_cast(opts.report_every) == 0U || r_norm <= abs_target)) { + CARBON_LOG_INFO( + "cg_poisson_unified[{}]: iter {:5d} ||r||={:.6e} alpha={:+.3e} beta={:+.3e}", grid_tag, + iter + 1, r_norm, alpha_host, beta_host); + } + if (r_norm <= abs_target) { + converged = true; + } + nvtxRangePop(); + } + const double final_r_norm = std::sqrt(std::max(0.0, delta_new_h)); + if (world_rank == 0) { + if (converged) { + CARBON_LOG_INFO("cg_poisson_unified[{}]: CONVERGED at iter {} ||r||={:.6e}", grid_tag, iter, + final_r_norm); + } else { + CARBON_LOG_INFO( + "cg_poisson_unified[{}]: STOPPED at iter {} ||r||={:.6e} (tolerance not met)", grid_tag, + iter, final_r_norm); + } + + if (iteration_ms.empty()) { + CARBON_LOG_INFO( + "cg_poisson_unified[{}]: no timed iterations (warmup={}, max_iter={})", grid_tag, + opts.warmup, opts.max_iter); + } else { + const SampleStats stats = compute_sample_stats(iteration_ms); + CARBON_LOG_INFO( + "cg_poisson_unified[{}]: iteration ms: n={} warmup={} min={:.3f} max={:.3f} " + "mean={:.3f} std={:.3f} median={:.3f}", + grid_tag, stats.n, opts.warmup, stats.min, stats.max, stats.mean, stats.stddev, + stats.median); + } + } + + if (iter == opts.max_iter && world_rank == 0) { + CARBON_LOG_INFO("cg_poisson_unified[{}]: halted at max_iter={}, convergence status: {}", + grid_tag, opts.max_iter, is_true(converged)); + return EXIT_SUCCESS; + } + + return (final_r_norm <= abs_target) ? EXIT_SUCCESS : EXIT_FAILURE; + +} + +} // namespace + +auto +main(int argc, char** argv) -> int { + carbon::init(); + + Options opts; + if (!parse_cli(argc, argv, opts)) { + return opts.show_help ? EXIT_SUCCESS : EXIT_FAILURE; + } + +#ifdef CARBON_HAVE_MPI_NCCL + // Decomposition only matters for distributed (MPI + NCCL/RCCL/oneCCL) runs. + // Without CARBON_HAVE_MPI_NCCL every run is single-rank, so --decomposition + // is accepted but ignored and no validation is performed. + const auto dec_opt = parse_decomposition_mode(opts.dec); + if (!dec_opt) { + CARBON_LOG_ERROR( + "cg_poisson_unified: unknown --decomposition '{}' (expected slab|pencil|brick)", + opts.dec); + return EXIT_FAILURE; + } + const carbon::DecompositionMode dec_mode = *dec_opt; +#else + const carbon::DecompositionMode dec_mode = carbon::DecompositionMode::Slab; +#endif + +#ifdef CARBON_HAVE_MPI_NCCL + auto distributed = std::make_shared(); + const int world_size = distributed->world_size(); + const int world_rank = distributed->world_rank(); + carbon::System sys = + (world_size > 1) ? carbon::System(distributed) : carbon::System(carbon::get_all_devices()); + const bool is_distributed = (world_size > 1); +#else + carbon::System sys(carbon::get_all_devices()); + const int world_size = 1; + const int world_rank = 0; + const bool is_distributed = false; +#endif + + if (sys.gpu_group().size() == 0U) { + CARBON_LOG_ERROR("cg_poisson_unified: no devices visible"); + return EXIT_FAILURE; + } + + if (world_rank == 0) { + CARBON_LOG_INFO( + "cg_poisson_unified: grid={} nx={} ny={} nz={} max_iter={} tol_rel={:.1e} tol_abs={:.1e} " + "bd_min={:+.3f} bd_max={:+.3f} backend={} gpus_local={} world_size={} distributed={} " + "decomposition={}", + opts.grid_kind, opts.nx, opts.ny, opts.nz, opts.max_iter, opts.tol_rel, opts.tol_abs, + opts.bd_min, opts.bd_max, +#if CARBON_BACKEND_IS_SYCL + "SYCL", +#else + "CUDA", +#endif + sys.gpu_group().size(), world_size, is_distributed, + is_distributed ? decomposition_mode_name(dec_mode) : "n/a"); + } + + const carbon::int64_3d global{opts.nx, opts.ny, opts.nz}; + + // Build the process grid for distributed DenseDistributed runs from --decomposition. + // ProcessGrid::make performs a balanced prime-factorization of world_size + // across the free axes of the mode (1 for slab, 2 for pencil, 3 for brick). + // Single-GPU / single-rank runs keep the grid-less constructors and the + // auto-inserted halo collapses to a no-op. The original Dense is Z-slab only + // and splits z across ranks by itself, so it never takes a process grid. + std::optional pg; + if (is_distributed && opts.grid_kind == "dense_distributed") { + pg.emplace(carbon::ProcessGrid::make(world_size, dec_mode)); + const carbon::int32_3d dims = pg->dims(); + if (world_rank == 0) { + CARBON_LOG_INFO("cg_poisson_unified: process_grid={}x{}x{} (world_size={})", dims.x, dims.y, + dims.z, world_size); + } + } + + // 6-point face stencil -> halo_z = 1 . + 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); + + try { + if (opts.grid_kind == "dense") { + if (is_distributed && dec_mode != carbon::DecompositionMode::Slab) { + CARBON_LOG_ERROR( + "cg_poisson_unified: --grid dense only supports --decomposition slab; use " + "--grid dense_distributed for pencil/brick"); + return EXIT_FAILURE; + } + carbon::Dense dense(sys, global, stencil); + return run_cg(dense, sys, opts, "dense", world_rank); + } + if (opts.grid_kind == "dense_distributed") { + std::optional dense_distributed; + if (pg) { + dense_distributed.emplace(sys, global, *pg, stencil); + } else { + dense_distributed.emplace(sys, global, stencil); + } + return run_cg(*dense_distributed, sys, opts, "dense_distributed", world_rank); + } + if (opts.grid_kind == "disg") { + std::optional disg; + // if (pg) { + // disg.emplace(sys, global, /*halo_z=*/1, *pg); + // } else { + // disg.emplace(sys, global, /*halo_z=*/1); + // } + disg.emplace(sys, global, /*halo_z=*/1); + + return run_cg(*disg, sys, opts, "disg", world_rank); + } + if (opts.grid_kind == "block") { + const int64_t nmax = std::max({opts.nx, opts.ny, opts.nz}); + const auto predicate = [nmax](const carbon::int64_3d& gc) -> bool { + return sphere_predicate(nmax, gc); + }; + using BlockGrid = carbon::Block; + std::optional block; + // if (pg) { + // block.emplace(sys, global, predicate, "cg_poisson_unified_block", *pg); + // } else { + // block.emplace(sys, global, predicate, "cg_poisson_unified_block"); + // } + block.emplace(sys, global, predicate, "cg_poisson_unified_block"); + + return run_cg(*block, sys, opts, "block", world_rank); + } + CARBON_LOG_ERROR( + "cg_poisson_unified: unknown --grid '{}' (expected dense|dense_distributed|disg|block)", + opts.grid_kind); + return EXIT_FAILURE; + } catch (const std::exception& e) { + CARBON_LOG_ERROR("cg_poisson_unified: failed: {}", e.what()); + return EXIT_FAILURE; + } +} From 96182e8c9b0e47e4e772eb6c50807d89a53f8aaa Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:52:38 +0100 Subject: [PATCH 05/33] Add initial porting ldc benchmark to distributed --- benchmarks/CMakeLists.txt | 1 + .../CMakeLists.txt | 33 + .../lbm_lid_driven_cavity_distributed.cu | 1017 +++++++++++++++++ .../src/cell_type.h | 60 + .../src/d3q19.h | 126 ++ .../src/d3q27.h | 206 ++++ .../src/lbm_kernels.h | 637 +++++++++++ 7 files changed, 2080 insertions(+) create mode 100644 benchmarks/lbm_lid_driven_cavity_distributed/CMakeLists.txt create mode 100644 benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu create mode 100644 benchmarks/lbm_lid_driven_cavity_distributed/src/cell_type.h create mode 100644 benchmarks/lbm_lid_driven_cavity_distributed/src/d3q19.h create mode 100644 benchmarks/lbm_lid_driven_cavity_distributed/src/d3q27.h create mode 100644 benchmarks/lbm_lid_driven_cavity_distributed/src/lbm_kernels.h diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index 02b016ad..8d3616d3 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -48,6 +48,7 @@ endfunction() add_subdirectory(common) add_subdirectory(lbm_lid_driven_cavity) +add_subdirectory(lbm_lid_driven_cavity_distributed) add_subdirectory(halo_scalability) add_subdirectory(reduce_throughput) add_subdirectory(skeleton_overlap) diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/CMakeLists.txt b/benchmarks/lbm_lid_driven_cavity_distributed/CMakeLists.txt new file mode 100644 index 00000000..c5e88756 --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/CMakeLists.txt @@ -0,0 +1,33 @@ +# LBM lid-driven cavity benchmark with optional DenseDistributed decomposition. +# +# Carbon port of Neon/benchmarks/lbm-lid-driven-cavity-flow. D3Q19 BGK, two-pop +# pull streaming, half-way bounce-back walls, moving lid on +y face. The +# iteration loop is wrapped in carbon::Skeleton so the halo exchange between +# successive collide-stream sweeps is auto-inserted (loader.read_stencil on the +# input population) — same pattern as examples/jacobi_unified.cu, scaled up +# from a 1-component scalar field to a 19-component population field. +# +# Headers live under src/ and are #included directly from the .cu / .cpp twin +# so a single TU drives the build. CLI parsing uses the bundled clipp header +# from third_party/ (same single-header parser examples/cg_poisson uses). + +_carbon_benchmark_add(carbon_benchmark_lbm_lid_driven_cavity_distributed + lbm_lid_driven_cavity_distributed.cu) +target_link_libraries(carbon_benchmark_lbm_lid_driven_cavity_distributed + PRIVATE carbon::carbon carbon::third_party::clipp) +# Two include roots so the same `#include "src/cell_type.h"` headers in +# the .cu/.cpp twin resolve under both backends: +# - CARBON_BACKEND=Cuda compiles the .cu in-place, so `src/...` already +# resolves relative to the source dir; the explicit entry is redundant +# but harmless. +# - CARBON_BACKEND=Sycl configure_file's the .cu to a .cpp twin inside +# the build tree; relative-to-file lookup of `src/...` would land in +# `/benchmarks/lbm_lid_driven_cavity_distributed/src/`, which +# doesn't exist. Adding the *parent* source dir to the include path makes +# `#include "src/cell_type.h"` resolve back to the real headers under +# both backends without rewriting every include in lbm_kernels.h / +# lbm_lid_driven_cavity_distributed.cu. +target_include_directories(carbon_benchmark_lbm_lid_driven_cavity_distributed + PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}" + "${CMAKE_CURRENT_SOURCE_DIR}/src") diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu b/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu new file mode 100644 index 00000000..dc33f72f --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu @@ -0,0 +1,1017 @@ +// Carbon LBM lid-driven cavity benchmark — port of +// Neon/benchmarks/lbm-lid-driven-cavity-flow on top of carbon::Skeleton. +// +// Models a unit-cube cavity with bounce-back walls on the -x/+x, -y/+y, -z +// faces and a moving lid (u = (ulb, 0, 0)) on the +y face. Each iteration +// is wrapped in a 1-kernel carbon::Skeleton (the halo on the input +// population is auto-inserted by Skeleton::compile because the iteration +// kernel calls loader.read_stencil(fIn)). Two skeletons (one per +// ping-pong direction) are precompiled before the timing loop so the hot +// loop is a tight `sk.run(); sk.wait();` pair with no allocation / +// no recompilation. +// +// Lattice + collision are runtime-selectable via CLI: +// --lattice {q19,q27} : D3Q19 (default) or D3Q27. +// --collision {bgk,kbc} : BGK SRT (default) or KBC entropic stabilisation +// (Karlin-Bösch-Chikatamarla, 2014). KBC requires +// D3Q27 — the moment matrix and shear-decomposition +// table needed by the entropic step are only +// defined for the full 27-velocity lattice. +// +// Headline metric is MLUPS — Million Lattice Updates Per Second — computed +// over the post-warmup iterations only: +// +// MLUPS = (N^3 * iters_timed) / (1e6 * elapsed_seconds) +// +// CLI (clipp; same one-shot man page as examples/cg_poisson_unified.cu). + +#include "src/cell_type.h" +#include "src/d3q19.h" +#include "src/d3q27.h" +#include "src/lbm_kernels.h" + +#include +#include +#include +#include +#include +// CARBON_BACKEND_NAME is "cuda" or "sycl" depending on which backend the +// library was configured with. Stamped into the JSON report's system block +// so a sweep that drives both backends from the same scripts/ directory +// can colour-code them without resorting to filename heuristics. +#include +#ifdef CARBON_HAVE_MPI_NCCL +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using carbon::bench::lbm::BgkCollision; +using carbon::bench::lbm::Classification; +using carbon::bench::lbm::D3Q19; +using carbon::bench::lbm::D3Q27; +using carbon::bench::lbm::encode_cell; +using carbon::bench::lbm::KbcCollision; +using carbon::bench::lbm::LbmParameters; +using carbon::bench::lbm::make_compute_wall_mask_kernel; +using carbon::bench::lbm::make_iteration_kernel; +using carbon::bench::lbm::make_iteration_kernel_d3q19_bgk_fast; +using carbon::bench::lbm::make_macroscopic_kernel; + +struct Options { + int64_t n = 128; + int64_t iters = 1000; + int64_t warmup = 100; + double re = 100.0; + double ulb = 0.05; + bool ulb_set = false; + int64_t report_every = 100; + bool no_warmup_skip = false; + std::string lattice = "q19"; + std::string collision = "bgk"; + // Grid family the benchmark runs on. "dense" is carbon::Dense (aggregated + // Cartesian z-slabs); "disg" is carbon::DenseDisg (the disaggregated, + // five-region-per-slab lattice-Boltzmann layout); "dense_distributed" is + // carbon::DenseDistributed, which honours --decomposition and exchanges + // halos along all decomposed axes. All three run the identical hot kernel + // (the pull-stream + half-way bounce-back + symmetric BGK body) — the only + // differences are the per-slab storage layout and the auto-inserted halo + // family (Halo / HaloDisg / HaloDistributed). + std::string grid = "dense"; + std::string decomposition = "slab"; + std::string report_path = ""; + std::string label = ""; + std::string vtk_path = ""; + // Skeleton OCC mode applied to both ping-pong skeletons. "none" (default, + // single-stream Standard launch) keeps the existing baseline behaviour; + // "standard" enables the carbon::Skeleton OCC rewrite that splits the + // stencil node into Internal + Boundary halves and overlaps the halo with + // the Internal launch on a second stream — the default-OFF state of + // OverlapMode is the dominant reason multi-GPU regresses below 1-GPU on + // PCIe-only hosts (the halo serialises behind every iteration). + // "extended" / "twoway-extended" are the more aggressive OCC modes; in + // the LBM iteration there is only one stencil node so they degenerate to + // "standard" but are exposed here for symmetry with carbon::OverlapMode. + std::string overlap = "none"; + std::string export_dot_path = ""; + std::string export_dot_png_path = ""; + // Opt in to carbon::Skeleton CUDA-graph capture + replay of each ping-pong + // skeleton. Engaged only for single-GPU / single-stream schedules (the + // OverlapMode::None single-GPU case); a no-op fallback otherwise. + bool cuda_graph = false; + // After the timed loop, Sum-reduce the whole final population field and print + // CHECKSUM=. Because sum_q pop_q == rho per cell, this is the total + // mass in the domain — a single scalar that is invariant across grid families + // when the streaming/collision is numerically identical. Used to verify that + // --grid dense and --grid disg produce bit-comparable physics (they run the + // same hot kernel; only the storage layout + halo family differ). + bool checksum = false; + bool show_help = false; + /** Limit to first N visible CUDA devices (-1 = all visible). Same as jacobi_nvidia -gpus. */ + int n_gpus = -1; +}; + +[[nodiscard]] auto +build_cli(Options& opts) -> clipp::group { + using clipp::integer; + using clipp::number; + using clipp::option; + using clipp::value; + return clipp::group( + (option("-h", "--help").set(opts.show_help) % "Show this help message and exit"), + (option("--n") & integer("n", opts.n)) % "Cavity edge length in cells (default 128)", + (option("--iters") & integer("iters", opts.iters)) % + "Total iterations including warmup (default 1000)", + (option("--warmup") & integer("warmup", opts.warmup)) % + "Warmup iterations excluded from timing (default 100)", + (option("--re") & number("re", opts.re)) % "Reynolds number (default 1e2)", + (option("--ulb") & number("ulb", opts.ulb).set(opts.ulb_set)) % + "Override lid velocity in lattice units (default 0.05)", + (option("--lattice") & value("q19|q27", opts.lattice)) % + "Lattice stencil: q19 (D3Q19, default) or q27 (D3Q27)", + (option("--collision") & value("bgk|kbc", opts.collision)) % + "Collision model: bgk (default) or kbc (entropic; D3Q27 only)", + (option("--grid") & value("dense|disg|dense_distributed", opts.grid)) % + "Grid family: dense (carbon::Dense, default), disg (carbon::DenseDisg, " + "the disaggregated five-region LBM layout), or dense_distributed " + "(carbon::DenseDistributed, honours --decomposition). Same hot kernel on all.", + (option("--decomposition") & value("slab|pencil|brick", opts.decomposition)) % + "Process decomposition for --grid dense_distributed (default: slab). " + "slab splits z; pencil splits y and z; brick splits all three axes. " + "Auto-factorized across ranks; ignored for dense/disg, which are slab-only.", + (option("-gpus", "--gpus") & integer("n", opts.n_gpus)) % + "Use the first N visible CUDA devices (-1 = all visible; default -1). " + "Combine with CUDA_VISIBLE_DEVICES to pick physical GPUs.", + (option("--report-every") & integer("n", opts.report_every)) % + "Log progress every N iterations (default 100; 0 silences)", + (option("--report") & value("path", opts.report_path)) % + "Write a structured JSON report to PATH on success " + "(consumed by scripts/sweep_and_plot.py)", + (option("--label") & value("string", opts.label)) % + "Free-form label written into the JSON report under config.label " + "(useful for tagging sweeps)", + (option("--vtk-out") & value("path", opts.vtk_path)) % + "After the timed loop, run the macroscopic kernel and dump rho + u " + "as a VTK legacy STRUCTURED_POINTS file at PATH (carbon::io::write_vtk; " + "appends .rankN under MPI). Off by default — adds ~one kernel + a " + "GPU->host copy of size cells*16B.", + (option("--overlap") & value("none|standard|extended|twoway-extended", opts.overlap)) % + "Skeleton OCC mode (default 'none'). 'standard' splits the stencil " + "node into Internal + Boundary so the halo overlaps with Internal on " + "a second stream — improves multi-GPU significantly on PCIe-only " + "hosts where halo otherwise blocks compute.", + (option("--export-dot") & value("path", opts.export_dot_path)) % + "Write the compiled Skeleton schedule graph (GraphViz .dot) for the " + "AB ping-pong skeleton to PATH after compile.", + (option("--export-dot-png") & value("path", opts.export_dot_png_path)) % + "Render the schedule graph to PNG via GraphViz (requires dot on PATH). " + "Also writes a sibling .dot file.", + option("--cuda-graph").set(opts.cuda_graph) % + "Capture + replay each ping-pong skeleton as a CUDA graph (single-GPU / " + "single-stream only; transparently falls back to eager launch otherwise). " + "Collapses per-iteration host launch overhead.", + option("--checksum").set(opts.checksum) % + "After the loop, Sum-reduce the final population field and print " + "CHECKSUM=. Grid-family invariant — used to verify " + "dense, disg, and dense_distributed runs match numerically.", + option("--no-warmup-skip").set(opts.no_warmup_skip) % + "Include warmup iterations in the timing window (debug aid)"); +} + +[[nodiscard]] auto +parse_cli(int argc, + char** argv, + Options& opts) -> bool { + auto cli = build_cli(opts); + if (!clipp::parse(argc, argv, cli) || opts.show_help) { + auto fmt = clipp::doc_formatting{}.doc_column(31); + std::cout << clipp::make_man_page(cli, argv[0], fmt) << '\n'; + return opts.show_help; + } + if (opts.n < 4) { + std::cerr << "lbm_lid_driven_cavity: --n must be >= 4 (got " << opts.n << ")\n"; + return false; + } + if (opts.iters <= 0) { + std::cerr << "lbm_lid_driven_cavity: --iters must be > 0 (got " << opts.iters << ")\n"; + return false; + } + if (opts.warmup < 0 || opts.warmup >= opts.iters) { + std::cerr << "lbm_lid_driven_cavity: --warmup must be in [0, iters) (got " << opts.warmup + << " for iters=" << opts.iters << ")\n"; + return false; + } + if (opts.lattice != "q19" && opts.lattice != "q27") { + std::cerr << "lbm_lid_driven_cavity: --lattice must be q19 or q27 (got '" << opts.lattice + << "')\n"; + return false; + } + if (opts.collision != "bgk" && opts.collision != "kbc") { + std::cerr << "lbm_lid_driven_cavity: --collision must be bgk or kbc (got '" << opts.collision + << "')\n"; + return false; + } + if (opts.collision == "kbc" && opts.lattice != "q27") { + std::cerr << "lbm_lid_driven_cavity: --collision kbc requires --lattice q27 " + "(KBC's moment basis is defined for D3Q27 only)\n"; + return false; + } + if (opts.grid != "dense" && opts.grid != "disg" && opts.grid != "dense_distributed") { + std::cerr << "lbm_lid_driven_cavity: --grid must be dense, disg, or dense_distributed (got '" + << opts.grid << "')\n"; + return false; + } + if (opts.decomposition != "slab" && opts.decomposition != "pencil" && + opts.decomposition != "brick") { + std::cerr << "lbm_lid_driven_cavity: --decomposition must be slab, pencil, or brick (got '" + << opts.decomposition << "')\n"; + return false; + } + if (opts.grid != "dense_distributed" && opts.decomposition != "slab") { + std::cerr << "lbm_lid_driven_cavity: --decomposition " << opts.decomposition + << " requires --grid dense_distributed (dense/disg are slab-only)\n"; + return false; + } + if (opts.overlap != "none" && opts.overlap != "standard" && opts.overlap != "extended" && + opts.overlap != "twoway-extended") { + std::cerr << "lbm_lid_driven_cavity: --overlap must be one of " + "{none, standard, extended, twoway-extended} (got '" + << opts.overlap << "')\n"; + return false; + } + return true; +} + +[[nodiscard]] auto +overlap_mode_from_string(std::string_view s) -> carbon::OverlapMode { + if (s == "standard") { + return carbon::OverlapMode::Standard; + } + if (s == "extended") { + return carbon::OverlapMode::Extended; + } + if (s == "twoway-extended") { + return carbon::OverlapMode::TwoWayExtended; + } + return carbon::OverlapMode::None; +} + +[[nodiscard]] auto +parse_decomposition_mode(std::string_view s) -> std::optional { + if (s == "slab" || s.empty()) { + return carbon::DecompositionMode::Slab; + } + if (s == "pencil") { + return carbon::DecompositionMode::Pencil; + } + if (s == "brick") { + return carbon::DecompositionMode::Brick; + } + return std::nullopt; +} + +[[nodiscard]] auto +decomposition_mode_name(carbon::DecompositionMode m) -> const char* { + switch (m) { + case carbon::DecompositionMode::Slab: + return "slab"; + case carbon::DecompositionMode::Pencil: + return "pencil"; + case carbon::DecompositionMode::Brick: + return "brick"; + case carbon::DecompositionMode::Custom: + return "custom"; + } + return "?"; +} + +// Tiny RFC-3339 / ISO-8601 timestamp helper used in the JSON report. +[[nodiscard]] auto +utc_timestamp_now() -> std::string { + const std::time_t now = std::time(nullptr); + std::tm tm_utc{}; +#if defined(_WIN32) + gmtime_s(&tm_utc, &now); +#else + gmtime_r(&now, &tm_utc); +#endif + std::ostringstream oss; + oss << std::put_time(&tm_utc, "%Y-%m-%dT%H:%M:%SZ"); + return oss.str(); +} + +// Minimal JSON string escape (handles ", \, control chars). Hand-rolled +// because a full rapidjson dependency would be overkill for the ~12 fields +// we emit. Keep this function private to the TU. +[[nodiscard]] auto +json_escape(const std::string& s) -> std::string { + std::string out; + out.reserve(s.size() + 2); + for (char c : s) { + switch (c) { + case '"': + out += "\\\""; + break; + case '\\': + out += "\\\\"; + break; + case '\b': + out += "\\b"; + break; + case '\f': + out += "\\f"; + break; + case '\n': + out += "\\n"; + break; + case '\r': + out += "\\r"; + break; + case '\t': + out += "\\t"; + break; + default: + if (static_cast(c) < 0x20) { + char buf[8]; + std::snprintf(buf, sizeof(buf), "\\u%04x", static_cast(c)); + out += buf; + } else { + out += c; + } + } + } + return out; +} + +// Equilibrium population for component q at zero velocity and rho = 1: w_q. +// The lid layer also seeds populations with the bounce-back lid-momentum +// correction (-6 * w_q * ulb * (c_q . ulid)) so the very first iteration +// sees a reasonable approximation of the steady state instead of having to +// spin up from rest. Templated on Lattice so the same init logic feeds +// either D3Q19 or D3Q27. +template +[[nodiscard]] auto +init_population_value(const carbon::int64_3d& gc, + const carbon::int64_3d& global, + int q, + double ulb) -> float { + const float w = Lattice::w(q); + const bool on_boundary = (gc.x == 0 || gc.x == global.x - 1 || gc.y == 0 || + gc.y == global.y - 1 || gc.z == 0 || gc.z == global.z - 1); + if (!on_boundary) { + return w; + } + if (gc.y == global.y - 1) { + // Moving lid. Mirrors Neon's init: -6 * w_q * ulb * (c_q . ulid), + // where ulid = (1, 0, 0). c_q.x carries the sign. + const auto cq = Lattice::c(q); + const float dot = static_cast(cq.x) * 1.0F; + return static_cast(-6.0F * w * static_cast(ulb) * dot); + } + return 0.0F; +} + +[[nodiscard]] auto +init_cell_value(const carbon::int64_3d& gc, + const carbon::int64_3d& global) -> int32_t { + const bool on_boundary = (gc.x == 0 || gc.x == global.x - 1 || gc.y == 0 || + gc.y == global.y - 1 || gc.z == 0 || gc.z == global.z - 1); + if (!on_boundary) { + return encode_cell(Classification::Bulk); + } + if (gc.y == global.y - 1) { + return encode_cell(Classification::MovingWall); + } + return encode_cell(Classification::BounceBack); +} + +// Build the carbon::Stencil for a given lattice — radius-1 stencil +// covering every non-center direction. Used to seed Span::halo_z so multi- +// GPU runs allocate the right z-halo on each slab. Both D3Q19 and D3Q27 have +// |c_q|_inf == 1 so radius is 1 either way; what changes is the count +// (18 for D3Q19, 26 for D3Q27). +template +[[nodiscard]] auto +make_lbm_stencil() -> carbon::Stencil { + std::vector stencil_points; + stencil_points.reserve(Lattice::Q - 1); + for (int q = 0; q < Lattice::Q; ++q) { + if (q == Lattice::kCenter) { + continue; + } + const auto cq = Lattice::c(q); + stencil_points.push_back({cq.x, cq.y, cq.z}); + } + return carbon::Stencil(stencil_points, /*remove_center=*/true); +} + +// One-shot benchmark body, instantiated once per (lattice, collision) pair +// from main(). The dispatch is: parse opts, switch on the (lattice, +// collision) combo, instantiate this template, run it, return its exit +// code. This keeps all the instantiation cost on configurations the user +// actually exercises (the dispatch only calls one of the three +// instantiations for a given run). +[[nodiscard]] auto +make_single_process_system(int n_gpus_limit) -> carbon::System { + std::vector devices = carbon::get_all_devices(); + if (devices.empty()) { + carbon::log::throw_with_log( + "lbm_lid_driven_cavity: no CUDA devices visible"); + } + if (n_gpus_limit > 0 && static_cast(n_gpus_limit) < devices.size()) { + devices.erase(devices.begin() + static_cast(n_gpus_limit), devices.end()); + } + if (n_gpus_limit > 0 && static_cast(n_gpus_limit) > devices.size()) { + CARBON_LOG_WARN( + "lbm_lid_driven_cavity: --gpus {} requested but only {} CUDA device(s) visible " + "(check CUDA_VISIBLE_DEVICES)", + n_gpus_limit, devices.size()); + } + return carbon::System(std::move(devices)); +} + +template +[[nodiscard]] auto +run_benchmark(const Options& opts, + const std::string& lattice_name, + const std::string& collision_name, + carbon::DecompositionMode dec_mode) -> int { + static_assert(std::is_same_v || std::is_same_v || + std::is_same_v, + "LBM benchmark supports carbon::Dense, carbon::DenseDisg, and " + "carbon::DenseDistributed only."); +#ifdef CARBON_HAVE_MPI_NCCL + // Auto-detect MPI launches: the `Distributed` ctor invokes `MPI_Init` (a + // no-op when already initialised) and bootstraps an `ncclComm_t` over every + // visible rank. Under a single-process launch (no `mpiexec` wrapping) + // `world_size() == 1` and we fall through to the local-`get_all_devices()` + // path so the existing single-host behaviour is byte-for-byte preserved. + // Under `mpiexec -n R` the constructor binds rank `r` to its local GPU via + // `pin_local_device` and `System(distributed)` carries `gpu_group.size() == + // 1` (carbon's strict one-rank-per-GPU model). + auto distributed = std::make_shared(); + const bool use_mpi = distributed->world_size() > 1; + carbon::System sys = + use_mpi ? carbon::System(distributed) : make_single_process_system(opts.n_gpus); + const int world_rank = use_mpi ? distributed->world_rank() : 0; + const int world_size = use_mpi ? distributed->world_size() : 1; +#else + carbon::System sys = make_single_process_system(opts.n_gpus); + const bool use_mpi = false; + const int world_rank = 0; + const int world_size = 1; +#endif + const size_t n_gpus = sys.gpu_group().size(); + const int local_gpu_count = static_cast(n_gpus); + const int total_gpu_count = use_mpi ? world_size : local_gpu_count; + + const carbon::Stencil stencil = make_lbm_stencil(); + const carbon::int64_3d global{opts.n, opts.n, opts.n}; + + std::optional pg; + if constexpr (std::is_same_v) { + const int grid_world = use_mpi ? world_size : local_gpu_count; + pg.emplace(carbon::ProcessGrid::make(grid_world, dec_mode)); + if (world_rank == 0) { + const carbon::int32_3d dims = pg->dims(); + CARBON_LOG_INFO("lbm_lid_driven_cavity: process_grid={}x{}x{} (world_size={})", dims.x, + dims.y, dims.z, grid_world); + } + } + + // Construct the selected grid family. Dense/DenseDisg give a radius-1 z-halo + // (D3Q19 / D3Q27 have |c|_inf == 1); DenseDistributed derives per-axis halos + // from the same stencil and honours the requested decomposition. Only one + // branch is instantiated per Grid, so the IIFE's return type is the concrete + // grid type for this instantiation. + Grid grid = [&]() -> Grid { + if constexpr (std::is_same_v) { + return carbon::Dense(sys, global, stencil); + } else if constexpr (std::is_same_v) { + return carbon::DenseDisg(sys, global, /*halo_z=*/1); + } else { + return carbon::DenseDistributed(sys, global, *pg, stencil); + } + }(); + + const double ulb = opts.ulb; + // Re = u_lb * L / nu_lb => nu_lb = u_lb * L / Re. omega is the BGK + // (or KBC, beta = omega/2) relaxation timescale tied to nu via + // nu = (1/omega - 1/2) / 3. + const double nu_lb = ulb * static_cast(opts.n - 1) / opts.re; + const double omega = 1.0 / (3.0 * nu_lb + 0.5); + const LbmParameters params{static_cast(ulb), static_cast(omega)}; + + CARBON_LOG_INFO( + "lbm_lid_driven_cavity: lattice={} collision={} N={} iters={} warmup={} " + "Re={:.3g} ulb={:.4g} omega={:.4g} GPUs={} local_gpus={} ranks={} decomposition={} Q={}", + lattice_name, collision_name, opts.n, opts.iters, opts.warmup, opts.re, ulb, omega, + total_gpu_count, local_gpu_count, world_size, decomposition_mode_name(dec_mode), Lattice::Q); + + // Two ping-pong populations + a cell-type field. HostDevice so we can + // seed them from the CPU via fill_owned_host then upload once. + auto pop_a = grid.template newField(carbon::MemorySide::HostDevice, "pop_a"); + auto pop_b = grid.template newField(carbon::MemorySide::HostDevice, "pop_b"); + auto cells = grid.template newField(carbon::MemorySide::HostDevice, "cells"); + auto cells_scratch = + grid.template newField(carbon::MemorySide::HostDevice, "cells_scratch"); + + auto pop_filler = [&global, ulb](carbon::int64_3d gc, int q) -> float { + return init_population_value(gc, global, q, ulb); + }; + pop_a.fill_owned_host(pop_filler); + pop_b.fill_owned_host(pop_filler); + cells.fill_owned_host([&global](carbon::int64_3d gc, int /*c*/) { + return init_cell_value(gc, global); + }); + cells_scratch.fill_owned_host([&global](carbon::int64_3d gc, int /*c*/) { + return init_cell_value(gc, global); + }); + + carbon::Stream upload_stream = sys.stream(); + try { + carbon::Transfer(sys, pop_a.cpu_buffers(), pop_a.gpu_buffers())(upload_stream); + carbon::Transfer(sys, pop_b.cpu_buffers(), pop_b.gpu_buffers())(upload_stream); + carbon::Transfer(sys, cells.cpu_buffers(), cells.gpu_buffers())(upload_stream); + carbon::Transfer(sys, cells_scratch.cpu_buffers(), + cells_scratch.gpu_buffers())(upload_stream); + upload_stream.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: upload failed: {}", e.what()); + return EXIT_FAILURE; + } + + // Precompute wall_neighbour_bits once into cells (reads cells, writes + // cells_scratch through the auto-halo + Stencil pattern; then a peer-copy + // publishes the result back into the canonical "cells" field). + { + carbon::Skeleton precompute(sys); + precompute.add(make_compute_wall_mask_kernel(grid, cells, cells_scratch)); + try { + precompute.compile(); + precompute.run(); + precompute.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: wall-mask compute failed: {}", e.what()); + return EXIT_FAILURE; + } + try { + carbon::Transfer(sys, cells_scratch.gpu_buffers(), + cells.gpu_buffers())(upload_stream); + upload_stream.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: wall-mask publish failed: {}", e.what()); + return EXIT_FAILURE; + } + } + + // Pick the symmetry-unrolled D3Q19+BGK fast-path when the (lattice, + // collision) combo allows it (factored macroscopic + GO/BK eqopp = eq + + // rho * w * 6 * c.u, mirroring Neon's lbm-flow-over-sphere SOTA path); + // otherwise fall through to the lattice-generic body that also covers + // (D3Q27, BGK) and (D3Q27, KBC). Selected at compile time so the two + // ping-pong skeletons each instantiate exactly one kernel. + auto build_iter = [&](typename Grid::template Field& fIn, + typename Grid::template Field& fOut, std::string name) { + if constexpr (std::is_same_v && std::is_same_v) { + return make_iteration_kernel_d3q19_bgk_fast(grid, fIn, fOut, cells, params, + std::move(name)); + } else { + return make_iteration_kernel(grid, fIn, fOut, cells, params, + std::move(name)); + } + }; + + const carbon::Skeleton::Options sk_opts(overlap_mode_from_string(opts.overlap), + /*strict_halo=*/false, /*max_streams=*/0U, + /*log_dot_on_compile=*/false, + /*use_cuda_graph=*/opts.cuda_graph); + carbon::Skeleton sk_ab(sys, sk_opts); + sk_ab.add(build_iter(pop_a, pop_b, "lbm_step_ab")); + carbon::Skeleton sk_ba(sys, sk_opts); + sk_ba.add(build_iter(pop_b, pop_a, "lbm_step_ba")); + try { + sk_ab.compile(); + sk_ba.compile(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: skeleton compile failed: {}", e.what()); + return EXIT_FAILURE; + } + CARBON_LOG_INFO( + "lbm_lid_driven_cavity: skeletons compiled — sk_ab.effective_kernels={} " + "sk_ba.effective_kernels={} (auto-halos included)", + sk_ab.effective_kernels().size(), sk_ba.effective_kernels().size()); + + if (!opts.export_dot_path.empty()) { + if (!sk_ab.export_dot_file(opts.export_dot_path, "lbm_sk_ab")) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: --export-dot failed for {}", opts.export_dot_path); + return EXIT_FAILURE; + } + CARBON_LOG_INFO("lbm_lid_driven_cavity: wrote schedule DOT to {}", opts.export_dot_path); + } + if (!opts.export_dot_png_path.empty()) { + if (!sk_ab.export_dot_png(opts.export_dot_png_path, "lbm_sk_ab")) { + CARBON_LOG_ERROR( + "lbm_lid_driven_cavity: --export-dot-png failed for {} (is graphviz dot on PATH?)", + opts.export_dot_png_path); + return EXIT_FAILURE; + } + CARBON_LOG_INFO("lbm_lid_driven_cavity: wrote schedule PNG to {}", opts.export_dot_png_path); + } + + using Clock = std::chrono::steady_clock; + using Seconds = std::chrono::duration; + const int64_t timed_start = opts.no_warmup_skip ? 0 : opts.warmup; + + Clock::time_point timing_started{}; + Clock::time_point overall_started = Clock::now(); + bool timing_running = false; + + for (int64_t it = 0; it < opts.iters; ++it) { + if (it == timed_start) { + try { + sk_ab.wait(); + sk_ba.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: pre-timing drain failed at iter {}: {}", it, + e.what()); + return EXIT_FAILURE; + } + timing_started = Clock::now(); + timing_running = true; + if (!opts.no_warmup_skip) { + CARBON_LOG_INFO("lbm_lid_driven_cavity: warmup complete ({} iters), starting timing window", + opts.warmup); + } + } + carbon::Skeleton& sk = (it % 2 == 0) ? sk_ab : sk_ba; + try { + sk.run(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: iter {} failed: {}", it, e.what()); + return EXIT_FAILURE; + } + if (opts.report_every > 0 && (it + 1) % opts.report_every == 0) { + try { + sk_ab.wait(); + sk_ba.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: progress sync failed at iter {}: {}", it + 1, + e.what()); + return EXIT_FAILURE; + } + const auto now = Clock::now(); + const double elapsed_overall = Seconds(now - overall_started).count(); + CARBON_LOG_INFO("lbm_lid_driven_cavity: iter {}/{} elapsed={:.3f}s", it + 1, opts.iters, + elapsed_overall); + } + } + + try { + sk_ab.wait(); + sk_ba.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: final sync failed: {}", e.what()); + return EXIT_FAILURE; + } + const auto timing_ended = Clock::now(); + if (!timing_running) { + CARBON_LOG_ERROR( + "lbm_lid_driven_cavity: timing window never opened (timed_start={} but the loop " + "never reached that iteration).", + timed_start); + return EXIT_FAILURE; + } + const double timing_seconds = Seconds(timing_ended - timing_started).count(); + const int64_t timed_iters = opts.iters - timed_start; + const double cells_per_iter = + static_cast(opts.n) * static_cast(opts.n) * static_cast(opts.n); + const double mlups = + (cells_per_iter * static_cast(timed_iters)) / (1.0e6 * timing_seconds); + const double overall_seconds = Seconds(timing_ended - overall_started).count(); + + // Under MPI all ranks measure the same `cells_per_iter` (= global N^3) and + // run lock-step (halo exchanges synchronise them), so each rank's `mlups` + // is the global throughput up to small per-rank timing noise. Print only on + // rank 0 to keep the scrape-friendly headline single-shot. `total_gpu_count` + // is the world size under MPI (one rank per GPU) and the local GPU count + // otherwise; `local_gpu_count` stays useful on multi-GPU single-process runs. + if (world_rank == 0) { + CARBON_LOG_INFO( + "lbm_lid_driven_cavity: DONE lattice={} collision={} timing_window={} iters in " + "{:.3f}s => {:.2f} MLUPS ({:.2f} MLUPS/GPU) overall={:.3f}s GPUs={} " + "local_gpus={} ranks={} decomposition={}", + lattice_name, collision_name, timed_iters, timing_seconds, mlups, + mlups / static_cast(total_gpu_count), overall_seconds, total_gpu_count, + local_gpu_count, world_size, decomposition_mode_name(dec_mode)); + std::cout << "MLUPS=" << mlups << " (cavity N=" << opts.n << " iters=" << timed_iters + << " gpus=" << total_gpu_count << " local_gpus=" << local_gpu_count + << " ranks=" << world_size << " decomposition=" << decomposition_mode_name(dec_mode) + << " lattice=" << lattice_name << " collision=" << collision_name + << (use_mpi ? " transport=mpi+nccl" : "") << ")" << '\n'; + } + + // Optional grid-family parity checksum: Sum-reduce the whole final population + // field. sum_q pop_q == rho per cell, so this equals the total mass in the + // domain — a single scalar that must agree across dense, disg, and + // dense_distributed when the physics is numerically identical (they share the + // hot kernel; only the storage layout + auto-halo family differ). Cross-rank + // allreduce kicks in automatically under MPI via ReductionResult's stage-3 + // path. + if (opts.checksum) { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + auto& latest_pop = (opts.iters % 2 == 1) ? pop_b : pop_a; + carbon::ReductionResult mass_result(sys); + carbon::Skeleton checksum_sk(sys); + checksum_sk.add(carbon::Kernel::reduce( + grid, + [&latest_pop](carbon::KernelLoader& loader) { + const auto fin = loader.read(latest_pop); + return [fin] CARBON_HOST_DEVICE(Span s, Idx idx) -> double { + double acc = 0.0; +#pragma unroll + for (int q = 0; q < Lattice::Q; ++q) { + acc += static_cast(fin.read(s, idx, q)); + } + return acc; + }; + }, + mass_result, carbon::reduce::Sum{}, "lbm_mass_checksum", /*shared_mem=*/0U)); + try { + checksum_sk.compile(); + checksum_sk.run(); + checksum_sk.wait(); + mass_result.sync(sys.stream()); + sys.stream().wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: checksum reduction failed: {}", e.what()); + return EXIT_FAILURE; + } + const double total_mass = mass_result.host_value(); + CARBON_LOG_INFO( + "lbm_lid_driven_cavity: CHECKSUM (total mass, grid={} decomposition={}) = {:.10g}", + opts.grid, decomposition_mode_name(dec_mode), total_mass); + std::cout << "CHECKSUM=" << std::setprecision(12) << total_mass << " (grid=" << opts.grid + << " decomposition=" << decomposition_mode_name(dec_mode) << " N=" << opts.n + << " iters=" << opts.iters << ")" << '\n'; + } + + // Optional VTK dump of the final macroscopic fields (rho, u). Off the hot + // path: only triggered with --vtk-out, runs make_macroscopic_kernel against + // whichever ping-pong buffer holds the latest populations, downloads the + // host mirrors, and writes via carbon::io::write_vtk (legacy + // STRUCTURED_POINTS BINARY; one .rankN shard per rank under MPI). + if (!opts.vtk_path.empty()) { + // carbon::io::write_vtk is specialised on carbon::Dense (the legacy + // STRUCTURED_POINTS writer walks the aggregated dense row layout). + // DenseDisg and DenseDistributed have no VTK writer today, so the dump is + // Dense-only; those runs still report MLUPS, they just skip the optional + // VTK export. + if constexpr (std::is_same_v) { + // The hot loop alternates sk_ab (reads pop_a, writes pop_b) on even iters + // with sk_ba (reads pop_b, writes pop_a) on odd. After `iters` iterations + // the freshest output buffer is therefore pop_b when iters is odd and + // pop_a otherwise. + auto& latest_pop = (opts.iters % 2 == 1) ? pop_b : pop_a; + + // The field names propagate into the VTK SCALARS labels, so name them + // "rho" and "u" — that's what shows up in ParaView's Pipeline Browser + // (rather than the legacy ordinal "field_0" / "field_1") and keeps the + // dump self-describing. + auto rho_field = grid.template newField(carbon::MemorySide::HostDevice, "rho"); + auto u_field = grid.template newField(carbon::MemorySide::HostDevice, "u"); + + carbon::Skeleton macro_sk(sys); + macro_sk.add(make_macroscopic_kernel(grid, latest_pop, cells, rho_field, + u_field, params)); + try { + macro_sk.compile(); + macro_sk.run(); + macro_sk.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: macroscopic kernel failed: {}", e.what()); + return EXIT_FAILURE; + } + + carbon::Stream dl_stream = sys.stream(); + try { + carbon::Transfer(sys, rho_field.gpu_buffers(), rho_field.cpu_buffers())(dl_stream); + carbon::Transfer(sys, u_field.gpu_buffers(), u_field.cpu_buffers())(dl_stream); + dl_stream.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: VTK download failed: {}", e.what()); + return EXIT_FAILURE; + } + + try { + carbon::io::write_vtk(opts.vtk_path, grid, rho_field, u_field); + // Drop a `.vtm` master alongside the per-rank shards so users can open + // one file in ParaView instead of N. No-op in the single-process case. + carbon::io::write_vtk_multiblock_index(opts.vtk_path, grid); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: write_vtk('{}') failed: {}", opts.vtk_path, + e.what()); + return EXIT_FAILURE; + } + CARBON_LOG_INFO("lbm_lid_driven_cavity: wrote VTK (rho + u) to {} after {} iters", + opts.vtk_path, opts.iters); + } else { + CARBON_LOG_WARN( + "lbm_lid_driven_cavity: --vtk-out is only supported for --grid dense " + "(carbon::io::write_vtk has no {} writer); skipping VTK dump.", + opts.grid); + } + } + + // Optional structured JSON report. Schema documented in + // benchmarks/lbm_lid_driven_cavity/scripts/sweep_and_plot.py — bump the + // schema string below and the parser there in lockstep when extending. + // Effective bandwidth assumes a pull-stream + ping-pong layout: each cell + // update reads Q populations from fIn and writes Q populations to fOut, + // so the dominant traffic is 2 * Q * sizeof(float) bytes per update. + // Only rank 0 writes the report: under MPI every rank runs this block, and + // if they all open the same --report path the writes interleave and produce + // corrupt JSON (e.g. a duplicated trailing brace). MLUPS is a global figure + // already reduced across ranks, so rank 0's copy is authoritative. +#ifdef CARBON_HAVE_MPI_NCCL + const int report_rank = use_mpi ? distributed->world_rank() : 0; +#else + const int report_rank = 0; +#endif + if (!opts.report_path.empty() && report_rank == 0) { + const double bytes_per_update = + 2.0 * static_cast(Lattice::Q) * static_cast(sizeof(float)); + const double effective_bandwidth_gb_s = (mlups * 1.0e6 * bytes_per_update) / 1.0e9; + std::ofstream out(opts.report_path); + if (!out.is_open()) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: failed to open --report path '{}'", + opts.report_path); + return EXIT_FAILURE; + } + out << std::setprecision(10); + out << "{\n"; + out << " \"schema\": \"carbon-lbm-report-v1\",\n"; + out << " \"benchmark\": \"lbm_lid_driven_cavity\",\n"; + out << " \"timestamp_utc\": \"" << utc_timestamp_now() << "\",\n"; + out << " \"config\": {\n"; + out << " \"n\": " << opts.n << ",\n"; + out << " \"iters\": " << opts.iters << ",\n"; + out << " \"warmup\": " << opts.warmup << ",\n"; + out << " \"lattice\": \"" << json_escape(lattice_name) << "\",\n"; + out << " \"collision\": \"" << json_escape(collision_name) << "\",\n"; + out << " \"grid\": \"" << json_escape(opts.grid) << "\",\n"; + out << " \"decomposition\": \"" << decomposition_mode_name(dec_mode) << "\",\n"; + out << " \"q\": " << Lattice::Q << ",\n"; + out << " \"re\": " << opts.re << ",\n"; + out << " \"ulb\": " << ulb << ",\n"; + out << " \"nu_lb\": " << nu_lb << ",\n"; + out << " \"omega\": " << omega << ",\n"; + out << " \"no_warmup_skip\": " << (opts.no_warmup_skip ? "true" : "false") << ",\n"; + out << " \"overlap\": \"" << json_escape(opts.overlap) << "\",\n"; + out << " \"cuda_graph\": " << (opts.cuda_graph ? "true" : "false") << ",\n"; + out << " \"label\": \"" << json_escape(opts.label) << "\"\n"; + out << " },\n"; + out << " \"system\": {\n"; + out << " \"backend\": \"" << CARBON_BACKEND_NAME << "\",\n"; + // `distributed` distinguishes the carbon transport path actually in use: + // - false : intra-process multi-GPU only (cudaMemcpyPeerAsync / + // SYCL queue-to-queue copy for halo). + // - true : MPI/NCCL build, *and* >1 rank present at runtime — halo + // flows over NCCL between adjacent ranks (one rank per GPU + // under carbon's strict model). The single-rank case still + // reports false even on an MPI build, because no NCCL ever + // gets called. +#ifdef CARBON_HAVE_MPI_NCCL + out << " \"distributed\": " << (use_mpi ? "true" : "false") << ",\n"; +#else + out << " \"distributed\": false,\n"; +#endif + out << " \"gpu_count\": " << total_gpu_count << ",\n"; + out << " \"local_gpu_count\": " << local_gpu_count << ",\n"; + out << " \"world_size\": " << world_size << ",\n"; + out << " \"rank\": " << world_rank << ",\n"; + out << " \"gpus\": [\n"; + const auto& gpu_devices = sys.gpu_group().devices(); + for (size_t i = 0; i < gpu_devices.size(); ++i) { + const auto& props = gpu_devices[i].properties(); + out << " {\n"; + out << " \"device_id\": " << gpu_devices[i].device_id() << ",\n"; + out << " \"name\": \"" << json_escape(props.name) << "\",\n"; + out << " \"compute_capability\": \"" << props.compute_major << "." + << props.compute_minor << "\",\n"; + out << " \"total_memory_bytes\": " << props.total_global_mem_bytes << ",\n"; + out << " \"multiprocessor_count\": " << props.multiprocessor_count << "\n"; + out << " }" << (i + 1 == gpu_devices.size() ? "" : ",") << "\n"; + } + out << " ]\n"; + out << " },\n"; + out << " \"results\": {\n"; + out << " \"timed_iters\": " << timed_iters << ",\n"; + out << " \"timing_seconds\": " << timing_seconds << ",\n"; + out << " \"overall_seconds\": " << overall_seconds << ",\n"; + out << " \"cells_per_iter\": " << static_cast(cells_per_iter) << ",\n"; + out << " \"mlups\": " << mlups << ",\n"; + out << " \"mlups_per_gpu\": " << (mlups / static_cast(total_gpu_count)) << ",\n"; + out << " \"effective_bandwidth_gb_s\": " << effective_bandwidth_gb_s << "\n"; + out << " }\n"; + out << "}\n"; + out.close(); + if (out.fail()) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: failed to write --report path '{}'", + opts.report_path); + return EXIT_FAILURE; + } + CARBON_LOG_INFO("lbm_lid_driven_cavity: wrote JSON report to {}", opts.report_path); + } + return EXIT_SUCCESS; +} + +} // namespace + +int +main(int argc, + char** argv) { + Options opts; + if (!parse_cli(argc, argv, opts)) { + return opts.show_help ? EXIT_SUCCESS : EXIT_FAILURE; + } + + carbon::init(); + if (carbon::device_count() <= 0) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: no CUDA devices visible"); + return EXIT_FAILURE; + } + + const auto dec_opt = parse_decomposition_mode(opts.decomposition); + if (!dec_opt) { + CARBON_LOG_ERROR( + "lbm_lid_driven_cavity: unknown --decomposition '{}' (expected slab|pencil|brick)", + opts.decomposition); + return EXIT_FAILURE; + } + const carbon::DecompositionMode dec_mode = *dec_opt; + + // Dispatch to the matching template instantiation. The runtime knobs + // --grid {dense,disg,dense_distributed} x --lattice {q19,q27} x --collision + // {bgk,kbc} select one compile-time run_benchmark. + // Three valid (lattice, collision) combos: (q19, bgk), (q27, bgk), (q27, + // kbc) — (q19, kbc) is rejected upstream in parse_cli because KBC's moment + // basis is D3Q27-specific. Each grid family runs the identical hot kernel. + auto dispatch_grid = [&](auto grid_tag) -> int { + using GridT = typename decltype(grid_tag)::type; + if (opts.lattice == "q19" && opts.collision == "bgk") { + return run_benchmark(opts, "q19", "bgk", dec_mode); + } + if (opts.lattice == "q27" && opts.collision == "bgk") { + return run_benchmark(opts, "q27", "bgk", dec_mode); + } + if (opts.lattice == "q27" && opts.collision == "kbc") { + return run_benchmark(opts, "q27", "kbc", dec_mode); + } + CARBON_LOG_ERROR( + "lbm_lid_driven_cavity: unsupported (lattice='{}', collision='{}') combination — " + "KBC requires D3Q27.", + opts.lattice, opts.collision); + return EXIT_FAILURE; + }; + + if (opts.grid == "disg") { + return dispatch_grid(std::type_identity{}); + } + if (opts.grid == "dense_distributed") { + return dispatch_grid(std::type_identity{}); + } + return dispatch_grid(std::type_identity{}); +} diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/src/cell_type.h b/benchmarks/lbm_lid_driven_cavity_distributed/src/cell_type.h new file mode 100644 index 00000000..b83ff1e3 --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/src/cell_type.h @@ -0,0 +1,60 @@ +#pragma once + +// Per-cell classification for the LBM lid-driven cavity benchmark. +// +// One int32 per cell, encoded as a packed (classification, wall_neighbour_bits) +// pair — same scheme Neon uses (Neon/.../src/CellType.h) but flat-packed into +// a single int32 so it can ride a carbon::Dense::Field without +// adding a custom POD type. +// +// Bit layout (LSB to MSB): +// bits 0..3 : classification (Bulk = 0, BounceBack = 1, MovingWall = 2) +// bits 4..30 : up to 27-bit wall_neighbour_bits — bit k set iff the +// kth direction's source neighbour (the cell at -c[k]) is a +// wall (any non-Bulk cell). Used by the iteration kernel +// to choose the bounce-back path without a second Field +// load + branch on classification. +// +// 4 bits is plenty for the 3-value classification enum and gives 28 bits +// for the wall mask — enough for any lattice up to D3Q27 with one bit to +// spare. Older revisions of this benchmark used an 8-bit class field / +// 19-bit wall mask (D3Q19-only); the layout was widened when D3Q27 + KBC +// landed. + +#include + +#include + +namespace carbon::bench::lbm { + +enum class Classification : int { + Bulk = 0, + BounceBack = 1, + MovingWall = 2, +}; + +inline constexpr int kClassMask = 0xF; +inline constexpr int kWallBitsShift = 4; + +[[nodiscard]] CARBON_HD constexpr auto +encode_cell(Classification cls, + uint32_t wall_bits = 0U) noexcept -> int32_t { + // wall_bits is a Q-bit mask (Q in {19, 27} for the lattices we support); + // 28 bits available so D3Q27's 27-bit mask fits with one bit to spare. + // Cast through uint32_t so the shift does not turn into UB on negative + // ints. + return static_cast(static_cast(cls) | + (wall_bits << static_cast(kWallBitsShift))); +} + +[[nodiscard]] CARBON_HD constexpr auto +classification_of(int32_t packed) noexcept -> Classification { + return static_cast(packed & kClassMask); +} + +[[nodiscard]] CARBON_HD constexpr auto +wall_bits_of(int32_t packed) noexcept -> uint32_t { + return static_cast(packed) >> static_cast(kWallBitsShift); +} + +} // namespace carbon::bench::lbm diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/src/d3q19.h b/benchmarks/lbm_lid_driven_cavity_distributed/src/d3q19.h new file mode 100644 index 00000000..b0649141 --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/src/d3q19.h @@ -0,0 +1,126 @@ +#pragma once + +// D3Q19 lattice constants for the carbon LBM benchmark. +// +// Indexing: populations are bucketed by sign(c.z) so the disg lattice halo +// (carbon::HaloDisg with StencilSemantic::Lattice) collapses to exactly two +// fused cudaMemcpyAsync calls per inter-slab adjacency pair, regardless of Q. +// +// q in [0, 4] : c.z = -1 (5 populations, sent downward) +// q in [5, 13] : c.z = 0 (9 populations including center, no z-halo) +// q in [14, 18]: c.z = +1 (5 populations, sent upward) +// +// Within each bucket the assignment is palindromic: c(q) = -c(Q - 1 - q), +// which gives the closed-form +// +// opp(q) = 18 - q +// +// and lets the GO/BK split fall out of "q < 9 / q == 9 / q > 9" rather than +// the old +10 offset trick. The center sits at q = 9 (its own opposite). +// +// This ordering matches Neon's `Neon::set::StencilSemantic::lattice` +// recommendation and Carbon's halo_scalability benchmark — see the +// 2026-05 CHANGELOG entry for the design rationale and 86% bandwidth- +// efficiency numbers vs the unfused ordering. + +#include +#include + +#include + +namespace carbon::bench::lbm { + +struct D3Q19 { + static constexpr int Q = 19; + static constexpr int kCenter = 9; + // Z-bucket boundaries (half-open intervals), exposed for callers that want + // to assert lattice-friendly population ordering at compile time. + static constexpr int kZNegBegin = 0; + static constexpr int kZNegEnd = 5; + static constexpr int kZZeroBegin = 5; + static constexpr int kZZeroEnd = 14; + static constexpr int kZPosBegin = 14; + static constexpr int kZPosEnd = 19; + + // Discrete velocities c_q. Bucketed by sign(c.z) so all c.z<0 entries are + // contiguous in [0, 5), c.z=0 in [5, 14), c.z>0 in [14, 19); palindromic + // within the lattice so c(18 - q) = -c(q). + [[nodiscard]] CARBON_HD static constexpr auto + c(int q) noexcept -> ::carbon::int8_3d { + switch (q) { + // ---- c.z = -1 (5 entries; sent downward by the lattice halo) ---- + case 0: + return {0, 0, -1}; + case 1: + return {-1, 0, -1}; + case 2: + return {1, 0, -1}; + case 3: + return {0, -1, -1}; + case 4: + return {0, 1, -1}; + // ---- c.z = 0 (9 entries; not exchanged across z-slabs) ---- + case 5: + return {-1, 0, 0}; + case 6: + return {0, -1, 0}; + case 7: + return {-1, -1, 0}; + case 8: + return {-1, 1, 0}; + case 9: + return {0, 0, 0}; // center + case 10: + return {1, -1, 0}; + case 11: + return {1, 1, 0}; + case 12: + return {0, 1, 0}; + case 13: + return {1, 0, 0}; + // ---- c.z = +1 (5 entries; sent upward by the lattice halo) ---- + case 14: + return {0, -1, 1}; + case 15: + return {0, 1, 1}; + case 16: + return {-1, 0, 1}; + case 17: + return {1, 0, 1}; + case 18: + return {0, 0, 1}; + default: + return {0, 0, 0}; + } + } + + // Closed-form opposite-direction map: c(18 - q) = -c(q). Verified by + // construction in c() above and locked by tests/test_d3q19_lattice.cpp. + [[nodiscard]] CARBON_HD static constexpr auto + opp(int q) noexcept -> int { + return Q - 1 - q; + } + + // Lattice weights w_q. Standard D3Q19: 1/3 (center), 1/18 (axial), + // 1/36 (face-diagonal). Returned as float so the BGK arithmetic stays on a + // single precision and does not promote. + // + // Axial = exactly one component nonzero; face-diagonal = exactly two + // nonzero components (D3Q19 has no corner / 3-component directions). + [[nodiscard]] CARBON_HD static constexpr auto + w(int q) noexcept -> float { + if (q == kCenter) { + return 1.0F / 3.0F; + } + const auto cq = c(q); + const int nz = (cq.x != 0 ? 1 : 0) + (cq.y != 0 ? 1 : 0) + (cq.z != 0 ? 1 : 0); + return (nz == 1) ? (1.0F / 18.0F) : (1.0F / 36.0F); + } + + // KBC is not supported on D3Q19 in this benchmark — the standard KBC + // formulation (Karlin et al.) targets D3Q27 and Neon's reference only + // wires KBC against D3Q27. main() rejects (q19, kbc) at the CLI parse + // stage so the moment / shear-decompose helpers are not needed here. +}; + +} // namespace carbon::bench::lbm diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/src/d3q27.h b/benchmarks/lbm_lid_driven_cavity_distributed/src/d3q27.h new file mode 100644 index 00000000..790e81e0 --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/src/d3q27.h @@ -0,0 +1,206 @@ +#pragma once + +// D3Q27 lattice (full 3D 27-velocity stencil) for the carbon LBM benchmark. +// +// Indexing: populations are bucketed by sign(c.z) so the disg lattice halo +// collapses to exactly two fused transfers per inter-slab adjacency pair: +// +// q in [0, 9) : c.z = -1 (9 populations, sent downward) +// q in [9, 18) : c.z = 0 (9 populations including center, no z-halo) +// q in [18, 27) : c.z = +1 (9 populations, sent upward) +// +// Palindromic within the lattice: c(q) = -c(26 - q), which gives the closed +// form +// +// opp(q) = 26 - q +// +// and places the center at q = 13 (its own opposite). This differs from the +// Neon lbmMultiRes ordering (which placed center at q=0) but matches the +// Neon::set::StencilSemantic::lattice fusion contract. The kernels in +// lbm_kernels.h are written generically over q in [0, Q) so the iteration +// kernel and macroscopic-extraction kernel pick up the new ordering for free. +// +// The KBC moment and shear-decomposition helpers used to be hand-tabulated +// per q-index against the legacy ordering. They are now derived directly +// from c(q) (moment is the c⊗c outer product's six unique entries; shear +// projection is a closed form of the active components and their signs), +// so the table stays correct under any future re-ordering. + +#include +#include + +#include + +namespace carbon::bench::lbm { + +struct D3Q27 { + static constexpr int Q = 27; + static constexpr int kCenter = 13; + static constexpr int kZNegBegin = 0; + static constexpr int kZNegEnd = 9; + static constexpr int kZZeroBegin = 9; + static constexpr int kZZeroEnd = 18; + static constexpr int kZPosBegin = 18; + static constexpr int kZPosEnd = 27; + + // Discrete velocities c_q. Bucketed by sign(c.z); palindromic so + // c(26 - q) = -c(q). + [[nodiscard]] CARBON_HD static constexpr auto + c(int q) noexcept -> ::carbon::int8_3d { + switch (q) { + // ---- c.z = -1 (9 entries) ---- + case 0: + return {0, 0, -1}; + case 1: + return {-1, 0, -1}; + case 2: + return {1, 0, -1}; + case 3: + return {0, -1, -1}; + case 4: + return {0, 1, -1}; + case 5: + return {-1, -1, -1}; + case 6: + return {-1, 1, -1}; + case 7: + return {1, -1, -1}; + case 8: + return {1, 1, -1}; + // ---- c.z = 0 (9 entries) ---- + case 9: + return {-1, 0, 0}; + case 10: + return {0, -1, 0}; + case 11: + return {-1, -1, 0}; + case 12: + return {-1, 1, 0}; + case 13: + return {0, 0, 0}; // center + case 14: + return {1, -1, 0}; + case 15: + return {1, 1, 0}; + case 16: + return {0, 1, 0}; + case 17: + return {1, 0, 0}; + // ---- c.z = +1 (9 entries) ---- + case 18: + return {-1, -1, 1}; + case 19: + return {-1, 1, 1}; + case 20: + return {1, -1, 1}; + case 21: + return {1, 1, 1}; + case 22: + return {0, -1, 1}; + case 23: + return {0, 1, 1}; + case 24: + return {-1, 0, 1}; + case 25: + return {1, 0, 1}; + case 26: + return {0, 0, 1}; + default: + return {0, 0, 0}; + } + } + + // Closed-form opposite: c(26 - q) = -c(q) by construction. + [[nodiscard]] CARBON_HD static constexpr auto + opp(int q) noexcept -> int { + return Q - 1 - q; + } + + // Lattice weights w_q. Standard D3Q27: + // 8/27 (center), 2/27 (axial, 1 nonzero), 1/54 (face, 2 nonzero), + // 1/216 (corner, 3 nonzero). + // Derived from |c(q)|_0 (the count of nonzero components) so the table + // stays correct under any reordering. + [[nodiscard]] CARBON_HD static constexpr auto + w(int q) noexcept -> float { + if (q == kCenter) { + return 8.0F / 27.0F; + } + const auto cq = c(q); + const int nz = (cq.x != 0 ? 1 : 0) + (cq.y != 0 ? 1 : 0) + (cq.z != 0 ? 1 : 0); + if (nz == 1) { + return 2.0F / 27.0F; + } + if (nz == 2) { + return 1.0F / 54.0F; + } + return 1.0F / 216.0F; + } + + // Moment-projection matrix Mq[6] for the second-order non-equilibrium + // stress tensor used by KBC. Layout matches Neon's lbmMultiRes/lattice.h + // latticeMoment but is now derived from c(q) directly: + // + // m = (c.x*c.x, c.x*c.y, c.x*c.z, c.y*c.y, c.y*c.z, c.z*c.z) + // + // i.e. the 6 unique entries of the outer product c ⊗ c. All entries fit + // int8_t since |c.i| <= 1. + struct Moment { + int8_t v[6]; + }; + + [[nodiscard]] CARBON_HD static constexpr auto + moment(int q) noexcept -> Moment { + const auto cq = c(q); + return {{static_cast(cq.x * cq.x), static_cast(cq.x * cq.y), + static_cast(cq.x * cq.z), static_cast(cq.y * cq.y), + static_cast(cq.y * cq.z), static_cast(cq.z * cq.z)}}; + } + + // KBC shear decomposition — direction-dependent linear combination of the + // off-diagonal stress moments Pi[1] (xy), Pi[2] (xz), Pi[4] (yz) and the + // axial-deviator moments Nxz = Pi[0] - Pi[5], Nyz = Pi[3] - Pi[5]. + // + // Closed form derived from c(q): + // + // - cardinal x (|c.x|=1, others 0) : (2*Nxz - Nyz) / 6 + // - cardinal y (|c.y|=1, others 0) : (-Nxz + 2*Nyz) / 6 + // - cardinal z (|c.z|=1, others 0) : (-Nxz - Nyz) / 6 + // - face xy (|c.x|=1, |c.y|=1, c.z=0) : sign(c.x*c.y) * Pi[1] / 4 + // - face xz (|c.x|=1, c.y=0, |c.z|=1) : sign(c.x*c.z) * Pi[2] / 4 + // - face yz (c.x=0, |c.y|=1, |c.z|=1) : sign(c.y*c.z) * Pi[4] / 4 + // - corner / center : 0 + // + // Mirrors Neon's fdecompose_shear lambda in lbmMultiRes/collide.h byte-for- + // byte under the legacy ordering; expressed via c(q) here so it stays + // correct under any reordering. + [[nodiscard]] CARBON_HD static constexpr auto + shear_decompose(int q, + const float Pi[6]) noexcept -> float { + const auto cq = c(q); + const int nz = (cq.x != 0 ? 1 : 0) + (cq.y != 0 ? 1 : 0) + (cq.z != 0 ? 1 : 0); + if (nz == 1) { + const float Nxz = Pi[0] - Pi[5]; + const float Nyz = Pi[3] - Pi[5]; + if (cq.x != 0) { + return (2.0F * Nxz - Nyz) / 6.0F; + } + if (cq.y != 0) { + return (-Nxz + 2.0F * Nyz) / 6.0F; + } + return (-Nxz - Nyz) / 6.0F; // cq.z != 0 + } + if (nz == 2) { + if (cq.z == 0) { + return static_cast(cq.x * cq.y) * Pi[1] / 4.0F; + } + if (cq.y == 0) { + return static_cast(cq.x * cq.z) * Pi[2] / 4.0F; + } + return static_cast(cq.y * cq.z) * Pi[4] / 4.0F; // cq.x == 0 + } + return 0.0F; // corners (3 nonzero) and center. + } +}; + +} // namespace carbon::bench::lbm diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/src/lbm_kernels.h b/benchmarks/lbm_lid_driven_cavity_distributed/src/lbm_kernels.h new file mode 100644 index 00000000..14d3a2a6 --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/src/lbm_kernels.h @@ -0,0 +1,637 @@ +#pragma once + +// LBM kernel builders for the carbon lid-driven cavity benchmark. +// +// All kernels are templated over a @c Lattice trait struct (@ref D3Q19 in +// d3q19.h, @ref D3Q27 in d3q27.h) that exposes: +// - static constexpr int Q +// - static constexpr int kCenter +// - constexpr static auto c(int q) -> ::carbon::int8_3d +// - constexpr static auto opp(int q) -> int +// - constexpr static auto w(int q) -> float +// and additionally, for KBC support: +// - struct Moment { int8_t v[6]; }; static constexpr auto moment(int q) -> Moment; +// - constexpr static auto shear_decompose(int q, const float Pi[6]) -> float +// +// Three carbon::Kernel factories live here, all templated on Lattice (and +// CollisionPolicy for the iteration kernel): +// +// make_compute_wall_mask_kernel(...) — one-shot kernel that +// walks every direction q != kCenter around every Bulk cell and sets +// bit q in wall_neighbour_bits when the source neighbour at -c[q] is +// a non-Bulk cell. Lattice-generic — same body works for D3Q19 (19 +// bits) and D3Q27 (27 bits). +// +// make_iteration_kernel(...) — the hot kernel. +// For each Bulk cell: +// 1. Pull-stream the Q populations from neighbours, applying +// half-way bounce-back from this cell's opposite-direction +// population whenever the wall_neighbour_bits flag is set. +// 2. Compute macroscopic rho and u from the pulled populations. +// 3. Apply CollisionPolicy (BGK or KBC) in-place on the +// populations. +// 4. Write the post-collision populations back to fOut. +// Loaded via loader.read_stencil(fIn, lattice_stencil, Lattice) so +// carbon::Skeleton auto-inserts the z-filtered population halo. +// +// make_macroscopic_kernel(...) — extracts rho + u into separate +// fields (one component for rho, three for u). Off the hot path; used +// by callers that want to dump VTK for visualization. +// +// CollisionPolicy is one of: +// - BgkCollision: standard single-relaxation-time BGK with +// omega = 1 / (3 * nu_lb + 0.5). Works for any lattice. +// - KbcCollision: Karlin-Bösch-Chikatamarla entropic-stabilised collision +// with per-cell gamma derived from the non-equilibrium moment ratio +// e0 / e1 (Karlin et al., 2014). The standard formulation targets +// D3Q27 — the moment matrix and shear-decomposition table on the +// lattice traits are mandatory. + +#include "cell_type.h" + +#include +#include +#include + +#include + +#include + +namespace carbon::bench::lbm { + +// Running set of physical knobs derived from the user's CLI: ulb is the +// dimensionless lid velocity, omega the BGK relaxation parameter (also used +// by KBC: beta = omega/2). Carried through both the iteration kernel and +// the macroscopic-extraction kernel as a single value-typed struct so the +// loading lambda only captures one POD. +struct LbmParameters { + float ulb; + float omega; +}; + +// --------------------------------------------------------------------------- +// Collision policies +// --------------------------------------------------------------------------- + +// Standard BGK single-relaxation-time collision. f_q^post = (1-omega)*f_q + +// omega * f_q^eq, where the equilibrium is the standard 2nd-order Hermite +// expansion: f_q^eq = w_q * rho * (1 + 3 c.u + 4.5 (c.u)^2 - 1.5 |u|^2). +// Lattice-agnostic — works for D3Q19, D3Q27, or any future Q. +struct BgkCollision { + template + CARBON_HD static auto + apply(float omega, + float rho, + float ux, + float uy, + float uz, + float pop[Lattice::Q]) noexcept -> void { + const float usqr = 1.5F * (ux * ux + uy * uy + uz * uz); + const float one_minus_omega = 1.0F - omega; +#pragma unroll + for (int q = 0; q < Lattice::Q; ++q) { + const auto cq = Lattice::c(q); + const float cu = 3.0F * (static_cast(cq.x) * ux + static_cast(cq.y) * uy + + static_cast(cq.z) * uz); + const float feq = rho * Lattice::w(q) * (1.0F + cu + 0.5F * cu * cu - usqr); + pop[q] = one_minus_omega * pop[q] + omega * feq; + } + } +}; + +// KBC entropic-stabilised collision (Karlin-Bösch-Chikatamarla, 2014). +// Splits the non-equilibrium part fneq = f - feq into a "shear" component +// (deltaS, governed by the second-moment stress) and a "rest" component +// (deltaH = fneq - deltaS, the higher-order moments). The rest component +// is relaxed with a per-cell, per-iteration multiplier gamma chosen to +// minimise the H-functional along the collision step: +// +// gamma = 1/beta - (2 - 1/beta) * _feq / _feq +// +// where the inner product is sum_q (X_q * Y_q / feq_q). beta = omega/2 is +// the relaxation timescale shared with BGK (when gamma == 1/beta the model +// reduces to BGK exactly). The stabilisation gives KBC much better +// behaviour at low viscosity / high Re where BGK becomes oscillatory. +// +// Mirrors Neon/apps/lbmMultiRes/collide.h::collideKBC. Requires the +// Lattice traits to expose @c moment(q) and @c shear_decompose — D3Q27 +// in this benchmark. +struct KbcCollision { + template + CARBON_HD static auto + apply(float omega, + float rho, + float ux, + float uy, + float uz, + float pop[Lattice::Q]) noexcept -> void { + constexpr int Q = Lattice::Q; + const float beta = omega * 0.5F; + const float inv_beta = 1.0F / beta; + const float usqr = 1.5F * (ux * ux + uy * uy + uz * uz); + + // ---- equilibrium + non-equilibrium ---- + float feq[Q]; + float fneq[Q]; +#pragma unroll + for (int q = 0; q < Q; ++q) { + const auto cq = Lattice::c(q); + const float cu = 3.0F * (static_cast(cq.x) * ux + static_cast(cq.y) * uy + + static_cast(cq.z) * uz); + feq[q] = rho * Lattice::w(q) * (1.0F + cu + 0.5F * cu * cu - usqr); + fneq[q] = pop[q] - feq[q]; + } + + // ---- second-moment stress Pi[6] = sum_q fneq_q * Mq[i] ---- + float Pi[6] = {0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F}; +#pragma unroll + for (int q = 0; q < Q; ++q) { + const auto m = Lattice::moment(q); +#pragma unroll + for (int i = 0; i < 6; ++i) { + Pi[i] += fneq[q] * static_cast(m.v[i]); + } + } + + // ---- shear component deltaS_q + entropic ratio e0 / e1 ---- + float deltaS[Q]; + float e0 = 0.0F; + float e1 = 0.0F; + constexpr float tiny = 1.0e-7F; // guards 1/feq when feq -> 0 (rare). +#pragma unroll + for (int q = 0; q < Q; ++q) { + deltaS[q] = rho * Lattice::shear_decompose(q, Pi); + const float deltaH = fneq[q] - deltaS[q]; + // Entropic inner products _feq and _feq. + const float inv_feq = 1.0F / (feq[q] + tiny); + e0 += deltaS[q] * deltaH * inv_feq; + e1 += deltaH * deltaH * inv_feq; + } + + // ---- per-cell gamma + collision write-back ---- + const float gamma = inv_beta - (2.0F - inv_beta) * e0 / (tiny + e1); +#pragma unroll + for (int q = 0; q < Q; ++q) { + const float deltaH = fneq[q] - deltaS[q]; + pop[q] = pop[q] - beta * (2.0F * deltaS[q] + gamma * deltaH); + } + } +}; + +// --------------------------------------------------------------------------- +// Wall-mask precomputation +// --------------------------------------------------------------------------- + +// One-shot precomputation of wall_neighbour_bits per Bulk cell. For each +// direction q != kCenter, sets bit q if the source neighbour at -c[q] is +// out of the global domain or holds a non-Bulk cell. Halo / global edge +// cells (!valid) are treated as walls so the cavity boundary cells fall +// straight into bounce-back. +template +[[nodiscard]] inline auto +make_compute_wall_mask_kernel(Grid& grid, + typename Grid::template Field& cell_in, + typename Grid::template Field& cell_out) -> ::carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return ::carbon::Kernel::compute( + grid, + [&cell_in, &cell_out](::carbon::KernelLoader& loader) { + const auto in = loader.read_stencil(cell_in); + const auto out = loader.write(cell_out); + return [in, out] CARBON_HOST_DEVICE(Span s, Idx idx) { + const int32_t self_packed = in.read(s, idx, 0); + const Classification self_cls = classification_of(self_packed); + if (self_cls != Classification::Bulk) { + out.write(s, idx, 0, self_packed); + return; + } + uint32_t wall_bits = 0U; +#pragma unroll + for (int q = 0; q < Lattice::Q; ++q) { + if (q == Lattice::kCenter) { + continue; + } + // Source for direction q under pull streaming sits at -c[q]. + const auto cq = Lattice::c(q); + const ::carbon::int8_3d src_off{static_cast(-cq.x), static_cast(-cq.y), + static_cast(-cq.z)}; + const auto ngh = in.neighbour(s, idx, src_off, 0); + const bool is_wall = !ngh.valid || classification_of(ngh.value) != Classification::Bulk; + if (is_wall) { + wall_bits |= (1U << static_cast(q)); + } + } + out.write(s, idx, 0, encode_cell(Classification::Bulk, wall_bits)); + }; + }, + "lbm_compute_wall_mask", + /*shared_mem=*/0U); +} + +// --------------------------------------------------------------------------- +// Hot iteration kernel (collide-stream) +// --------------------------------------------------------------------------- + +// Q-aligned velocity stencil for lattice-semantic halo: population q pairs with +// stencil.points()[q] == Lattice::c(q). Center at kCenter has c.z == 0 and is +// never sent across z-slab boundaries. +template +[[nodiscard]] inline auto +make_lattice_population_stencil() -> ::carbon::Stencil { + std::vector<::carbon::int32_3d> pts; + pts.reserve(Lattice::Q); + for (int q = 0; q < Lattice::Q; ++q) { + const auto c = Lattice::c(q); + pts.push_back({c.x, c.y, c.z}); + } + return ::carbon::Stencil(pts); +} + +// Pull-stream source offset for direction q: under pull streaming the cell +// reads its q population from the neighbour at -c[q]. Returned as an +// int8_3d so it can feed Partition::read_pull, the grid-generic @b trusted +// neighbour read (no per-direction validity branch). +// +// The iteration kernel only follows the non-wall branch when wall_bits +// guarantees the source neighbour is an in-domain Bulk cell (set by +// make_compute_wall_mask_kernel: bit q is 0 iff the neighbour at -c[q] is +// both .valid and Bulk), so a bounds check would always succeed there — +// skipping it removes one branch per direction per cell update and is what +// closes the bandwidth gap with hand-rolled LBM kernels. read_pull is the +// primitive that lets Dense and DenseDisg share this hot kernel verbatim: +// each family builds the shifted Idx through its own pitch math (aggregated +// cell shift vs. five-region reclassification) behind the same call, mirroring +// Neon's dPartition::pull. +template +[[nodiscard]] CARBON_HD inline auto +pull_offset(int q) noexcept -> ::carbon::int8_3d { + const auto cq = Lattice::c(q); + return ::carbon::int8_3d{static_cast(-cq.x), static_cast(-cq.y), + static_cast(-cq.z)}; +} + +// Per-Bulk-cell pipeline: pull-stream Q populations into a register array, +// compute macroscopic rho/u, apply the CollisionPolicy in-place, write Q +// post-collision populations back to fOut. Non-Bulk cells leave fOut alone +// (their populations are kept at the initial equilibrium, matching Neon's +// behaviour). +// +// loader.read_stencil(fIn) records an AccessPattern::Stencil token, which +// causes carbon::Skeleton::compile to insert an auto-halo on fIn before this +// kernel — multi-GPU correctness without manual halo plumbing. +template +[[nodiscard]] inline auto +make_iteration_kernel(Grid& grid, + typename Grid::template Field& f_in, + typename Grid::template Field& f_out, + typename Grid::template Field& cell_field, + LbmParameters params, + std::string name) -> ::carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return ::carbon::Kernel::compute( + grid, + [&f_in, &f_out, &cell_field, params](::carbon::KernelLoader& loader) { + const auto fin = loader.read_stencil(f_in, make_lattice_population_stencil(), + ::carbon::StencilSemantic::Lattice); + const auto fout = loader.write(f_out); + const auto cell = loader.read(cell_field); + const float omega = params.omega; + return [fin, fout, cell, omega] CARBON_HOST_DEVICE(Span s, Idx idx) { + const int32_t packed = cell.read(s, idx, 0); + if (classification_of(packed) != Classification::Bulk) { + return; + } + const uint32_t wall_bits = wall_bits_of(packed); + + // ---- 1. Pull-stream Q populations into pop[Q] ---- + // For q != kCenter: pop[q] either pulls from the cell at -c[q] + // (normal stream) or, when wall_bits bit q is set, applies the + // half-way bounce-back boundary condition. The bounce-back read + // pulls (a) self.pop[opp(q)] — the standard reflected population — + // PLUS (b) wall_neighbour.pop[opp(q)]. The wall cell at -c[q] has + // its opp(q) population pre-seeded by the host-side init: 0 for + // stationary walls (collapses to plain bounce-back) and + // -6 * w_opp(q) * ulb * (c_opp(q) . u_lid) for the moving lid + // (the half-way moving-wall momentum-correction term that drives + // the cavity flow). Same shape as Neon's + // lbm-flow-over-sphere PULL_STREAM macro. Without (b) the lid is + // indistinguishable from a stationary wall and u stays ~0 + // everywhere — the bug that prompted this fix. + // + // The wall mask precomputation already filtered out-of-domain + // and non-Bulk neighbours into wall_bits, so the non-wall branch + // is provably safe to read through raw offset arithmetic — no + // per-direction validity check needed. + float pop[Lattice::Q]; +#pragma unroll + for (int q = 0; q < Lattice::Q; ++q) { + if (q == Lattice::kCenter) { + pop[q] = fin.read(s, idx, q); + continue; + } + const ::carbon::int8_3d off = pull_offset(q); + if (wall_bits & (1U << static_cast(q))) { + const int oq = Lattice::opp(q); + pop[q] = fin.read(s, idx, oq) + fin.read_pull(s, idx, off, oq); + } else { + pop[q] = fin.read_pull(s, idx, off, q); + } + } + + // ---- 2. Macroscopic rho, u (sum over q with c[q] weighting) ---- + float rho = 0.0F; + float mx = 0.0F; + float my = 0.0F; + float mz = 0.0F; +#pragma unroll + for (int q = 0; q < Lattice::Q; ++q) { + const auto cq = Lattice::c(q); + rho += pop[q]; + mx += static_cast(cq.x) * pop[q]; + my += static_cast(cq.y) * pop[q]; + mz += static_cast(cq.z) * pop[q]; + } + const float inv_rho = 1.0F / rho; + const float ux = mx * inv_rho; + const float uy = my * inv_rho; + const float uz = mz * inv_rho; + + // ---- 3. Collision (BGK or KBC) in-place on pop[] ---- + Collision::template apply(omega, rho, ux, uy, uz, pop); + + // ---- 4. Write back ---- +#pragma unroll + for (int q = 0; q < Lattice::Q; ++q) { + fout.write(s, idx, q, pop[q]); + } + }; + }, + std::move(name), + /*shared_mem=*/0U); +} + +// --------------------------------------------------------------------------- +// D3Q19 + BGK hand-unrolled fast-path +// --------------------------------------------------------------------------- +// +// Specialised iteration kernel that exploits two BGK-D3Q19 symmetries that +// the generic make_iteration_kernel above can't: the post-collision write +// pairs (q, opp(q)) share most of their equilibrium (eqopp = eq + rho * w * +// 6 * c.u), and the macroscopic moments factor through sub-sums grouped by +// the sign of each component of c. This brings the kernel onto Neon's +// `lbm-flow-over-sphere` SOTA arithmetic profile — ~2x fewer collision FLOPs +// and ~3x fewer macroscopic FLOPs than the lattice-generic body. +// +// The structural layout (pull-stream + half-way bounce-back + two-pop ping- +// pong + auto-halo via loader.read_stencil) is identical to the generic +// kernel; only the math inside the per-cell body differs. Used only for the +// (D3Q19, BGK) combo — D3Q27 and KBC stay on the lattice-generic path +// because their symmetry tables are different (D3Q27) or the collision step +// itself is not symmetry-factorisable (KBC). +template +[[nodiscard]] inline auto +make_iteration_kernel_d3q19_bgk_fast(Grid& grid, + typename Grid::template Field& f_in, + typename Grid::template Field& f_out, + typename Grid::template Field& cell_field, + LbmParameters params, + std::string name) -> ::carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return ::carbon::Kernel::compute( + grid, + [&f_in, &f_out, &cell_field, params](::carbon::KernelLoader& loader) { + const auto fin = loader.read_stencil(f_in, make_lattice_population_stencil(), + ::carbon::StencilSemantic::Lattice); + const auto fout = loader.write(f_out); + const auto cell = loader.read(cell_field); + const float omega = params.omega; + return [fin, fout, cell, omega] CARBON_HOST_DEVICE(Span s, Idx idx) { + const int32_t packed = cell.read(s, idx, 0); + if (classification_of(packed) != Classification::Bulk) { + return; + } + const uint32_t wall_bits = wall_bits_of(packed); + + // ---- 1. Pull-stream — same logic as the generic body ---- + // See the matching comment in make_iteration_kernel: bounce-back + // adds the wall neighbour's pre-seeded opp(q) population so the + // moving lid's -6*w*ulb*(c.u_lid) correction actually feeds in. + float pop[D3Q19::Q]; +#pragma unroll + for (int q = 0; q < D3Q19::Q; ++q) { + if (q == D3Q19::kCenter) { + pop[q] = fin.read(s, idx, q); + continue; + } + const ::carbon::int8_3d off = pull_offset(q); + if (wall_bits & (1U << static_cast(q))) { + const int oq = D3Q19::opp(q); + pop[q] = fin.read(s, idx, oq) + fin.read_pull(s, idx, off, oq); + } else { + pop[q] = fin.read_pull(s, idx, off, q); + } + } + + // ---- 2. Factored macroscopic ---- + // Sub-sums grouped by the sign of each component of c. Indices + // pair with the new c.z-bucketed q-id table in d3q19.h: + // c.x = -1 : {1, 5, 7, 8, 16} + // c.x = +1 : {2, 10, 11, 13, 17} + // c.y = -1 : {3, 6, 7, 10, 14} + // c.y = +1 : {4, 8, 11, 12, 15} + // c.z = -1 : {0, 1, 2, 3, 4} (entire bucket [0, 5)) + // c.z = +1 : {14, 15, 16, 17, 18} (entire bucket [14, 19)) + // The c.z sums are now full contiguous-bucket scans, mirroring + // the disg lattice halo's per-bucket fused transfers. + const float X_M1 = pop[1] + pop[5] + pop[7] + pop[8] + pop[16]; + const float X_P1 = pop[2] + pop[10] + pop[11] + pop[13] + pop[17]; + const float Y_M1 = pop[3] + pop[6] + pop[7] + pop[10] + pop[14]; + const float Y_P1 = pop[4] + pop[8] + pop[11] + pop[12] + pop[15]; + const float Z_M1 = pop[0] + pop[1] + pop[2] + pop[3] + pop[4]; + const float Z_P1 = pop[14] + pop[15] + pop[16] + pop[17] + pop[18]; + + // rho = sum over all q. Cheaper to add up the three z-buckets. + const float Z_0 = + pop[5] + pop[6] + pop[7] + pop[8] + pop[9] + pop[10] + pop[11] + pop[12] + pop[13]; + const float rho = Z_M1 + Z_0 + Z_P1; + const float inv_rho = 1.0F / rho; + const float ux = (X_P1 - X_M1) * inv_rho; + const float uy = (Y_P1 - Y_M1) * inv_rho; + const float uz = (Z_P1 - Z_M1) * inv_rho; + const float usqr = 1.5F * (ux * ux + uy * uy + uz * uz); + + // ---- 3. Symmetric BGK collision ---- + // Compute equilibria for q in [0, 9] (the "first half" + center) + // and derive q in [10, 18] via the BGK symmetry + // feq(c) - feq(-c) = 6 * rho * w * c.u . + // Under the new palindromic ordering c(18 - q) = -c(q), so + // eq_(18 - q) = eq_q + 6 * rho * w_q * c(18 - q).u . + // (c.u for the BK velocity of each pair is filled in below.) + constexpr float c1over18 = 1.0F / 18.0F; + constexpr float c1over36 = 1.0F / 36.0F; + constexpr float c1over3 = 1.0F / 3.0F; + + // Off-axial projections used by the face-diagonal pairs. + const float ck_xy = ux + uy; // (1, 1, 0) / (-1, -1, 0) + const float ck_xz = ux + uz; // (1, 0, 1) / (-1, 0, -1) + const float ck_yz = uy + uz; // (0, 1, 1) / (0, -1, -1) + const float dk_xy = ux - uy; // (1, -1, 0) / (-1, 1, 0) + const float dk_xz = ux - uz; // (1, 0, -1) / (-1, 0, 1) + const float dk_yz = uy - uz; // (0, 1, -1) / (0, -1, 1) + + // First-half equilibria. c.u for q in [0, 9]: + // q=0 c=(0,0,-1) c.u = -uz + // q=1 c=(-1,0,-1) c.u = -ck_xz + // q=2 c=(1,0,-1) c.u = +dk_xz + // q=3 c=(0,-1,-1) c.u = -ck_yz + // q=4 c=(0,1,-1) c.u = +dk_yz + // q=5 c=(-1,0,0) c.u = -ux + // q=6 c=(0,-1,0) c.u = -uy + // q=7 c=(-1,-1,0) c.u = -ck_xy + // q=8 c=(-1,1,0) c.u = -dk_xy + // q=9 center c.u = 0 + const float eq_0 = rho * c1over18 * (1.0F - 3.0F * uz + 4.5F * uz * uz - usqr); + const float eq_1 = rho * c1over36 * (1.0F - 3.0F * ck_xz + 4.5F * ck_xz * ck_xz - usqr); + const float eq_2 = rho * c1over36 * (1.0F + 3.0F * dk_xz + 4.5F * dk_xz * dk_xz - usqr); + const float eq_3 = rho * c1over36 * (1.0F - 3.0F * ck_yz + 4.5F * ck_yz * ck_yz - usqr); + const float eq_4 = rho * c1over36 * (1.0F + 3.0F * dk_yz + 4.5F * dk_yz * dk_yz - usqr); + const float eq_5 = rho * c1over18 * (1.0F - 3.0F * ux + 4.5F * ux * ux - usqr); + const float eq_6 = rho * c1over18 * (1.0F - 3.0F * uy + 4.5F * uy * uy - usqr); + const float eq_7 = rho * c1over36 * (1.0F - 3.0F * ck_xy + 4.5F * ck_xy * ck_xy - usqr); + const float eq_8 = rho * c1over36 * (1.0F - 3.0F * dk_xy + 4.5F * dk_xy * dk_xy - usqr); + const float eq_9 = rho * c1over3 * (1.0F - usqr); + + // Second-half equilibria via the symmetry. c.u for q in [10, 18]: + // q=10 c=(1,-1,0) c.u = +dk_xy + // q=11 c=(1,1,0) c.u = +ck_xy + // q=12 c=(0,1,0) c.u = +uy + // q=13 c=(1,0,0) c.u = +ux + // q=14 c=(0,-1,1) c.u = -dk_yz + // q=15 c=(0,1,1) c.u = +ck_yz + // q=16 c=(-1,0,1) c.u = -dk_xz + // q=17 c=(1,0,1) c.u = +ck_xz + // q=18 c=(0,0,1) c.u = +uz + const float eq_10 = eq_8 + rho * c1over36 * 6.0F * dk_xy; + const float eq_11 = eq_7 + rho * c1over36 * 6.0F * ck_xy; + const float eq_12 = eq_6 + rho * c1over18 * 6.0F * uy; + const float eq_13 = eq_5 + rho * c1over18 * 6.0F * ux; + const float eq_14 = eq_4 - rho * c1over36 * 6.0F * dk_yz; + const float eq_15 = eq_3 + rho * c1over36 * 6.0F * ck_yz; + const float eq_16 = eq_2 - rho * c1over36 * 6.0F * dk_xz; + const float eq_17 = eq_1 + rho * c1over36 * 6.0F * ck_xz; + const float eq_18 = eq_0 + rho * c1over18 * 6.0F * uz; + + const float one_minus_omega = 1.0F - omega; + + // ---- 4. Write back ---- + fout.write(s, idx, 0, one_minus_omega * pop[0] + omega * eq_0); + fout.write(s, idx, 1, one_minus_omega * pop[1] + omega * eq_1); + fout.write(s, idx, 2, one_minus_omega * pop[2] + omega * eq_2); + fout.write(s, idx, 3, one_minus_omega * pop[3] + omega * eq_3); + fout.write(s, idx, 4, one_minus_omega * pop[4] + omega * eq_4); + fout.write(s, idx, 5, one_minus_omega * pop[5] + omega * eq_5); + fout.write(s, idx, 6, one_minus_omega * pop[6] + omega * eq_6); + fout.write(s, idx, 7, one_minus_omega * pop[7] + omega * eq_7); + fout.write(s, idx, 8, one_minus_omega * pop[8] + omega * eq_8); + fout.write(s, idx, 9, one_minus_omega * pop[9] + omega * eq_9); + fout.write(s, idx, 10, one_minus_omega * pop[10] + omega * eq_10); + fout.write(s, idx, 11, one_minus_omega * pop[11] + omega * eq_11); + fout.write(s, idx, 12, one_minus_omega * pop[12] + omega * eq_12); + fout.write(s, idx, 13, one_minus_omega * pop[13] + omega * eq_13); + fout.write(s, idx, 14, one_minus_omega * pop[14] + omega * eq_14); + fout.write(s, idx, 15, one_minus_omega * pop[15] + omega * eq_15); + fout.write(s, idx, 16, one_minus_omega * pop[16] + omega * eq_16); + fout.write(s, idx, 17, one_minus_omega * pop[17] + omega * eq_17); + fout.write(s, idx, 18, one_minus_omega * pop[18] + omega * eq_18); + }; + }, + std::move(name), + /*shared_mem=*/0U); +} + +// --------------------------------------------------------------------------- +// Optional macroscopic-extraction kernel (rho + u out) +// --------------------------------------------------------------------------- + +// Off the hot path. Projects rho + u out of the current population field +// into separate (1, 3)-component fields. Used when callers want to dump +// VTK / probe profiles between benchmark runs. Same generic Q-loop the +// iteration kernel uses for the moment computation. +template +[[nodiscard]] inline auto +make_macroscopic_kernel(Grid& grid, + typename Grid::template Field& f_in, + typename Grid::template Field& cell_field, + typename Grid::template Field& rho_field, + typename Grid::template Field& u_field, + LbmParameters params) -> ::carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return ::carbon::Kernel::compute( + grid, + [&f_in, &cell_field, &rho_field, &u_field, params](::carbon::KernelLoader& loader) { + const auto fin = loader.read(f_in); + const auto cell = loader.read(cell_field); + const auto rho_w = loader.write(rho_field); + const auto u_w = loader.write(u_field); + const float ulb = params.ulb; + return [fin, cell, rho_w, u_w, ulb] CARBON_HOST_DEVICE(Span s, Idx idx) { + const int32_t packed = cell.read(s, idx, 0); + const Classification cls = classification_of(packed); + if (cls == Classification::Bulk) { + float rho = 0.0F; + float mx = 0.0F; + float my = 0.0F; + float mz = 0.0F; +#pragma unroll + for (int q = 0; q < Lattice::Q; ++q) { + const auto cq = Lattice::c(q); + const float fq = fin.read(s, idx, q); + rho += fq; + mx += static_cast(cq.x) * fq; + my += static_cast(cq.y) * fq; + mz += static_cast(cq.z) * fq; + } + const float inv_rho = 1.0F / rho; + rho_w.write(s, idx, 0, rho); + u_w.write(s, idx, 0, mx * inv_rho); + u_w.write(s, idx, 1, my * inv_rho); + u_w.write(s, idx, 2, mz * inv_rho); + } else if (cls == Classification::MovingWall) { + // Lid moves with u = (ulb, 0, 0); rho = 1 by construction. + rho_w.write(s, idx, 0, 1.0F); + u_w.write(s, idx, 0, ulb); + u_w.write(s, idx, 1, 0.0F); + u_w.write(s, idx, 2, 0.0F); + } else { + rho_w.write(s, idx, 0, 1.0F); + u_w.write(s, idx, 0, 0.0F); + u_w.write(s, idx, 1, 0.0F); + u_w.write(s, idx, 2, 0.0F); + } + }; + }, + "lbm_macroscopic", + /*shared_mem=*/0U); +} + +} // namespace carbon::bench::lbm From bf3df6eb8c566ad4e9b25314f2594c23d7835c0b Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:04:42 +0100 Subject: [PATCH 06/33] vtk output for pencil and brick --- CMakeLists.txt | 2 + denseDistributed_compactBoundary_vtk.patch | 2073 +++++++++++++++++ docs/CHANGELOG.md | 83 +- .../carbon/detail/dense_distributed/span.h | 129 +- include/carbon/detail/io_vtk_distributed.inl | 313 +++ include/carbon/io.h | 9 +- src/io_vtk_distributed.cpp | 832 +++++++ tests/test_dense_distributed_dist.cu | 175 +- tests/test_dense_distributed_host.cpp | 307 +++ 9 files changed, 3884 insertions(+), 39 deletions(-) create mode 100644 denseDistributed_compactBoundary_vtk.patch create mode 100644 include/carbon/detail/io_vtk_distributed.inl create mode 100644 src/io_vtk_distributed.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 00d478dc..9162d81a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -286,6 +286,7 @@ add_library(carbon SHARED src/dist_render.cpp src/io.cpp src/io_vtk.cpp + src/io_vtk_distributed.cpp src/logging.cpp src/memory_side.cpp src/process_grid.cpp @@ -402,6 +403,7 @@ elseif(CARBON_BACKEND STREQUAL "Sycl") src/dist_reduce.cpp src/io.cpp src/io_vtk.cpp + src/io_vtk_distributed.cpp src/logging.cpp src/memory_side.cpp src/process_grid.cpp diff --git a/denseDistributed_compactBoundary_vtk.patch b/denseDistributed_compactBoundary_vtk.patch new file mode 100644 index 00000000..2648a3ce --- /dev/null +++ b/denseDistributed_compactBoundary_vtk.patch @@ -0,0 +1,2073 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 00d478d..9162d81 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -286,6 +286,7 @@ add_library(carbon SHARED + src/dist_render.cpp + src/io.cpp + src/io_vtk.cpp ++ src/io_vtk_distributed.cpp + src/logging.cpp + src/memory_side.cpp + src/process_grid.cpp +@@ -402,6 +403,7 @@ elseif(CARBON_BACKEND STREQUAL "Sycl") + src/dist_reduce.cpp + src/io.cpp + src/io_vtk.cpp ++ src/io_vtk_distributed.cpp + src/logging.cpp + src/memory_side.cpp + src/process_grid.cpp +diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md +index 1f384e7..1f02638 100644 +--- a/docs/CHANGELOG.md ++++ b/docs/CHANGELOG.md +@@ -6046,31 +6046,64 @@ This unblocked the matrix on this host: the `sycl` and `hip-nvidia` images build + (and DenseDisg forwarding) compute one centre offset then constant-strided `pull()` neighbours; + Jacobi uses it instead of `neighbour()` + a redundant `read()` partition. `Dense` rejects layouts + whose `xy_slab_elements` or haloed x extent exceed `int32_t`. New test `test_partition_cursor`. +-- **2026-10 — `DenseDistributed`: slab / pencil / brick split out of `Dense`.** `Dense` is back to +- its original Z-slab-only implementation (`dense.h`, `dense.cpp`, `detail/dense/{span,field, +- partition}.h`, `halo.h`, `detail/halo_build.h` and `boundary_mode.h` are unchanged from before +- the decomposition work; `BoundaryMode::PeriodicZ` is `1` again, so `DenseDisg`, `libcarbonpy` +- and the Python bindings are untouched). The process-grid decomposition now lives in a sibling +- grid family: `carbon::DenseDistributed` (+ `HaloDistributed`, and the per-axis +- `BoundaryModeDistributed`, whose `PeriodicX | PeriodicY | PeriodicZ` bits are independent; it +- is a separate type so a per-axis mask can never reach a grid that only understands a Z wrap). +- It takes a `ProcessGrid` / `DecompositionMode` (default slab) and exposes the same `Span` / +- `Partition` / `Field` / kernel / reduce surface as `Dense`, wired through a +- `DenseDistributedPolicy` marker in `launch_traits.h` (same mechanism as `DisgPolicy`) and +- `Kernel::halo_distributed`; `Idx` is shared with `Dense`. The split / halo-thickness / per-rank +- chunk arithmetic is a pure host function set in `detail/dense_distributed/layout.h`, so tests +- can exercise the production decomposition without a GPU. The cross-rank NCCL pairing key still +- ends with the run index: X/Y halo faces are non-contiguous in the x-fastest buffer, so one face +- fans out into many runs sharing the same `(axis, source, dest, side, component)` key, and an +- unordered sort could permute them differently on the two ranks. Tests: the nine multi-axis +- tests and `test_halo_decomp_common.h` are replaced by `dense_distributed_host` (host-only: +- geometry of every rank for slab / pencil / brick, Span views, open vs periodic neighbours, and +- the packed X→Y→Z exchange on an emulated world) and `dense_distributed_dist` (4 ranks: raw halo +- exchange byte-checked on slab `(1,1,4)`, pencil `(1,2,2)` and bricks `(2,2,1)` / `(2,1,2)`, +- packed and run-based, plus a Skeleton stencil kernel with and without overlap; launched with +- `mpiexec -n 8` it covers the full `(2,2,2)` brick, so `CARBON_TEST_BRICK_8GPU` is gone). +- `benchmarks_giulio`: CG gains `--grid dense_distributed` (`--grid dense` is the original +- slab-only grid and rejects pencil / brick); LDC and Jacobi run on `DenseDistributed`. ++- **2026-10 — `DenseDistributed`: slab / pencil / brick decomposition as a sibling of `Dense`.** ++ `Dense` is untouched (still the Z-slab-only grid: one slab per GPU/rank). The per-axis ++ decomposition lives in a new grid family, `carbon::DenseDistributed`, so the original code path ++ keeps its exact geometry, halo builder and generated code. It takes a `ProcessGrid` / ++ `DecompositionMode` (slab by default), uses its own `Span` / `Partition` / `Field` under ++ `detail/dense_distributed/` (`Idx` is shared with `Dense`), and exposes the same kernel, reduce ++ and Skeleton surface through a `DenseDistributedPolicy` marker in `launch_traits.h` (the ++ mechanism `DisgPolicy` already uses) plus `Kernel::halo_distributed`. Halo exchange is ++ `HaloDistributed`: a staged X→Y→Z exchange (so edges and corners travel without diagonal ++ messages) with a packed fast path (`halo_pack*.h`, `src/halo_pack.cu`; `CARBON_HALO_PACK=0` ++ selects the run-based path). Per-axis periodicity is a separate type, ++ `BoundaryModeDistributed` (`PeriodicX | PeriodicY | PeriodicZ` are independent bits), so ++ `BoundaryMode` and its numeric values stay as they were for `Dense`, `DenseDisg`, `libcarbonpy` ++ and the Python bindings. The split / halo-thickness / per-rank chunk arithmetic is a pure host ++ function set in `detail/dense_distributed/layout.h`, so tests exercise the production ++ decomposition without a GPU. The cross-rank NCCL pairing key ends with the run index: X/Y halo ++ faces are non-contiguous in the x-fastest buffer, so one face fans out into many runs sharing ++ the same `(axis, source, dest, side, component)` key, and an unordered sort could permute them ++ differently on the two ranks. Supporting additions: `ProcessGrid` / `DecompositionMode` ++ (`process_grid.h`, balanced prime factorisation over the free axes, plus explicit ++ `ProcessGrid::custom`) and `Stencil::radius3()` (per-axis Chebyshev radius). Tests: ++ `test_process_grid`; `dense_distributed_host` (host-only: geometry of every rank for slab / ++ pencil / brick, Span views, open vs periodic neighbours, and the packed exchange on an emulated ++ world); `dense_distributed_dist` (4 ranks: raw halo exchange byte-checked on slab `(1,1,4)`, ++ pencil `(1,2,2)` and bricks `(2,2,1)` / `(2,1,2)`, packed and run-based, plus a Skeleton stencil ++ kernel with and without overlap; launched with `mpiexec -n 8` it covers the full `(2,2,2)` ++ brick). ++- **2026-11 — Compact `Boundary` view for pencil / brick.** For multi-axis chunks ++ `DenseDistributed::Span::iter_extent(Boundary)` returned the full owned extent and ++ `set_and_validate` rejected the interior threads, so every Boundary launch (Standard overlap, and ++ the Boundary half of Extended / TwoWayExtended producers, which runs before the halo can start) ++ spawned one thread per owned cell for a shell of about `6·h·n²` cells (roughly 30-40x more ++ threads than needed for a 256³ chunk with halo 1). The view now iterates the shell directly: six ++ non-overlapping slabs (Z faces over the full XY extent, Y faces over the middle Z range, X faces ++ over the middle Y/Z range), launched as a 2-D `(128, ceil(S/128), 1)` box whose padded tail is ++ `valid = false`. Slab layouts keep the existing two-band domain. `Internal + Boundary == ++ Standard` still holds, including chunks thinner than `2·halo` (band thickness is clamped so the ++ bands never overlap). Contract change, documented on `Span`: consecutive Boundary threads are no ++ longer spatial neighbours. `dense_distributed_host` additionally asserts that the launch box is ++ less than one 128-wide row larger than the shell. ++- **2026-11 — VTK I/O for `DenseDistributed`.** `io::write_vtk(path, grid, fields...)`, ++ `io::read_vtk(path, grid, fields...)` and `io::write_vtk_multiblock_index(base, grid)` accept a ++ `DenseDistributed` (slab / pencil / brick). The format is the Dense one (legacy BINARY ++ `STRUCTURED_POINTS`, one `.rank` shard per rank, `.vtm` index written by rank 0); a shard is ++ the rank's owned bounding box (`DIMENSIONS` = owned extent, `ORIGIN` = its global cell offset, ++ `SPACING 1`, halo excluded) and rows are streamed with the real haloed row stride in 4 MiB ++ blocks, where the Dense writer assumes full-width XY planes. A rank that owns no cells writes a ++ placeholder shard (`DIMENSIONS 0 0 0`, no payload) and is not listed in the `.vtm`. The `Dense` ++ path is untouched (`src/io_vtk_distributed.cpp`, `detail/io_vtk_distributed.inl`). Tests: ++ `dense_distributed_host` round-trips shards for slab / pencil / brick / thin / empty-rank layouts ++ through the byte-level writer, decoding the payload with an independent big-endian parser and ++ checking that the shard boxes tile the domain; `dense_distributed_dist` writes, indexes and reads ++ back real GPU fields. ++- **2026-11 — `HaloDistributed` pass barrier is off by default.** The host `stream.wait()` + ++ `MPI_Barrier` between axis passes is now opt-in (`CARBON_HALO_PASS_BARRIER=1`). Every pass is ++ ordered on the exchange stream and intra copies are fenced, so it should not be needed for ++ correctness, and it serialised the host against the GPU, which defeats overlap with interior ++ compute. + - **2026-10 — Extended / TwoWayExtended on the step graph.** Every `OverlapMode` now lowers + through `compile_step_graph_and_lower_`; the legacy in-place `apply_occ_` rewrite and + `compile_assign_streams_and_events_` are gone. `compile_step_graph_occ_` applies the Standard +diff --git a/include/carbon/detail/dense_distributed/span.h b/include/carbon/detail/dense_distributed/span.h +index d886bc3..636006c 100644 +--- a/include/carbon/detail/dense_distributed/span.h ++++ b/include/carbon/detail/dense_distributed/span.h +@@ -153,9 +153,18 @@ public: + * - @c Standard: @c logic_extent(). Covers every owned cell exactly once. + * - @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: legacy z-only chunks ( @c halo.x == halo.y == 0 ) use the compact +- * @c 2 * halo.z z-band domain; multi-axis chunks iterate the full owned extent and +- * @ref set_and_validate rejects interior cells. ++ * - @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 ++ * 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 ++ * Boundary threads are @b not spatial neighbours: a kernel must not assume that thread ++ * @c (ix, iy, iz) addresses cell @c (ix, iy, iz) on this view (Standard and Internal keep ++ * that property). + * + * The ranges are non-overlapping, so dispatching Internal and Boundary back-to-back + * (in any order) writes every owned cell exactly once — same coverage as a single +@@ -175,11 +184,17 @@ public: + return int64_3d{ix > 0 ? ix : 0, iy > 0 ? iy : 0, iz > 0 ? iz : 0}; + } + +- case ::carbon::DataView::Boundary: ++ case ::carbon::DataView::Boundary: { + if (halo_.x == 0 && halo_.y == 0) { + return int64_3d{owned.x, owned.y, halo_.z > 0 ? 2 * halo_.z : 0}; + } +- return owned; ++ const int64_t shell = shell_bands_().total; ++ if (shell == 0) { ++ return int64_3d{0, 0, 0}; ++ } ++ const int64_t w = shell >= kShellRowWidth ? kShellRowWidth : shell; ++ return int64_3d{w, (shell + w - 1) / w, 1}; ++ } + } + return owned; + } +@@ -326,7 +341,8 @@ public: + * - @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 +- * pass the owned index through and return @c valid=false for interior cells. ++ * 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 +@@ -337,6 +353,95 @@ public: + int64_t ix, + int64_t iy, + int64_t iz) const noexcept -> ValidatedIdx; ++ ++private: ++ /** Row width of the 2-D Boundary launch box (two full 64-wide blocks per row). */ ++ static constexpr int64_t kShellRowWidth = 128; ++ ++ /** ++ * The Boundary shell as six disjoint boxes over the owned extent. Per axis the low / high band ++ * thickness is clamped so the two never overlap (a chunk thinner than @c 2 * halo is shell ++ * entirely and @c Internal is empty). Box order: Z-low, Z-high (full XY); Y-low, Y-high ++ * (full X, middle Z); X-low, X-high (middle Y, middle Z). ++ */ ++ struct ShellBands { ++ int64_3d lo{}; ++ int64_3d hi{}; ++ int64_t vol[6]{}; ++ int64_t total{0}; ++ }; ++ ++ [[nodiscard]] CARBON_HD constexpr auto ++ shell_bands_() const noexcept -> ShellBands { ++ const int64_3d n = logic_extent(); ++ ShellBands b; ++ b.lo = int64_3d{halo_.x < n.x ? halo_.x : n.x, halo_.y < n.y ? halo_.y : n.y, ++ halo_.z < n.z ? halo_.z : n.z}; ++ const int64_t rx = n.x - b.lo.x; ++ const int64_t ry = n.y - b.lo.y; ++ const int64_t rz = n.z - b.lo.z; ++ b.hi = int64_3d{halo_.x < rx ? halo_.x : rx, halo_.y < ry ? halo_.y : ry, ++ halo_.z < rz ? halo_.z : rz}; ++ const int64_t mz = n.z - b.lo.z - b.hi.z; // middle extents (>= 0 by the clamps) ++ const int64_t my = n.y - b.lo.y - b.hi.y; ++ b.vol[0] = n.x * n.y * b.lo.z; ++ b.vol[1] = n.x * n.y * b.hi.z; ++ b.vol[2] = n.x * b.lo.y * mz; ++ b.vol[3] = n.x * b.hi.y * mz; ++ b.vol[4] = b.lo.x * my * mz; ++ b.vol[5] = b.hi.x * my * mz; ++ b.total = b.vol[0] + b.vol[1] + b.vol[2] + b.vol[3] + b.vol[4] + b.vol[5]; ++ return b; ++ } ++ ++ /** Owned-local cell of linear shell index @p t in [0, bands.total); x varies fastest. */ ++ [[nodiscard]] CARBON_HD constexpr auto ++ shell_cell_(const ShellBands& b, ++ int64_t t) const noexcept -> int64_3d { ++ const int64_3d n = logic_extent(); ++ int box = 0; ++ while (box < 5 && t >= b.vol[box]) { ++ t -= b.vol[box]; ++ ++box; ++ } ++ int64_t bx = 0; // box origin ++ int64_t by = 0; ++ int64_t bz = 0; ++ int64_t w = n.x; // box XY footprint ++ int64_t h = n.y; ++ switch (box) { ++ case 0: ++ break; ++ case 1: ++ bz = n.z - b.hi.z; ++ break; ++ case 2: ++ bz = b.lo.z; ++ h = b.lo.y; ++ break; ++ case 3: ++ by = n.y - b.hi.y; ++ bz = b.lo.z; ++ h = b.hi.y; ++ break; ++ case 4: ++ by = b.lo.y; ++ bz = b.lo.z; ++ w = b.lo.x; ++ h = n.y - b.lo.y - b.hi.y; ++ break; ++ default: ++ bx = n.x - b.hi.x; ++ by = b.lo.y; ++ bz = b.lo.z; ++ w = b.hi.x; ++ h = n.y - b.lo.y - b.hi.y; ++ break; ++ } ++ const int64_t x = t % w; ++ const int64_t r = t / w; ++ return int64_3d{bx + x, by + r % h, bz + r / h}; ++ } + }; + + [[nodiscard]] CARBON_HD constexpr auto +@@ -389,13 +494,15 @@ Span::set_and_validate(::carbon::DataView view, + return ValidatedIdx{Idx(ix, iy, bz), true}; + } + +- const int64_3d owned = logic_extent(); +- const bool internal = ix >= halo_.x && ix < owned.x - halo_.x && iy >= halo_.y && +- iy < owned.y - halo_.y && iz >= halo_.z && iz < owned.z - halo_.z; +- if (internal) { ++ // Compact shell: thread (ix, iy) is the linear shell index t (iz is 0 by the range check ++ // above); the padded tail of the last row is invalid. ++ const ShellBands bands = shell_bands_(); ++ const int64_t t = iy * ext.x + ix; ++ if (t >= bands.total) { + return ValidatedIdx{Idx{}, false}; + } +- return ValidatedIdx{Idx(halo_.x + ix, halo_.y + iy, halo_.z + iz), true}; ++ const int64_3d c = shell_cell_(bands, t); ++ return ValidatedIdx{Idx(halo_.x + c.x, halo_.y + c.y, halo_.z + c.z), true}; + } + } + return ValidatedIdx{Idx{}, false}; +diff --git a/include/carbon/detail/io_vtk_distributed.inl b/include/carbon/detail/io_vtk_distributed.inl +new file mode 100644 +index 0000000..33fc51a +--- /dev/null ++++ b/include/carbon/detail/io_vtk_distributed.inl +@@ -0,0 +1,313 @@ ++// io_vtk_distributed.inl — VTK legacy backend for carbon::DenseDistributed, split out of ++// . Tail include of io.h (see io_vtk.inl for the include-context contract); not a ++// standalone header. ++// ++// Same on-disk format as the Dense backend (legacy BINARY STRUCTURED_POINTS, one `.rank` shard ++// per rank under MPI, `.vtm` multiblock index written by rank 0), generalised from "full XY ++// planes, z-slab" to "the rank's owned bounding box": ++// ++// # vtk DataFile Version 3.0 ++// carbon dense field shard ++// BINARY ++// DATASET STRUCTURED_POINTS ++// DIMENSIONS // the rank's owned box (halo excluded) ++// ORIGIN // global index of the box's first cell ++// SPACING 1 1 1 // index space, same as the Dense writer ++// POINT_DATA ++// SCALARS ++// LOOKUP_TABLE default ++// ++// ++// A rank that owns no cells (global extent smaller than the process grid on some axis) writes a ++// placeholder shard: valid header with `DIMENSIONS 0 0 0` / `POINT_DATA 0` and each SCALARS ++// header without payload, so every rank leaves exactly one file. The `.vtm` index lists only the ++// non-empty shards (there is nothing to display for the others). ++// ++// Index space (SPACING 1, ORIGIN in cells) is deliberate: it is what the Dense writer/reader use, ++// costs nothing extra to write, and keeps shards of both grid families interchangeable in ++// ParaView. The span's physical origin/spacing are not applied. ++namespace detail { ++ ++/** Pointer-parametrised block of owned cells inside a haloed per-GPU buffer. */ ++template ++struct VtkBoxPieceT { ++ /** First @b owned cell of component 0. */ ++ P start{}; ++ /** Owned extent of the block. */ ++ int64_t nx{0}; ++ int64_t ny{0}; ++ int64_t nz{0}; ++ /** Elements between consecutive rows (the haloed x extent). */ ++ int64_t row_stride{0}; ++ /** Elements between consecutive z planes. */ ++ int64_t plane_pitch{0}; ++ /** Elements between consecutive components. */ ++ int64_t comp_stride{0}; ++}; ++using VtkBoxPiece = VtkBoxPieceT; ++using VtkBoxPieceMut = VtkBoxPieceT; ++ ++/** Bounding box of one rank's shard in global index space; all-zero @c dims means "empty". */ ++struct VtkBox { ++ int64_t dims[3] = {0, 0, 0}; ++ int64_t origin[3] = {0, 0, 0}; ++ ++ [[nodiscard]] auto ++ empty() const noexcept -> bool { ++ return dims[0] <= 0 || dims[1] <= 0 || dims[2] <= 0; ++ } ++ [[nodiscard]] auto ++ points() const noexcept -> int64_t { ++ return empty() ? 0 : dims[0] * dims[1] * dims[2]; ++ } ++}; ++ ++/** Per-SCALARS record found while parsing a shard header. */ ++struct VtkBoxFieldRecord { ++ std::string name; ++ std::string vtk_dtype; ++ int components = 0; ++ std::streampos payload_offset = 0; ++}; ++ ++/** ++ * The shard box of @p grid on this rank: the union of its local spans' owned cells. Single-GPU ++ * ranks give their span's owned box; a single-process multi-GPU slab stacks the per-GPU z ranges. ++ * Throws @c std::invalid_argument if the local spans do not form one box. A rank owning no cells ++ * returns an empty box whose @c origin is still the global index of its (empty) owned region. ++ */ ++[[nodiscard]] CARBON_API auto ++vtk_box_of(const DenseDistributed& grid) -> VtkBox; ++ ++// ---- stream-level building blocks (what the session and the unit tests share) --------------- ++ ++/** Write the legacy header for @p box (placeholder header when @c box.empty()). */ ++CARBON_API void ++write_vtk_box_header(std::ostream& out, ++ const VtkBox& box); ++ ++/** ++ * Write one SCALARS block: header line, LOOKUP_TABLE, then (unless @p box is empty) the payload ++ * gathered from @p pieces, in file order, as big-endian component-fastest records. ++ */ ++CARBON_API void ++write_vtk_box_field(std::ostream& out, ++ std::string_view name, ++ const char* dtype_tag, ++ size_t element_size, ++ int components, ++ const VtkBox& box, ++ const std::vector& pieces); ++ ++/** ++ * Parse a shard header and record every SCALARS block. DIMENSIONS / ORIGIN / POINT_DATA must match ++ * @p expected (an empty @p expected requires the placeholder form); SPACING must be unit. ++ */ ++CARBON_API void ++parse_vtk_box_header(std::istream& in, ++ std::string_view path, ++ const VtkBox& expected, ++ std::vector& out_fields); ++ ++/** Read one field's payload (stream already positioned) and scatter it into @p pieces. */ ++CARBON_API void ++read_vtk_box_field_payload(std::istream& in, ++ size_t element_size, ++ int components, ++ const VtkBox& box, ++ const std::vector& pieces); ++ ++/** Per-rank VTK shard session for a @c DenseDistributed grid. */ ++class CARBON_API VtkBoxSession { ++public: ++ VtkBoxSession() noexcept; ++ ~VtkBoxSession(); ++ VtkBoxSession(const VtkBoxSession&) = delete; ++ auto ++ operator=(const VtkBoxSession&) -> VtkBoxSession& = delete; ++ VtkBoxSession(VtkBoxSession&&) noexcept; ++ auto ++ operator=(VtkBoxSession&&) noexcept -> VtkBoxSession&; ++ ++ void ++ open_for_write(std::string_view path, ++ const DenseDistributed& grid, ++ std::uint32_t num_fields); ++ void ++ open_for_read(std::string_view path, ++ const DenseDistributed& grid); ++ ++ void ++ write_field(std::string_view name, ++ const char* dtype_tag, ++ size_t element_size, ++ int components, ++ const std::vector& pieces); ++ void ++ read_field(std::string_view name, ++ const char* dtype_tag, ++ size_t element_size, ++ int components, ++ const std::vector& pieces); ++ ++ [[nodiscard]] auto ++ num_fields() const noexcept -> std::uint32_t; ++ ++ [[nodiscard]] static auto ++ shard_path(std::string_view base, ++ const DenseDistributed& grid) -> std::string; ++ ++private: ++ struct Impl; ++ std::unique_ptr impl_; ++}; ++ ++/** ++ * Owned-cell blocks of @p field, one per local span (the host mirror, halo excluded). Const ++ * variant for writers, mutable variant for readers. ++ */ ++template ++void ++collect_vtk_pieces(const DenseDistributed& grid, ++ const DenseDistributed::Field& field, ++ std::vector& pieces, ++ std::string_view callsite) { ++ const auto& spans = grid.spans(); ++ if (field.cpu_buffers().size() != spans.size()) { ++ log::throw_with_log( ++ "{}: field has no host mirror (cpu_buffers().size()={}, gpu_count={}); construct the field " ++ "with MemorySide::Host or HostDevice and download from device before writing", ++ callsite, field.cpu_buffers().size(), spans.size()); ++ } ++ pieces.clear(); ++ for (size_t g = 0; g < spans.size(); ++g) { ++ const auto& span = spans[g]; ++ const int64_3d owned = span.logic_extent(); ++ if (owned.x <= 0 || owned.y <= 0 || owned.z <= 0) { ++ continue; ++ } ++ const int64_3d halo = span.halo(); ++ VtkBoxPiece p; ++ p.row_stride = span.haloed_extent().x; ++ p.plane_pitch = span.xy_slab_elements(); ++ p.comp_stride = span.linear_storage_elements(); ++ p.nx = owned.x; ++ p.ny = owned.y; ++ p.nz = owned.z; ++ p.start = static_cast(field.cpu_buffers()[g].data() + halo.z * p.plane_pitch + ++ halo.y * p.row_stride + halo.x); ++ pieces.push_back(p); ++ } ++} ++ ++template ++void ++collect_vtk_pieces_mut(const DenseDistributed& grid, ++ DenseDistributed::Field& field, ++ std::vector& pieces, ++ std::string_view callsite) { ++ const auto& spans = grid.spans(); ++ if (field.cpu_buffers().size() != spans.size()) { ++ log::throw_with_log( ++ "{}: field has no host mirror (cpu_buffers().size()={}, gpu_count={}); construct the field " ++ "with MemorySide::Host or HostDevice before reading", ++ callsite, field.cpu_buffers().size(), spans.size()); ++ } ++ pieces.clear(); ++ for (size_t g = 0; g < spans.size(); ++g) { ++ const auto& span = spans[g]; ++ const int64_3d owned = span.logic_extent(); ++ if (owned.x <= 0 || owned.y <= 0 || owned.z <= 0) { ++ continue; ++ } ++ const int64_3d halo = span.halo(); ++ VtkBoxPieceMut p; ++ p.row_stride = span.haloed_extent().x; ++ p.plane_pitch = span.xy_slab_elements(); ++ p.comp_stride = span.linear_storage_elements(); ++ p.nx = owned.x; ++ p.ny = owned.y; ++ p.nz = owned.z; ++ p.start = static_cast(field.cpu_buffers()[g].data() + halo.z * p.plane_pitch + ++ halo.y * p.row_stride + halo.x); ++ pieces.push_back(p); ++ } ++} ++ ++} // namespace detail ++ ++/** ++ * Write @p fields (host mirrors, halo excluded) of @p grid as one legacy BINARY VTK shard per ++ * rank (`.rank` under MPI, `` otherwise). Works for every decomposition ++ * (slab / pencil / brick). Download device data to the host mirror first. Call ++ * @ref write_vtk_multiblock_index afterwards (any rank may call it; rank 0 writes) to get a ++ * single `.vtm` that ParaView opens as one multiblock dataset. ++ */ ++template ++void ++write_vtk(std::string_view path, ++ const DenseDistributed& grid, ++ const Fields&... fields) { ++ detail::VtkBoxSession sess; ++ sess.open_for_write(path, grid, static_cast(sizeof...(Fields))); ++ size_t i = 0; ++ ( ++ [&] { ++ using FieldT = std::remove_cv_t>; ++ using ScalarT = typename FieldT::value_type; ++ constexpr int kComponents = FieldT::components; ++ std::vector pieces; ++ detail::collect_vtk_pieces(grid, fields, pieces, "io::write_vtk"); ++ const std::string& field_name = fields.name(); ++ std::string vtk_name = field_name.empty() ? ("field_" + std::to_string(i)) : field_name; ++ sess.write_field(vtk_name, detail::native_dtype_tag(), sizeof(ScalarT), ++ kComponents, pieces); ++ ++i; ++ }(), ++ ...); ++} ++ ++/** ++ * Read @p fields of @p grid from the shard @ref write_vtk wrote for this rank. DIMENSIONS and ++ * ORIGIN must match this rank's owned box; fields bind by ordinal. Only owned cells are touched ++ * (halo cells keep their contents). ++ */ ++template ++void ++read_vtk(std::string_view path, ++ const DenseDistributed& grid, ++ Fields&... fields) { ++ detail::VtkBoxSession sess; ++ sess.open_for_read(path, grid); ++ if (sess.num_fields() != sizeof...(Fields)) { ++ log::throw_with_log( ++ "io::read_vtk: file '{}' has {} fields, but {} were passed to read", path, ++ sess.num_fields(), sizeof...(Fields)); ++ } ++ size_t i = 0; ++ ( ++ [&] { ++ using FieldT = std::remove_cv_t>; ++ using ScalarT = typename FieldT::value_type; ++ constexpr int kComponents = FieldT::components; ++ std::vector pieces; ++ detail::collect_vtk_pieces_mut(grid, fields, pieces, "io::read_vtk"); ++ sess.read_field("field_" + std::to_string(i), detail::native_dtype_tag(), ++ sizeof(ScalarT), kComponents, pieces); ++ ++i; ++ }(), ++ ...); ++} ++ ++/** ++ * Write `.vtm`, a vtkMultiBlockDataSet index over the per-rank shards of ++ * @ref write_vtk, so ParaView opens the whole decomposed domain at once. Only rank 0 writes; ++ * ranks that own no cells are not listed. No-op without a distributed System. ++ */ ++CARBON_API auto ++write_vtk_multiblock_index(std::string_view base, ++ const DenseDistributed& grid) -> void; +diff --git a/include/carbon/io.h b/include/carbon/io.h +index 5a27547..fb88817 100644 +--- a/include/carbon/io.h ++++ b/include/carbon/io.h +@@ -2,8 +2,10 @@ + + #include + #include ++#include + #include + #include ++#include + #include + #include + +@@ -11,7 +13,9 @@ + #include + #include + #include ++#include + #include ++#include + #include + #include + #include +@@ -29,7 +33,9 @@ + * @code + * carbon::io::write_native(path, grid, field_a, field_b, ...); + * carbon::io::read_native (path, grid, field_a, field_b, ...); +- * // VTK / HDF5 / nanoVDB are Dense-only today. ++ * // VTK / HDF5 / nanoVDB are Dense-only today, except VTK, which also accepts a ++ * // DenseDistributed (slab / pencil / brick): write_vtk / read_vtk / ++ * // write_vtk_multiblock_index overloads in detail/io_vtk_distributed.inl. + * @endcode + * + * Both @c Dense and @c DenseDisg share the same on-disk file format: the file header +@@ -579,6 +585,7 @@ collect_field_views_mut(const Dense& dense, + #include + #include + #include ++#include + + namespace detail { + +diff --git a/src/io_vtk_distributed.cpp b/src/io_vtk_distributed.cpp +new file mode 100644 +index 0000000..099c340 +--- /dev/null ++++ b/src/io_vtk_distributed.cpp +@@ -0,0 +1,832 @@ ++// VTK legacy backend for carbon::DenseDistributed (slab / pencil / brick). See ++// include/carbon/detail/io_vtk_distributed.inl for the on-disk format and the public surface. ++// ++// The helpers below (byte order, dtype keywords, header parsing) intentionally mirror the Dense ++// backend in io_vtk.cpp instead of sharing it, so the Dense path stays byte-for-byte untouched. ++// What differs is the geometry: a shard is the rank's owned *box* (DIMENSIONS = owned extent, ++// ORIGIN = global index of its first cell) and rows are read/written with the real haloed row ++// stride instead of assuming full-width XY planes. ++ ++#include ++#include ++#include ++#include ++ ++#ifdef CARBON_HAVE_MPI_NCCL ++#include ++#endif ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace carbon::io::detail { ++ ++namespace { ++ ++namespace dd = ::carbon::detail::dense_distributed; ++ ++/** Staging block for payload I/O: rows are batched so the stream sees few, large transfers. */ ++constexpr size_t kBlockBytes = size_t{4} << 20; ++ ++[[nodiscard]] constexpr auto ++host_is_little_endian() noexcept -> bool { ++ return std::endian::native == std::endian::little; ++} ++ ++/** Reverse the bytes of @p n consecutive @c ES -byte elements (legacy VTK payloads are BE). */ ++template ++void ++swap_run(std::uint8_t* p, ++ size_t n) noexcept { ++ if constexpr (ES > 1) { ++ for (size_t i = 0; i < n; ++i) { ++ std::uint8_t* e = p + i * ES; ++ for (size_t k = 0; k < ES / 2; ++k) { ++ std::swap(e[k], e[ES - 1 - k]); ++ } ++ } ++ } ++} ++ ++/** Map a carbon native dtype tag (8-char, NUL padded) to the VTK legacy keyword; null if unknown. */ ++[[nodiscard]] auto ++vtk_keyword_from_native_tag(const char* tag) noexcept -> const char* { ++ const std::string_view t(tag, 8); ++ if (t.starts_with("f32")) { ++ return "float"; ++ } ++ if (t.starts_with("f64")) { ++ return "double"; ++ } ++ if (t.starts_with("i8")) { ++ return "char"; ++ } ++ if (t.starts_with("u8")) { ++ return "unsigned_char"; ++ } ++ if (t.starts_with("i16")) { ++ return "short"; ++ } ++ if (t.starts_with("u16")) { ++ return "unsigned_short"; ++ } ++ if (t.starts_with("i32")) { ++ return "int"; ++ } ++ if (t.starts_with("u32")) { ++ return "unsigned_int"; ++ } ++ if (t.starts_with("i64")) { ++ return "vtktypeint64"; ++ } ++ if (t.starts_with("u64")) { ++ return "vtktypeuint64"; ++ } ++ return nullptr; ++} ++ ++[[nodiscard]] auto ++element_size_of_keyword(const std::string& kw) noexcept -> size_t { ++ if (kw == "char" || kw == "unsigned_char") { ++ return 1; ++ } ++ if (kw == "short" || kw == "unsigned_short") { ++ return 2; ++ } ++ if (kw == "int" || kw == "unsigned_int" || kw == "float") { ++ return 4; ++ } ++ if (kw == "double" || kw == "vtktypeint64" || kw == "vtktypeuint64" || kw == "long" || ++ kw == "unsigned_long") { ++ return 8; ++ } ++ return 0; ++} ++ ++void ++rtrim_inplace(std::string& s) noexcept { ++ while (!s.empty() && (s.back() == '\r' || s.back() == ' ' || s.back() == '\t')) { ++ s.pop_back(); ++ } ++} ++ ++/** Legacy SCALARS names are whitespace-delimited tokens: make the label a single token. */ ++[[nodiscard]] auto ++sanitize_name(std::string_view name) -> std::string { ++ std::string out(name); ++ for (char& c : out) { ++ if (c == ' ' || c == '\t' || c == '\r' || c == '\n') { ++ c = '_'; ++ } ++ } ++ return out.empty() ? std::string("field") : out; ++} ++ ++[[nodiscard]] auto ++shard_path_of(std::string_view base, ++ const DenseDistributed& grid) -> std::string { ++#ifdef CARBON_HAVE_MPI_NCCL ++ if (grid.system().distributed() != nullptr) { ++ std::ostringstream oss; ++ oss << base << ".rank" << grid.system().distributed()->world_rank(); ++ return oss.str(); ++ } ++#else ++ (void)grid; ++#endif ++ return std::string(base); ++} ++ ++[[nodiscard]] auto ++pieces_cells(const std::vector& pieces) -> int64_t { ++ int64_t n = 0; ++ for (const auto& p : pieces) { ++ n += p.nx * p.ny * p.nz; ++ } ++ return n; ++} ++ ++// ---- payload gather / scatter (compile-time element size) ---------------------------------- ++ ++/** One owned row of @p nx cells -> interleaved (component-fastest) record bytes. */ ++template ++void ++gather_row(std::uint8_t* dst, ++ const std::uint8_t* src, ++ int64_t nx, ++ int comps, ++ int64_t comp_stride_elems) noexcept { ++ if (comps == 1) { ++ std::memcpy(dst, src, static_cast(nx) * ES); ++ return; ++ } ++ const size_t stride = static_cast(comps) * ES; ++ for (int c = 0; c < comps; ++c) { ++ const std::uint8_t* s = src + static_cast(c * comp_stride_elems) * ES; ++ std::uint8_t* d = dst + static_cast(c) * ES; ++ for (int64_t x = 0; x < nx; ++x) { ++ std::memcpy(d + static_cast(x) * stride, s + static_cast(x) * ES, ES); ++ } ++ } ++} ++ ++/** Interleaved record bytes -> one owned row (inverse of @ref gather_row). */ ++template ++void ++scatter_row(std::uint8_t* dst, ++ const std::uint8_t* src, ++ int64_t nx, ++ int comps, ++ int64_t comp_stride_elems) noexcept { ++ if (comps == 1) { ++ std::memcpy(dst, src, static_cast(nx) * ES); ++ return; ++ } ++ const size_t stride = static_cast(comps) * ES; ++ for (int c = 0; c < comps; ++c) { ++ std::uint8_t* d = dst + static_cast(c * comp_stride_elems) * ES; ++ const std::uint8_t* s = src + static_cast(c) * ES; ++ for (int64_t x = 0; x < nx; ++x) { ++ std::memcpy(d + static_cast(x) * ES, s + static_cast(x) * stride, ES); ++ } ++ } ++} ++ ++[[nodiscard]] inline auto ++row_ptr(const VtkBoxPiece& p, ++ size_t es, ++ int64_t z, ++ int64_t y) noexcept -> const std::uint8_t* { ++ return static_cast(p.start) + ++ static_cast(z * p.plane_pitch + y * p.row_stride) * es; ++} ++ ++[[nodiscard]] inline auto ++row_ptr(const VtkBoxPieceMut& p, ++ size_t es, ++ int64_t z, ++ int64_t y) noexcept -> std::uint8_t* { ++ return static_cast(p.start) + ++ static_cast(z * p.plane_pitch + y * p.row_stride) * es; ++} ++ ++template ++void ++write_payload(std::ostream& out, ++ int comps, ++ const std::vector& pieces) { ++ size_t total_bytes = 0; ++ size_t max_row_bytes = 0; ++ for (const auto& p : pieces) { ++ const size_t row = static_cast(p.nx) * static_cast(comps) * ES; ++ total_bytes += row * static_cast(p.ny) * static_cast(p.nz); ++ max_row_bytes = std::max(max_row_bytes, row); ++ } ++ if (total_bytes == 0) { ++ return; ++ } ++ std::vector block(std::max(std::min(total_bytes, kBlockBytes), max_row_bytes)); ++ size_t used = 0; ++ const auto flush = [&] { ++ if (used == 0) { ++ return; ++ } ++ if (host_is_little_endian()) { ++ swap_run(block.data(), used / ES); ++ } ++ out.write(reinterpret_cast(block.data()), static_cast(used)); ++ used = 0; ++ }; ++ for (const auto& p : pieces) { ++ const size_t row_bytes = static_cast(p.nx) * static_cast(comps) * ES; ++ for (int64_t z = 0; z < p.nz; ++z) { ++ for (int64_t y = 0; y < p.ny; ++y) { ++ if (used + row_bytes > block.size()) { ++ flush(); ++ } ++ gather_row(block.data() + used, row_ptr(p, ES, z, y), p.nx, comps, p.comp_stride); ++ used += row_bytes; ++ } ++ } ++ } ++ flush(); ++} ++ ++template ++void ++read_payload(std::istream& in, ++ int comps, ++ const std::vector& pieces) { ++ size_t max_row_bytes = 0; ++ size_t total_bytes = 0; ++ for (const auto& p : pieces) { ++ const size_t row = static_cast(p.nx) * static_cast(comps) * ES; ++ max_row_bytes = std::max(max_row_bytes, row); ++ total_bytes += row * static_cast(p.ny) * static_cast(p.nz); ++ } ++ if (total_bytes == 0) { ++ return; ++ } ++ std::vector block(std::max(std::min(total_bytes, kBlockBytes), max_row_bytes)); ++ for (const auto& p : pieces) { ++ const size_t row_bytes = static_cast(p.nx) * static_cast(comps) * ES; ++ const int64_t rows_total = p.ny * p.nz; ++ const int64_t rows_per_block = static_cast(block.size() / row_bytes); ++ for (int64_t r0 = 0; r0 < rows_total; r0 += rows_per_block) { ++ const int64_t rows = std::min(rows_per_block, rows_total - r0); ++ const size_t bytes = static_cast(rows) * row_bytes; ++ in.read(reinterpret_cast(block.data()), static_cast(bytes)); ++ if (!in.good()) { ++ log::throw_with_log( ++ "io::read_vtk: short read in payload (row {} of {})", r0, rows_total); ++ } ++ if (host_is_little_endian()) { ++ swap_run(block.data(), bytes / ES); ++ } ++ for (int64_t i = 0; i < rows; ++i) { ++ const int64_t r = r0 + i; ++ scatter_row(row_ptr(p, ES, r / p.ny, r % p.ny), ++ block.data() + static_cast(i) * row_bytes, p.nx, comps, ++ p.comp_stride); ++ } ++ } ++ } ++} ++ ++} // namespace ++ ++// ================================================================================================ ++// Box geometry ++// ================================================================================================ ++ ++auto ++vtk_box_of(const DenseDistributed& grid) -> VtkBox { ++ VtkBox box; ++ const auto& spans = grid.spans(); ++ if (spans.empty()) { ++ return box; ++ } ++ // Global index of the first owned cell of a span = buffer origin + halo. ++ const auto owned_origin = [](const auto& span) -> int64_3d { ++ const int64_3d o = span.offset(); ++ const int64_3d h = span.halo(); ++ return int64_3d{o.x + h.x, o.y + h.y, o.z + h.z}; ++ }; ++ const int64_3d first = owned_origin(spans.front()); ++ box.origin[0] = first.x; ++ box.origin[1] = first.y; ++ box.origin[2] = first.z; ++ ++ int64_t z_total = 0; ++ int64_3d prev_origin{}; ++ int64_t prev_nz = 0; ++ bool have_prev = false; ++ int64_t nx = 0; ++ int64_t ny = 0; ++ for (const auto& span : spans) { ++ const int64_3d owned = span.logic_extent(); ++ if (owned.x <= 0 || owned.y <= 0 || owned.z <= 0) { ++ continue; // this GPU owns nothing ++ } ++ const int64_3d o = owned_origin(span); ++ if (!have_prev) { ++ nx = owned.x; ++ ny = owned.y; ++ box.origin[0] = o.x; ++ box.origin[1] = o.y; ++ box.origin[2] = o.z; ++ } else if (owned.x != nx || owned.y != ny || o.x != prev_origin.x || o.y != prev_origin.y || ++ o.z != prev_origin.z + prev_nz) { ++ log::throw_with_log( ++ "io::vtk: the local spans of this DenseDistributed do not form a single box (only a " ++ "z-stacked slab can span several local GPUs)"); ++ } ++ z_total += owned.z; ++ prev_origin = o; ++ prev_nz = owned.z; ++ have_prev = true; ++ } ++ if (have_prev) { ++ box.dims[0] = nx; ++ box.dims[1] = ny; ++ box.dims[2] = z_total; ++ } ++ return box; ++} ++ ++// ================================================================================================ ++// Stream-level building blocks ++// ================================================================================================ ++ ++void ++write_vtk_box_header(std::ostream& out, ++ const VtkBox& box) { ++ const bool empty = box.empty(); ++ out << "# vtk DataFile Version 3.0\n"; ++ out << (empty ? "carbon dense field shard (empty: this rank owns no cells)\n" ++ : "carbon dense field shard\n"); ++ out << "BINARY\n"; ++ out << "DATASET STRUCTURED_POINTS\n"; ++ out << "DIMENSIONS " << (empty ? 0 : box.dims[0]) << ' ' << (empty ? 0 : box.dims[1]) << ' ' ++ << (empty ? 0 : box.dims[2]) << '\n'; ++ out << "ORIGIN " << box.origin[0] << ' ' << box.origin[1] << ' ' << box.origin[2] << '\n'; ++ out << "SPACING 1 1 1\n"; ++ out << "POINT_DATA " << box.points() << '\n'; ++ if (!out.good()) { ++ log::throw_with_log("io::write_vtk: failed to write the shard header"); ++ } ++} ++ ++void ++write_vtk_box_field(std::ostream& out, ++ std::string_view name, ++ const char* dtype_tag, ++ size_t element_size, ++ int components, ++ const VtkBox& box, ++ const std::vector& pieces) { ++ const char* kw = vtk_keyword_from_native_tag(dtype_tag); ++ if (kw == nullptr) { ++ log::throw_with_log( ++ "io::write_vtk: field '{}' has a dtype VTK legacy cannot express", name); ++ } ++ if (components < 1 || components > 4) { ++ log::throw_with_log( ++ "io::write_vtk: field '{}' has {} components (legacy VTK SCALARS supports 1..4)", name, ++ components); ++ } ++ if (!box.empty()) { ++ if (pieces_cells(pieces) != box.points()) { ++ log::throw_with_log( ++ "io::write_vtk: field '{}' pieces hold {} cells but the shard box has {}", name, ++ pieces_cells(pieces), box.points()); ++ } ++ for (const auto& p : pieces) { ++ if (p.nx != box.dims[0] || p.ny != box.dims[1]) { ++ log::throw_with_log( ++ "io::write_vtk: field '{}' piece ({}x{}) does not match the shard box ({}x{})", name, ++ p.nx, p.ny, box.dims[0], box.dims[1]); ++ } ++ } ++ } ++ out << "SCALARS " << sanitize_name(name) << ' ' << kw << ' ' << components << '\n'; ++ out << "LOOKUP_TABLE default\n"; ++ if (!box.empty()) { ++ switch (element_size) { ++ case 1: ++ write_payload<1>(out, components, pieces); ++ break; ++ case 2: ++ write_payload<2>(out, components, pieces); ++ break; ++ case 4: ++ write_payload<4>(out, components, pieces); ++ break; ++ case 8: ++ write_payload<8>(out, components, pieces); ++ break; ++ default: ++ log::throw_with_log( ++ "io::write_vtk: unsupported element size {} for field '{}'", element_size, name); ++ } ++ } ++ out << '\n'; ++ if (!out.good()) { ++ log::throw_with_log("io::write_vtk: write of field '{}' failed", name); ++ } ++} ++ ++void ++parse_vtk_box_header(std::istream& in, ++ std::string_view path, ++ const VtkBox& expected, ++ std::vector& out_fields) { ++ const auto next_line = [&](bool strict) -> std::string { ++ std::string line; ++ if (!std::getline(in, line)) { ++ if (strict) { ++ log::throw_with_log("io::read_vtk: '{}' ended inside the header", ++ path); ++ } ++ return {}; ++ } ++ rtrim_inplace(line); ++ return line; ++ }; ++ ++ const auto magic = next_line(true); ++ if (magic.rfind("# vtk DataFile Version", 0) != 0) { ++ log::throw_with_log( ++ "io::read_vtk: '{}' does not start with a VTK legacy magic line (got '{}')", path, magic); ++ } ++ next_line(true); // free-form title ++ const auto fmt = next_line(true); ++ if (fmt != "BINARY") { ++ log::throw_with_log( ++ "io::read_vtk: '{}' is '{}' but only BINARY legacy VTK is supported", path, fmt); ++ } ++ const auto ds = next_line(true); ++ if (ds != "DATASET STRUCTURED_POINTS") { ++ log::throw_with_log( ++ "io::read_vtk: '{}' is '{}' but only DATASET STRUCTURED_POINTS is supported", path, ds); ++ } ++ ++ int64_t dims[3] = {0, 0, 0}; ++ int64_t origin[3] = {0, 0, 0}; ++ double spacing[3] = {1.0, 1.0, 1.0}; ++ int64_t point_count = -1; ++ while (point_count < 0) { ++ const auto cur = next_line(true); ++ if (cur.empty()) { ++ continue; ++ } ++ std::istringstream iss(cur); ++ std::string head; ++ iss >> head; ++ if (head == "DIMENSIONS") { ++ iss >> dims[0] >> dims[1] >> dims[2]; ++ } else if (head == "ORIGIN") { ++ iss >> origin[0] >> origin[1] >> origin[2]; ++ } else if (head == "SPACING" || head == "ASPECT_RATIO") { ++ iss >> spacing[0] >> spacing[1] >> spacing[2]; ++ } else if (head == "POINT_DATA") { ++ iss >> point_count; ++ if (point_count < 0) { ++ log::throw_with_log("io::read_vtk: '{}' has a bad POINT_DATA line", ++ path); ++ } ++ } else if (head == "CELL_DATA") { ++ log::throw_with_log( ++ "io::read_vtk: '{}' uses CELL_DATA; carbon writes POINT_DATA only", path); ++ } else { ++ log::throw_with_log( ++ "io::read_vtk: '{}' has unexpected header line '{}'", path, cur); ++ } ++ } ++ ++ // Validate against the box this rank is about to load into. ++ const bool want_empty = expected.empty(); ++ const int64_t want_dims[3] = {want_empty ? 0 : expected.dims[0], ++ want_empty ? 0 : expected.dims[1], ++ want_empty ? 0 : expected.dims[2]}; ++ if (dims[0] != want_dims[0] || dims[1] != want_dims[1] || dims[2] != want_dims[2]) { ++ log::throw_with_log( ++ "io::read_vtk: '{}' DIMENSIONS ({}, {}, {}) do not match this rank's owned box ({}, {}, " ++ "{})", ++ path, dims[0], dims[1], dims[2], want_dims[0], want_dims[1], want_dims[2]); ++ } ++ if (origin[0] != expected.origin[0] || origin[1] != expected.origin[1] || ++ origin[2] != expected.origin[2]) { ++ log::throw_with_log( ++ "io::read_vtk: '{}' ORIGIN ({}, {}, {}) does not match this rank's box origin ({}, {}, {})", ++ path, origin[0], origin[1], origin[2], expected.origin[0], expected.origin[1], ++ expected.origin[2]); ++ } ++ if (spacing[0] != 1.0 || spacing[1] != 1.0 || spacing[2] != 1.0) { ++ log::throw_with_log( ++ "io::read_vtk: '{}' SPACING ({}, {}, {}) is non-unit; carbon uses integer voxel " ++ "coordinates", ++ path, spacing[0], spacing[1], spacing[2]); ++ } ++ if (point_count != expected.points()) { ++ log::throw_with_log( ++ "io::read_vtk: '{}' POINT_DATA {} disagrees with the box size {}", path, point_count, ++ expected.points()); ++ } ++ ++ // Walk the SCALARS blocks, recording each payload offset. ++ while (in) { ++ const auto cur = next_line(false); ++ if (cur.empty()) { ++ if (in.eof()) { ++ break; ++ } ++ continue; ++ } ++ std::istringstream iss(cur); ++ std::string head; ++ iss >> head; ++ if (head != "SCALARS") { ++ log::throw_with_log( ++ "io::read_vtk: unsupported attribute '{}' in '{}'; only SCALARS blocks are accepted", ++ head, path); ++ } ++ VtkBoxFieldRecord rec; ++ iss >> rec.name >> rec.vtk_dtype; ++ rec.components = 1; ++ iss >> rec.components; ++ if (rec.components < 1 || rec.components > 4) { ++ log::throw_with_log( ++ "io::read_vtk: SCALARS '{}' has components={} (legacy VTK supports 1..4)", rec.name, ++ rec.components); ++ } ++ const auto lookup = next_line(true); ++ if (lookup.rfind("LOOKUP_TABLE", 0) != 0) { ++ log::throw_with_log( ++ "io::read_vtk: expected LOOKUP_TABLE after SCALARS '{}', got '{}'", rec.name, lookup); ++ } ++ rec.payload_offset = in.tellg(); ++ if (rec.payload_offset == std::streampos(-1)) { ++ log::throw_with_log( ++ "io::read_vtk: failed to query the stream offset of SCALARS '{}'", rec.name); ++ } ++ const size_t es = element_size_of_keyword(rec.vtk_dtype); ++ if (es == 0) { ++ log::throw_with_log( ++ "io::read_vtk: SCALARS '{}' has dtype '{}' which carbon does not map back", rec.name, ++ rec.vtk_dtype); ++ } ++ in.seekg(rec.payload_offset + static_cast(point_count) * ++ static_cast(rec.components) * ++ static_cast(es)); ++ out_fields.push_back(std::move(rec)); ++ const int next_c = in.peek(); // optional trailing newline after the payload ++ if (next_c == '\n' || next_c == '\r') { ++ in.get(); ++ if (next_c == '\r' && in.peek() == '\n') { ++ in.get(); ++ } ++ } ++ } ++} ++ ++void ++read_vtk_box_field_payload(std::istream& in, ++ size_t element_size, ++ int components, ++ const VtkBox& box, ++ const std::vector& pieces) { ++ if (box.empty()) { ++ return; ++ } ++ int64_t cells = 0; ++ for (const auto& p : pieces) { ++ cells += p.nx * p.ny * p.nz; ++ if (p.nx != box.dims[0] || p.ny != box.dims[1]) { ++ log::throw_with_log( ++ "io::read_vtk: piece ({}x{}) does not match the shard box ({}x{})", p.nx, p.ny, ++ box.dims[0], box.dims[1]); ++ } ++ } ++ if (cells != box.points()) { ++ log::throw_with_log( ++ "io::read_vtk: pieces hold {} cells but the shard box has {}", cells, box.points()); ++ } ++ switch (element_size) { ++ case 1: ++ read_payload<1>(in, components, pieces); ++ break; ++ case 2: ++ read_payload<2>(in, components, pieces); ++ break; ++ case 4: ++ read_payload<4>(in, components, pieces); ++ break; ++ case 8: ++ read_payload<8>(in, components, pieces); ++ break; ++ default: ++ log::throw_with_log("io::read_vtk: unsupported element size {}", ++ element_size); ++ } ++} ++ ++// ================================================================================================ ++// Session ++// ================================================================================================ ++ ++struct VtkBoxSession::Impl { ++ std::string path; ++ bool for_write = false; ++ std::uint32_t num_fields_recorded = 0; ++ VtkBox box; ++ std::ofstream writer; ++ std::ifstream reader; ++ std::vector read_fields; ++ size_t read_fields_cursor = 0; ++}; ++ ++VtkBoxSession::VtkBoxSession() noexcept = default; ++VtkBoxSession::~VtkBoxSession() = default; ++VtkBoxSession::VtkBoxSession(VtkBoxSession&&) noexcept = default; ++auto ++VtkBoxSession::operator=(VtkBoxSession&&) noexcept -> VtkBoxSession& = default; ++ ++auto ++VtkBoxSession::shard_path(std::string_view base, ++ const DenseDistributed& grid) -> std::string { ++ return shard_path_of(base, grid); ++} ++ ++void ++VtkBoxSession::open_for_write(std::string_view path, ++ const DenseDistributed& grid, ++ std::uint32_t /*num_fields*/) { ++ impl_ = std::make_unique(); ++ impl_->path = shard_path_of(path, grid); ++ impl_->for_write = true; ++ impl_->box = vtk_box_of(grid); ++ impl_->writer.open(impl_->path, std::ios::binary | std::ios::trunc); ++ if (!impl_->writer) { ++ log::throw_with_log("io::write_vtk: failed to open '{}' for writing", ++ impl_->path); ++ } ++ write_vtk_box_header(impl_->writer, impl_->box); ++} ++ ++void ++VtkBoxSession::write_field(std::string_view name, ++ const char* dtype_tag, ++ size_t element_size, ++ int components, ++ const std::vector& pieces) { ++ if (impl_ == nullptr || !impl_->for_write) { ++ log::throw_with_log("io::write_vtk: session is not in a writable state"); ++ } ++ write_vtk_box_field(impl_->writer, name, dtype_tag, element_size, components, impl_->box, pieces); ++ ++impl_->num_fields_recorded; ++} ++ ++void ++VtkBoxSession::open_for_read(std::string_view path, ++ const DenseDistributed& grid) { ++ impl_ = std::make_unique(); ++ impl_->path = shard_path_of(path, grid); ++ impl_->for_write = false; ++ impl_->box = vtk_box_of(grid); ++ impl_->reader.open(impl_->path, std::ios::binary); ++ if (!impl_->reader) { ++ log::throw_with_log("io::read_vtk: failed to open '{}' for reading", ++ impl_->path); ++ } ++ parse_vtk_box_header(impl_->reader, impl_->path, impl_->box, impl_->read_fields); ++} ++ ++void ++VtkBoxSession::read_field(std::string_view /*name*/, ++ const char* dtype_tag, ++ size_t element_size, ++ int components, ++ const std::vector& pieces) { ++ if (impl_ == nullptr || impl_->for_write) { ++ log::throw_with_log("io::read_vtk: session is not in a readable state"); ++ } ++ if (impl_->read_fields_cursor >= impl_->read_fields.size()) { ++ log::throw_with_log( ++ "io::read_vtk: more fields requested than '{}' contains", impl_->path); ++ } ++ // Fields bind by ordinal (names differ between writers). ++ const auto& rec = impl_->read_fields[impl_->read_fields_cursor++]; ++ const char* expected_kw = vtk_keyword_from_native_tag(dtype_tag); ++ if (expected_kw == nullptr || rec.vtk_dtype != expected_kw) { ++ log::throw_with_log( ++ "io::read_vtk: field {} dtype '{}' does not match bound carbon dtype '{}' in '{}'", ++ rec.name, rec.vtk_dtype, (expected_kw != nullptr ? expected_kw : "?"), impl_->path); ++ } ++ if (rec.components != components) { ++ log::throw_with_log( ++ "io::read_vtk: field {} has {} components but the bound Field has {}", rec.name, ++ rec.components, components); ++ } ++ impl_->reader.clear(); ++ impl_->reader.seekg(rec.payload_offset); ++ if (!impl_->reader.good()) { ++ log::throw_with_log( ++ "io::read_vtk: seek to the payload of '{}' failed in '{}'", rec.name, impl_->path); ++ } ++ read_vtk_box_field_payload(impl_->reader, element_size, components, impl_->box, pieces); ++} ++ ++auto ++VtkBoxSession::num_fields() const noexcept -> std::uint32_t { ++ if (impl_ == nullptr) { ++ return 0U; ++ } ++ return impl_->for_write ? impl_->num_fields_recorded ++ : static_cast(impl_->read_fields.size()); ++} ++ ++} // namespace carbon::io::detail ++ ++namespace carbon::io { ++ ++auto ++write_vtk_multiblock_index(std::string_view base, ++ const DenseDistributed& grid) -> void { ++#ifdef CARBON_HAVE_MPI_NCCL ++ const auto* dist = grid.system().distributed(); ++ if (dist == nullptr) { ++ return; // single process: the shard at is the whole dataset ++ } ++ const int world_size = dist->world_size(); ++ if (world_size <= 1 || dist->world_rank() != 0) { ++ return; ++ } ++ ++ // Which ranks own cells? Every rank's owned box follows from the global split alone, so the ++ // index needs no communication. Ranks with an empty box wrote a placeholder shard that is not ++ // listed (there is nothing to display). ++ const ProcessGrid& pg = grid.process_grid(); ++ const int64_3d global = grid.global_extent(); ++ std::vector listed; ++ for (int r = 0; r < world_size; ++r) { ++ bool owns = true; ++ if (pg.world_size() == world_size) { ++ const auto chunk = ::carbon::detail::dense_distributed::rank_chunk( ++ global, pg, pg.coords_of(r), int64_3d{0, 0, 0}); ++ owns = chunk.owned.x > 0 && chunk.owned.y > 0 && chunk.owned.z > 0; ++ } ++ if (owns) { ++ listed.push_back(r); ++ } ++ } ++ ++ const std::filesystem::path base_path(std::string{base}); ++ const std::filesystem::path master_path = base_path.string() + ".vtm"; ++ const std::filesystem::path base_filename = base_path.filename(); ++ ++ std::ofstream out(master_path, std::ios::binary | std::ios::trunc); ++ if (!out) { ++ log::throw_with_log( ++ "io::write_vtk_multiblock_index: failed to open '{}' for writing", master_path.string()); ++ } ++ out << "\n"; ++ out << "\n"; ++ out << " \n"; ++ int block = 0; ++ for (const int r : listed) { ++ out << " \n"; ++ out << " \n"; ++ out << " \n"; ++ } ++ out << " \n"; ++ out << "\n"; ++ if (!out.good()) { ++ log::throw_with_log("io::write_vtk_multiblock_index: write to '{}' failed", ++ master_path.string()); ++ } ++#else ++ (void)base; ++ (void)grid; ++#endif ++} ++ ++} // namespace carbon::io +diff --git a/tests/test_dense_distributed_dist.cu b/tests/test_dense_distributed_dist.cu +index ddb48a0..332abdd 100644 +--- a/tests/test_dense_distributed_dist.cu ++++ b/tests/test_dense_distributed_dist.cu +@@ -25,7 +25,15 @@ + // neighbour is outside an open boundary) is compiled into a Skeleton, so the halo kernel is + // auto-inserted from read_stencil and DenseDistributed::Span / Partition run on the device. + // Run once without overlap and once with OverlapMode::Standard, which splits the kernel into +-// Internal + Boundary launches and therefore exercises those Span views for real. ++// Internal + Boundary launches and therefore exercises those Span views for real. (For pencil ++// and brick the Boundary launch is the compact shell, not the full owned extent.) ++// ++// 3. VTK shard I/O. A 3-component float field goes host -> device -> host, is written with ++// io::write_vtk (one `.rank` shard per rank) plus the `.vtm` index, and read back with ++// io::read_vtk into a second field. Each rank checks its own shard header against its owned box ++// (DIMENSIONS / ORIGIN), every owned cell after the round trip, that halo cells were not ++// touched, and rank 0 checks that the index lists every rank. Files are written to the ++// working directory (like test_io_dist) and removed afterwards. + + #include + #include +@@ -34,6 +42,7 @@ + #include + #include + #include ++#include + #include + #include + #include +@@ -47,7 +56,10 @@ + #include + #include + #include ++#include ++#include + #include ++#include + #include + #include + #include +@@ -470,6 +482,164 @@ run_stencil(carbon::System& sys, + return true; + } + ++// ------------------------------------------------------------------------------------------------ ++// Check 3: VTK shard I/O for DenseDistributed (write_vtk / read_vtk / multiblock index). ++// ------------------------------------------------------------------------------------------------ ++ ++[[nodiscard]] auto ++run_vtk(carbon::System& sys, ++ int rank, ++ int world, ++ const ProcessGrid& pg, ++ BoundaryModeDistributed mode, ++ const std::string& label, ++ const int64_3d& global) -> bool { ++ const std::string base = "carbon_test_dense_distributed_vtk_" + label; ++ const std::string shard = base + ".rank" + std::to_string(rank); ++ const std::string index = base + ".vtm"; ++ bool ok = true; ++ try { ++ DenseDistributed grid(sys, global, pg, six_point(), mode); ++ const auto& span = grid.spans()[0]; ++ const int64_3d halo = span.halo(); ++ const int64_3d owned = span.logic_extent(); ++ const int64_3d haloed = span.haloed_extent(); ++ const int64_t pitch = span.xy_slab_elements(); ++ const int64_t per_comp = span.linear_storage_elements(); ++ constexpr int kComps = 3; ++ constexpr float kSentinelIn = -1.0F; ++ constexpr float kSentinelOut = -2.0F; ++ ++ auto f = grid.template newField(carbon::MemorySide::HostDevice, "pop"); ++ auto g = grid.template newField(carbon::MemorySide::HostDevice, "pop_in"); ++ const auto is_owned_cell = [&](int64_t x, int64_t y, int64_t z) -> bool { ++ return x >= halo.x && x < halo.x + owned.x && y >= halo.y && y < halo.y + owned.y && ++ z >= halo.z && z < halo.z + owned.z; ++ }; ++ { ++ float* hf = f.cpu_buffers()[0].data(); ++ float* hg = g.cpu_buffers()[0].data(); ++ for (int64_t z = 0; z < haloed.z; ++z) { ++ for (int64_t y = 0; y < haloed.y; ++y) { ++ for (int64_t x = 0; x < haloed.x; ++x) { ++ const int64_3d gl = span.global_location(span.make_idx(x, y, z)); ++ const int64_t off = z * pitch + y * haloed.x + x; ++ for (int c = 0; c < kComps; ++c) { ++ hf[c * per_comp + off] = is_owned_cell(x, y, z) ++ ? static_cast(encode(gl.x, gl.y, gl.z, c)) ++ : kSentinelIn; ++ hg[c * per_comp + off] = kSentinelOut; ++ } ++ } ++ } ++ } ++ } ++ // host -> device -> host, so the field written is what a real run would download ++ carbon::Stream stream = sys.stream(); ++ carbon::Transfer(sys, f.cpu_buffers(), f.gpu_buffers())(stream); ++ if (!sync_all(stream, "vtk upload")) { ++ return false; ++ } ++ { ++ float* hf = f.cpu_buffers()[0].data(); ++ for (size_t i = 0; i < f.cpu_buffers()[0].size(); ++i) { ++ hf[i] = 0.0F; ++ } ++ } ++ carbon::Transfer(sys, f.gpu_buffers(), f.cpu_buffers())(stream); ++ if (!sync_all(stream, "vtk download")) { ++ return false; ++ } ++ ++ carbon::io::write_vtk(base, grid, f); ++ carbon::io::write_vtk_multiblock_index(base, grid); ++ ++ // --- this rank's shard header must describe its owned box ---------------------------------- ++ { ++ std::ifstream in(shard, std::ios::binary); ++ std::string line; ++ int64_t dims[3] = {-1, -1, -1}; ++ int64_t org[3] = {-1, -1, -1}; ++ while (std::getline(in, line)) { ++ std::istringstream ls(line); ++ std::string head; ++ ls >> head; ++ if (head == "DIMENSIONS") { ++ ls >> dims[0] >> dims[1] >> dims[2]; ++ } else if (head == "ORIGIN") { ++ ls >> org[0] >> org[1] >> org[2]; ++ } else if (head == "SCALARS") { ++ break; ++ } ++ } ++ const int64_3d o0 = span.global_location(span.make_idx(halo.x, halo.y, halo.z)); ++ if (dims[0] != owned.x || dims[1] != owned.y || dims[2] != owned.z || org[0] != o0.x || ++ org[1] != o0.y || org[2] != o0.z) { ++ CARBON_LOG_ERROR( ++ "test_dense_distributed_dist[{}]: rank {} shard header DIMENSIONS=({},{},{}) " ++ "ORIGIN=({},{},{}) want owned=({},{},{}) origin=({},{},{})", ++ label, rank, dims[0], dims[1], dims[2], org[0], org[1], org[2], owned.x, owned.y, ++ owned.z, o0.x, o0.y, o0.z); ++ ok = false; ++ } ++ } ++ ++ // --- rank 0's index lists every rank (all own cells for this extent) ------------------------- ++ if (rank == 0) { ++ std::ifstream in(index); ++ const std::string text((std::istreambuf_iterator(in)), ++ std::istreambuf_iterator()); ++ if (text.find("vtkMultiBlockDataSet") == std::string::npos) { ++ CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: missing/invalid {}", label, index); ++ ok = false; ++ } ++ for (int r = 0; r < world; ++r) { ++ if (text.find("name=\"rank" + std::to_string(r) + "\"") == std::string::npos) { ++ CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: index does not list rank {}", label, ++ r); ++ ok = false; ++ } ++ } ++ } ++ ++ // --- read back into a fresh field: owned == written, halo untouched ---------------------------- ++ carbon::io::read_vtk(base, grid, g); ++ size_t mismatches = 0; ++ const float* hg = g.cpu_buffers()[0].data(); ++ for (int64_t z = 0; z < haloed.z; ++z) { ++ for (int64_t y = 0; y < haloed.y; ++y) { ++ for (int64_t x = 0; x < haloed.x; ++x) { ++ const int64_3d gl = span.global_location(span.make_idx(x, y, z)); ++ const int64_t off = z * pitch + y * haloed.x + x; ++ for (int c = 0; c < kComps; ++c) { ++ const float want = is_owned_cell(x, y, z) ++ ? static_cast(encode(gl.x, gl.y, gl.z, c)) ++ : kSentinelOut; ++ if (hg[c * per_comp + off] != want) { ++ ++mismatches; ++ } ++ } ++ } ++ } ++ } ++ if (mismatches != 0U) { ++ CARBON_LOG_ERROR( ++ "test_dense_distributed_dist[{}]: rank {} VTK round trip has {} wrong values", label, ++ rank, mismatches); ++ ok = false; ++ } ++ } catch (const std::exception& e) { ++ CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: VTK I/O failed: {}", label, e.what()); ++ ok = false; ++ } ++ std::error_code ec; ++ std::filesystem::remove(shard, ec); ++ if (rank == 0) { ++ std::filesystem::remove(index, ec); ++ } ++ return ok; ++} ++ + struct Case { + ProcessGrid pg; + BoundaryModeDistributed mode; +@@ -540,7 +710,8 @@ main() { + !run_stencil(sys, rank, c.pg, c.mode, carbon::OverlapMode::None, + std::string(c.label) + "/stencil", global) || + !run_stencil(sys, rank, c.pg, c.mode, carbon::OverlapMode::Standard, +- std::string(c.label) + "/stencil-overlap", global)) { ++ std::string(c.label) + "/stencil-overlap", 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 079dcd6..21a52b4 100644 +--- a/tests/test_dense_distributed_host.cpp ++++ b/tests/test_dense_distributed_host.cpp +@@ -7,6 +7,10 @@ + // hand-written expectations, the owned boxes must tile the global domain exactly once, and + // the resulting Span must iterate (Standard, Internal + Boundary) and resolve + // neighbours (open vs periodic) correctly. ++// Part D VTK shard I/O (io::detail stream-level writer/reader behind write_vtk / read_vtk for ++// DenseDistributed): byte-level check of the legacy BINARY payload with an independent ++// decoder, library round trip that must leave halo cells untouched, shard boxes that tile ++// the domain exactly once, and the placeholder shard of a rank that owns no cells. + // Part C correctness of the full X -> Y -> Z staged halo exchange on an emulated multi-rank world + // (corners/edges, periodic wraps, uneven splits, self-wrap), driven by the production + // plan builder and checked against the run-based builder (kept as the oracle) and against +@@ -20,16 +24,22 @@ + #include + #include + #include ++#include ++#include + #include + #include + + #include + #include ++#include + #include + #include + #include ++#include + #include + #include ++#include ++#include + #include + #include + +@@ -704,6 +714,23 @@ 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) { ++ // 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 ++ // padded tail is exactly the invalid threads. ++ const auto pos = [](int64_t v) { ++ return v > 0 ? v : 0; ++ }; ++ const int64_t owned_cells = ch.owned.x * ch.owned.y * ch.owned.z; ++ const int64_t internal_cells = pos(ch.owned.x - 2 * halo.x) * ++ pos(ch.owned.y - 2 * halo.y) * ++ pos(ch.owned.z - 2 * halo.z); ++ const int64_t shell = owned_cells - internal_cells; ++ CHECK(e.z == 1 || shell == 0); ++ CHECK(e.x * e.y * e.z >= shell); ++ CHECK(e.x * e.y * e.z < shell + 128); ++ } ++ int64_t valid_threads = 0; + for (int64_t iz = 0; iz < e.z; ++iz) { + for (int64_t iy = 0; iy < e.y; ++iy) { + for (int64_t ix = 0; ix < e.x; ++ix) { +@@ -711,6 +738,7 @@ check_geometry(const GeomCase& c, + if (!v.valid) { + continue; + } ++ ++valid_threads; + const int64_3d cell = v.idx.cell(); + const int64_t lx = cell.x - halo.x; + const int64_t ly = cell.y - halo.y; +@@ -721,6 +749,15 @@ check_geometry(const GeomCase& c, + } + } + } ++ if (view == carbon::DataView::Boundary && !legacy_slab) { ++ // Every valid Boundary thread is a distinct shell cell; the rest of the box is padding. ++ const auto pos = [](int64_t v) { ++ return v > 0 ? v : 0; ++ }; ++ CHECK(valid_threads == ch.owned.x * ch.owned.y * ch.owned.z - ++ pos(ch.owned.x - 2 * halo.x) * pos(ch.owned.y - 2 * halo.y) * ++ pos(ch.owned.z - 2 * halo.z)); ++ } + } + for (const int m : mark) { + CHECK(m == 1); +@@ -820,6 +857,269 @@ part_b_geometry(size_t& cells, + return cases.size(); + } + ++// ------------------------------------------------------------------------------------------------ ++// Part D: VTK shard I/O for DenseDistributed. ++// ------------------------------------------------------------------------------------------------ ++ ++namespace vtk = carbon::io::detail; ++ ++// Injective for extents < 16 and up to 3 components, and it fits in int16. ++auto ++vtk_value(int64_t x, ++ int64_t y, ++ int64_t z, ++ int c) -> int { ++ return static_cast(x + 16 * y + 256 * z + 4096 * c); ++} ++ ++// Independent big-endian decoder (does not use the library's swap code). ++template ++auto ++decode_be(const unsigned char* p) -> T { ++ unsigned char b[sizeof(T)]; ++ for (size_t i = 0; i < sizeof(T); ++i) { ++ b[i] = p[sizeof(T) - 1 - i]; // BE on the wire -> LE host (this test runs on LE hosts) ++ } ++ T v; ++ std::memcpy(&v, b, sizeof(T)); ++ return v; ++} ++ ++struct VtkCase { ++ const char* name; ++ int px, py, pz; ++ BoundaryModeDistributed bm; ++ int64_t gx, gy, gz; ++}; ++ ++template ++auto ++vtk_roundtrip_case(const VtkCase& c, ++ int comps, ++ std::vector& cover, ++ size_t& shards, ++ size_t& empty_shards, ++ size_t& points) -> void { ++ g_ctx = std::string("part D ") + c.name + " T" + std::to_string(sizeof(T)) + " c" + ++ std::to_string(comps); ++ static_assert(std::endian::native == std::endian::little, "decoder assumes a little-endian host"); ++ const ProcessGrid pg = ProcessGrid::custom(c.px * c.py * c.pz, c.px, c.py, c.pz); ++ 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 int64_3d global{c.gx, c.gy, c.gz}; ++ const int64_3d halo = dd::halo_extent(pg, c.bm, stencil); ++ const char* tag = ++ sizeof(T) == 2 ? "i16\0\0\0\0" : (sizeof(T) == 4 ? "i32\0\0\0\0" : "f64\0\0\0\0"); ++ const char* kw = sizeof(T) == 2 ? "short" : (sizeof(T) == 4 ? "int" : "double"); ++ ++ for (int32_t r = 0; r < pg.world_size(); ++r) { ++ const dd::RankChunk ch = dd::rank_chunk(global, pg, pg.coords_of(r), halo); ++ const int64_t per_comp = ch.xy_pitch * ch.haloed.z; ++ const T sentinel = static_cast(-777); ++ std::vector buf(static_cast(per_comp) * static_cast(comps), sentinel); ++ const int64_3d own0{ch.offset.x + halo.x, ch.offset.y + halo.y, ch.offset.z + halo.z}; ++ for (int64_t z = 0; z < ch.owned.z; ++z) { ++ for (int64_t y = 0; y < ch.owned.y; ++y) { ++ for (int64_t x = 0; x < ch.owned.x; ++x) { ++ for (int k = 0; k < comps; ++k) { ++ const int64_t off = ++ (halo.z + z) * ch.xy_pitch + (halo.y + y) * ch.haloed.x + halo.x + x; ++ buf[static_cast(k * per_comp + off)] = ++ static_cast(vtk_value(own0.x + x, own0.y + y, own0.z + z, k)); ++ } ++ } ++ } ++ } ++ ++ vtk::VtkBox box; ++ box.origin[0] = own0.x; ++ box.origin[1] = own0.y; ++ box.origin[2] = own0.z; ++ const bool owns = ch.owned.x > 0 && ch.owned.y > 0 && ch.owned.z > 0; ++ if (owns) { ++ box.dims[0] = ch.owned.x; ++ box.dims[1] = ch.owned.y; ++ box.dims[2] = ch.owned.z; ++ } ++ std::vector pieces; ++ if (owns) { ++ vtk::VtkBoxPiece p; ++ p.start = buf.data() + halo.z * ch.xy_pitch + halo.y * ch.haloed.x + halo.x; ++ p.nx = ch.owned.x; ++ p.ny = ch.owned.y; ++ p.nz = ch.owned.z; ++ p.row_stride = ch.haloed.x; ++ p.plane_pitch = ch.xy_pitch; ++ p.comp_stride = per_comp; ++ pieces.push_back(p); ++ } ++ ++ std::ostringstream os; ++ vtk::write_vtk_box_header(os, box); ++ vtk::write_vtk_box_field(os, "my field", tag, sizeof(T), comps, box, pieces); ++ const std::string bytes = os.str(); ++ ++shards; ++ ++ // --- independent parse of the text header ------------------------------------------------- ++ std::istringstream hs(bytes); ++ std::string line; ++ int64_t dims[3] = {-1, -1, -1}; ++ int64_t org[3] = {-1, -1, -1}; ++ int64_t npts = -1; ++ std::string scal_name; ++ std::string scal_type; ++ int scal_comps = -1; ++ size_t payload_at = 0; ++ while (std::getline(hs, line)) { ++ std::istringstream ls(line); ++ std::string head; ++ ls >> head; ++ if (head == "DIMENSIONS") { ++ ls >> dims[0] >> dims[1] >> dims[2]; ++ } else if (head == "ORIGIN") { ++ ls >> org[0] >> org[1] >> org[2]; ++ } else if (head == "POINT_DATA") { ++ ls >> npts; ++ } else if (head == "SCALARS") { ++ ls >> scal_name >> scal_type >> scal_comps; ++ } else if (head == "LOOKUP_TABLE") { ++ payload_at = static_cast(hs.tellg()); ++ break; ++ } ++ } ++ CHECK(scal_name == "my_field"); // whitespace in the label is made a single token ++ CHECK(scal_type == kw); ++ CHECK(scal_comps == comps); ++ if (!owns) { ++ // Placeholder shard: valid header, no payload, flagged as empty in the title. ++ ++empty_shards; ++ CHECK(dims[0] == 0 && dims[1] == 0 && dims[2] == 0 && npts == 0); ++ CHECK(bytes.size() == payload_at + 1U); // just the newline that ends the SCALARS block ++ CHECK(bytes.find("empty") != std::string::npos); ++ } else { ++ CHECK(dims[0] == ch.owned.x && dims[1] == ch.owned.y && dims[2] == ch.owned.z); ++ CHECK(org[0] == own0.x && org[1] == own0.y && org[2] == own0.z); ++ CHECK(npts == ch.owned.x * ch.owned.y * ch.owned.z); ++ const size_t payload_bytes = ++ static_cast(npts) * static_cast(comps) * sizeof(T); ++ CHECK(bytes.size() == payload_at + payload_bytes + 1U); ++ const auto* raw = reinterpret_cast(bytes.data()) + payload_at; ++ for (int64_t z = 0; z < dims[2]; ++z) { ++ for (int64_t y = 0; y < dims[1]; ++y) { ++ for (int64_t x = 0; x < dims[0]; ++x) { ++ const int64_t pt = (z * dims[1] + y) * dims[0] + x; ++ for (int k = 0; k < comps; ++k) { ++ const T got = ++ decode_be(raw + (static_cast(pt) * static_cast(comps) + ++ static_cast(k)) * ++ sizeof(T)); ++ CHECK(got == static_cast(vtk_value(org[0] + x, org[1] + y, org[2] + z, k))); ++ } ++ } ++ } ++ // tiling bookkeeping (uses only what the header says) ++ } ++ for (int64_t z = 0; z < dims[2]; ++z) { ++ for (int64_t y = 0; y < dims[1]; ++y) { ++ for (int64_t x = 0; x < dims[0]; ++x) { ++ cover[static_cast(((org[2] + z) * c.gy + (org[1] + y)) * c.gx + org[0] + x)] += ++ 1; ++ } ++ } ++ } ++ points += static_cast(npts); ++ } ++ ++ // --- library round trip: owned cells restored, halo cells untouched ------------------------ ++ std::istringstream in(bytes); ++ std::vector recs; ++ vtk::parse_vtk_box_header(in, "mem", box, recs); ++ CHECK(recs.size() == 1U); ++ CHECK(recs[0].components == comps && recs[0].vtk_dtype == kw); ++ const T sentinel2 = static_cast(-555); ++ std::vector back(buf.size(), sentinel2); ++ std::vector mut; ++ if (owns) { ++ vtk::VtkBoxPieceMut m; ++ m.start = back.data() + halo.z * ch.xy_pitch + halo.y * ch.haloed.x + halo.x; ++ m.nx = ch.owned.x; ++ m.ny = ch.owned.y; ++ m.nz = ch.owned.z; ++ m.row_stride = ch.haloed.x; ++ m.plane_pitch = ch.xy_pitch; ++ m.comp_stride = per_comp; ++ mut.push_back(m); ++ } ++ in.clear(); ++ in.seekg(recs[0].payload_offset); ++ vtk::read_vtk_box_field_payload(in, sizeof(T), comps, box, mut); ++ for (int64_t z = 0; z < ch.haloed.z; ++z) { ++ for (int64_t y = 0; y < ch.haloed.y; ++y) { ++ for (int64_t x = 0; x < ch.haloed.x; ++x) { ++ const bool in_owned = x >= halo.x && x < halo.x + ch.owned.x && y >= halo.y && ++ y < halo.y + ch.owned.y && z >= halo.z && z < halo.z + ch.owned.z; ++ for (int k = 0; k < comps; ++k) { ++ const size_t i = ++ static_cast(k * per_comp + z * ch.xy_pitch + y * ch.haloed.x + x); ++ CHECK(in_owned ? back[i] == buf[i] : back[i] == sentinel2); ++ } ++ } ++ } ++ } ++ ++ // --- a shard from a different box must be rejected ----------------------------------------- ++ if (owns) { ++ vtk::VtkBox other = box; ++ other.origin[0] += 1; ++ std::istringstream in2(bytes); ++ std::vector recs2; ++ bool threw = false; ++ carbon::log::set_level(spdlog::level::off); // the library logs the (expected) rejection ++ try { ++ vtk::parse_vtk_box_header(in2, "mem", other, recs2); ++ } catch (const std::invalid_argument&) { ++ threw = true; ++ } ++ carbon::log::set_level(spdlog::level::info); ++ CHECK(threw); ++ } ++ } ++} ++ ++auto ++part_d_vtk(size_t& shards, ++ size_t& empty_shards, ++ size_t& points) -> size_t { ++ constexpr auto kO = BoundaryModeDistributed::Open; ++ constexpr auto kX = BoundaryModeDistributed::PeriodicX; ++ constexpr auto kZ = BoundaryModeDistributed::PeriodicZ; ++ const std::vector cases = { ++ {"slab", 1, 1, 4, kO, 6, 5, 9}, ++ {"slab-periodicZ", 1, 1, 3, kZ, 5, 4, 7}, ++ {"pencil", 1, 2, 2, kO, 6, 7, 8}, ++ {"pencil-periodicX", 1, 2, 2, kX, 5, 6, 4}, ++ {"brick-uneven", 3, 2, 2, kO, 8, 5, 6}, ++ {"brick-thin", 2, 2, 2, kX | kZ, 3, 3, 3}, ++ // 2 layers over 4 z-parts and 1 over 2 y-parts: half of the ranks own no cells. ++ {"brick-empty-ranks", 2, 2, 4, kO, 3, 1, 2}, ++ }; ++ for (const VtkCase& c : cases) { ++ std::vector cover(static_cast(c.gx * c.gy * c.gz), 0); ++ vtk_roundtrip_case(c, 2, cover, shards, empty_shards, points); ++ for (const int m : cover) { ++ CHECK(m == 1); // shard boxes tile the global domain exactly once ++ } ++ // Other element sizes / component counts (tiling already shown above; reuse a scratch map). ++ std::vector scratch32(cover.size(), 0); ++ vtk_roundtrip_case(c, 3, scratch32, shards, empty_shards, points); ++ std::vector scratch64(cover.size(), 0); ++ vtk_roundtrip_case(c, 1, scratch64, shards, empty_shards, points); ++ } ++ CHECK(empty_shards > 0U); // the placeholder path must actually be exercised ++ return cases.size(); ++} ++ + struct Scenario { + const char* name; + int px, py, pz; +@@ -900,6 +1200,13 @@ main() { + std::printf("geometry cases=%zu owned cells checked=%zu neighbour reads checked=%zu\n", + geom_cases, geom_cells, geom_neighbours); + ++ size_t vtk_shards = 0; ++ size_t vtk_empty = 0; ++ size_t vtk_points = 0; ++ const size_t vtk_cases = part_d_vtk(vtk_shards, vtk_empty, vtk_points); ++ std::printf("vtk cases=%zu shards=%zu (placeholders=%zu) points verified=%zu\n", vtk_cases, ++ vtk_shards, vtk_empty, vtk_points); ++ + std::vector sc; + const BoundaryModeDistributed modes[] = { + kOpen, kPX, kPY, kPZ, bm_or(kPX, kPZ), bm_or(bm_or(kPX, kPY), kPZ)}; diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 1f384e78..1f026382 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6046,31 +6046,64 @@ This unblocked the matrix on this host: the `sycl` and `hip-nvidia` images build (and DenseDisg forwarding) compute one centre offset then constant-strided `pull()` neighbours; Jacobi uses it instead of `neighbour()` + a redundant `read()` partition. `Dense` rejects layouts whose `xy_slab_elements` or haloed x extent exceed `int32_t`. New test `test_partition_cursor`. -- **2026-10 — `DenseDistributed`: slab / pencil / brick split out of `Dense`.** `Dense` is back to - its original Z-slab-only implementation (`dense.h`, `dense.cpp`, `detail/dense/{span,field, - partition}.h`, `halo.h`, `detail/halo_build.h` and `boundary_mode.h` are unchanged from before - the decomposition work; `BoundaryMode::PeriodicZ` is `1` again, so `DenseDisg`, `libcarbonpy` - and the Python bindings are untouched). The process-grid decomposition now lives in a sibling - grid family: `carbon::DenseDistributed` (+ `HaloDistributed`, and the per-axis - `BoundaryModeDistributed`, whose `PeriodicX | PeriodicY | PeriodicZ` bits are independent; it - is a separate type so a per-axis mask can never reach a grid that only understands a Z wrap). - It takes a `ProcessGrid` / `DecompositionMode` (default slab) and exposes the same `Span` / - `Partition` / `Field` / kernel / reduce surface as `Dense`, wired through a - `DenseDistributedPolicy` marker in `launch_traits.h` (same mechanism as `DisgPolicy`) and - `Kernel::halo_distributed`; `Idx` is shared with `Dense`. The split / halo-thickness / per-rank - chunk arithmetic is a pure host function set in `detail/dense_distributed/layout.h`, so tests - can exercise the production decomposition without a GPU. The cross-rank NCCL pairing key still - ends with the run index: X/Y halo faces are non-contiguous in the x-fastest buffer, so one face - fans out into many runs sharing the same `(axis, source, dest, side, component)` key, and an - unordered sort could permute them differently on the two ranks. Tests: the nine multi-axis - tests and `test_halo_decomp_common.h` are replaced by `dense_distributed_host` (host-only: - geometry of every rank for slab / pencil / brick, Span views, open vs periodic neighbours, and - the packed X→Y→Z exchange on an emulated world) and `dense_distributed_dist` (4 ranks: raw halo - exchange byte-checked on slab `(1,1,4)`, pencil `(1,2,2)` and bricks `(2,2,1)` / `(2,1,2)`, - packed and run-based, plus a Skeleton stencil kernel with and without overlap; launched with - `mpiexec -n 8` it covers the full `(2,2,2)` brick, so `CARBON_TEST_BRICK_8GPU` is gone). - `benchmarks_giulio`: CG gains `--grid dense_distributed` (`--grid dense` is the original - slab-only grid and rejects pencil / brick); LDC and Jacobi run on `DenseDistributed`. +- **2026-10 — `DenseDistributed`: slab / pencil / brick decomposition as a sibling of `Dense`.** + `Dense` is untouched (still the Z-slab-only grid: one slab per GPU/rank). The per-axis + decomposition lives in a new grid family, `carbon::DenseDistributed`, so the original code path + keeps its exact geometry, halo builder and generated code. It takes a `ProcessGrid` / + `DecompositionMode` (slab by default), uses its own `Span` / `Partition` / `Field` under + `detail/dense_distributed/` (`Idx` is shared with `Dense`), and exposes the same kernel, reduce + and Skeleton surface through a `DenseDistributedPolicy` marker in `launch_traits.h` (the + mechanism `DisgPolicy` already uses) plus `Kernel::halo_distributed`. Halo exchange is + `HaloDistributed`: a staged X→Y→Z exchange (so edges and corners travel without diagonal + messages) with a packed fast path (`halo_pack*.h`, `src/halo_pack.cu`; `CARBON_HALO_PACK=0` + selects the run-based path). Per-axis periodicity is a separate type, + `BoundaryModeDistributed` (`PeriodicX | PeriodicY | PeriodicZ` are independent bits), so + `BoundaryMode` and its numeric values stay as they were for `Dense`, `DenseDisg`, `libcarbonpy` + and the Python bindings. The split / halo-thickness / per-rank chunk arithmetic is a pure host + function set in `detail/dense_distributed/layout.h`, so tests exercise the production + decomposition without a GPU. The cross-rank NCCL pairing key ends with the run index: X/Y halo + faces are non-contiguous in the x-fastest buffer, so one face fans out into many runs sharing + the same `(axis, source, dest, side, component)` key, and an unordered sort could permute them + differently on the two ranks. Supporting additions: `ProcessGrid` / `DecompositionMode` + (`process_grid.h`, balanced prime factorisation over the free axes, plus explicit + `ProcessGrid::custom`) and `Stencil::radius3()` (per-axis Chebyshev radius). Tests: + `test_process_grid`; `dense_distributed_host` (host-only: geometry of every rank for slab / + pencil / brick, Span views, open vs periodic neighbours, and the packed exchange on an emulated + world); `dense_distributed_dist` (4 ranks: raw halo exchange byte-checked on slab `(1,1,4)`, + pencil `(1,2,2)` and bricks `(2,2,1)` / `(2,1,2)`, packed and run-based, plus a Skeleton stencil + kernel with and without overlap; launched with `mpiexec -n 8` it covers the full `(2,2,2)` + brick). +- **2026-11 — Compact `Boundary` view for pencil / brick.** For multi-axis chunks + `DenseDistributed::Span::iter_extent(Boundary)` returned the full owned extent and + `set_and_validate` rejected the interior threads, so every Boundary launch (Standard overlap, and + the Boundary half of Extended / TwoWayExtended producers, which runs before the halo can start) + spawned one thread per owned cell for a shell of about `6·h·n²` cells (roughly 30-40x more + threads than needed for a 256³ chunk with halo 1). The view now iterates the shell directly: six + non-overlapping slabs (Z faces over the full XY extent, Y faces over the middle Z range, X faces + over the middle Y/Z range), launched as a 2-D `(128, ceil(S/128), 1)` box whose padded tail is + `valid = false`. Slab layouts keep the existing two-band domain. `Internal + Boundary == + Standard` still holds, including chunks thinner than `2·halo` (band thickness is clamped so the + bands never overlap). Contract change, documented on `Span`: consecutive Boundary threads are no + longer spatial neighbours. `dense_distributed_host` additionally asserts that the launch box is + less than one 128-wide row larger than the shell. +- **2026-11 — VTK I/O for `DenseDistributed`.** `io::write_vtk(path, grid, fields...)`, + `io::read_vtk(path, grid, fields...)` and `io::write_vtk_multiblock_index(base, grid)` accept a + `DenseDistributed` (slab / pencil / brick). The format is the Dense one (legacy BINARY + `STRUCTURED_POINTS`, one `.rank` shard per rank, `.vtm` index written by rank 0); a shard is + the rank's owned bounding box (`DIMENSIONS` = owned extent, `ORIGIN` = its global cell offset, + `SPACING 1`, halo excluded) and rows are streamed with the real haloed row stride in 4 MiB + blocks, where the Dense writer assumes full-width XY planes. A rank that owns no cells writes a + placeholder shard (`DIMENSIONS 0 0 0`, no payload) and is not listed in the `.vtm`. The `Dense` + path is untouched (`src/io_vtk_distributed.cpp`, `detail/io_vtk_distributed.inl`). Tests: + `dense_distributed_host` round-trips shards for slab / pencil / brick / thin / empty-rank layouts + through the byte-level writer, decoding the payload with an independent big-endian parser and + checking that the shard boxes tile the domain; `dense_distributed_dist` writes, indexes and reads + back real GPU fields. +- **2026-11 — `HaloDistributed` pass barrier is off by default.** The host `stream.wait()` + + `MPI_Barrier` between axis passes is now opt-in (`CARBON_HALO_PASS_BARRIER=1`). Every pass is + ordered on the exchange stream and intra copies are fenced, so it should not be needed for + correctness, and it serialised the host against the GPU, which defeats overlap with interior + compute. - **2026-10 — Extended / TwoWayExtended on the step graph.** Every `OverlapMode` now lowers through `compile_step_graph_and_lower_`; the legacy in-place `apply_occ_` rewrite and `compile_assign_streams_and_events_` are gone. `compile_step_graph_occ_` applies the Standard diff --git a/include/carbon/detail/dense_distributed/span.h b/include/carbon/detail/dense_distributed/span.h index d886bc31..636006cf 100644 --- a/include/carbon/detail/dense_distributed/span.h +++ b/include/carbon/detail/dense_distributed/span.h @@ -153,9 +153,18 @@ class Span { * - @c Standard: @c logic_extent(). Covers every owned cell exactly once. * - @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: legacy z-only chunks ( @c halo.x == halo.y == 0 ) use the compact - * @c 2 * halo.z z-band domain; multi-axis chunks iterate the full owned extent and - * @ref set_and_validate rejects interior cells. + * - @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 + * 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 + * Boundary threads are @b not spatial neighbours: a kernel must not assume that thread + * @c (ix, iy, iz) addresses cell @c (ix, iy, iz) on this view (Standard and Internal keep + * that property). * * The ranges are non-overlapping, so dispatching Internal and Boundary back-to-back * (in any order) writes every owned cell exactly once — same coverage as a single @@ -175,11 +184,17 @@ class Span { return int64_3d{ix > 0 ? ix : 0, iy > 0 ? iy : 0, iz > 0 ? iz : 0}; } - case ::carbon::DataView::Boundary: + case ::carbon::DataView::Boundary: { if (halo_.x == 0 && halo_.y == 0) { return int64_3d{owned.x, owned.y, halo_.z > 0 ? 2 * halo_.z : 0}; } - return owned; + const int64_t shell = shell_bands_().total; + if (shell == 0) { + return int64_3d{0, 0, 0}; + } + const int64_t w = shell >= kShellRowWidth ? kShellRowWidth : shell; + return int64_3d{w, (shell + w - 1) / w, 1}; + } } return owned; } @@ -326,7 +341,8 @@ 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 - * pass the owned index through and return @c valid=false for interior cells. + * 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 @@ -337,6 +353,95 @@ class Span { int64_t ix, int64_t iy, int64_t iz) const noexcept -> ValidatedIdx; + +private: + /** Row width of the 2-D Boundary launch box (two full 64-wide blocks per row). */ + static constexpr int64_t kShellRowWidth = 128; + + /** + * The Boundary shell as six disjoint boxes over the owned extent. Per axis the low / high band + * thickness is clamped so the two never overlap (a chunk thinner than @c 2 * halo is shell + * entirely and @c Internal is empty). Box order: Z-low, Z-high (full XY); Y-low, Y-high + * (full X, middle Z); X-low, X-high (middle Y, middle Z). + */ + struct ShellBands { + int64_3d lo{}; + int64_3d hi{}; + int64_t vol[6]{}; + int64_t total{0}; + }; + + [[nodiscard]] CARBON_HD constexpr auto + shell_bands_() const noexcept -> ShellBands { + const int64_3d n = logic_extent(); + ShellBands b; + b.lo = int64_3d{halo_.x < n.x ? halo_.x : n.x, halo_.y < n.y ? halo_.y : n.y, + halo_.z < n.z ? halo_.z : n.z}; + const int64_t rx = n.x - b.lo.x; + const int64_t ry = n.y - b.lo.y; + const int64_t rz = n.z - b.lo.z; + b.hi = int64_3d{halo_.x < rx ? halo_.x : rx, halo_.y < ry ? halo_.y : ry, + halo_.z < rz ? halo_.z : rz}; + const int64_t mz = n.z - b.lo.z - b.hi.z; // middle extents (>= 0 by the clamps) + const int64_t my = n.y - b.lo.y - b.hi.y; + b.vol[0] = n.x * n.y * b.lo.z; + b.vol[1] = n.x * n.y * b.hi.z; + b.vol[2] = n.x * b.lo.y * mz; + b.vol[3] = n.x * b.hi.y * mz; + b.vol[4] = b.lo.x * my * mz; + b.vol[5] = b.hi.x * my * mz; + b.total = b.vol[0] + b.vol[1] + b.vol[2] + b.vol[3] + b.vol[4] + b.vol[5]; + return b; + } + + /** Owned-local cell of linear shell index @p t in [0, bands.total); x varies fastest. */ + [[nodiscard]] CARBON_HD constexpr auto + shell_cell_(const ShellBands& b, + int64_t t) const noexcept -> int64_3d { + const int64_3d n = logic_extent(); + int box = 0; + while (box < 5 && t >= b.vol[box]) { + t -= b.vol[box]; + ++box; + } + int64_t bx = 0; // box origin + int64_t by = 0; + int64_t bz = 0; + int64_t w = n.x; // box XY footprint + int64_t h = n.y; + switch (box) { + case 0: + break; + case 1: + bz = n.z - b.hi.z; + break; + case 2: + bz = b.lo.z; + h = b.lo.y; + break; + case 3: + by = n.y - b.hi.y; + bz = b.lo.z; + h = b.hi.y; + break; + case 4: + by = b.lo.y; + bz = b.lo.z; + w = b.lo.x; + h = n.y - b.lo.y - b.hi.y; + break; + default: + bx = n.x - b.hi.x; + by = b.lo.y; + bz = b.lo.z; + w = b.hi.x; + h = n.y - b.lo.y - b.hi.y; + break; + } + const int64_t x = t % w; + const int64_t r = t / w; + return int64_3d{bx + x, by + r % h, bz + r / h}; + } }; [[nodiscard]] CARBON_HD constexpr auto @@ -389,13 +494,15 @@ Span::set_and_validate(::carbon::DataView view, return ValidatedIdx{Idx(ix, iy, bz), true}; } - const int64_3d owned = logic_extent(); - const bool internal = ix >= halo_.x && ix < owned.x - halo_.x && iy >= halo_.y && - iy < owned.y - halo_.y && iz >= halo_.z && iz < owned.z - halo_.z; - if (internal) { + // Compact shell: thread (ix, iy) is the linear shell index t (iz is 0 by the range check + // above); the padded tail of the last row is invalid. + const ShellBands bands = shell_bands_(); + const int64_t t = iy * ext.x + ix; + if (t >= bands.total) { return ValidatedIdx{Idx{}, false}; } - return ValidatedIdx{Idx(halo_.x + ix, halo_.y + iy, halo_.z + iz), true}; + const int64_3d c = shell_cell_(bands, t); + return ValidatedIdx{Idx(halo_.x + c.x, halo_.y + c.y, halo_.z + c.z), true}; } } return ValidatedIdx{Idx{}, false}; diff --git a/include/carbon/detail/io_vtk_distributed.inl b/include/carbon/detail/io_vtk_distributed.inl new file mode 100644 index 00000000..33fc51ab --- /dev/null +++ b/include/carbon/detail/io_vtk_distributed.inl @@ -0,0 +1,313 @@ +// io_vtk_distributed.inl — VTK legacy backend for carbon::DenseDistributed, split out of +// . Tail include of io.h (see io_vtk.inl for the include-context contract); not a +// standalone header. +// +// Same on-disk format as the Dense backend (legacy BINARY STRUCTURED_POINTS, one `.rank` shard +// per rank under MPI, `.vtm` multiblock index written by rank 0), generalised from "full XY +// planes, z-slab" to "the rank's owned bounding box": +// +// # vtk DataFile Version 3.0 +// carbon dense field shard +// BINARY +// DATASET STRUCTURED_POINTS +// DIMENSIONS // the rank's owned box (halo excluded) +// ORIGIN // global index of the box's first cell +// SPACING 1 1 1 // index space, same as the Dense writer +// POINT_DATA +// SCALARS +// LOOKUP_TABLE default +// +// +// A rank that owns no cells (global extent smaller than the process grid on some axis) writes a +// placeholder shard: valid header with `DIMENSIONS 0 0 0` / `POINT_DATA 0` and each SCALARS +// header without payload, so every rank leaves exactly one file. The `.vtm` index lists only the +// non-empty shards (there is nothing to display for the others). +// +// Index space (SPACING 1, ORIGIN in cells) is deliberate: it is what the Dense writer/reader use, +// costs nothing extra to write, and keeps shards of both grid families interchangeable in +// ParaView. The span's physical origin/spacing are not applied. +namespace detail { + +/** Pointer-parametrised block of owned cells inside a haloed per-GPU buffer. */ +template +struct VtkBoxPieceT { + /** First @b owned cell of component 0. */ + P start{}; + /** Owned extent of the block. */ + int64_t nx{0}; + int64_t ny{0}; + int64_t nz{0}; + /** Elements between consecutive rows (the haloed x extent). */ + int64_t row_stride{0}; + /** Elements between consecutive z planes. */ + int64_t plane_pitch{0}; + /** Elements between consecutive components. */ + int64_t comp_stride{0}; +}; +using VtkBoxPiece = VtkBoxPieceT; +using VtkBoxPieceMut = VtkBoxPieceT; + +/** Bounding box of one rank's shard in global index space; all-zero @c dims means "empty". */ +struct VtkBox { + int64_t dims[3] = {0, 0, 0}; + int64_t origin[3] = {0, 0, 0}; + + [[nodiscard]] auto + empty() const noexcept -> bool { + return dims[0] <= 0 || dims[1] <= 0 || dims[2] <= 0; + } + [[nodiscard]] auto + points() const noexcept -> int64_t { + return empty() ? 0 : dims[0] * dims[1] * dims[2]; + } +}; + +/** Per-SCALARS record found while parsing a shard header. */ +struct VtkBoxFieldRecord { + std::string name; + std::string vtk_dtype; + int components = 0; + std::streampos payload_offset = 0; +}; + +/** + * The shard box of @p grid on this rank: the union of its local spans' owned cells. Single-GPU + * ranks give their span's owned box; a single-process multi-GPU slab stacks the per-GPU z ranges. + * Throws @c std::invalid_argument if the local spans do not form one box. A rank owning no cells + * returns an empty box whose @c origin is still the global index of its (empty) owned region. + */ +[[nodiscard]] CARBON_API auto +vtk_box_of(const DenseDistributed& grid) -> VtkBox; + +// ---- stream-level building blocks (what the session and the unit tests share) --------------- + +/** Write the legacy header for @p box (placeholder header when @c box.empty()). */ +CARBON_API void +write_vtk_box_header(std::ostream& out, + const VtkBox& box); + +/** + * Write one SCALARS block: header line, LOOKUP_TABLE, then (unless @p box is empty) the payload + * gathered from @p pieces, in file order, as big-endian component-fastest records. + */ +CARBON_API void +write_vtk_box_field(std::ostream& out, + std::string_view name, + const char* dtype_tag, + size_t element_size, + int components, + const VtkBox& box, + const std::vector& pieces); + +/** + * Parse a shard header and record every SCALARS block. DIMENSIONS / ORIGIN / POINT_DATA must match + * @p expected (an empty @p expected requires the placeholder form); SPACING must be unit. + */ +CARBON_API void +parse_vtk_box_header(std::istream& in, + std::string_view path, + const VtkBox& expected, + std::vector& out_fields); + +/** Read one field's payload (stream already positioned) and scatter it into @p pieces. */ +CARBON_API void +read_vtk_box_field_payload(std::istream& in, + size_t element_size, + int components, + const VtkBox& box, + const std::vector& pieces); + +/** Per-rank VTK shard session for a @c DenseDistributed grid. */ +class CARBON_API VtkBoxSession { +public: + VtkBoxSession() noexcept; + ~VtkBoxSession(); + VtkBoxSession(const VtkBoxSession&) = delete; + auto + operator=(const VtkBoxSession&) -> VtkBoxSession& = delete; + VtkBoxSession(VtkBoxSession&&) noexcept; + auto + operator=(VtkBoxSession&&) noexcept -> VtkBoxSession&; + + void + open_for_write(std::string_view path, + const DenseDistributed& grid, + std::uint32_t num_fields); + void + open_for_read(std::string_view path, + const DenseDistributed& grid); + + void + write_field(std::string_view name, + const char* dtype_tag, + size_t element_size, + int components, + const std::vector& pieces); + void + read_field(std::string_view name, + const char* dtype_tag, + size_t element_size, + int components, + const std::vector& pieces); + + [[nodiscard]] auto + num_fields() const noexcept -> std::uint32_t; + + [[nodiscard]] static auto + shard_path(std::string_view base, + const DenseDistributed& grid) -> std::string; + +private: + struct Impl; + std::unique_ptr impl_; +}; + +/** + * Owned-cell blocks of @p field, one per local span (the host mirror, halo excluded). Const + * variant for writers, mutable variant for readers. + */ +template +void +collect_vtk_pieces(const DenseDistributed& grid, + const DenseDistributed::Field& field, + std::vector& pieces, + std::string_view callsite) { + const auto& spans = grid.spans(); + if (field.cpu_buffers().size() != spans.size()) { + log::throw_with_log( + "{}: field has no host mirror (cpu_buffers().size()={}, gpu_count={}); construct the field " + "with MemorySide::Host or HostDevice and download from device before writing", + callsite, field.cpu_buffers().size(), spans.size()); + } + pieces.clear(); + for (size_t g = 0; g < spans.size(); ++g) { + const auto& span = spans[g]; + const int64_3d owned = span.logic_extent(); + if (owned.x <= 0 || owned.y <= 0 || owned.z <= 0) { + continue; + } + const int64_3d halo = span.halo(); + VtkBoxPiece p; + p.row_stride = span.haloed_extent().x; + p.plane_pitch = span.xy_slab_elements(); + p.comp_stride = span.linear_storage_elements(); + p.nx = owned.x; + p.ny = owned.y; + p.nz = owned.z; + p.start = static_cast(field.cpu_buffers()[g].data() + halo.z * p.plane_pitch + + halo.y * p.row_stride + halo.x); + pieces.push_back(p); + } +} + +template +void +collect_vtk_pieces_mut(const DenseDistributed& grid, + DenseDistributed::Field& field, + std::vector& pieces, + std::string_view callsite) { + const auto& spans = grid.spans(); + if (field.cpu_buffers().size() != spans.size()) { + log::throw_with_log( + "{}: field has no host mirror (cpu_buffers().size()={}, gpu_count={}); construct the field " + "with MemorySide::Host or HostDevice before reading", + callsite, field.cpu_buffers().size(), spans.size()); + } + pieces.clear(); + for (size_t g = 0; g < spans.size(); ++g) { + const auto& span = spans[g]; + const int64_3d owned = span.logic_extent(); + if (owned.x <= 0 || owned.y <= 0 || owned.z <= 0) { + continue; + } + const int64_3d halo = span.halo(); + VtkBoxPieceMut p; + p.row_stride = span.haloed_extent().x; + p.plane_pitch = span.xy_slab_elements(); + p.comp_stride = span.linear_storage_elements(); + p.nx = owned.x; + p.ny = owned.y; + p.nz = owned.z; + p.start = static_cast(field.cpu_buffers()[g].data() + halo.z * p.plane_pitch + + halo.y * p.row_stride + halo.x); + pieces.push_back(p); + } +} + +} // namespace detail + +/** + * Write @p fields (host mirrors, halo excluded) of @p grid as one legacy BINARY VTK shard per + * rank (`.rank` under MPI, `` otherwise). Works for every decomposition + * (slab / pencil / brick). Download device data to the host mirror first. Call + * @ref write_vtk_multiblock_index afterwards (any rank may call it; rank 0 writes) to get a + * single `.vtm` that ParaView opens as one multiblock dataset. + */ +template +void +write_vtk(std::string_view path, + const DenseDistributed& grid, + const Fields&... fields) { + detail::VtkBoxSession sess; + sess.open_for_write(path, grid, static_cast(sizeof...(Fields))); + size_t i = 0; + ( + [&] { + using FieldT = std::remove_cv_t>; + using ScalarT = typename FieldT::value_type; + constexpr int kComponents = FieldT::components; + std::vector pieces; + detail::collect_vtk_pieces(grid, fields, pieces, "io::write_vtk"); + const std::string& field_name = fields.name(); + std::string vtk_name = field_name.empty() ? ("field_" + std::to_string(i)) : field_name; + sess.write_field(vtk_name, detail::native_dtype_tag(), sizeof(ScalarT), + kComponents, pieces); + ++i; + }(), + ...); +} + +/** + * Read @p fields of @p grid from the shard @ref write_vtk wrote for this rank. DIMENSIONS and + * ORIGIN must match this rank's owned box; fields bind by ordinal. Only owned cells are touched + * (halo cells keep their contents). + */ +template +void +read_vtk(std::string_view path, + const DenseDistributed& grid, + Fields&... fields) { + detail::VtkBoxSession sess; + sess.open_for_read(path, grid); + if (sess.num_fields() != sizeof...(Fields)) { + log::throw_with_log( + "io::read_vtk: file '{}' has {} fields, but {} were passed to read", path, + sess.num_fields(), sizeof...(Fields)); + } + size_t i = 0; + ( + [&] { + using FieldT = std::remove_cv_t>; + using ScalarT = typename FieldT::value_type; + constexpr int kComponents = FieldT::components; + std::vector pieces; + detail::collect_vtk_pieces_mut(grid, fields, pieces, "io::read_vtk"); + sess.read_field("field_" + std::to_string(i), detail::native_dtype_tag(), + sizeof(ScalarT), kComponents, pieces); + ++i; + }(), + ...); +} + +/** + * Write `.vtm`, a vtkMultiBlockDataSet index over the per-rank shards of + * @ref write_vtk, so ParaView opens the whole decomposed domain at once. Only rank 0 writes; + * ranks that own no cells are not listed. No-op without a distributed System. + */ +CARBON_API auto +write_vtk_multiblock_index(std::string_view base, + const DenseDistributed& grid) -> void; diff --git a/include/carbon/io.h b/include/carbon/io.h index 5a275471..fb88817d 100644 --- a/include/carbon/io.h +++ b/include/carbon/io.h @@ -2,8 +2,10 @@ #include #include +#include #include #include +#include #include #include @@ -11,7 +13,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -29,7 +33,9 @@ * @code * carbon::io::write_native(path, grid, field_a, field_b, ...); * carbon::io::read_native (path, grid, field_a, field_b, ...); - * // VTK / HDF5 / nanoVDB are Dense-only today. + * // VTK / HDF5 / nanoVDB are Dense-only today, except VTK, which also accepts a + * // DenseDistributed (slab / pencil / brick): write_vtk / read_vtk / + * // write_vtk_multiblock_index overloads in detail/io_vtk_distributed.inl. * @endcode * * Both @c Dense and @c DenseDisg share the same on-disk file format: the file header @@ -579,6 +585,7 @@ collect_field_views_mut(const Dense& dense, #include #include #include +#include namespace detail { diff --git a/src/io_vtk_distributed.cpp b/src/io_vtk_distributed.cpp new file mode 100644 index 00000000..099c340c --- /dev/null +++ b/src/io_vtk_distributed.cpp @@ -0,0 +1,832 @@ +// VTK legacy backend for carbon::DenseDistributed (slab / pencil / brick). See +// include/carbon/detail/io_vtk_distributed.inl for the on-disk format and the public surface. +// +// The helpers below (byte order, dtype keywords, header parsing) intentionally mirror the Dense +// backend in io_vtk.cpp instead of sharing it, so the Dense path stays byte-for-byte untouched. +// What differs is the geometry: a shard is the rank's owned *box* (DIMENSIONS = owned extent, +// ORIGIN = global index of its first cell) and rows are read/written with the real haloed row +// stride instead of assuming full-width XY planes. + +#include +#include +#include +#include + +#ifdef CARBON_HAVE_MPI_NCCL +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace carbon::io::detail { + +namespace { + +namespace dd = ::carbon::detail::dense_distributed; + +/** Staging block for payload I/O: rows are batched so the stream sees few, large transfers. */ +constexpr size_t kBlockBytes = size_t{4} << 20; + +[[nodiscard]] constexpr auto +host_is_little_endian() noexcept -> bool { + return std::endian::native == std::endian::little; +} + +/** Reverse the bytes of @p n consecutive @c ES -byte elements (legacy VTK payloads are BE). */ +template +void +swap_run(std::uint8_t* p, + size_t n) noexcept { + if constexpr (ES > 1) { + for (size_t i = 0; i < n; ++i) { + std::uint8_t* e = p + i * ES; + for (size_t k = 0; k < ES / 2; ++k) { + std::swap(e[k], e[ES - 1 - k]); + } + } + } +} + +/** Map a carbon native dtype tag (8-char, NUL padded) to the VTK legacy keyword; null if unknown. */ +[[nodiscard]] auto +vtk_keyword_from_native_tag(const char* tag) noexcept -> const char* { + const std::string_view t(tag, 8); + if (t.starts_with("f32")) { + return "float"; + } + if (t.starts_with("f64")) { + return "double"; + } + if (t.starts_with("i8")) { + return "char"; + } + if (t.starts_with("u8")) { + return "unsigned_char"; + } + if (t.starts_with("i16")) { + return "short"; + } + if (t.starts_with("u16")) { + return "unsigned_short"; + } + if (t.starts_with("i32")) { + return "int"; + } + if (t.starts_with("u32")) { + return "unsigned_int"; + } + if (t.starts_with("i64")) { + return "vtktypeint64"; + } + if (t.starts_with("u64")) { + return "vtktypeuint64"; + } + return nullptr; +} + +[[nodiscard]] auto +element_size_of_keyword(const std::string& kw) noexcept -> size_t { + if (kw == "char" || kw == "unsigned_char") { + return 1; + } + if (kw == "short" || kw == "unsigned_short") { + return 2; + } + if (kw == "int" || kw == "unsigned_int" || kw == "float") { + return 4; + } + if (kw == "double" || kw == "vtktypeint64" || kw == "vtktypeuint64" || kw == "long" || + kw == "unsigned_long") { + return 8; + } + return 0; +} + +void +rtrim_inplace(std::string& s) noexcept { + while (!s.empty() && (s.back() == '\r' || s.back() == ' ' || s.back() == '\t')) { + s.pop_back(); + } +} + +/** Legacy SCALARS names are whitespace-delimited tokens: make the label a single token. */ +[[nodiscard]] auto +sanitize_name(std::string_view name) -> std::string { + std::string out(name); + for (char& c : out) { + if (c == ' ' || c == '\t' || c == '\r' || c == '\n') { + c = '_'; + } + } + return out.empty() ? std::string("field") : out; +} + +[[nodiscard]] auto +shard_path_of(std::string_view base, + const DenseDistributed& grid) -> std::string { +#ifdef CARBON_HAVE_MPI_NCCL + if (grid.system().distributed() != nullptr) { + std::ostringstream oss; + oss << base << ".rank" << grid.system().distributed()->world_rank(); + return oss.str(); + } +#else + (void)grid; +#endif + return std::string(base); +} + +[[nodiscard]] auto +pieces_cells(const std::vector& pieces) -> int64_t { + int64_t n = 0; + for (const auto& p : pieces) { + n += p.nx * p.ny * p.nz; + } + return n; +} + +// ---- payload gather / scatter (compile-time element size) ---------------------------------- + +/** One owned row of @p nx cells -> interleaved (component-fastest) record bytes. */ +template +void +gather_row(std::uint8_t* dst, + const std::uint8_t* src, + int64_t nx, + int comps, + int64_t comp_stride_elems) noexcept { + if (comps == 1) { + std::memcpy(dst, src, static_cast(nx) * ES); + return; + } + const size_t stride = static_cast(comps) * ES; + for (int c = 0; c < comps; ++c) { + const std::uint8_t* s = src + static_cast(c * comp_stride_elems) * ES; + std::uint8_t* d = dst + static_cast(c) * ES; + for (int64_t x = 0; x < nx; ++x) { + std::memcpy(d + static_cast(x) * stride, s + static_cast(x) * ES, ES); + } + } +} + +/** Interleaved record bytes -> one owned row (inverse of @ref gather_row). */ +template +void +scatter_row(std::uint8_t* dst, + const std::uint8_t* src, + int64_t nx, + int comps, + int64_t comp_stride_elems) noexcept { + if (comps == 1) { + std::memcpy(dst, src, static_cast(nx) * ES); + return; + } + const size_t stride = static_cast(comps) * ES; + for (int c = 0; c < comps; ++c) { + std::uint8_t* d = dst + static_cast(c * comp_stride_elems) * ES; + const std::uint8_t* s = src + static_cast(c) * ES; + for (int64_t x = 0; x < nx; ++x) { + std::memcpy(d + static_cast(x) * ES, s + static_cast(x) * stride, ES); + } + } +} + +[[nodiscard]] inline auto +row_ptr(const VtkBoxPiece& p, + size_t es, + int64_t z, + int64_t y) noexcept -> const std::uint8_t* { + return static_cast(p.start) + + static_cast(z * p.plane_pitch + y * p.row_stride) * es; +} + +[[nodiscard]] inline auto +row_ptr(const VtkBoxPieceMut& p, + size_t es, + int64_t z, + int64_t y) noexcept -> std::uint8_t* { + return static_cast(p.start) + + static_cast(z * p.plane_pitch + y * p.row_stride) * es; +} + +template +void +write_payload(std::ostream& out, + int comps, + const std::vector& pieces) { + size_t total_bytes = 0; + size_t max_row_bytes = 0; + for (const auto& p : pieces) { + const size_t row = static_cast(p.nx) * static_cast(comps) * ES; + total_bytes += row * static_cast(p.ny) * static_cast(p.nz); + max_row_bytes = std::max(max_row_bytes, row); + } + if (total_bytes == 0) { + return; + } + std::vector block(std::max(std::min(total_bytes, kBlockBytes), max_row_bytes)); + size_t used = 0; + const auto flush = [&] { + if (used == 0) { + return; + } + if (host_is_little_endian()) { + swap_run(block.data(), used / ES); + } + out.write(reinterpret_cast(block.data()), static_cast(used)); + used = 0; + }; + for (const auto& p : pieces) { + const size_t row_bytes = static_cast(p.nx) * static_cast(comps) * ES; + for (int64_t z = 0; z < p.nz; ++z) { + for (int64_t y = 0; y < p.ny; ++y) { + if (used + row_bytes > block.size()) { + flush(); + } + gather_row(block.data() + used, row_ptr(p, ES, z, y), p.nx, comps, p.comp_stride); + used += row_bytes; + } + } + } + flush(); +} + +template +void +read_payload(std::istream& in, + int comps, + const std::vector& pieces) { + size_t max_row_bytes = 0; + size_t total_bytes = 0; + for (const auto& p : pieces) { + const size_t row = static_cast(p.nx) * static_cast(comps) * ES; + max_row_bytes = std::max(max_row_bytes, row); + total_bytes += row * static_cast(p.ny) * static_cast(p.nz); + } + if (total_bytes == 0) { + return; + } + std::vector block(std::max(std::min(total_bytes, kBlockBytes), max_row_bytes)); + for (const auto& p : pieces) { + const size_t row_bytes = static_cast(p.nx) * static_cast(comps) * ES; + const int64_t rows_total = p.ny * p.nz; + const int64_t rows_per_block = static_cast(block.size() / row_bytes); + for (int64_t r0 = 0; r0 < rows_total; r0 += rows_per_block) { + const int64_t rows = std::min(rows_per_block, rows_total - r0); + const size_t bytes = static_cast(rows) * row_bytes; + in.read(reinterpret_cast(block.data()), static_cast(bytes)); + if (!in.good()) { + log::throw_with_log( + "io::read_vtk: short read in payload (row {} of {})", r0, rows_total); + } + if (host_is_little_endian()) { + swap_run(block.data(), bytes / ES); + } + for (int64_t i = 0; i < rows; ++i) { + const int64_t r = r0 + i; + scatter_row(row_ptr(p, ES, r / p.ny, r % p.ny), + block.data() + static_cast(i) * row_bytes, p.nx, comps, + p.comp_stride); + } + } + } +} + +} // namespace + +// ================================================================================================ +// Box geometry +// ================================================================================================ + +auto +vtk_box_of(const DenseDistributed& grid) -> VtkBox { + VtkBox box; + const auto& spans = grid.spans(); + if (spans.empty()) { + return box; + } + // Global index of the first owned cell of a span = buffer origin + halo. + const auto owned_origin = [](const auto& span) -> int64_3d { + const int64_3d o = span.offset(); + const int64_3d h = span.halo(); + return int64_3d{o.x + h.x, o.y + h.y, o.z + h.z}; + }; + const int64_3d first = owned_origin(spans.front()); + box.origin[0] = first.x; + box.origin[1] = first.y; + box.origin[2] = first.z; + + int64_t z_total = 0; + int64_3d prev_origin{}; + int64_t prev_nz = 0; + bool have_prev = false; + int64_t nx = 0; + int64_t ny = 0; + for (const auto& span : spans) { + const int64_3d owned = span.logic_extent(); + if (owned.x <= 0 || owned.y <= 0 || owned.z <= 0) { + continue; // this GPU owns nothing + } + const int64_3d o = owned_origin(span); + if (!have_prev) { + nx = owned.x; + ny = owned.y; + box.origin[0] = o.x; + box.origin[1] = o.y; + box.origin[2] = o.z; + } else if (owned.x != nx || owned.y != ny || o.x != prev_origin.x || o.y != prev_origin.y || + o.z != prev_origin.z + prev_nz) { + log::throw_with_log( + "io::vtk: the local spans of this DenseDistributed do not form a single box (only a " + "z-stacked slab can span several local GPUs)"); + } + z_total += owned.z; + prev_origin = o; + prev_nz = owned.z; + have_prev = true; + } + if (have_prev) { + box.dims[0] = nx; + box.dims[1] = ny; + box.dims[2] = z_total; + } + return box; +} + +// ================================================================================================ +// Stream-level building blocks +// ================================================================================================ + +void +write_vtk_box_header(std::ostream& out, + const VtkBox& box) { + const bool empty = box.empty(); + out << "# vtk DataFile Version 3.0\n"; + out << (empty ? "carbon dense field shard (empty: this rank owns no cells)\n" + : "carbon dense field shard\n"); + out << "BINARY\n"; + out << "DATASET STRUCTURED_POINTS\n"; + out << "DIMENSIONS " << (empty ? 0 : box.dims[0]) << ' ' << (empty ? 0 : box.dims[1]) << ' ' + << (empty ? 0 : box.dims[2]) << '\n'; + out << "ORIGIN " << box.origin[0] << ' ' << box.origin[1] << ' ' << box.origin[2] << '\n'; + out << "SPACING 1 1 1\n"; + out << "POINT_DATA " << box.points() << '\n'; + if (!out.good()) { + log::throw_with_log("io::write_vtk: failed to write the shard header"); + } +} + +void +write_vtk_box_field(std::ostream& out, + std::string_view name, + const char* dtype_tag, + size_t element_size, + int components, + const VtkBox& box, + const std::vector& pieces) { + const char* kw = vtk_keyword_from_native_tag(dtype_tag); + if (kw == nullptr) { + log::throw_with_log( + "io::write_vtk: field '{}' has a dtype VTK legacy cannot express", name); + } + if (components < 1 || components > 4) { + log::throw_with_log( + "io::write_vtk: field '{}' has {} components (legacy VTK SCALARS supports 1..4)", name, + components); + } + if (!box.empty()) { + if (pieces_cells(pieces) != box.points()) { + log::throw_with_log( + "io::write_vtk: field '{}' pieces hold {} cells but the shard box has {}", name, + pieces_cells(pieces), box.points()); + } + for (const auto& p : pieces) { + if (p.nx != box.dims[0] || p.ny != box.dims[1]) { + log::throw_with_log( + "io::write_vtk: field '{}' piece ({}x{}) does not match the shard box ({}x{})", name, + p.nx, p.ny, box.dims[0], box.dims[1]); + } + } + } + out << "SCALARS " << sanitize_name(name) << ' ' << kw << ' ' << components << '\n'; + out << "LOOKUP_TABLE default\n"; + if (!box.empty()) { + switch (element_size) { + case 1: + write_payload<1>(out, components, pieces); + break; + case 2: + write_payload<2>(out, components, pieces); + break; + case 4: + write_payload<4>(out, components, pieces); + break; + case 8: + write_payload<8>(out, components, pieces); + break; + default: + log::throw_with_log( + "io::write_vtk: unsupported element size {} for field '{}'", element_size, name); + } + } + out << '\n'; + if (!out.good()) { + log::throw_with_log("io::write_vtk: write of field '{}' failed", name); + } +} + +void +parse_vtk_box_header(std::istream& in, + std::string_view path, + const VtkBox& expected, + std::vector& out_fields) { + const auto next_line = [&](bool strict) -> std::string { + std::string line; + if (!std::getline(in, line)) { + if (strict) { + log::throw_with_log("io::read_vtk: '{}' ended inside the header", + path); + } + return {}; + } + rtrim_inplace(line); + return line; + }; + + const auto magic = next_line(true); + if (magic.rfind("# vtk DataFile Version", 0) != 0) { + log::throw_with_log( + "io::read_vtk: '{}' does not start with a VTK legacy magic line (got '{}')", path, magic); + } + next_line(true); // free-form title + const auto fmt = next_line(true); + if (fmt != "BINARY") { + log::throw_with_log( + "io::read_vtk: '{}' is '{}' but only BINARY legacy VTK is supported", path, fmt); + } + const auto ds = next_line(true); + if (ds != "DATASET STRUCTURED_POINTS") { + log::throw_with_log( + "io::read_vtk: '{}' is '{}' but only DATASET STRUCTURED_POINTS is supported", path, ds); + } + + int64_t dims[3] = {0, 0, 0}; + int64_t origin[3] = {0, 0, 0}; + double spacing[3] = {1.0, 1.0, 1.0}; + int64_t point_count = -1; + while (point_count < 0) { + const auto cur = next_line(true); + if (cur.empty()) { + continue; + } + std::istringstream iss(cur); + std::string head; + iss >> head; + if (head == "DIMENSIONS") { + iss >> dims[0] >> dims[1] >> dims[2]; + } else if (head == "ORIGIN") { + iss >> origin[0] >> origin[1] >> origin[2]; + } else if (head == "SPACING" || head == "ASPECT_RATIO") { + iss >> spacing[0] >> spacing[1] >> spacing[2]; + } else if (head == "POINT_DATA") { + iss >> point_count; + if (point_count < 0) { + log::throw_with_log("io::read_vtk: '{}' has a bad POINT_DATA line", + path); + } + } else if (head == "CELL_DATA") { + log::throw_with_log( + "io::read_vtk: '{}' uses CELL_DATA; carbon writes POINT_DATA only", path); + } else { + log::throw_with_log( + "io::read_vtk: '{}' has unexpected header line '{}'", path, cur); + } + } + + // Validate against the box this rank is about to load into. + const bool want_empty = expected.empty(); + const int64_t want_dims[3] = {want_empty ? 0 : expected.dims[0], + want_empty ? 0 : expected.dims[1], + want_empty ? 0 : expected.dims[2]}; + if (dims[0] != want_dims[0] || dims[1] != want_dims[1] || dims[2] != want_dims[2]) { + log::throw_with_log( + "io::read_vtk: '{}' DIMENSIONS ({}, {}, {}) do not match this rank's owned box ({}, {}, " + "{})", + path, dims[0], dims[1], dims[2], want_dims[0], want_dims[1], want_dims[2]); + } + if (origin[0] != expected.origin[0] || origin[1] != expected.origin[1] || + origin[2] != expected.origin[2]) { + log::throw_with_log( + "io::read_vtk: '{}' ORIGIN ({}, {}, {}) does not match this rank's box origin ({}, {}, {})", + path, origin[0], origin[1], origin[2], expected.origin[0], expected.origin[1], + expected.origin[2]); + } + if (spacing[0] != 1.0 || spacing[1] != 1.0 || spacing[2] != 1.0) { + log::throw_with_log( + "io::read_vtk: '{}' SPACING ({}, {}, {}) is non-unit; carbon uses integer voxel " + "coordinates", + path, spacing[0], spacing[1], spacing[2]); + } + if (point_count != expected.points()) { + log::throw_with_log( + "io::read_vtk: '{}' POINT_DATA {} disagrees with the box size {}", path, point_count, + expected.points()); + } + + // Walk the SCALARS blocks, recording each payload offset. + while (in) { + const auto cur = next_line(false); + if (cur.empty()) { + if (in.eof()) { + break; + } + continue; + } + std::istringstream iss(cur); + std::string head; + iss >> head; + if (head != "SCALARS") { + log::throw_with_log( + "io::read_vtk: unsupported attribute '{}' in '{}'; only SCALARS blocks are accepted", + head, path); + } + VtkBoxFieldRecord rec; + iss >> rec.name >> rec.vtk_dtype; + rec.components = 1; + iss >> rec.components; + if (rec.components < 1 || rec.components > 4) { + log::throw_with_log( + "io::read_vtk: SCALARS '{}' has components={} (legacy VTK supports 1..4)", rec.name, + rec.components); + } + const auto lookup = next_line(true); + if (lookup.rfind("LOOKUP_TABLE", 0) != 0) { + log::throw_with_log( + "io::read_vtk: expected LOOKUP_TABLE after SCALARS '{}', got '{}'", rec.name, lookup); + } + rec.payload_offset = in.tellg(); + if (rec.payload_offset == std::streampos(-1)) { + log::throw_with_log( + "io::read_vtk: failed to query the stream offset of SCALARS '{}'", rec.name); + } + const size_t es = element_size_of_keyword(rec.vtk_dtype); + if (es == 0) { + log::throw_with_log( + "io::read_vtk: SCALARS '{}' has dtype '{}' which carbon does not map back", rec.name, + rec.vtk_dtype); + } + in.seekg(rec.payload_offset + static_cast(point_count) * + static_cast(rec.components) * + static_cast(es)); + out_fields.push_back(std::move(rec)); + const int next_c = in.peek(); // optional trailing newline after the payload + if (next_c == '\n' || next_c == '\r') { + in.get(); + if (next_c == '\r' && in.peek() == '\n') { + in.get(); + } + } + } +} + +void +read_vtk_box_field_payload(std::istream& in, + size_t element_size, + int components, + const VtkBox& box, + const std::vector& pieces) { + if (box.empty()) { + return; + } + int64_t cells = 0; + for (const auto& p : pieces) { + cells += p.nx * p.ny * p.nz; + if (p.nx != box.dims[0] || p.ny != box.dims[1]) { + log::throw_with_log( + "io::read_vtk: piece ({}x{}) does not match the shard box ({}x{})", p.nx, p.ny, + box.dims[0], box.dims[1]); + } + } + if (cells != box.points()) { + log::throw_with_log( + "io::read_vtk: pieces hold {} cells but the shard box has {}", cells, box.points()); + } + switch (element_size) { + case 1: + read_payload<1>(in, components, pieces); + break; + case 2: + read_payload<2>(in, components, pieces); + break; + case 4: + read_payload<4>(in, components, pieces); + break; + case 8: + read_payload<8>(in, components, pieces); + break; + default: + log::throw_with_log("io::read_vtk: unsupported element size {}", + element_size); + } +} + +// ================================================================================================ +// Session +// ================================================================================================ + +struct VtkBoxSession::Impl { + std::string path; + bool for_write = false; + std::uint32_t num_fields_recorded = 0; + VtkBox box; + std::ofstream writer; + std::ifstream reader; + std::vector read_fields; + size_t read_fields_cursor = 0; +}; + +VtkBoxSession::VtkBoxSession() noexcept = default; +VtkBoxSession::~VtkBoxSession() = default; +VtkBoxSession::VtkBoxSession(VtkBoxSession&&) noexcept = default; +auto +VtkBoxSession::operator=(VtkBoxSession&&) noexcept -> VtkBoxSession& = default; + +auto +VtkBoxSession::shard_path(std::string_view base, + const DenseDistributed& grid) -> std::string { + return shard_path_of(base, grid); +} + +void +VtkBoxSession::open_for_write(std::string_view path, + const DenseDistributed& grid, + std::uint32_t /*num_fields*/) { + impl_ = std::make_unique(); + impl_->path = shard_path_of(path, grid); + impl_->for_write = true; + impl_->box = vtk_box_of(grid); + impl_->writer.open(impl_->path, std::ios::binary | std::ios::trunc); + if (!impl_->writer) { + log::throw_with_log("io::write_vtk: failed to open '{}' for writing", + impl_->path); + } + write_vtk_box_header(impl_->writer, impl_->box); +} + +void +VtkBoxSession::write_field(std::string_view name, + const char* dtype_tag, + size_t element_size, + int components, + const std::vector& pieces) { + if (impl_ == nullptr || !impl_->for_write) { + log::throw_with_log("io::write_vtk: session is not in a writable state"); + } + write_vtk_box_field(impl_->writer, name, dtype_tag, element_size, components, impl_->box, pieces); + ++impl_->num_fields_recorded; +} + +void +VtkBoxSession::open_for_read(std::string_view path, + const DenseDistributed& grid) { + impl_ = std::make_unique(); + impl_->path = shard_path_of(path, grid); + impl_->for_write = false; + impl_->box = vtk_box_of(grid); + impl_->reader.open(impl_->path, std::ios::binary); + if (!impl_->reader) { + log::throw_with_log("io::read_vtk: failed to open '{}' for reading", + impl_->path); + } + parse_vtk_box_header(impl_->reader, impl_->path, impl_->box, impl_->read_fields); +} + +void +VtkBoxSession::read_field(std::string_view /*name*/, + const char* dtype_tag, + size_t element_size, + int components, + const std::vector& pieces) { + if (impl_ == nullptr || impl_->for_write) { + log::throw_with_log("io::read_vtk: session is not in a readable state"); + } + if (impl_->read_fields_cursor >= impl_->read_fields.size()) { + log::throw_with_log( + "io::read_vtk: more fields requested than '{}' contains", impl_->path); + } + // Fields bind by ordinal (names differ between writers). + const auto& rec = impl_->read_fields[impl_->read_fields_cursor++]; + const char* expected_kw = vtk_keyword_from_native_tag(dtype_tag); + if (expected_kw == nullptr || rec.vtk_dtype != expected_kw) { + log::throw_with_log( + "io::read_vtk: field {} dtype '{}' does not match bound carbon dtype '{}' in '{}'", + rec.name, rec.vtk_dtype, (expected_kw != nullptr ? expected_kw : "?"), impl_->path); + } + if (rec.components != components) { + log::throw_with_log( + "io::read_vtk: field {} has {} components but the bound Field has {}", rec.name, + rec.components, components); + } + impl_->reader.clear(); + impl_->reader.seekg(rec.payload_offset); + if (!impl_->reader.good()) { + log::throw_with_log( + "io::read_vtk: seek to the payload of '{}' failed in '{}'", rec.name, impl_->path); + } + read_vtk_box_field_payload(impl_->reader, element_size, components, impl_->box, pieces); +} + +auto +VtkBoxSession::num_fields() const noexcept -> std::uint32_t { + if (impl_ == nullptr) { + return 0U; + } + return impl_->for_write ? impl_->num_fields_recorded + : static_cast(impl_->read_fields.size()); +} + +} // namespace carbon::io::detail + +namespace carbon::io { + +auto +write_vtk_multiblock_index(std::string_view base, + const DenseDistributed& grid) -> void { +#ifdef CARBON_HAVE_MPI_NCCL + const auto* dist = grid.system().distributed(); + if (dist == nullptr) { + return; // single process: the shard at is the whole dataset + } + const int world_size = dist->world_size(); + if (world_size <= 1 || dist->world_rank() != 0) { + return; + } + + // Which ranks own cells? Every rank's owned box follows from the global split alone, so the + // index needs no communication. Ranks with an empty box wrote a placeholder shard that is not + // listed (there is nothing to display). + const ProcessGrid& pg = grid.process_grid(); + const int64_3d global = grid.global_extent(); + std::vector listed; + for (int r = 0; r < world_size; ++r) { + bool owns = true; + if (pg.world_size() == world_size) { + const auto chunk = ::carbon::detail::dense_distributed::rank_chunk( + global, pg, pg.coords_of(r), int64_3d{0, 0, 0}); + owns = chunk.owned.x > 0 && chunk.owned.y > 0 && chunk.owned.z > 0; + } + if (owns) { + listed.push_back(r); + } + } + + const std::filesystem::path base_path(std::string{base}); + const std::filesystem::path master_path = base_path.string() + ".vtm"; + const std::filesystem::path base_filename = base_path.filename(); + + std::ofstream out(master_path, std::ios::binary | std::ios::trunc); + if (!out) { + log::throw_with_log( + "io::write_vtk_multiblock_index: failed to open '{}' for writing", master_path.string()); + } + out << "\n"; + out << "\n"; + out << " \n"; + int block = 0; + for (const int r : listed) { + out << " \n"; + out << " \n"; + out << " \n"; + } + out << " \n"; + out << "\n"; + if (!out.good()) { + log::throw_with_log("io::write_vtk_multiblock_index: write to '{}' failed", + master_path.string()); + } +#else + (void)base; + (void)grid; +#endif +} + +} // namespace carbon::io diff --git a/tests/test_dense_distributed_dist.cu b/tests/test_dense_distributed_dist.cu index ddb48a03..332abdd3 100644 --- a/tests/test_dense_distributed_dist.cu +++ b/tests/test_dense_distributed_dist.cu @@ -25,7 +25,15 @@ // neighbour is outside an open boundary) is compiled into a Skeleton, so the halo kernel is // auto-inserted from read_stencil and DenseDistributed::Span / Partition run on the device. // Run once without overlap and once with OverlapMode::Standard, which splits the kernel into -// Internal + Boundary launches and therefore exercises those Span views for real. +// Internal + Boundary launches and therefore exercises those Span views for real. (For pencil +// and brick the Boundary launch is the compact shell, not the full owned extent.) +// +// 3. VTK shard I/O. A 3-component float field goes host -> device -> host, is written with +// io::write_vtk (one `.rank` shard per rank) plus the `.vtm` index, and read back with +// io::read_vtk into a second field. Each rank checks its own shard header against its owned box +// (DIMENSIONS / ORIGIN), every owned cell after the round trip, that halo cells were not +// touched, and rank 0 checks that the index lists every rank. Files are written to the +// working directory (like test_io_dist) and removed afterwards. #include #include @@ -34,6 +42,7 @@ #include #include #include +#include #include #include #include @@ -47,7 +56,10 @@ #include #include #include +#include +#include #include +#include #include #include #include @@ -470,6 +482,164 @@ run_stencil(carbon::System& sys, return true; } +// ------------------------------------------------------------------------------------------------ +// Check 3: VTK shard I/O for DenseDistributed (write_vtk / read_vtk / multiblock index). +// ------------------------------------------------------------------------------------------------ + +[[nodiscard]] auto +run_vtk(carbon::System& sys, + int rank, + int world, + const ProcessGrid& pg, + BoundaryModeDistributed mode, + const std::string& label, + const int64_3d& global) -> bool { + const std::string base = "carbon_test_dense_distributed_vtk_" + label; + const std::string shard = base + ".rank" + std::to_string(rank); + const std::string index = base + ".vtm"; + bool ok = true; + try { + DenseDistributed grid(sys, global, pg, six_point(), mode); + const auto& span = grid.spans()[0]; + const int64_3d halo = span.halo(); + const int64_3d owned = span.logic_extent(); + const int64_3d haloed = span.haloed_extent(); + const int64_t pitch = span.xy_slab_elements(); + const int64_t per_comp = span.linear_storage_elements(); + constexpr int kComps = 3; + constexpr float kSentinelIn = -1.0F; + constexpr float kSentinelOut = -2.0F; + + auto f = grid.template newField(carbon::MemorySide::HostDevice, "pop"); + auto g = grid.template newField(carbon::MemorySide::HostDevice, "pop_in"); + const auto is_owned_cell = [&](int64_t x, int64_t y, int64_t z) -> bool { + return x >= halo.x && x < halo.x + owned.x && y >= halo.y && y < halo.y + owned.y && + z >= halo.z && z < halo.z + owned.z; + }; + { + float* hf = f.cpu_buffers()[0].data(); + float* hg = g.cpu_buffers()[0].data(); + for (int64_t z = 0; z < haloed.z; ++z) { + for (int64_t y = 0; y < haloed.y; ++y) { + for (int64_t x = 0; x < haloed.x; ++x) { + const int64_3d gl = span.global_location(span.make_idx(x, y, z)); + const int64_t off = z * pitch + y * haloed.x + x; + for (int c = 0; c < kComps; ++c) { + hf[c * per_comp + off] = is_owned_cell(x, y, z) + ? static_cast(encode(gl.x, gl.y, gl.z, c)) + : kSentinelIn; + hg[c * per_comp + off] = kSentinelOut; + } + } + } + } + } + // host -> device -> host, so the field written is what a real run would download + carbon::Stream stream = sys.stream(); + carbon::Transfer(sys, f.cpu_buffers(), f.gpu_buffers())(stream); + if (!sync_all(stream, "vtk upload")) { + return false; + } + { + float* hf = f.cpu_buffers()[0].data(); + for (size_t i = 0; i < f.cpu_buffers()[0].size(); ++i) { + hf[i] = 0.0F; + } + } + carbon::Transfer(sys, f.gpu_buffers(), f.cpu_buffers())(stream); + if (!sync_all(stream, "vtk download")) { + return false; + } + + carbon::io::write_vtk(base, grid, f); + carbon::io::write_vtk_multiblock_index(base, grid); + + // --- this rank's shard header must describe its owned box ---------------------------------- + { + std::ifstream in(shard, std::ios::binary); + std::string line; + int64_t dims[3] = {-1, -1, -1}; + int64_t org[3] = {-1, -1, -1}; + while (std::getline(in, line)) { + std::istringstream ls(line); + std::string head; + ls >> head; + if (head == "DIMENSIONS") { + ls >> dims[0] >> dims[1] >> dims[2]; + } else if (head == "ORIGIN") { + ls >> org[0] >> org[1] >> org[2]; + } else if (head == "SCALARS") { + break; + } + } + const int64_3d o0 = span.global_location(span.make_idx(halo.x, halo.y, halo.z)); + if (dims[0] != owned.x || dims[1] != owned.y || dims[2] != owned.z || org[0] != o0.x || + org[1] != o0.y || org[2] != o0.z) { + CARBON_LOG_ERROR( + "test_dense_distributed_dist[{}]: rank {} shard header DIMENSIONS=({},{},{}) " + "ORIGIN=({},{},{}) want owned=({},{},{}) origin=({},{},{})", + label, rank, dims[0], dims[1], dims[2], org[0], org[1], org[2], owned.x, owned.y, + owned.z, o0.x, o0.y, o0.z); + ok = false; + } + } + + // --- rank 0's index lists every rank (all own cells for this extent) ------------------------- + if (rank == 0) { + std::ifstream in(index); + const std::string text((std::istreambuf_iterator(in)), + std::istreambuf_iterator()); + if (text.find("vtkMultiBlockDataSet") == std::string::npos) { + CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: missing/invalid {}", label, index); + ok = false; + } + for (int r = 0; r < world; ++r) { + if (text.find("name=\"rank" + std::to_string(r) + "\"") == std::string::npos) { + CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: index does not list rank {}", label, + r); + ok = false; + } + } + } + + // --- read back into a fresh field: owned == written, halo untouched ---------------------------- + carbon::io::read_vtk(base, grid, g); + size_t mismatches = 0; + const float* hg = g.cpu_buffers()[0].data(); + for (int64_t z = 0; z < haloed.z; ++z) { + for (int64_t y = 0; y < haloed.y; ++y) { + for (int64_t x = 0; x < haloed.x; ++x) { + const int64_3d gl = span.global_location(span.make_idx(x, y, z)); + const int64_t off = z * pitch + y * haloed.x + x; + for (int c = 0; c < kComps; ++c) { + const float want = is_owned_cell(x, y, z) + ? static_cast(encode(gl.x, gl.y, gl.z, c)) + : kSentinelOut; + if (hg[c * per_comp + off] != want) { + ++mismatches; + } + } + } + } + } + if (mismatches != 0U) { + CARBON_LOG_ERROR( + "test_dense_distributed_dist[{}]: rank {} VTK round trip has {} wrong values", label, + rank, mismatches); + ok = false; + } + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: VTK I/O failed: {}", label, e.what()); + ok = false; + } + std::error_code ec; + std::filesystem::remove(shard, ec); + if (rank == 0) { + std::filesystem::remove(index, ec); + } + return ok; +} + struct Case { ProcessGrid pg; BoundaryModeDistributed mode; @@ -540,7 +710,8 @@ main() { !run_stencil(sys, rank, c.pg, c.mode, carbon::OverlapMode::None, std::string(c.label) + "/stencil", global) || !run_stencil(sys, rank, c.pg, c.mode, carbon::OverlapMode::Standard, - std::string(c.label) + "/stencil-overlap", global)) { + std::string(c.label) + "/stencil-overlap", 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 079dcd68..21a52b44 100644 --- a/tests/test_dense_distributed_host.cpp +++ b/tests/test_dense_distributed_host.cpp @@ -7,6 +7,10 @@ // hand-written expectations, the owned boxes must tile the global domain exactly once, and // the resulting Span must iterate (Standard, Internal + Boundary) and resolve // neighbours (open vs periodic) correctly. +// Part D VTK shard I/O (io::detail stream-level writer/reader behind write_vtk / read_vtk for +// DenseDistributed): byte-level check of the legacy BINARY payload with an independent +// decoder, library round trip that must leave halo cells untouched, shard boxes that tile +// the domain exactly once, and the placeholder shard of a rank that owns no cells. // Part C correctness of the full X -> Y -> Z staged halo exchange on an emulated multi-rank world // (corners/edges, periodic wraps, uneven splits, self-wrap), driven by the production // plan builder and checked against the run-based builder (kept as the oracle) and against @@ -20,16 +24,22 @@ #include #include #include +#include +#include #include #include #include #include +#include #include #include #include +#include #include #include +#include +#include #include #include @@ -704,6 +714,23 @@ 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) { + // 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 + // padded tail is exactly the invalid threads. + const auto pos = [](int64_t v) { + return v > 0 ? v : 0; + }; + const int64_t owned_cells = ch.owned.x * ch.owned.y * ch.owned.z; + const int64_t internal_cells = pos(ch.owned.x - 2 * halo.x) * + pos(ch.owned.y - 2 * halo.y) * + pos(ch.owned.z - 2 * halo.z); + const int64_t shell = owned_cells - internal_cells; + CHECK(e.z == 1 || shell == 0); + CHECK(e.x * e.y * e.z >= shell); + CHECK(e.x * e.y * e.z < shell + 128); + } + int64_t valid_threads = 0; for (int64_t iz = 0; iz < e.z; ++iz) { for (int64_t iy = 0; iy < e.y; ++iy) { for (int64_t ix = 0; ix < e.x; ++ix) { @@ -711,6 +738,7 @@ check_geometry(const GeomCase& c, if (!v.valid) { continue; } + ++valid_threads; const int64_3d cell = v.idx.cell(); const int64_t lx = cell.x - halo.x; const int64_t ly = cell.y - halo.y; @@ -721,6 +749,15 @@ check_geometry(const GeomCase& c, } } } + if (view == carbon::DataView::Boundary && !legacy_slab) { + // Every valid Boundary thread is a distinct shell cell; the rest of the box is padding. + const auto pos = [](int64_t v) { + return v > 0 ? v : 0; + }; + CHECK(valid_threads == ch.owned.x * ch.owned.y * ch.owned.z - + pos(ch.owned.x - 2 * halo.x) * pos(ch.owned.y - 2 * halo.y) * + pos(ch.owned.z - 2 * halo.z)); + } } for (const int m : mark) { CHECK(m == 1); @@ -820,6 +857,269 @@ part_b_geometry(size_t& cells, return cases.size(); } +// ------------------------------------------------------------------------------------------------ +// Part D: VTK shard I/O for DenseDistributed. +// ------------------------------------------------------------------------------------------------ + +namespace vtk = carbon::io::detail; + +// Injective for extents < 16 and up to 3 components, and it fits in int16. +auto +vtk_value(int64_t x, + int64_t y, + int64_t z, + int c) -> int { + return static_cast(x + 16 * y + 256 * z + 4096 * c); +} + +// Independent big-endian decoder (does not use the library's swap code). +template +auto +decode_be(const unsigned char* p) -> T { + unsigned char b[sizeof(T)]; + for (size_t i = 0; i < sizeof(T); ++i) { + b[i] = p[sizeof(T) - 1 - i]; // BE on the wire -> LE host (this test runs on LE hosts) + } + T v; + std::memcpy(&v, b, sizeof(T)); + return v; +} + +struct VtkCase { + const char* name; + int px, py, pz; + BoundaryModeDistributed bm; + int64_t gx, gy, gz; +}; + +template +auto +vtk_roundtrip_case(const VtkCase& c, + int comps, + std::vector& cover, + size_t& shards, + size_t& empty_shards, + size_t& points) -> void { + g_ctx = std::string("part D ") + c.name + " T" + std::to_string(sizeof(T)) + " c" + + std::to_string(comps); + static_assert(std::endian::native == std::endian::little, "decoder assumes a little-endian host"); + const ProcessGrid pg = ProcessGrid::custom(c.px * c.py * c.pz, c.px, c.py, c.pz); + 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 int64_3d global{c.gx, c.gy, c.gz}; + const int64_3d halo = dd::halo_extent(pg, c.bm, stencil); + const char* tag = + sizeof(T) == 2 ? "i16\0\0\0\0" : (sizeof(T) == 4 ? "i32\0\0\0\0" : "f64\0\0\0\0"); + const char* kw = sizeof(T) == 2 ? "short" : (sizeof(T) == 4 ? "int" : "double"); + + for (int32_t r = 0; r < pg.world_size(); ++r) { + const dd::RankChunk ch = dd::rank_chunk(global, pg, pg.coords_of(r), halo); + const int64_t per_comp = ch.xy_pitch * ch.haloed.z; + const T sentinel = static_cast(-777); + std::vector buf(static_cast(per_comp) * static_cast(comps), sentinel); + const int64_3d own0{ch.offset.x + halo.x, ch.offset.y + halo.y, ch.offset.z + halo.z}; + for (int64_t z = 0; z < ch.owned.z; ++z) { + for (int64_t y = 0; y < ch.owned.y; ++y) { + for (int64_t x = 0; x < ch.owned.x; ++x) { + for (int k = 0; k < comps; ++k) { + const int64_t off = + (halo.z + z) * ch.xy_pitch + (halo.y + y) * ch.haloed.x + halo.x + x; + buf[static_cast(k * per_comp + off)] = + static_cast(vtk_value(own0.x + x, own0.y + y, own0.z + z, k)); + } + } + } + } + + vtk::VtkBox box; + box.origin[0] = own0.x; + box.origin[1] = own0.y; + box.origin[2] = own0.z; + const bool owns = ch.owned.x > 0 && ch.owned.y > 0 && ch.owned.z > 0; + if (owns) { + box.dims[0] = ch.owned.x; + box.dims[1] = ch.owned.y; + box.dims[2] = ch.owned.z; + } + std::vector pieces; + if (owns) { + vtk::VtkBoxPiece p; + p.start = buf.data() + halo.z * ch.xy_pitch + halo.y * ch.haloed.x + halo.x; + p.nx = ch.owned.x; + p.ny = ch.owned.y; + p.nz = ch.owned.z; + p.row_stride = ch.haloed.x; + p.plane_pitch = ch.xy_pitch; + p.comp_stride = per_comp; + pieces.push_back(p); + } + + std::ostringstream os; + vtk::write_vtk_box_header(os, box); + vtk::write_vtk_box_field(os, "my field", tag, sizeof(T), comps, box, pieces); + const std::string bytes = os.str(); + ++shards; + + // --- independent parse of the text header ------------------------------------------------- + std::istringstream hs(bytes); + std::string line; + int64_t dims[3] = {-1, -1, -1}; + int64_t org[3] = {-1, -1, -1}; + int64_t npts = -1; + std::string scal_name; + std::string scal_type; + int scal_comps = -1; + size_t payload_at = 0; + while (std::getline(hs, line)) { + std::istringstream ls(line); + std::string head; + ls >> head; + if (head == "DIMENSIONS") { + ls >> dims[0] >> dims[1] >> dims[2]; + } else if (head == "ORIGIN") { + ls >> org[0] >> org[1] >> org[2]; + } else if (head == "POINT_DATA") { + ls >> npts; + } else if (head == "SCALARS") { + ls >> scal_name >> scal_type >> scal_comps; + } else if (head == "LOOKUP_TABLE") { + payload_at = static_cast(hs.tellg()); + break; + } + } + CHECK(scal_name == "my_field"); // whitespace in the label is made a single token + CHECK(scal_type == kw); + CHECK(scal_comps == comps); + if (!owns) { + // Placeholder shard: valid header, no payload, flagged as empty in the title. + ++empty_shards; + CHECK(dims[0] == 0 && dims[1] == 0 && dims[2] == 0 && npts == 0); + CHECK(bytes.size() == payload_at + 1U); // just the newline that ends the SCALARS block + CHECK(bytes.find("empty") != std::string::npos); + } else { + CHECK(dims[0] == ch.owned.x && dims[1] == ch.owned.y && dims[2] == ch.owned.z); + CHECK(org[0] == own0.x && org[1] == own0.y && org[2] == own0.z); + CHECK(npts == ch.owned.x * ch.owned.y * ch.owned.z); + const size_t payload_bytes = + static_cast(npts) * static_cast(comps) * sizeof(T); + CHECK(bytes.size() == payload_at + payload_bytes + 1U); + const auto* raw = reinterpret_cast(bytes.data()) + payload_at; + for (int64_t z = 0; z < dims[2]; ++z) { + for (int64_t y = 0; y < dims[1]; ++y) { + for (int64_t x = 0; x < dims[0]; ++x) { + const int64_t pt = (z * dims[1] + y) * dims[0] + x; + for (int k = 0; k < comps; ++k) { + const T got = + decode_be(raw + (static_cast(pt) * static_cast(comps) + + static_cast(k)) * + sizeof(T)); + CHECK(got == static_cast(vtk_value(org[0] + x, org[1] + y, org[2] + z, k))); + } + } + } + // tiling bookkeeping (uses only what the header says) + } + for (int64_t z = 0; z < dims[2]; ++z) { + for (int64_t y = 0; y < dims[1]; ++y) { + for (int64_t x = 0; x < dims[0]; ++x) { + cover[static_cast(((org[2] + z) * c.gy + (org[1] + y)) * c.gx + org[0] + x)] += + 1; + } + } + } + points += static_cast(npts); + } + + // --- library round trip: owned cells restored, halo cells untouched ------------------------ + std::istringstream in(bytes); + std::vector recs; + vtk::parse_vtk_box_header(in, "mem", box, recs); + CHECK(recs.size() == 1U); + CHECK(recs[0].components == comps && recs[0].vtk_dtype == kw); + const T sentinel2 = static_cast(-555); + std::vector back(buf.size(), sentinel2); + std::vector mut; + if (owns) { + vtk::VtkBoxPieceMut m; + m.start = back.data() + halo.z * ch.xy_pitch + halo.y * ch.haloed.x + halo.x; + m.nx = ch.owned.x; + m.ny = ch.owned.y; + m.nz = ch.owned.z; + m.row_stride = ch.haloed.x; + m.plane_pitch = ch.xy_pitch; + m.comp_stride = per_comp; + mut.push_back(m); + } + in.clear(); + in.seekg(recs[0].payload_offset); + vtk::read_vtk_box_field_payload(in, sizeof(T), comps, box, mut); + for (int64_t z = 0; z < ch.haloed.z; ++z) { + for (int64_t y = 0; y < ch.haloed.y; ++y) { + for (int64_t x = 0; x < ch.haloed.x; ++x) { + const bool in_owned = x >= halo.x && x < halo.x + ch.owned.x && y >= halo.y && + y < halo.y + ch.owned.y && z >= halo.z && z < halo.z + ch.owned.z; + for (int k = 0; k < comps; ++k) { + const size_t i = + static_cast(k * per_comp + z * ch.xy_pitch + y * ch.haloed.x + x); + CHECK(in_owned ? back[i] == buf[i] : back[i] == sentinel2); + } + } + } + } + + // --- a shard from a different box must be rejected ----------------------------------------- + if (owns) { + vtk::VtkBox other = box; + other.origin[0] += 1; + std::istringstream in2(bytes); + std::vector recs2; + bool threw = false; + carbon::log::set_level(spdlog::level::off); // the library logs the (expected) rejection + try { + vtk::parse_vtk_box_header(in2, "mem", other, recs2); + } catch (const std::invalid_argument&) { + threw = true; + } + carbon::log::set_level(spdlog::level::info); + CHECK(threw); + } + } +} + +auto +part_d_vtk(size_t& shards, + size_t& empty_shards, + size_t& points) -> size_t { + constexpr auto kO = BoundaryModeDistributed::Open; + constexpr auto kX = BoundaryModeDistributed::PeriodicX; + constexpr auto kZ = BoundaryModeDistributed::PeriodicZ; + const std::vector cases = { + {"slab", 1, 1, 4, kO, 6, 5, 9}, + {"slab-periodicZ", 1, 1, 3, kZ, 5, 4, 7}, + {"pencil", 1, 2, 2, kO, 6, 7, 8}, + {"pencil-periodicX", 1, 2, 2, kX, 5, 6, 4}, + {"brick-uneven", 3, 2, 2, kO, 8, 5, 6}, + {"brick-thin", 2, 2, 2, kX | kZ, 3, 3, 3}, + // 2 layers over 4 z-parts and 1 over 2 y-parts: half of the ranks own no cells. + {"brick-empty-ranks", 2, 2, 4, kO, 3, 1, 2}, + }; + for (const VtkCase& c : cases) { + std::vector cover(static_cast(c.gx * c.gy * c.gz), 0); + vtk_roundtrip_case(c, 2, cover, shards, empty_shards, points); + for (const int m : cover) { + CHECK(m == 1); // shard boxes tile the global domain exactly once + } + // Other element sizes / component counts (tiling already shown above; reuse a scratch map). + std::vector scratch32(cover.size(), 0); + vtk_roundtrip_case(c, 3, scratch32, shards, empty_shards, points); + std::vector scratch64(cover.size(), 0); + vtk_roundtrip_case(c, 1, scratch64, shards, empty_shards, points); + } + CHECK(empty_shards > 0U); // the placeholder path must actually be exercised + return cases.size(); +} + struct Scenario { const char* name; int px, py, pz; @@ -900,6 +1200,13 @@ main() { std::printf("geometry cases=%zu owned cells checked=%zu neighbour reads checked=%zu\n", geom_cases, geom_cells, geom_neighbours); + size_t vtk_shards = 0; + size_t vtk_empty = 0; + size_t vtk_points = 0; + const size_t vtk_cases = part_d_vtk(vtk_shards, vtk_empty, vtk_points); + std::printf("vtk cases=%zu shards=%zu (placeholders=%zu) points verified=%zu\n", vtk_cases, + vtk_shards, vtk_empty, vtk_points); + std::vector sc; const BoundaryModeDistributed modes[] = { kOpen, kPX, kPY, kPZ, bm_or(kPX, kPZ), bm_or(bm_or(kPX, kPY), kPZ)}; From 5b0d192ff839c8900351a00c5748a45076b68e1f Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Thu, 5 Nov 2026 17:50:17 +0100 Subject: [PATCH 07/33] Checking correctness vtk output --- benchmarks/cg/CMakeLists.txt | 3 +- benchmarks/cg/cg_poisson.cu | 143 ++- .../lbm_lid_driven_cavity_distributed.cu | 3 +- src/io_vtk_distributed.cpp | 4 +- src/io_vtk_distributed_wrong.cpp | 881 ++++++++++++++++++ 5 files changed, 1029 insertions(+), 5 deletions(-) create mode 100644 src/io_vtk_distributed_wrong.cpp diff --git a/benchmarks/cg/CMakeLists.txt b/benchmarks/cg/CMakeLists.txt index 7d655e69..4e7df925 100644 --- a/benchmarks/cg/CMakeLists.txt +++ b/benchmarks/cg/CMakeLists.txt @@ -1,2 +1,3 @@ _carbon_benchmark_add(carbon_benchmark_cg_poisson cg_poisson.cu) -target_link_libraries(carbon_benchmark_cg_poisson PRIVATE carbon::carbon carbon_benchmark_common) +target_link_libraries(carbon_benchmark_cg_poisson PRIVATE carbon::carbon carbon::third_party::clipp carbon_benchmark_common) + diff --git a/benchmarks/cg/cg_poisson.cu b/benchmarks/cg/cg_poisson.cu index b20bfbdd..6495eb4d 100644 --- a/benchmarks/cg/cg_poisson.cu +++ b/benchmarks/cg/cg_poisson.cu @@ -113,6 +113,7 @@ #include #include #include +#include // NEW: write_vtk / write_vtk_multiblock_index #include #include #include @@ -122,6 +123,7 @@ #include #include + #ifdef CARBON_HAVE_MPI_NCCL #include #endif @@ -143,6 +145,7 @@ #include #include #include +#include // NEW: std::is_same_v #if __has_include() # include @@ -219,6 +222,7 @@ struct Options { std::string dec; std::string dot_out_prefix; bool dot_matrix = false; + std::string vtk_path = ""; // NEW }; // Build a clipp parser bound directly to @p opts. Mirrors the structure of the @@ -260,6 +264,10 @@ build_cli(Options& opts) -> clipp::group { "(tag = init | iter_pre | iter_post)", (option("--dot-matrix").set(opts.dot_matrix)) % "With --dot-out, also write launch-matrix and kernel-list DOT files", + (option("--vtk-out") & value("path", opts.vtk_path)) % + "After the solve, dump the solution u and its gradient as a VTK " + "legacy STRUCTURED_POINTS file at PATH (appends .rankN under MPI; " + "Dense and DenseDistributed only). Off by default.", (option("--decomposition") & value("mode", opts.dec)) % "MPI decomposition: slab | pencil | brick (default: slab, only relevant for distributed runs)"; @@ -675,6 +683,74 @@ build_reduce_pAp(const Grid& grid, dst, carbon::reduce::Sum{}, std::move(name), /*shared_mem=*/0U); } + + +// Convert the (double) solution to a (float) HostDevice field for VTK export. +template +[[nodiscard]] auto +build_solution_to_float(const Grid& grid, + typename Grid::template Field& u, + typename Grid::template Field& u_out, + std::string name) -> carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return carbon::Kernel::compute( + grid, + [&u, &u_out](carbon::KernelLoader& loader) { + const auto u_p = loader.read(u); + auto out_p = loader.write(u_out); + return [u_p, out_p] CARBON_HOST_DEVICE(Span s, Idx idx) -> void { + out_p.write(s, idx, 0, static_cast(u_p.read(s, idx, 0))); + }; + }, + std::move(name)); +} + +// Central-difference gradient of the solution (for the VTK vector field). +// Dirichlet rows (zm or zp missing) -> zero vector: their u is the prescribed +// boundary value, so an interior-difference there is not meaningful. +template +[[nodiscard]] auto +build_gradient(const Grid& grid, + typename Grid::template Field& u, + typename Grid::template Field& grad, + double inv2h, + std::string name) -> carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return carbon::Kernel::compute( + grid, + [&u, &grad, inv2h](carbon::KernelLoader& loader) { + const auto u_p = loader.read_stencil(u); + auto g_p = loader.write(grad); + return [u_p, g_p, inv2h] CARBON_HOST_DEVICE(Span s, Idx idx) -> void { + const auto zm = u_p.neighbour(s, idx, carbon::int8_3d{0, 0, -1}, 0); + const auto zp = u_p.neighbour(s, idx, carbon::int8_3d{0, 0, 1}, 0); + if (!zm.valid || !zp.valid) { + g_p.write(s, idx, 0, 0.0F); + g_p.write(s, idx, 1, 0.0F); + g_p.write(s, idx, 2, 0.0F); + return; + } + const auto xp = u_p.neighbour(s, idx, carbon::int8_3d{1, 0, 0}, 0); + const auto xm = u_p.neighbour(s, idx, carbon::int8_3d{-1, 0, 0}, 0); + const auto yp = u_p.neighbour(s, idx, carbon::int8_3d{0, 1, 0}, 0); + const auto ym = u_p.neighbour(s, idx, carbon::int8_3d{0, -1, 0}, 0); + const float gx = (xp.valid && xm.valid) + ? static_cast((xp.value - xm.value) * inv2h) + : 0.0F; + const float gy = (yp.valid && ym.valid) + ? static_cast((yp.value - ym.value) * inv2h) + : 0.0F; + const float gz = static_cast((zp.value - zm.value) * inv2h); + g_p.write(s, idx, 0, gx); + g_p.write(s, idx, 1, gy); + g_p.write(s, idx, 2, gz); + }; + }, + std::move(name)); +} + // ---- Solver ---- template @@ -875,9 +951,74 @@ run_cg(Grid& grid, } } + + + // ---- Optional VTK dump ------------------------------------------------ + // Same pattern as benchmarks/lbm_lid_driven_cavity: build a small + // Skeleton that materialises the solution (and a gradient) into + // HostDevice fields, download them, then write via carbon::io::write_vtk. + // Only carbon::Dense and carbon::DenseDistributed have a VTK writer; + // DenseDisg and Block are skipped with a warning (matching LBM). + if (!opts.vtk_path.empty()) { + if constexpr (std::is_same_v || + std::is_same_v) { + auto u_scalar = + grid.template newField(carbon::MemorySide::HostDevice, "u"); + auto grad_field = + grid.template newField(carbon::MemorySide::HostDevice, "grad_u"); + + carbon::Skeleton vtk_sk(sys); + vtk_sk.add(build_solution_to_float(grid, u, u_scalar, "vtk_u")); + vtk_sk.add(build_gradient(grid, u, grad_field, /*inv2h=*/invh2 * 0.5, + "vtk_grad")); + try { + vtk_sk.compile(); + vtk_sk.run(); + vtk_sk.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("cg_poisson_unified: VTK kernel failed: {}", e.what()); + return EXIT_FAILURE; + } + + carbon::Stream dl_stream = sys.stream(); + try { + carbon::Transfer(sys, u_scalar.gpu_buffers(), + u_scalar.cpu_buffers())(dl_stream); + carbon::Transfer(sys, grad_field.gpu_buffers(), + grad_field.cpu_buffers())(dl_stream); + dl_stream.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("cg_poisson_unified: VTK download failed: {}", e.what()); + return EXIT_FAILURE; + } + + try { + carbon::io::write_vtk(opts.vtk_path, grid, u_scalar, grad_field); + // Master .vtm alongside the per-rank shards (no-op on single rank). + carbon::io::write_vtk_multiblock_index(opts.vtk_path, grid); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("cg_poisson_unified: write_vtk('{}') failed: {}", + opts.vtk_path, e.what()); + return EXIT_FAILURE; + } + if (world_rank == 0) { + CARBON_LOG_INFO("cg_poisson_unified[{}]: wrote VTK (u + grad_u) to {}", + grid_tag, opts.vtk_path); + } + } else { + if (world_rank == 0) { + CARBON_LOG_WARN( + "cg_poisson_unified[{}]: --vtk-out is only supported for --grid dense " + "and --grid dense_distributed (no VTK writer for {}); skipping dump.", + grid_tag, grid_tag); + } + } + } + // ---- end VTK dump ----------------------------------------------------- + if (iter == opts.max_iter && world_rank == 0) { CARBON_LOG_INFO("cg_poisson_unified[{}]: halted at max_iter={}, convergence status: {}", - grid_tag, opts.max_iter, is_true(converged)); + grid_tag, opts.max_iter, converged); return EXIT_SUCCESS; } diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu b/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu index dc33f72f..afbded5f 100644 --- a/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu +++ b/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu @@ -799,7 +799,8 @@ run_benchmark(const Options& opts, // DenseDisg and DenseDistributed have no VTK writer today, so the dump is // Dense-only; those runs still report MLUPS, they just skip the optional // VTK export. - if constexpr (std::is_same_v) { + + if constexpr (std::is_same_v || std::is_same_v) { // The hot loop alternates sk_ab (reads pop_a, writes pop_b) on even iters // with sk_ba (reads pop_b, writes pop_a) on odd. After `iters` iterations // the freshest output buffer is therefore pop_b when iters is odd and diff --git a/src/io_vtk_distributed.cpp b/src/io_vtk_distributed.cpp index 099c340c..2beb19a5 100644 --- a/src/io_vtk_distributed.cpp +++ b/src/io_vtk_distributed.cpp @@ -143,7 +143,7 @@ shard_path_of(std::string_view base, #ifdef CARBON_HAVE_MPI_NCCL if (grid.system().distributed() != nullptr) { std::ostringstream oss; - oss << base << ".rank" << grid.system().distributed()->world_rank(); + oss << base << ".rank" << grid.system().distributed()->world_rank()<<".vtk"; return oss.str(); } #else @@ -813,7 +813,7 @@ write_vtk_multiblock_index(std::string_view base, int block = 0; for (const int r : listed) { out << " \n"; - out << " \n"; out << " \n"; } diff --git a/src/io_vtk_distributed_wrong.cpp b/src/io_vtk_distributed_wrong.cpp new file mode 100644 index 00000000..c9abce68 --- /dev/null +++ b/src/io_vtk_distributed_wrong.cpp @@ -0,0 +1,881 @@ +// VTK XML (vti) backend for carbon::DenseDistributed (slab / pencil / brick). +// See include/carbon/detail/io_vtk_distributed.inl for the public surface. + +#include +#include +#include +#include + +#ifdef CARBON_HAVE_MPI_NCCL +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace carbon::io::detail { + +namespace { + +namespace dd = ::carbon::detail::dense_distributed; + +/** Staging block for payload I/O: rows are batched so the stream sees few, large transfers. */ +constexpr size_t kBlockBytes = size_t{4} << 20; + +[[nodiscard]] constexpr auto +host_is_little_endian() noexcept -> bool { + return std::endian::native == std::endian::little; +} + +/** Reverse the bytes of @p n consecutive @c ES -byte elements (legacy VTK payloads are BE). */ +template +void +swap_run(std::uint8_t* p, + size_t n) noexcept { + if constexpr (ES > 1) { + for (size_t i = 0; i < n; ++i) { + std::uint8_t* e = p + i * ES; + for (size_t k = 0; k < ES / 2; ++k) { + std::swap(e[k], e[ES - 1 - k]); + } + } + } +} + +/** Map a carbon native dtype tag (8-char, NUL padded) to the VTK legacy keyword; null if unknown. */ +[[nodiscard]] auto +vtk_keyword_from_native_tag(const char* tag) noexcept -> const char* { + const std::string_view t(tag, 8); + if (t.starts_with("f32")) { + return "float"; + } + if (t.starts_with("f64")) { + return "double"; + } + if (t.starts_with("i8")) { + return "char"; + } + if (t.starts_with("u8")) { + return "unsigned_char"; + } + if (t.starts_with("i16")) { + return "short"; + } + if (t.starts_with("u16")) { + return "unsigned_short"; + } + if (t.starts_with("i32")) { + return "int"; + } + if (t.starts_with("u32")) { + return "unsigned_int"; + } + if (t.starts_with("i64")) { + return "vtktypeint64"; + } + if (t.starts_with("u64")) { + return "vtktypeuint64"; + } + return nullptr; +} + +/** Map a carbon native dtype tag to the VTK XML keyword; null if unknown. */ +[[nodiscard]] auto +vtk_xml_keyword_from_native_tag(const char* tag) noexcept -> const char* { + const std::string_view t(tag, 8); + if (t.starts_with("f32")) return "Float32"; + if (t.starts_with("f64")) return "Float64"; + if (t.starts_with("i8")) return "Int8"; + if (t.starts_with("u8")) return "UInt8"; + if (t.starts_with("i16")) return "Int16"; + if (t.starts_with("u16")) return "UInt16"; + if (t.starts_with("i32")) return "Int32"; + if (t.starts_with("u32")) return "UInt32"; + if (t.starts_with("i64")) return "Int64"; + if (t.starts_with("u64")) return "UInt64"; + return nullptr; +} + +[[nodiscard]] auto +element_size_of_keyword(const std::string& kw) noexcept -> size_t { + if (kw == "char" || kw == "unsigned_char" || kw == "Int8" || kw == "UInt8") return 1; + if (kw == "short" || kw == "unsigned_short" || kw == "Int16" || kw == "UInt16") return 2; + if (kw == "int" || kw == "unsigned_int" || kw == "float" || kw == "Int32" || kw == "UInt32" || kw == "Float32") return 4; + if (kw == "double" || kw == "vtktypeint64" || kw == "vtktypeuint64" || kw == "long" || + kw == "unsigned_long" || kw == "Int64" || kw == "UInt64" || kw == "Float64") return 8; + return 0; +} + +void +rtrim_inplace(std::string& s) noexcept { + while (!s.empty() && (s.back() == '\r' || s.back() == ' ' || s.back() == '\t')) { + s.pop_back(); + } +} + +/** Legacy SCALARS names are whitespace-delimited tokens: make the label a single token. */ +[[nodiscard]] auto +sanitize_name(std::string_view name) -> std::string { + std::string out(name); + for (char& c : out) { + if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\"' || c == '<' || c == '>') { + c = '_'; + } + } + return out.empty() ? std::string("field") : out; +} + +[[nodiscard]] auto +shard_path_of(std::string_view base, + const DenseDistributed& grid) -> std::string { +#ifdef CARBON_HAVE_MPI_NCCL + if (grid.system().distributed() != nullptr) { + std::ostringstream oss; + oss << base << ".rank" << grid.system().distributed()->world_rank() << ".vti"; + return oss.str(); + } +#else + (void)grid; +#endif + return std::string(base) + ".vti"; +} + +[[nodiscard]] auto +pieces_cells(const std::vector& pieces) -> int64_t { + int64_t n = 0; + for (const auto& p : pieces) { + n += p.nx * p.ny * p.nz; + } + return n; +} + +// ---- payload gather / scatter (compile-time element size) ---------------------------------- + +/** One owned row of @p nx cells -> interleaved (component-fastest) record bytes. */ +template +void +gather_row(std::uint8_t* dst, + const std::uint8_t* src, + int64_t nx, + int comps, + int64_t comp_stride_elems) noexcept { + if (comps == 1) { + std::memcpy(dst, src, static_cast(nx) * ES); + return; + } + const size_t stride = static_cast(comps) * ES; + for (int c = 0; c < comps; ++c) { + const std::uint8_t* s = src + static_cast(c * comp_stride_elems) * ES; + std::uint8_t* d = dst + static_cast(c) * ES; + for (int64_t x = 0; x < nx; ++x) { + std::memcpy(d + static_cast(x) * stride, s + static_cast(x) * ES, ES); + } + } +} + +/** Interleaved record bytes -> one owned row (inverse of @ref gather_row). */ +template +void +scatter_row(std::uint8_t* dst, + const std::uint8_t* src, + int64_t nx, + int comps, + int64_t comp_stride_elems) noexcept { + if (comps == 1) { + std::memcpy(dst, src, static_cast(nx) * ES); + return; + } + const size_t stride = static_cast(comps) * ES; + for (int c = 0; c < comps; ++c) { + std::uint8_t* d = dst + static_cast(c * comp_stride_elems) * ES; + const std::uint8_t* s = src + static_cast(c) * ES; + for (int64_t x = 0; x < nx; ++x) { + std::memcpy(d + static_cast(x) * ES, s + static_cast(x) * stride, ES); + } + } +} + +[[nodiscard]] inline auto +row_ptr(const VtkBoxPiece& p, + size_t es, + int64_t z, + int64_t y) noexcept -> const std::uint8_t* { + return static_cast(p.start) + + static_cast(z * p.plane_pitch + y * p.row_stride) * es; +} + +[[nodiscard]] inline auto +row_ptr(const VtkBoxPieceMut& p, + size_t es, + int64_t z, + int64_t y) noexcept -> std::uint8_t* { + return static_cast(p.start) + + static_cast(z * p.plane_pitch + y * p.row_stride) * es; +} + +// --- LEGACY PAYLOAD HELPERS (Required for tests) --- + +template +void +write_payload(std::ostream& out, + int comps, + const std::vector& pieces) { + size_t total_bytes = 0; + size_t max_row_bytes = 0; + for (const auto& p : pieces) { + const size_t row = static_cast(p.nx) * static_cast(comps) * ES; + total_bytes += row * static_cast(p.ny) * static_cast(p.nz); + max_row_bytes = std::max(max_row_bytes, row); + } + if (total_bytes == 0) { + return; + } + std::vector block(std::max(std::min(total_bytes, kBlockBytes), max_row_bytes)); + size_t used = 0; + const auto flush = [&] { + if (used == 0) { + return; + } + if (host_is_little_endian()) { + swap_run(block.data(), used / ES); + } + out.write(reinterpret_cast(block.data()), static_cast(used)); + used = 0; + }; + for (const auto& p : pieces) { + const size_t row_bytes = static_cast(p.nx) * static_cast(comps) * ES; + for (int64_t z = 0; z < p.nz; ++z) { + for (int64_t y = 0; y < p.ny; ++y) { + if (used + row_bytes > block.size()) { + flush(); + } + gather_row(block.data() + used, row_ptr(p, ES, z, y), p.nx, comps, p.comp_stride); + used += row_bytes; + } + } + } + flush(); +} + +template +void +read_payload(std::istream& in, + int comps, + const std::vector& pieces) { + size_t max_row_bytes = 0; + size_t total_bytes = 0; + for (const auto& p : pieces) { + const size_t row = static_cast(p.nx) * static_cast(comps) * ES; + max_row_bytes = std::max(max_row_bytes, row); + total_bytes += row * static_cast(p.ny) * static_cast(p.nz); + } + if (total_bytes == 0) { + return; + } + std::vector block(std::max(std::min(total_bytes, kBlockBytes), max_row_bytes)); + for (const auto& p : pieces) { + const size_t row_bytes = static_cast(p.nx) * static_cast(comps) * ES; + const int64_t rows_total = p.ny * p.nz; + const int64_t rows_per_block = static_cast(block.size() / row_bytes); + for (int64_t r0 = 0; r0 < rows_total; r0 += rows_per_block) { + const int64_t rows = std::min(rows_per_block, rows_total - r0); + const size_t bytes = static_cast(rows) * row_bytes; + in.read(reinterpret_cast(block.data()), static_cast(bytes)); + if (!in.good()) { + log::throw_with_log( + "io::read_vtk: short read in payload (row {} of {})", r0, rows_total); + } + if (host_is_little_endian()) { + swap_run(block.data(), bytes / ES); + } + for (int64_t i = 0; i < rows; ++i) { + const int64_t r = r0 + i; + scatter_row(row_ptr(p, ES, r / p.ny, r % p.ny), + block.data() + static_cast(i) * row_bytes, p.nx, comps, + p.comp_stride); + } + } + } +} + +// --- XML PAYLOAD HELPERS --- + +template +void +write_xml_payload_to_buffer(std::uint8_t* dst, + int comps, + const std::vector& pieces) { + size_t used = 0; + for (const auto& p : pieces) { + const size_t row_bytes = static_cast(p.nx) * static_cast(comps) * ES; + for (int64_t z = 0; z < p.nz; ++z) { + for (int64_t y = 0; y < p.ny; ++y) { + gather_row(dst + used, row_ptr(p, ES, z, y), p.nx, comps, p.comp_stride); + used += row_bytes; + } + } + } +} + +} // namespace + +// ================================================================================================ +// Box geometry +// ================================================================================================ + +auto +vtk_box_of(const DenseDistributed& grid) -> VtkBox { + VtkBox box; + const auto& spans = grid.spans(); + if (spans.empty()) { + return box; + } + const auto owned_origin = [](const auto& span) -> int64_3d { + const int64_3d o = span.offset(); + const int64_3d h = span.halo(); + return int64_3d{o.x + h.x, o.y + h.y, o.z + h.z}; + }; + const int64_3d first = owned_origin(spans.front()); + box.origin[0] = first.x; + box.origin[1] = first.y; + box.origin[2] = first.z; + + int64_t z_total = 0; + int64_3d prev_origin{}; + int64_t prev_nz = 0; + bool have_prev = false; + int64_t nx = 0; + int64_t ny = 0; + for (const auto& span : spans) { + const int64_3d owned = span.logic_extent(); + if (owned.x <= 0 || owned.y <= 0 || owned.z <= 0) { + continue; + } + const int64_3d o = owned_origin(span); + if (!have_prev) { + nx = owned.x; + ny = owned.y; + box.origin[0] = o.x; + box.origin[1] = o.y; + box.origin[2] = o.z; + } else if (owned.x != nx || owned.y != ny || o.x != prev_origin.x || o.y != prev_origin.y || + o.z != prev_origin.z + prev_nz) { + log::throw_with_log( + "io::vtk: the local spans of this DenseDistributed do not form a single box (only a " + "z-stacked slab can span several local GPUs)"); + } + z_total += owned.z; + prev_origin = o; + prev_nz = owned.z; + have_prev = true; + } + if (have_prev) { + box.dims[0] = nx; + box.dims[1] = ny; + box.dims[2] = z_total; + } + return box; +} + +// ================================================================================================ +// Stream-level building blocks (Legacy - required for tests) +// ================================================================================================ + +void +write_vtk_box_header(std::ostream& out, + const VtkBox& box) { + const bool empty = box.empty(); + out << "# vtk DataFile Version 3.0\n"; + out << (empty ? "carbon dense field shard (empty: this rank owns no cells)\n" : "carbon dense field shard\n"); + out << "BINARY\n"; + out << "DATASET STRUCTURED_POINTS\n"; + out << "DIMENSIONS " << (empty ? 0 : box.dims[0]) << ' ' << (empty ? 0 : box.dims[1]) << ' ' << (empty ? 0 : box.dims[2]) << '\n'; + out << "ORIGIN " << box.origin[0] << ' ' << box.origin[1] << ' ' << box.origin[2] << '\n'; + out << "SPACING 1 1 1\n"; + out << "POINT_DATA " << box.points() << '\n'; + if (!out.good()) log::throw_with_log("io::write_vtk: failed to write the shard header"); +} + +void +write_vtk_box_field(std::ostream& out, + std::string_view name, + const char* dtype_tag, + size_t element_size, + int components, + const VtkBox& box, + const std::vector& pieces) { + const char* kw = vtk_keyword_from_native_tag(dtype_tag); + if (kw == nullptr) log::throw_with_log("io::write_vtk: dtype error"); + if (components < 1 || components > 4) log::throw_with_log("io::write_vtk: components error"); + + out << "SCALARS " << sanitize_name(name) << ' ' << kw << ' ' << components << '\n'; + out << "LOOKUP_TABLE default\n"; + if (!box.empty()) { + switch (element_size) { + case 1: write_payload<1>(out, components, pieces); break; + case 2: write_payload<2>(out, components, pieces); break; + case 4: write_payload<4>(out, components, pieces); break; + case 8: write_payload<8>(out, components, pieces); break; + default: log::throw_with_log("io::write_vtk: unsupported size"); + } + } + out << '\n'; +} + +void +parse_vtk_box_header(std::istream& in, + std::string_view path, + const VtkBox& expected, + std::vector& out_fields) { + const auto next_line = [&](bool strict) -> std::string { + std::string line; + if (!std::getline(in, line)) { + if (strict) log::throw_with_log("io::read_vtk: header ended"); + return {}; + } + rtrim_inplace(line); + return line; + }; + + const auto magic = next_line(true); + if (magic.rfind("# vtk DataFile Version", 0) != 0) log::throw_with_log("io::read_vtk: bad magic"); + next_line(true); // title + if (next_line(true) != "BINARY") log::throw_with_log("io::read_vtk: not BINARY"); + if (next_line(true) != "DATASET STRUCTURED_POINTS") log::throw_with_log("io::read_vtk: not STRUCTURED_POINTS"); + + int64_t dims[3] = {0, 0, 0}; + int64_t origin[3] = {0, 0, 0}; + double spacing[3] = {1.0, 1.0, 1.0}; + int64_t point_count = -1; + while (point_count < 0) { + const auto cur = next_line(true); + if (cur.empty()) continue; + std::istringstream iss(cur); + std::string head; + iss >> head; + if (head == "DIMENSIONS") iss >> dims[0] >> dims[1] >> dims[2]; + else if (head == "ORIGIN") iss >> origin[0] >> origin[1] >> origin[2]; + else if (head == "SPACING" || head == "ASPECT_RATIO") iss >> spacing[0] >> spacing[1] >> spacing[2]; + else if (head == "POINT_DATA") iss >> point_count; + else log::throw_with_log("io::read_vtk: unexpected header"); + } + + while (in) { + const auto cur = next_line(false); + if (cur.empty()) { + if (in.eof()) break; + continue; + } + std::istringstream iss(cur); + std::string head; + iss >> head; + if (head != "SCALARS") log::throw_with_log("io::read_vtk: expected SCALARS"); + VtkBoxFieldRecord rec; + iss >> rec.name >> rec.vtk_dtype; + rec.components = 1; + iss >> rec.components; + next_line(true); // LOOKUP_TABLE + rec.payload_offset = in.tellg(); + const size_t es = element_size_of_keyword(rec.vtk_dtype); + in.seekg(rec.payload_offset + static_cast(point_count * rec.components * es)); + out_fields.push_back(std::move(rec)); + const int next_c = in.peek(); + if (next_c == '\n' || next_c == '\r') { + in.get(); + if (next_c == '\r' && in.peek() == '\n') in.get(); + } + } +} + +void +read_vtk_box_field_payload(std::istream& in, + size_t element_size, + int components, + const VtkBox& box, + const std::vector& pieces) { + if (box.empty()) return; + switch (element_size) { + case 1: read_payload<1>(in, components, pieces); break; + case 2: read_payload<2>(in, components, pieces); break; + case 4: read_payload<4>(in, components, pieces); break; + case 8: read_payload<8>(in, components, pieces); break; + default: log::throw_with_log("io::read_vtk: bad size"); + } +} + +// ================================================================================================ +// Stream-level building blocks (XML - used by VtkBoxSession) +// ================================================================================================ + +void +write_vtk_xml_box_header(std::ostream& out, + const VtkBox& box) { + out << "\n"; + out << "\n"; + const bool empty = box.empty(); + if (empty) { + out << " \n"; + out << " \n"; + } else { + out << " \n"; + out << " \n"; + } + out << " \n"; +} + +void +write_vtk_xml_box_field(std::ostream& out, + std::string_view name, + const char* dtype_tag, + size_t element_size, + int components, + const VtkBox& box, + const std::vector& pieces) { + const char* kw = vtk_xml_keyword_from_native_tag(dtype_tag); + if (kw == nullptr) log::throw_with_log("io::write_vtk: bad xml dtype"); + + out << " \n"; + + if (!box.empty()) { + size_t payload_bytes = static_cast(box.points()) * components * element_size; + std::vector raw_data(payload_bytes); + + switch (element_size) { + case 1: write_xml_payload_to_buffer<1>(raw_data.data(), components, pieces); break; + case 2: write_xml_payload_to_buffer<2>(raw_data.data(), components, pieces); break; + case 4: write_xml_payload_to_buffer<4>(raw_data.data(), components, pieces); break; + case 8: write_xml_payload_to_buffer<8>(raw_data.data(), components, pieces); break; + default: log::throw_with_log("io::write_vtk: bad size"); + } + + if (element_size == 4) { + const float* fdata = reinterpret_cast(raw_data.data()); + size_t n = payload_bytes / 4; + for (size_t i = 0; i < n; ++i) { + out << fdata[i] << " "; + if (i % 10 == 9) out << "\n"; + } + } else if (element_size == 8) { + const double* ddata = reinterpret_cast(raw_data.data()); + size_t n = payload_bytes / 8; + for (size_t i = 0; i < n; ++i) { + out << ddata[i] << " "; + if (i % 10 == 9) out << "\n"; + } + } else { + for (size_t i = 0; i < payload_bytes; ++i) { + out << static_cast(raw_data[i]) << " "; + if (i % 10 == 9) out << "\n"; + } + } + } + out << "\n \n"; +} + +void +parse_vtk_xml_box_header(std::istream& in, + std::string_view path, + const VtkBox& expected, + std::vector& out_fields) { + std::string line; + auto get_attr = [](const std::string& s, const std::string& key) -> std::string { + std::string k = key + "=\""; + auto pos = s.find(k); + if (pos == std::string::npos) return ""; + pos += k.size(); + auto end = s.find("\"", pos); + return s.substr(pos, end - pos); + }; + + while (std::getline(in, line)) { + if (line.find("> e0 >> e1 >> e2 >> e3 >> e4 >> e5) { + dims[0] = e1 - e0 + 1; + dims[1] = e3 - e2 + 1; + dims[2] = e5 - e4 + 1; + } + + std::stringstream ss_org(origin_str); + ss_org >> origin[0] >> origin[1] >> origin[2]; + + const bool want_empty = expected.empty(); + const int64_t want_dims[3] = {want_empty ? 0 : expected.dims[0], + want_empty ? 0 : expected.dims[1], + want_empty ? 0 : expected.dims[2]}; + if (dims[0] != want_dims[0] || dims[1] != want_dims[1] || dims[2] != want_dims[2]) { + log::throw_with_log( + "io::read_vtk: '{}' DIMENSIONS ({}, {}, {}) do not match this rank's owned box ({}, {}, {})", + path, dims[0], dims[1], dims[2], want_dims[0], want_dims[1], want_dims[2]); + } + if (origin[0] != expected.origin[0] || origin[1] != expected.origin[1] || origin[2] != expected.origin[2]) { + log::throw_with_log( + "io::read_vtk: '{}' ORIGIN ({}, {}, {}) does not match this rank's box origin ({}, {}, {})", + path, origin[0], origin[1], origin[2], expected.origin[0], expected.origin[1], expected.origin[2]); + } + } else if (line.find("") != std::string::npos) break; + } + } + } +} + +void +read_vtk_xml_box_field_payload(std::istream& in, + size_t element_size, + int components, + const VtkBox& box, + const std::vector& pieces) { + if (box.empty()) return; + size_t total_elements = static_cast(box.points()) * components; + std::vector fdata(total_elements); + for (size_t i = 0; i < total_elements; ++i) { + in >> fdata[i]; + } + + size_t offset = 0; + for (const auto& p : pieces) { + const size_t row_bytes = static_cast(p.nx) * static_cast(components) * element_size; + for (int64_t z = 0; z < p.nz; ++z) { + for (int64_t y = 0; y < p.ny; ++y) { + std::memcpy(row_ptr(p, element_size, z, y), fdata.data() + offset, row_bytes); + offset += p.nx * components; + } + } + } +} + +// ================================================================================================ +// Session +// ================================================================================================ + +struct VtkBoxSession::Impl { + std::string path; + bool for_write = false; + std::uint32_t num_fields_recorded = 0; + VtkBox box; + std::ofstream writer; + std::ifstream reader; + std::vector read_fields; + size_t read_fields_cursor = 0; + + void finalize() { + if (!writer.is_open()) return; + writer << " \n"; + writer << " \n"; + writer << " \n"; + writer << "\n"; + writer.flush(); + if (!writer.good()) { + log::throw_with_log("io::write_vtk: failed to finalize the shard"); + } + writer.close(); + } +}; + +VtkBoxSession::VtkBoxSession() noexcept = default; +VtkBoxSession::~VtkBoxSession() { + if (impl_ && impl_->for_write) { + impl_->finalize(); + } +} +VtkBoxSession::VtkBoxSession(VtkBoxSession&&) noexcept = default; +auto +VtkBoxSession::operator=(VtkBoxSession&&) noexcept -> VtkBoxSession& = default; + +auto +VtkBoxSession::shard_path(std::string_view base, + const DenseDistributed& grid) -> std::string { + return shard_path_of(base, grid); +} + +void +VtkBoxSession::open_for_write(std::string_view path, + const DenseDistributed& grid, + std::uint32_t /*num_fields*/) { + if (impl_ && impl_->for_write) { + impl_->finalize(); + } + impl_ = std::make_unique(); + impl_->path = shard_path_of(path, grid); + impl_->for_write = true; + impl_->box = vtk_box_of(grid); + impl_->writer.open(impl_->path, std::ios::binary | std::ios::trunc); + if (!impl_->writer) { + log::throw_with_log("io::write_vtk: failed to open '{}' for writing", + impl_->path); + } + write_vtk_xml_box_header(impl_->writer, impl_->box); +} + +void +VtkBoxSession::write_field(std::string_view name, + const char* dtype_tag, + size_t element_size, + int components, + const std::vector& pieces) { + if (impl_ == nullptr || !impl_->for_write) { + log::throw_with_log("io::write_vtk: session is not in a writable state"); + } + write_vtk_xml_box_field(impl_->writer, name, dtype_tag, element_size, components, impl_->box, pieces); + ++impl_->num_fields_recorded; +} + +void +VtkBoxSession::open_for_read(std::string_view path, + const DenseDistributed& grid) { + impl_ = std::make_unique(); + impl_->path = shard_path_of(path, grid); + impl_->for_write = false; + impl_->box = vtk_box_of(grid); + impl_->reader.open(impl_->path, std::ios::binary); + if (!impl_->reader) { + log::throw_with_log("io::read_vtk: failed to open '{}' for reading", + impl_->path); + } + parse_vtk_xml_box_header(impl_->reader, impl_->path, impl_->box, impl_->read_fields); +} + +void +VtkBoxSession::read_field(std::string_view /*name*/, + const char* dtype_tag, + size_t element_size, + int components, + const std::vector& pieces) { + if (impl_ == nullptr || impl_->for_write) { + log::throw_with_log("io::read_vtk: session is not in a readable state"); + } + if (impl_->read_fields_cursor >= impl_->read_fields.size()) { + log::throw_with_log( + "io::read_vtk: more fields requested than '{}' contains", impl_->path); + } + const auto& rec = impl_->read_fields[impl_->read_fields_cursor++]; + const char* expected_kw = vtk_xml_keyword_from_native_tag(dtype_tag); + if (expected_kw == nullptr || rec.vtk_dtype != expected_kw) { + log::throw_with_log( + "io::read_vtk: field {} dtype '{}' does not match bound carbon dtype '{}' in '{}'", + rec.name, rec.vtk_dtype, (expected_kw != nullptr ? expected_kw : "?"), impl_->path); + } + if (rec.components != components) { + log::throw_with_log( + "io::read_vtk: field {} has {} components but the bound Field has {}", rec.name, + rec.components, components); + } + impl_->reader.clear(); + impl_->reader.seekg(rec.payload_offset); + if (!impl_->reader.good()) { + log::throw_with_log( + "io::read_vtk: seek to the payload of '{}' failed in '{}'", rec.name, impl_->path); + } + read_vtk_xml_box_field_payload(impl_->reader, element_size, components, impl_->box, pieces); +} + +auto +VtkBoxSession::num_fields() const noexcept -> std::uint32_t { + if (impl_ == nullptr) { + return 0U; + } + return impl_->for_write ? impl_->num_fields_recorded + : static_cast(impl_->read_fields.size()); +} + +} // namespace carbon::io::detail + +namespace carbon::io { + +auto +write_vtk_multiblock_index(std::string_view base, + const DenseDistributed& grid) -> void { +#ifdef CARBON_HAVE_MPI_NCCL + const auto* dist = grid.system().distributed(); + if (dist == nullptr) { + return; + } + const int world_size = dist->world_size(); + if (world_size <= 1 || dist->world_rank() != 0) { + return; + } + + const ProcessGrid& pg = grid.process_grid(); + const int64_3d global = grid.global_extent(); + std::vector listed; + for (int r = 0; r < world_size; ++r) { + bool owns = true; + if (pg.world_size() == world_size) { + const auto chunk = ::carbon::detail::dense_distributed::rank_chunk( + global, pg, pg.coords_of(r), int64_3d{0, 0, 0}); + owns = chunk.owned.x > 0 && chunk.owned.y > 0 && chunk.owned.z > 0; + } + if (owns) { + listed.push_back(r); + } + } + + const std::filesystem::path base_path(std::string{base}); + const std::filesystem::path master_path = base_path.string() + ".vtm"; + const std::filesystem::path base_filename = base_path.filename(); + + std::ofstream out(master_path, std::ios::binary | std::ios::trunc); + if (!out) { + log::throw_with_log( + "io::write_vtk_multiblock_index: failed to open '{}' for writing", master_path.string()); + } + out << "\n"; + out << "\n"; + out << " \n"; + int block = 0; + for (const int r : listed) { + out << " \n"; + out << " \n"; + out << " \n"; + } + out << " \n"; + out << "\n"; + if (!out.good()) { + log::throw_with_log("io::write_vtk_multiblock_index: write to '{}' failed", + master_path.string()); + } +#else + (void)base; + (void)grid; +#endif +} + +} // namespace carbon::io \ No newline at end of file From 76364c7bd0d074e11dfb796f7da3d24561a23055 Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:44:33 +0100 Subject: [PATCH 08/33] Fixing bug brick decomposition --- AGENTS.md | 29 +- .../lbm_lid_driven_cavity_distributed.cu | 20 + .../src/lbm_kernels.h | 29 +- denseDistributed_compactBoundary_vtk.patch | 2073 ----------------- docs/CHANGELOG.md | 13 + include/carbon/detail/halo_build.h | 18 +- include/carbon/detail/io_vtk.inl | 9 +- include/carbon/detail/io_vtk_distributed.inl | 63 +- include/carbon/halo.h | 13 +- include/carbon/halo_disg.h | 13 +- include/carbon/halo_distributed.h | 22 +- include/carbon/kernel.h | 3 +- include/carbon/stencil.h | 21 +- src/io_vtk_distributed.cpp | 751 +++++- src/io_vtk_distributed_wrong.cpp | 881 ------- src/stencil.cpp | 2 + tests/test_dense_distributed_dist.cu | 121 +- 17 files changed, 1007 insertions(+), 3074 deletions(-) delete mode 100644 denseDistributed_compactBoundary_vtk.patch delete mode 100644 src/io_vtk_distributed_wrong.cpp diff --git a/AGENTS.md b/AGENTS.md index f1981839..89f0b325 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -44,15 +44,17 @@ Optional HDF5 build adds `-DCARBON_ENABLE_HDF5=ON`; HDF5 is PRIVATE-linked and t is also set and the discovered HDF5 was compiled with MPI support, `CARBON_HAVE_PHDF5` is defined and `write_hdf5` / `read_hdf5` use collective MPI-IO writes against a single file. -VTK legacy I/O is always available — no external dependency, pure stdlib. -`carbon::io::write_vtk` / `read_vtk` write `DATASET STRUCTURED_POINTS` BINARY files -with one `SCALARS name dtype N` block per field under a shared `POINT_DATA` -section, big-endian payload (legacy spec mandates network byte order), component- -fastest interleaving. Multi-rank uses one file per rank with `.rank` suffix — -each shard is a self-contained VTK that ParaView/VTK can open independently. -Reader is strict (rejects XML VTK / non-BINARY / non-STRUCTURED_POINTS / non-unit -spacing / mismatched DIMENSIONS) so a wrong file fails fast rather than scrambling -field data. +VTK I/O is always available — no external dependency, pure stdlib. The `Dense` / +`DenseDisg` path writes legacy `DATASET STRUCTURED_POINTS` BINARY files with one +`SCALARS name dtype N` block per field under a shared `POINT_DATA` section, +big-endian payload (legacy spec mandates network byte order), component-fastest +interleaving. Multi-rank uses one file per rank with `.rank` suffix. The +`DenseDistributed` path writes XML ImageData `.vti` shards (unwrapped inline +base64 little-endian binary, `UInt64` block headers) named `.rank.vti` under MPI, plus +a `.vtm` multiblock index that references them. Both readers are strict (the legacy +reader rejects XML / non-BINARY / non-STRUCTURED_POINTS / non-unit spacing / +mismatched DIMENSIONS; the XML reader validates WholeExtent / Origin / Spacing and +inline block sizes) so a wrong file fails fast rather than scrambling field data. Optional nanoVDB build adds `-DCARBON_ENABLE_NANOVDB=ON`. Discovery order: first `-DCARBON_NANOVDB_INCLUDE_DIR=/path/to/nanovdb/headers` if the user already has @@ -449,10 +451,11 @@ how a feature behaves at the edges, grep the changelog for the section name include dir → `find_package(nanovdb)` → `FetchContent` OpenVDB `v11.0.0` (populate-only, skips TBB/Boost/blosc). Multi-rank writes one file per rank. Float / double / int32 today. -- **VTK legacy** — always-on, pure stdlib. `STRUCTURED_POINTS` BINARY - with one `SCALARS name dtype N` block per field; one file per rank - with `.rank` suffix. Strict reader (rejects XML / non-BINARY / - non-unit spacing / mismatched DIMENSIONS). +- **VTK** — always-on, pure stdlib. `Dense` / `DenseDisg` write legacy + `STRUCTURED_POINTS` BINARY with one `SCALARS name dtype N` block per + field; one file per rank with `.rank` suffix. `DenseDistributed` + writes XML ImageData `.vti` shards (inline base64 little-endian binary) + and a `.vtm` multiblock index. Strict readers on both paths. - **`carbon::io::write_native / read_native`** — multi-field per-rank binary format with explicit field metadata; the default for round-trip tests. Templated on Grid and shipping for both `Dense` and `DenseDisg` diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu b/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu index afbded5f..7863e758 100644 --- a/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu +++ b/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu @@ -73,6 +73,23 @@ #include #include + + +#if __has_include() +# include +# define CARBON_HALO_NVTX_PUSH(name) ::nvtxRangePushA(name) +# define CARBON_HALO_NVTX_POP() ::nvtxRangePop() +#elif __has_include() +# include +# define CARBON_HALO_NVTX_PUSH(name) ::nvtxRangePushA(name) +# define CARBON_HALO_NVTX_POP() ::nvtxRangePop() +#else +# define CARBON_HALO_NVTX_PUSH(name) ((void)0) +# define CARBON_HALO_NVTX_POP() ((void)0) +#endif + + + namespace { using carbon::bench::lbm::BgkCollision; @@ -675,6 +692,7 @@ run_benchmark(const Options& opts, opts.warmup); } } + CARBON_HALO_NVTX_PUSH("Iteration step"); carbon::Skeleton& sk = (it % 2 == 0) ? sk_ab : sk_ba; try { sk.run(); @@ -696,6 +714,8 @@ run_benchmark(const Options& opts, CARBON_LOG_INFO("lbm_lid_driven_cavity: iter {}/{} elapsed={:.3f}s", it + 1, opts.iters, elapsed_overall); } + CARBON_HALO_NVTX_POP(); + } try { diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/src/lbm_kernels.h b/benchmarks/lbm_lid_driven_cavity_distributed/src/lbm_kernels.h index 14d3a2a6..bc16844a 100644 --- a/benchmarks/lbm_lid_driven_cavity_distributed/src/lbm_kernels.h +++ b/benchmarks/lbm_lid_driven_cavity_distributed/src/lbm_kernels.h @@ -251,6 +251,21 @@ make_lattice_population_stencil() -> ::carbon::Stencil { return ::carbon::Stencil(pts); } +// Distributed brick / pencil decompositions need both nonzero signs of the +// face-normal population so a wall bounce-back can read opp(q) across a rank +// boundary. Slab layouts keep the cheaper one-sided lattice semantic. +template +[[nodiscard]] inline auto +population_halo_semantic(const Grid& grid) -> ::carbon::StencilSemantic { + if constexpr (requires { grid.process_grid(); }) { + const auto dims = grid.process_grid().dims(); + if (dims.x > 1 || dims.y > 1) { + return ::carbon::StencilSemantic::LatticeDistributed; + } + } + return ::carbon::StencilSemantic::Lattice; +} + // Pull-stream source offset for direction q: under pull streaming the cell // reads its q population from the neighbour at -c[q]. Returned as an // int8_3d so it can feed Partition::read_pull, the grid-generic @b trusted @@ -298,11 +313,12 @@ make_iteration_kernel(Grid& grid, std::string name) -> ::carbon::Kernel { using Span = typename Grid::Span; using Idx = typename Grid::Idx; + const auto semantic = population_halo_semantic(grid); return ::carbon::Kernel::compute( grid, - [&f_in, &f_out, &cell_field, params](::carbon::KernelLoader& loader) { - const auto fin = loader.read_stencil(f_in, make_lattice_population_stencil(), - ::carbon::StencilSemantic::Lattice); + [&f_in, &f_out, &cell_field, params, semantic](::carbon::KernelLoader& loader) { + const auto fin = + loader.read_stencil(f_in, make_lattice_population_stencil(), semantic); const auto fout = loader.write(f_out); const auto cell = loader.read(cell_field); const float omega = params.omega; @@ -411,11 +427,12 @@ make_iteration_kernel_d3q19_bgk_fast(Grid& grid, std::string name) -> ::carbon::Kernel { using Span = typename Grid::Span; using Idx = typename Grid::Idx; + const auto semantic = population_halo_semantic(grid); return ::carbon::Kernel::compute( grid, - [&f_in, &f_out, &cell_field, params](::carbon::KernelLoader& loader) { - const auto fin = loader.read_stencil(f_in, make_lattice_population_stencil(), - ::carbon::StencilSemantic::Lattice); + [&f_in, &f_out, &cell_field, params, semantic](::carbon::KernelLoader& loader) { + const auto fin = + loader.read_stencil(f_in, make_lattice_population_stencil(), semantic); const auto fout = loader.write(f_out); const auto cell = loader.read(cell_field); const float omega = params.omega; diff --git a/denseDistributed_compactBoundary_vtk.patch b/denseDistributed_compactBoundary_vtk.patch deleted file mode 100644 index 2648a3ce..00000000 --- a/denseDistributed_compactBoundary_vtk.patch +++ /dev/null @@ -1,2073 +0,0 @@ -diff --git a/CMakeLists.txt b/CMakeLists.txt -index 00d478d..9162d81 100644 ---- a/CMakeLists.txt -+++ b/CMakeLists.txt -@@ -286,6 +286,7 @@ add_library(carbon SHARED - src/dist_render.cpp - src/io.cpp - src/io_vtk.cpp -+ src/io_vtk_distributed.cpp - src/logging.cpp - src/memory_side.cpp - src/process_grid.cpp -@@ -402,6 +403,7 @@ elseif(CARBON_BACKEND STREQUAL "Sycl") - src/dist_reduce.cpp - src/io.cpp - src/io_vtk.cpp -+ src/io_vtk_distributed.cpp - src/logging.cpp - src/memory_side.cpp - src/process_grid.cpp -diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md -index 1f384e7..1f02638 100644 ---- a/docs/CHANGELOG.md -+++ b/docs/CHANGELOG.md -@@ -6046,31 +6046,64 @@ This unblocked the matrix on this host: the `sycl` and `hip-nvidia` images build - (and DenseDisg forwarding) compute one centre offset then constant-strided `pull()` neighbours; - Jacobi uses it instead of `neighbour()` + a redundant `read()` partition. `Dense` rejects layouts - whose `xy_slab_elements` or haloed x extent exceed `int32_t`. New test `test_partition_cursor`. --- **2026-10 — `DenseDistributed`: slab / pencil / brick split out of `Dense`.** `Dense` is back to -- its original Z-slab-only implementation (`dense.h`, `dense.cpp`, `detail/dense/{span,field, -- partition}.h`, `halo.h`, `detail/halo_build.h` and `boundary_mode.h` are unchanged from before -- the decomposition work; `BoundaryMode::PeriodicZ` is `1` again, so `DenseDisg`, `libcarbonpy` -- and the Python bindings are untouched). The process-grid decomposition now lives in a sibling -- grid family: `carbon::DenseDistributed` (+ `HaloDistributed`, and the per-axis -- `BoundaryModeDistributed`, whose `PeriodicX | PeriodicY | PeriodicZ` bits are independent; it -- is a separate type so a per-axis mask can never reach a grid that only understands a Z wrap). -- It takes a `ProcessGrid` / `DecompositionMode` (default slab) and exposes the same `Span` / -- `Partition` / `Field` / kernel / reduce surface as `Dense`, wired through a -- `DenseDistributedPolicy` marker in `launch_traits.h` (same mechanism as `DisgPolicy`) and -- `Kernel::halo_distributed`; `Idx` is shared with `Dense`. The split / halo-thickness / per-rank -- chunk arithmetic is a pure host function set in `detail/dense_distributed/layout.h`, so tests -- can exercise the production decomposition without a GPU. The cross-rank NCCL pairing key still -- ends with the run index: X/Y halo faces are non-contiguous in the x-fastest buffer, so one face -- fans out into many runs sharing the same `(axis, source, dest, side, component)` key, and an -- unordered sort could permute them differently on the two ranks. Tests: the nine multi-axis -- tests and `test_halo_decomp_common.h` are replaced by `dense_distributed_host` (host-only: -- geometry of every rank for slab / pencil / brick, Span views, open vs periodic neighbours, and -- the packed X→Y→Z exchange on an emulated world) and `dense_distributed_dist` (4 ranks: raw halo -- exchange byte-checked on slab `(1,1,4)`, pencil `(1,2,2)` and bricks `(2,2,1)` / `(2,1,2)`, -- packed and run-based, plus a Skeleton stencil kernel with and without overlap; launched with -- `mpiexec -n 8` it covers the full `(2,2,2)` brick, so `CARBON_TEST_BRICK_8GPU` is gone). -- `benchmarks_giulio`: CG gains `--grid dense_distributed` (`--grid dense` is the original -- slab-only grid and rejects pencil / brick); LDC and Jacobi run on `DenseDistributed`. -+- **2026-10 — `DenseDistributed`: slab / pencil / brick decomposition as a sibling of `Dense`.** -+ `Dense` is untouched (still the Z-slab-only grid: one slab per GPU/rank). The per-axis -+ decomposition lives in a new grid family, `carbon::DenseDistributed`, so the original code path -+ keeps its exact geometry, halo builder and generated code. It takes a `ProcessGrid` / -+ `DecompositionMode` (slab by default), uses its own `Span` / `Partition` / `Field` under -+ `detail/dense_distributed/` (`Idx` is shared with `Dense`), and exposes the same kernel, reduce -+ and Skeleton surface through a `DenseDistributedPolicy` marker in `launch_traits.h` (the -+ mechanism `DisgPolicy` already uses) plus `Kernel::halo_distributed`. Halo exchange is -+ `HaloDistributed`: a staged X→Y→Z exchange (so edges and corners travel without diagonal -+ messages) with a packed fast path (`halo_pack*.h`, `src/halo_pack.cu`; `CARBON_HALO_PACK=0` -+ selects the run-based path). Per-axis periodicity is a separate type, -+ `BoundaryModeDistributed` (`PeriodicX | PeriodicY | PeriodicZ` are independent bits), so -+ `BoundaryMode` and its numeric values stay as they were for `Dense`, `DenseDisg`, `libcarbonpy` -+ and the Python bindings. The split / halo-thickness / per-rank chunk arithmetic is a pure host -+ function set in `detail/dense_distributed/layout.h`, so tests exercise the production -+ decomposition without a GPU. The cross-rank NCCL pairing key ends with the run index: X/Y halo -+ faces are non-contiguous in the x-fastest buffer, so one face fans out into many runs sharing -+ the same `(axis, source, dest, side, component)` key, and an unordered sort could permute them -+ differently on the two ranks. Supporting additions: `ProcessGrid` / `DecompositionMode` -+ (`process_grid.h`, balanced prime factorisation over the free axes, plus explicit -+ `ProcessGrid::custom`) and `Stencil::radius3()` (per-axis Chebyshev radius). Tests: -+ `test_process_grid`; `dense_distributed_host` (host-only: geometry of every rank for slab / -+ pencil / brick, Span views, open vs periodic neighbours, and the packed exchange on an emulated -+ world); `dense_distributed_dist` (4 ranks: raw halo exchange byte-checked on slab `(1,1,4)`, -+ pencil `(1,2,2)` and bricks `(2,2,1)` / `(2,1,2)`, packed and run-based, plus a Skeleton stencil -+ kernel with and without overlap; launched with `mpiexec -n 8` it covers the full `(2,2,2)` -+ brick). -+- **2026-11 — Compact `Boundary` view for pencil / brick.** For multi-axis chunks -+ `DenseDistributed::Span::iter_extent(Boundary)` returned the full owned extent and -+ `set_and_validate` rejected the interior threads, so every Boundary launch (Standard overlap, and -+ the Boundary half of Extended / TwoWayExtended producers, which runs before the halo can start) -+ spawned one thread per owned cell for a shell of about `6·h·n²` cells (roughly 30-40x more -+ threads than needed for a 256³ chunk with halo 1). The view now iterates the shell directly: six -+ non-overlapping slabs (Z faces over the full XY extent, Y faces over the middle Z range, X faces -+ over the middle Y/Z range), launched as a 2-D `(128, ceil(S/128), 1)` box whose padded tail is -+ `valid = false`. Slab layouts keep the existing two-band domain. `Internal + Boundary == -+ Standard` still holds, including chunks thinner than `2·halo` (band thickness is clamped so the -+ bands never overlap). Contract change, documented on `Span`: consecutive Boundary threads are no -+ longer spatial neighbours. `dense_distributed_host` additionally asserts that the launch box is -+ less than one 128-wide row larger than the shell. -+- **2026-11 — VTK I/O for `DenseDistributed`.** `io::write_vtk(path, grid, fields...)`, -+ `io::read_vtk(path, grid, fields...)` and `io::write_vtk_multiblock_index(base, grid)` accept a -+ `DenseDistributed` (slab / pencil / brick). The format is the Dense one (legacy BINARY -+ `STRUCTURED_POINTS`, one `.rank` shard per rank, `.vtm` index written by rank 0); a shard is -+ the rank's owned bounding box (`DIMENSIONS` = owned extent, `ORIGIN` = its global cell offset, -+ `SPACING 1`, halo excluded) and rows are streamed with the real haloed row stride in 4 MiB -+ blocks, where the Dense writer assumes full-width XY planes. A rank that owns no cells writes a -+ placeholder shard (`DIMENSIONS 0 0 0`, no payload) and is not listed in the `.vtm`. The `Dense` -+ path is untouched (`src/io_vtk_distributed.cpp`, `detail/io_vtk_distributed.inl`). Tests: -+ `dense_distributed_host` round-trips shards for slab / pencil / brick / thin / empty-rank layouts -+ through the byte-level writer, decoding the payload with an independent big-endian parser and -+ checking that the shard boxes tile the domain; `dense_distributed_dist` writes, indexes and reads -+ back real GPU fields. -+- **2026-11 — `HaloDistributed` pass barrier is off by default.** The host `stream.wait()` + -+ `MPI_Barrier` between axis passes is now opt-in (`CARBON_HALO_PASS_BARRIER=1`). Every pass is -+ ordered on the exchange stream and intra copies are fenced, so it should not be needed for -+ correctness, and it serialised the host against the GPU, which defeats overlap with interior -+ compute. - - **2026-10 — Extended / TwoWayExtended on the step graph.** Every `OverlapMode` now lowers - through `compile_step_graph_and_lower_`; the legacy in-place `apply_occ_` rewrite and - `compile_assign_streams_and_events_` are gone. `compile_step_graph_occ_` applies the Standard -diff --git a/include/carbon/detail/dense_distributed/span.h b/include/carbon/detail/dense_distributed/span.h -index d886bc3..636006c 100644 ---- a/include/carbon/detail/dense_distributed/span.h -+++ b/include/carbon/detail/dense_distributed/span.h -@@ -153,9 +153,18 @@ public: - * - @c Standard: @c logic_extent(). Covers every owned cell exactly once. - * - @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: legacy z-only chunks ( @c halo.x == halo.y == 0 ) use the compact -- * @c 2 * halo.z z-band domain; multi-axis chunks iterate the full owned extent and -- * @ref set_and_validate rejects interior cells. -+ * - @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 -+ * 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 -+ * Boundary threads are @b not spatial neighbours: a kernel must not assume that thread -+ * @c (ix, iy, iz) addresses cell @c (ix, iy, iz) on this view (Standard and Internal keep -+ * that property). - * - * The ranges are non-overlapping, so dispatching Internal and Boundary back-to-back - * (in any order) writes every owned cell exactly once — same coverage as a single -@@ -175,11 +184,17 @@ public: - return int64_3d{ix > 0 ? ix : 0, iy > 0 ? iy : 0, iz > 0 ? iz : 0}; - } - -- case ::carbon::DataView::Boundary: -+ case ::carbon::DataView::Boundary: { - if (halo_.x == 0 && halo_.y == 0) { - return int64_3d{owned.x, owned.y, halo_.z > 0 ? 2 * halo_.z : 0}; - } -- return owned; -+ const int64_t shell = shell_bands_().total; -+ if (shell == 0) { -+ return int64_3d{0, 0, 0}; -+ } -+ const int64_t w = shell >= kShellRowWidth ? kShellRowWidth : shell; -+ return int64_3d{w, (shell + w - 1) / w, 1}; -+ } - } - return owned; - } -@@ -326,7 +341,8 @@ public: - * - @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 -- * pass the owned index through and return @c valid=false for interior cells. -+ * 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 -@@ -337,6 +353,95 @@ public: - int64_t ix, - int64_t iy, - int64_t iz) const noexcept -> ValidatedIdx; -+ -+private: -+ /** Row width of the 2-D Boundary launch box (two full 64-wide blocks per row). */ -+ static constexpr int64_t kShellRowWidth = 128; -+ -+ /** -+ * The Boundary shell as six disjoint boxes over the owned extent. Per axis the low / high band -+ * thickness is clamped so the two never overlap (a chunk thinner than @c 2 * halo is shell -+ * entirely and @c Internal is empty). Box order: Z-low, Z-high (full XY); Y-low, Y-high -+ * (full X, middle Z); X-low, X-high (middle Y, middle Z). -+ */ -+ struct ShellBands { -+ int64_3d lo{}; -+ int64_3d hi{}; -+ int64_t vol[6]{}; -+ int64_t total{0}; -+ }; -+ -+ [[nodiscard]] CARBON_HD constexpr auto -+ shell_bands_() const noexcept -> ShellBands { -+ const int64_3d n = logic_extent(); -+ ShellBands b; -+ b.lo = int64_3d{halo_.x < n.x ? halo_.x : n.x, halo_.y < n.y ? halo_.y : n.y, -+ halo_.z < n.z ? halo_.z : n.z}; -+ const int64_t rx = n.x - b.lo.x; -+ const int64_t ry = n.y - b.lo.y; -+ const int64_t rz = n.z - b.lo.z; -+ b.hi = int64_3d{halo_.x < rx ? halo_.x : rx, halo_.y < ry ? halo_.y : ry, -+ halo_.z < rz ? halo_.z : rz}; -+ const int64_t mz = n.z - b.lo.z - b.hi.z; // middle extents (>= 0 by the clamps) -+ const int64_t my = n.y - b.lo.y - b.hi.y; -+ b.vol[0] = n.x * n.y * b.lo.z; -+ b.vol[1] = n.x * n.y * b.hi.z; -+ b.vol[2] = n.x * b.lo.y * mz; -+ b.vol[3] = n.x * b.hi.y * mz; -+ b.vol[4] = b.lo.x * my * mz; -+ b.vol[5] = b.hi.x * my * mz; -+ b.total = b.vol[0] + b.vol[1] + b.vol[2] + b.vol[3] + b.vol[4] + b.vol[5]; -+ return b; -+ } -+ -+ /** Owned-local cell of linear shell index @p t in [0, bands.total); x varies fastest. */ -+ [[nodiscard]] CARBON_HD constexpr auto -+ shell_cell_(const ShellBands& b, -+ int64_t t) const noexcept -> int64_3d { -+ const int64_3d n = logic_extent(); -+ int box = 0; -+ while (box < 5 && t >= b.vol[box]) { -+ t -= b.vol[box]; -+ ++box; -+ } -+ int64_t bx = 0; // box origin -+ int64_t by = 0; -+ int64_t bz = 0; -+ int64_t w = n.x; // box XY footprint -+ int64_t h = n.y; -+ switch (box) { -+ case 0: -+ break; -+ case 1: -+ bz = n.z - b.hi.z; -+ break; -+ case 2: -+ bz = b.lo.z; -+ h = b.lo.y; -+ break; -+ case 3: -+ by = n.y - b.hi.y; -+ bz = b.lo.z; -+ h = b.hi.y; -+ break; -+ case 4: -+ by = b.lo.y; -+ bz = b.lo.z; -+ w = b.lo.x; -+ h = n.y - b.lo.y - b.hi.y; -+ break; -+ default: -+ bx = n.x - b.hi.x; -+ by = b.lo.y; -+ bz = b.lo.z; -+ w = b.hi.x; -+ h = n.y - b.lo.y - b.hi.y; -+ break; -+ } -+ const int64_t x = t % w; -+ const int64_t r = t / w; -+ return int64_3d{bx + x, by + r % h, bz + r / h}; -+ } - }; - - [[nodiscard]] CARBON_HD constexpr auto -@@ -389,13 +494,15 @@ Span::set_and_validate(::carbon::DataView view, - return ValidatedIdx{Idx(ix, iy, bz), true}; - } - -- const int64_3d owned = logic_extent(); -- const bool internal = ix >= halo_.x && ix < owned.x - halo_.x && iy >= halo_.y && -- iy < owned.y - halo_.y && iz >= halo_.z && iz < owned.z - halo_.z; -- if (internal) { -+ // Compact shell: thread (ix, iy) is the linear shell index t (iz is 0 by the range check -+ // above); the padded tail of the last row is invalid. -+ const ShellBands bands = shell_bands_(); -+ const int64_t t = iy * ext.x + ix; -+ if (t >= bands.total) { - return ValidatedIdx{Idx{}, false}; - } -- return ValidatedIdx{Idx(halo_.x + ix, halo_.y + iy, halo_.z + iz), true}; -+ const int64_3d c = shell_cell_(bands, t); -+ return ValidatedIdx{Idx(halo_.x + c.x, halo_.y + c.y, halo_.z + c.z), true}; - } - } - return ValidatedIdx{Idx{}, false}; -diff --git a/include/carbon/detail/io_vtk_distributed.inl b/include/carbon/detail/io_vtk_distributed.inl -new file mode 100644 -index 0000000..33fc51a ---- /dev/null -+++ b/include/carbon/detail/io_vtk_distributed.inl -@@ -0,0 +1,313 @@ -+// io_vtk_distributed.inl — VTK legacy backend for carbon::DenseDistributed, split out of -+// . Tail include of io.h (see io_vtk.inl for the include-context contract); not a -+// standalone header. -+// -+// Same on-disk format as the Dense backend (legacy BINARY STRUCTURED_POINTS, one `.rank` shard -+// per rank under MPI, `.vtm` multiblock index written by rank 0), generalised from "full XY -+// planes, z-slab" to "the rank's owned bounding box": -+// -+// # vtk DataFile Version 3.0 -+// carbon dense field shard -+// BINARY -+// DATASET STRUCTURED_POINTS -+// DIMENSIONS // the rank's owned box (halo excluded) -+// ORIGIN // global index of the box's first cell -+// SPACING 1 1 1 // index space, same as the Dense writer -+// POINT_DATA -+// SCALARS -+// LOOKUP_TABLE default -+// -+// -+// A rank that owns no cells (global extent smaller than the process grid on some axis) writes a -+// placeholder shard: valid header with `DIMENSIONS 0 0 0` / `POINT_DATA 0` and each SCALARS -+// header without payload, so every rank leaves exactly one file. The `.vtm` index lists only the -+// non-empty shards (there is nothing to display for the others). -+// -+// Index space (SPACING 1, ORIGIN in cells) is deliberate: it is what the Dense writer/reader use, -+// costs nothing extra to write, and keeps shards of both grid families interchangeable in -+// ParaView. The span's physical origin/spacing are not applied. -+namespace detail { -+ -+/** Pointer-parametrised block of owned cells inside a haloed per-GPU buffer. */ -+template -+struct VtkBoxPieceT { -+ /** First @b owned cell of component 0. */ -+ P start{}; -+ /** Owned extent of the block. */ -+ int64_t nx{0}; -+ int64_t ny{0}; -+ int64_t nz{0}; -+ /** Elements between consecutive rows (the haloed x extent). */ -+ int64_t row_stride{0}; -+ /** Elements between consecutive z planes. */ -+ int64_t plane_pitch{0}; -+ /** Elements between consecutive components. */ -+ int64_t comp_stride{0}; -+}; -+using VtkBoxPiece = VtkBoxPieceT; -+using VtkBoxPieceMut = VtkBoxPieceT; -+ -+/** Bounding box of one rank's shard in global index space; all-zero @c dims means "empty". */ -+struct VtkBox { -+ int64_t dims[3] = {0, 0, 0}; -+ int64_t origin[3] = {0, 0, 0}; -+ -+ [[nodiscard]] auto -+ empty() const noexcept -> bool { -+ return dims[0] <= 0 || dims[1] <= 0 || dims[2] <= 0; -+ } -+ [[nodiscard]] auto -+ points() const noexcept -> int64_t { -+ return empty() ? 0 : dims[0] * dims[1] * dims[2]; -+ } -+}; -+ -+/** Per-SCALARS record found while parsing a shard header. */ -+struct VtkBoxFieldRecord { -+ std::string name; -+ std::string vtk_dtype; -+ int components = 0; -+ std::streampos payload_offset = 0; -+}; -+ -+/** -+ * The shard box of @p grid on this rank: the union of its local spans' owned cells. Single-GPU -+ * ranks give their span's owned box; a single-process multi-GPU slab stacks the per-GPU z ranges. -+ * Throws @c std::invalid_argument if the local spans do not form one box. A rank owning no cells -+ * returns an empty box whose @c origin is still the global index of its (empty) owned region. -+ */ -+[[nodiscard]] CARBON_API auto -+vtk_box_of(const DenseDistributed& grid) -> VtkBox; -+ -+// ---- stream-level building blocks (what the session and the unit tests share) --------------- -+ -+/** Write the legacy header for @p box (placeholder header when @c box.empty()). */ -+CARBON_API void -+write_vtk_box_header(std::ostream& out, -+ const VtkBox& box); -+ -+/** -+ * Write one SCALARS block: header line, LOOKUP_TABLE, then (unless @p box is empty) the payload -+ * gathered from @p pieces, in file order, as big-endian component-fastest records. -+ */ -+CARBON_API void -+write_vtk_box_field(std::ostream& out, -+ std::string_view name, -+ const char* dtype_tag, -+ size_t element_size, -+ int components, -+ const VtkBox& box, -+ const std::vector& pieces); -+ -+/** -+ * Parse a shard header and record every SCALARS block. DIMENSIONS / ORIGIN / POINT_DATA must match -+ * @p expected (an empty @p expected requires the placeholder form); SPACING must be unit. -+ */ -+CARBON_API void -+parse_vtk_box_header(std::istream& in, -+ std::string_view path, -+ const VtkBox& expected, -+ std::vector& out_fields); -+ -+/** Read one field's payload (stream already positioned) and scatter it into @p pieces. */ -+CARBON_API void -+read_vtk_box_field_payload(std::istream& in, -+ size_t element_size, -+ int components, -+ const VtkBox& box, -+ const std::vector& pieces); -+ -+/** Per-rank VTK shard session for a @c DenseDistributed grid. */ -+class CARBON_API VtkBoxSession { -+public: -+ VtkBoxSession() noexcept; -+ ~VtkBoxSession(); -+ VtkBoxSession(const VtkBoxSession&) = delete; -+ auto -+ operator=(const VtkBoxSession&) -> VtkBoxSession& = delete; -+ VtkBoxSession(VtkBoxSession&&) noexcept; -+ auto -+ operator=(VtkBoxSession&&) noexcept -> VtkBoxSession&; -+ -+ void -+ open_for_write(std::string_view path, -+ const DenseDistributed& grid, -+ std::uint32_t num_fields); -+ void -+ open_for_read(std::string_view path, -+ const DenseDistributed& grid); -+ -+ void -+ write_field(std::string_view name, -+ const char* dtype_tag, -+ size_t element_size, -+ int components, -+ const std::vector& pieces); -+ void -+ read_field(std::string_view name, -+ const char* dtype_tag, -+ size_t element_size, -+ int components, -+ const std::vector& pieces); -+ -+ [[nodiscard]] auto -+ num_fields() const noexcept -> std::uint32_t; -+ -+ [[nodiscard]] static auto -+ shard_path(std::string_view base, -+ const DenseDistributed& grid) -> std::string; -+ -+private: -+ struct Impl; -+ std::unique_ptr impl_; -+}; -+ -+/** -+ * Owned-cell blocks of @p field, one per local span (the host mirror, halo excluded). Const -+ * variant for writers, mutable variant for readers. -+ */ -+template -+void -+collect_vtk_pieces(const DenseDistributed& grid, -+ const DenseDistributed::Field& field, -+ std::vector& pieces, -+ std::string_view callsite) { -+ const auto& spans = grid.spans(); -+ if (field.cpu_buffers().size() != spans.size()) { -+ log::throw_with_log( -+ "{}: field has no host mirror (cpu_buffers().size()={}, gpu_count={}); construct the field " -+ "with MemorySide::Host or HostDevice and download from device before writing", -+ callsite, field.cpu_buffers().size(), spans.size()); -+ } -+ pieces.clear(); -+ for (size_t g = 0; g < spans.size(); ++g) { -+ const auto& span = spans[g]; -+ const int64_3d owned = span.logic_extent(); -+ if (owned.x <= 0 || owned.y <= 0 || owned.z <= 0) { -+ continue; -+ } -+ const int64_3d halo = span.halo(); -+ VtkBoxPiece p; -+ p.row_stride = span.haloed_extent().x; -+ p.plane_pitch = span.xy_slab_elements(); -+ p.comp_stride = span.linear_storage_elements(); -+ p.nx = owned.x; -+ p.ny = owned.y; -+ p.nz = owned.z; -+ p.start = static_cast(field.cpu_buffers()[g].data() + halo.z * p.plane_pitch + -+ halo.y * p.row_stride + halo.x); -+ pieces.push_back(p); -+ } -+} -+ -+template -+void -+collect_vtk_pieces_mut(const DenseDistributed& grid, -+ DenseDistributed::Field& field, -+ std::vector& pieces, -+ std::string_view callsite) { -+ const auto& spans = grid.spans(); -+ if (field.cpu_buffers().size() != spans.size()) { -+ log::throw_with_log( -+ "{}: field has no host mirror (cpu_buffers().size()={}, gpu_count={}); construct the field " -+ "with MemorySide::Host or HostDevice before reading", -+ callsite, field.cpu_buffers().size(), spans.size()); -+ } -+ pieces.clear(); -+ for (size_t g = 0; g < spans.size(); ++g) { -+ const auto& span = spans[g]; -+ const int64_3d owned = span.logic_extent(); -+ if (owned.x <= 0 || owned.y <= 0 || owned.z <= 0) { -+ continue; -+ } -+ const int64_3d halo = span.halo(); -+ VtkBoxPieceMut p; -+ p.row_stride = span.haloed_extent().x; -+ p.plane_pitch = span.xy_slab_elements(); -+ p.comp_stride = span.linear_storage_elements(); -+ p.nx = owned.x; -+ p.ny = owned.y; -+ p.nz = owned.z; -+ p.start = static_cast(field.cpu_buffers()[g].data() + halo.z * p.plane_pitch + -+ halo.y * p.row_stride + halo.x); -+ pieces.push_back(p); -+ } -+} -+ -+} // namespace detail -+ -+/** -+ * Write @p fields (host mirrors, halo excluded) of @p grid as one legacy BINARY VTK shard per -+ * rank (`.rank` under MPI, `` otherwise). Works for every decomposition -+ * (slab / pencil / brick). Download device data to the host mirror first. Call -+ * @ref write_vtk_multiblock_index afterwards (any rank may call it; rank 0 writes) to get a -+ * single `.vtm` that ParaView opens as one multiblock dataset. -+ */ -+template -+void -+write_vtk(std::string_view path, -+ const DenseDistributed& grid, -+ const Fields&... fields) { -+ detail::VtkBoxSession sess; -+ sess.open_for_write(path, grid, static_cast(sizeof...(Fields))); -+ size_t i = 0; -+ ( -+ [&] { -+ using FieldT = std::remove_cv_t>; -+ using ScalarT = typename FieldT::value_type; -+ constexpr int kComponents = FieldT::components; -+ std::vector pieces; -+ detail::collect_vtk_pieces(grid, fields, pieces, "io::write_vtk"); -+ const std::string& field_name = fields.name(); -+ std::string vtk_name = field_name.empty() ? ("field_" + std::to_string(i)) : field_name; -+ sess.write_field(vtk_name, detail::native_dtype_tag(), sizeof(ScalarT), -+ kComponents, pieces); -+ ++i; -+ }(), -+ ...); -+} -+ -+/** -+ * Read @p fields of @p grid from the shard @ref write_vtk wrote for this rank. DIMENSIONS and -+ * ORIGIN must match this rank's owned box; fields bind by ordinal. Only owned cells are touched -+ * (halo cells keep their contents). -+ */ -+template -+void -+read_vtk(std::string_view path, -+ const DenseDistributed& grid, -+ Fields&... fields) { -+ detail::VtkBoxSession sess; -+ sess.open_for_read(path, grid); -+ if (sess.num_fields() != sizeof...(Fields)) { -+ log::throw_with_log( -+ "io::read_vtk: file '{}' has {} fields, but {} were passed to read", path, -+ sess.num_fields(), sizeof...(Fields)); -+ } -+ size_t i = 0; -+ ( -+ [&] { -+ using FieldT = std::remove_cv_t>; -+ using ScalarT = typename FieldT::value_type; -+ constexpr int kComponents = FieldT::components; -+ std::vector pieces; -+ detail::collect_vtk_pieces_mut(grid, fields, pieces, "io::read_vtk"); -+ sess.read_field("field_" + std::to_string(i), detail::native_dtype_tag(), -+ sizeof(ScalarT), kComponents, pieces); -+ ++i; -+ }(), -+ ...); -+} -+ -+/** -+ * Write `.vtm`, a vtkMultiBlockDataSet index over the per-rank shards of -+ * @ref write_vtk, so ParaView opens the whole decomposed domain at once. Only rank 0 writes; -+ * ranks that own no cells are not listed. No-op without a distributed System. -+ */ -+CARBON_API auto -+write_vtk_multiblock_index(std::string_view base, -+ const DenseDistributed& grid) -> void; -diff --git a/include/carbon/io.h b/include/carbon/io.h -index 5a27547..fb88817 100644 ---- a/include/carbon/io.h -+++ b/include/carbon/io.h -@@ -2,8 +2,10 @@ - - #include - #include -+#include - #include - #include -+#include - #include - #include - -@@ -11,7 +13,9 @@ - #include - #include - #include -+#include - #include -+#include - #include - #include - #include -@@ -29,7 +33,9 @@ - * @code - * carbon::io::write_native(path, grid, field_a, field_b, ...); - * carbon::io::read_native (path, grid, field_a, field_b, ...); -- * // VTK / HDF5 / nanoVDB are Dense-only today. -+ * // VTK / HDF5 / nanoVDB are Dense-only today, except VTK, which also accepts a -+ * // DenseDistributed (slab / pencil / brick): write_vtk / read_vtk / -+ * // write_vtk_multiblock_index overloads in detail/io_vtk_distributed.inl. - * @endcode - * - * Both @c Dense and @c DenseDisg share the same on-disk file format: the file header -@@ -579,6 +585,7 @@ collect_field_views_mut(const Dense& dense, - #include - #include - #include -+#include - - namespace detail { - -diff --git a/src/io_vtk_distributed.cpp b/src/io_vtk_distributed.cpp -new file mode 100644 -index 0000000..099c340 ---- /dev/null -+++ b/src/io_vtk_distributed.cpp -@@ -0,0 +1,832 @@ -+// VTK legacy backend for carbon::DenseDistributed (slab / pencil / brick). See -+// include/carbon/detail/io_vtk_distributed.inl for the on-disk format and the public surface. -+// -+// The helpers below (byte order, dtype keywords, header parsing) intentionally mirror the Dense -+// backend in io_vtk.cpp instead of sharing it, so the Dense path stays byte-for-byte untouched. -+// What differs is the geometry: a shard is the rank's owned *box* (DIMENSIONS = owned extent, -+// ORIGIN = global index of its first cell) and rows are read/written with the real haloed row -+// stride instead of assuming full-width XY planes. -+ -+#include -+#include -+#include -+#include -+ -+#ifdef CARBON_HAVE_MPI_NCCL -+#include -+#endif -+ -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+ -+namespace carbon::io::detail { -+ -+namespace { -+ -+namespace dd = ::carbon::detail::dense_distributed; -+ -+/** Staging block for payload I/O: rows are batched so the stream sees few, large transfers. */ -+constexpr size_t kBlockBytes = size_t{4} << 20; -+ -+[[nodiscard]] constexpr auto -+host_is_little_endian() noexcept -> bool { -+ return std::endian::native == std::endian::little; -+} -+ -+/** Reverse the bytes of @p n consecutive @c ES -byte elements (legacy VTK payloads are BE). */ -+template -+void -+swap_run(std::uint8_t* p, -+ size_t n) noexcept { -+ if constexpr (ES > 1) { -+ for (size_t i = 0; i < n; ++i) { -+ std::uint8_t* e = p + i * ES; -+ for (size_t k = 0; k < ES / 2; ++k) { -+ std::swap(e[k], e[ES - 1 - k]); -+ } -+ } -+ } -+} -+ -+/** Map a carbon native dtype tag (8-char, NUL padded) to the VTK legacy keyword; null if unknown. */ -+[[nodiscard]] auto -+vtk_keyword_from_native_tag(const char* tag) noexcept -> const char* { -+ const std::string_view t(tag, 8); -+ if (t.starts_with("f32")) { -+ return "float"; -+ } -+ if (t.starts_with("f64")) { -+ return "double"; -+ } -+ if (t.starts_with("i8")) { -+ return "char"; -+ } -+ if (t.starts_with("u8")) { -+ return "unsigned_char"; -+ } -+ if (t.starts_with("i16")) { -+ return "short"; -+ } -+ if (t.starts_with("u16")) { -+ return "unsigned_short"; -+ } -+ if (t.starts_with("i32")) { -+ return "int"; -+ } -+ if (t.starts_with("u32")) { -+ return "unsigned_int"; -+ } -+ if (t.starts_with("i64")) { -+ return "vtktypeint64"; -+ } -+ if (t.starts_with("u64")) { -+ return "vtktypeuint64"; -+ } -+ return nullptr; -+} -+ -+[[nodiscard]] auto -+element_size_of_keyword(const std::string& kw) noexcept -> size_t { -+ if (kw == "char" || kw == "unsigned_char") { -+ return 1; -+ } -+ if (kw == "short" || kw == "unsigned_short") { -+ return 2; -+ } -+ if (kw == "int" || kw == "unsigned_int" || kw == "float") { -+ return 4; -+ } -+ if (kw == "double" || kw == "vtktypeint64" || kw == "vtktypeuint64" || kw == "long" || -+ kw == "unsigned_long") { -+ return 8; -+ } -+ return 0; -+} -+ -+void -+rtrim_inplace(std::string& s) noexcept { -+ while (!s.empty() && (s.back() == '\r' || s.back() == ' ' || s.back() == '\t')) { -+ s.pop_back(); -+ } -+} -+ -+/** Legacy SCALARS names are whitespace-delimited tokens: make the label a single token. */ -+[[nodiscard]] auto -+sanitize_name(std::string_view name) -> std::string { -+ std::string out(name); -+ for (char& c : out) { -+ if (c == ' ' || c == '\t' || c == '\r' || c == '\n') { -+ c = '_'; -+ } -+ } -+ return out.empty() ? std::string("field") : out; -+} -+ -+[[nodiscard]] auto -+shard_path_of(std::string_view base, -+ const DenseDistributed& grid) -> std::string { -+#ifdef CARBON_HAVE_MPI_NCCL -+ if (grid.system().distributed() != nullptr) { -+ std::ostringstream oss; -+ oss << base << ".rank" << grid.system().distributed()->world_rank(); -+ return oss.str(); -+ } -+#else -+ (void)grid; -+#endif -+ return std::string(base); -+} -+ -+[[nodiscard]] auto -+pieces_cells(const std::vector& pieces) -> int64_t { -+ int64_t n = 0; -+ for (const auto& p : pieces) { -+ n += p.nx * p.ny * p.nz; -+ } -+ return n; -+} -+ -+// ---- payload gather / scatter (compile-time element size) ---------------------------------- -+ -+/** One owned row of @p nx cells -> interleaved (component-fastest) record bytes. */ -+template -+void -+gather_row(std::uint8_t* dst, -+ const std::uint8_t* src, -+ int64_t nx, -+ int comps, -+ int64_t comp_stride_elems) noexcept { -+ if (comps == 1) { -+ std::memcpy(dst, src, static_cast(nx) * ES); -+ return; -+ } -+ const size_t stride = static_cast(comps) * ES; -+ for (int c = 0; c < comps; ++c) { -+ const std::uint8_t* s = src + static_cast(c * comp_stride_elems) * ES; -+ std::uint8_t* d = dst + static_cast(c) * ES; -+ for (int64_t x = 0; x < nx; ++x) { -+ std::memcpy(d + static_cast(x) * stride, s + static_cast(x) * ES, ES); -+ } -+ } -+} -+ -+/** Interleaved record bytes -> one owned row (inverse of @ref gather_row). */ -+template -+void -+scatter_row(std::uint8_t* dst, -+ const std::uint8_t* src, -+ int64_t nx, -+ int comps, -+ int64_t comp_stride_elems) noexcept { -+ if (comps == 1) { -+ std::memcpy(dst, src, static_cast(nx) * ES); -+ return; -+ } -+ const size_t stride = static_cast(comps) * ES; -+ for (int c = 0; c < comps; ++c) { -+ std::uint8_t* d = dst + static_cast(c * comp_stride_elems) * ES; -+ const std::uint8_t* s = src + static_cast(c) * ES; -+ for (int64_t x = 0; x < nx; ++x) { -+ std::memcpy(d + static_cast(x) * ES, s + static_cast(x) * stride, ES); -+ } -+ } -+} -+ -+[[nodiscard]] inline auto -+row_ptr(const VtkBoxPiece& p, -+ size_t es, -+ int64_t z, -+ int64_t y) noexcept -> const std::uint8_t* { -+ return static_cast(p.start) + -+ static_cast(z * p.plane_pitch + y * p.row_stride) * es; -+} -+ -+[[nodiscard]] inline auto -+row_ptr(const VtkBoxPieceMut& p, -+ size_t es, -+ int64_t z, -+ int64_t y) noexcept -> std::uint8_t* { -+ return static_cast(p.start) + -+ static_cast(z * p.plane_pitch + y * p.row_stride) * es; -+} -+ -+template -+void -+write_payload(std::ostream& out, -+ int comps, -+ const std::vector& pieces) { -+ size_t total_bytes = 0; -+ size_t max_row_bytes = 0; -+ for (const auto& p : pieces) { -+ const size_t row = static_cast(p.nx) * static_cast(comps) * ES; -+ total_bytes += row * static_cast(p.ny) * static_cast(p.nz); -+ max_row_bytes = std::max(max_row_bytes, row); -+ } -+ if (total_bytes == 0) { -+ return; -+ } -+ std::vector block(std::max(std::min(total_bytes, kBlockBytes), max_row_bytes)); -+ size_t used = 0; -+ const auto flush = [&] { -+ if (used == 0) { -+ return; -+ } -+ if (host_is_little_endian()) { -+ swap_run(block.data(), used / ES); -+ } -+ out.write(reinterpret_cast(block.data()), static_cast(used)); -+ used = 0; -+ }; -+ for (const auto& p : pieces) { -+ const size_t row_bytes = static_cast(p.nx) * static_cast(comps) * ES; -+ for (int64_t z = 0; z < p.nz; ++z) { -+ for (int64_t y = 0; y < p.ny; ++y) { -+ if (used + row_bytes > block.size()) { -+ flush(); -+ } -+ gather_row(block.data() + used, row_ptr(p, ES, z, y), p.nx, comps, p.comp_stride); -+ used += row_bytes; -+ } -+ } -+ } -+ flush(); -+} -+ -+template -+void -+read_payload(std::istream& in, -+ int comps, -+ const std::vector& pieces) { -+ size_t max_row_bytes = 0; -+ size_t total_bytes = 0; -+ for (const auto& p : pieces) { -+ const size_t row = static_cast(p.nx) * static_cast(comps) * ES; -+ max_row_bytes = std::max(max_row_bytes, row); -+ total_bytes += row * static_cast(p.ny) * static_cast(p.nz); -+ } -+ if (total_bytes == 0) { -+ return; -+ } -+ std::vector block(std::max(std::min(total_bytes, kBlockBytes), max_row_bytes)); -+ for (const auto& p : pieces) { -+ const size_t row_bytes = static_cast(p.nx) * static_cast(comps) * ES; -+ const int64_t rows_total = p.ny * p.nz; -+ const int64_t rows_per_block = static_cast(block.size() / row_bytes); -+ for (int64_t r0 = 0; r0 < rows_total; r0 += rows_per_block) { -+ const int64_t rows = std::min(rows_per_block, rows_total - r0); -+ const size_t bytes = static_cast(rows) * row_bytes; -+ in.read(reinterpret_cast(block.data()), static_cast(bytes)); -+ if (!in.good()) { -+ log::throw_with_log( -+ "io::read_vtk: short read in payload (row {} of {})", r0, rows_total); -+ } -+ if (host_is_little_endian()) { -+ swap_run(block.data(), bytes / ES); -+ } -+ for (int64_t i = 0; i < rows; ++i) { -+ const int64_t r = r0 + i; -+ scatter_row(row_ptr(p, ES, r / p.ny, r % p.ny), -+ block.data() + static_cast(i) * row_bytes, p.nx, comps, -+ p.comp_stride); -+ } -+ } -+ } -+} -+ -+} // namespace -+ -+// ================================================================================================ -+// Box geometry -+// ================================================================================================ -+ -+auto -+vtk_box_of(const DenseDistributed& grid) -> VtkBox { -+ VtkBox box; -+ const auto& spans = grid.spans(); -+ if (spans.empty()) { -+ return box; -+ } -+ // Global index of the first owned cell of a span = buffer origin + halo. -+ const auto owned_origin = [](const auto& span) -> int64_3d { -+ const int64_3d o = span.offset(); -+ const int64_3d h = span.halo(); -+ return int64_3d{o.x + h.x, o.y + h.y, o.z + h.z}; -+ }; -+ const int64_3d first = owned_origin(spans.front()); -+ box.origin[0] = first.x; -+ box.origin[1] = first.y; -+ box.origin[2] = first.z; -+ -+ int64_t z_total = 0; -+ int64_3d prev_origin{}; -+ int64_t prev_nz = 0; -+ bool have_prev = false; -+ int64_t nx = 0; -+ int64_t ny = 0; -+ for (const auto& span : spans) { -+ const int64_3d owned = span.logic_extent(); -+ if (owned.x <= 0 || owned.y <= 0 || owned.z <= 0) { -+ continue; // this GPU owns nothing -+ } -+ const int64_3d o = owned_origin(span); -+ if (!have_prev) { -+ nx = owned.x; -+ ny = owned.y; -+ box.origin[0] = o.x; -+ box.origin[1] = o.y; -+ box.origin[2] = o.z; -+ } else if (owned.x != nx || owned.y != ny || o.x != prev_origin.x || o.y != prev_origin.y || -+ o.z != prev_origin.z + prev_nz) { -+ log::throw_with_log( -+ "io::vtk: the local spans of this DenseDistributed do not form a single box (only a " -+ "z-stacked slab can span several local GPUs)"); -+ } -+ z_total += owned.z; -+ prev_origin = o; -+ prev_nz = owned.z; -+ have_prev = true; -+ } -+ if (have_prev) { -+ box.dims[0] = nx; -+ box.dims[1] = ny; -+ box.dims[2] = z_total; -+ } -+ return box; -+} -+ -+// ================================================================================================ -+// Stream-level building blocks -+// ================================================================================================ -+ -+void -+write_vtk_box_header(std::ostream& out, -+ const VtkBox& box) { -+ const bool empty = box.empty(); -+ out << "# vtk DataFile Version 3.0\n"; -+ out << (empty ? "carbon dense field shard (empty: this rank owns no cells)\n" -+ : "carbon dense field shard\n"); -+ out << "BINARY\n"; -+ out << "DATASET STRUCTURED_POINTS\n"; -+ out << "DIMENSIONS " << (empty ? 0 : box.dims[0]) << ' ' << (empty ? 0 : box.dims[1]) << ' ' -+ << (empty ? 0 : box.dims[2]) << '\n'; -+ out << "ORIGIN " << box.origin[0] << ' ' << box.origin[1] << ' ' << box.origin[2] << '\n'; -+ out << "SPACING 1 1 1\n"; -+ out << "POINT_DATA " << box.points() << '\n'; -+ if (!out.good()) { -+ log::throw_with_log("io::write_vtk: failed to write the shard header"); -+ } -+} -+ -+void -+write_vtk_box_field(std::ostream& out, -+ std::string_view name, -+ const char* dtype_tag, -+ size_t element_size, -+ int components, -+ const VtkBox& box, -+ const std::vector& pieces) { -+ const char* kw = vtk_keyword_from_native_tag(dtype_tag); -+ if (kw == nullptr) { -+ log::throw_with_log( -+ "io::write_vtk: field '{}' has a dtype VTK legacy cannot express", name); -+ } -+ if (components < 1 || components > 4) { -+ log::throw_with_log( -+ "io::write_vtk: field '{}' has {} components (legacy VTK SCALARS supports 1..4)", name, -+ components); -+ } -+ if (!box.empty()) { -+ if (pieces_cells(pieces) != box.points()) { -+ log::throw_with_log( -+ "io::write_vtk: field '{}' pieces hold {} cells but the shard box has {}", name, -+ pieces_cells(pieces), box.points()); -+ } -+ for (const auto& p : pieces) { -+ if (p.nx != box.dims[0] || p.ny != box.dims[1]) { -+ log::throw_with_log( -+ "io::write_vtk: field '{}' piece ({}x{}) does not match the shard box ({}x{})", name, -+ p.nx, p.ny, box.dims[0], box.dims[1]); -+ } -+ } -+ } -+ out << "SCALARS " << sanitize_name(name) << ' ' << kw << ' ' << components << '\n'; -+ out << "LOOKUP_TABLE default\n"; -+ if (!box.empty()) { -+ switch (element_size) { -+ case 1: -+ write_payload<1>(out, components, pieces); -+ break; -+ case 2: -+ write_payload<2>(out, components, pieces); -+ break; -+ case 4: -+ write_payload<4>(out, components, pieces); -+ break; -+ case 8: -+ write_payload<8>(out, components, pieces); -+ break; -+ default: -+ log::throw_with_log( -+ "io::write_vtk: unsupported element size {} for field '{}'", element_size, name); -+ } -+ } -+ out << '\n'; -+ if (!out.good()) { -+ log::throw_with_log("io::write_vtk: write of field '{}' failed", name); -+ } -+} -+ -+void -+parse_vtk_box_header(std::istream& in, -+ std::string_view path, -+ const VtkBox& expected, -+ std::vector& out_fields) { -+ const auto next_line = [&](bool strict) -> std::string { -+ std::string line; -+ if (!std::getline(in, line)) { -+ if (strict) { -+ log::throw_with_log("io::read_vtk: '{}' ended inside the header", -+ path); -+ } -+ return {}; -+ } -+ rtrim_inplace(line); -+ return line; -+ }; -+ -+ const auto magic = next_line(true); -+ if (magic.rfind("# vtk DataFile Version", 0) != 0) { -+ log::throw_with_log( -+ "io::read_vtk: '{}' does not start with a VTK legacy magic line (got '{}')", path, magic); -+ } -+ next_line(true); // free-form title -+ const auto fmt = next_line(true); -+ if (fmt != "BINARY") { -+ log::throw_with_log( -+ "io::read_vtk: '{}' is '{}' but only BINARY legacy VTK is supported", path, fmt); -+ } -+ const auto ds = next_line(true); -+ if (ds != "DATASET STRUCTURED_POINTS") { -+ log::throw_with_log( -+ "io::read_vtk: '{}' is '{}' but only DATASET STRUCTURED_POINTS is supported", path, ds); -+ } -+ -+ int64_t dims[3] = {0, 0, 0}; -+ int64_t origin[3] = {0, 0, 0}; -+ double spacing[3] = {1.0, 1.0, 1.0}; -+ int64_t point_count = -1; -+ while (point_count < 0) { -+ const auto cur = next_line(true); -+ if (cur.empty()) { -+ continue; -+ } -+ std::istringstream iss(cur); -+ std::string head; -+ iss >> head; -+ if (head == "DIMENSIONS") { -+ iss >> dims[0] >> dims[1] >> dims[2]; -+ } else if (head == "ORIGIN") { -+ iss >> origin[0] >> origin[1] >> origin[2]; -+ } else if (head == "SPACING" || head == "ASPECT_RATIO") { -+ iss >> spacing[0] >> spacing[1] >> spacing[2]; -+ } else if (head == "POINT_DATA") { -+ iss >> point_count; -+ if (point_count < 0) { -+ log::throw_with_log("io::read_vtk: '{}' has a bad POINT_DATA line", -+ path); -+ } -+ } else if (head == "CELL_DATA") { -+ log::throw_with_log( -+ "io::read_vtk: '{}' uses CELL_DATA; carbon writes POINT_DATA only", path); -+ } else { -+ log::throw_with_log( -+ "io::read_vtk: '{}' has unexpected header line '{}'", path, cur); -+ } -+ } -+ -+ // Validate against the box this rank is about to load into. -+ const bool want_empty = expected.empty(); -+ const int64_t want_dims[3] = {want_empty ? 0 : expected.dims[0], -+ want_empty ? 0 : expected.dims[1], -+ want_empty ? 0 : expected.dims[2]}; -+ if (dims[0] != want_dims[0] || dims[1] != want_dims[1] || dims[2] != want_dims[2]) { -+ log::throw_with_log( -+ "io::read_vtk: '{}' DIMENSIONS ({}, {}, {}) do not match this rank's owned box ({}, {}, " -+ "{})", -+ path, dims[0], dims[1], dims[2], want_dims[0], want_dims[1], want_dims[2]); -+ } -+ if (origin[0] != expected.origin[0] || origin[1] != expected.origin[1] || -+ origin[2] != expected.origin[2]) { -+ log::throw_with_log( -+ "io::read_vtk: '{}' ORIGIN ({}, {}, {}) does not match this rank's box origin ({}, {}, {})", -+ path, origin[0], origin[1], origin[2], expected.origin[0], expected.origin[1], -+ expected.origin[2]); -+ } -+ if (spacing[0] != 1.0 || spacing[1] != 1.0 || spacing[2] != 1.0) { -+ log::throw_with_log( -+ "io::read_vtk: '{}' SPACING ({}, {}, {}) is non-unit; carbon uses integer voxel " -+ "coordinates", -+ path, spacing[0], spacing[1], spacing[2]); -+ } -+ if (point_count != expected.points()) { -+ log::throw_with_log( -+ "io::read_vtk: '{}' POINT_DATA {} disagrees with the box size {}", path, point_count, -+ expected.points()); -+ } -+ -+ // Walk the SCALARS blocks, recording each payload offset. -+ while (in) { -+ const auto cur = next_line(false); -+ if (cur.empty()) { -+ if (in.eof()) { -+ break; -+ } -+ continue; -+ } -+ std::istringstream iss(cur); -+ std::string head; -+ iss >> head; -+ if (head != "SCALARS") { -+ log::throw_with_log( -+ "io::read_vtk: unsupported attribute '{}' in '{}'; only SCALARS blocks are accepted", -+ head, path); -+ } -+ VtkBoxFieldRecord rec; -+ iss >> rec.name >> rec.vtk_dtype; -+ rec.components = 1; -+ iss >> rec.components; -+ if (rec.components < 1 || rec.components > 4) { -+ log::throw_with_log( -+ "io::read_vtk: SCALARS '{}' has components={} (legacy VTK supports 1..4)", rec.name, -+ rec.components); -+ } -+ const auto lookup = next_line(true); -+ if (lookup.rfind("LOOKUP_TABLE", 0) != 0) { -+ log::throw_with_log( -+ "io::read_vtk: expected LOOKUP_TABLE after SCALARS '{}', got '{}'", rec.name, lookup); -+ } -+ rec.payload_offset = in.tellg(); -+ if (rec.payload_offset == std::streampos(-1)) { -+ log::throw_with_log( -+ "io::read_vtk: failed to query the stream offset of SCALARS '{}'", rec.name); -+ } -+ const size_t es = element_size_of_keyword(rec.vtk_dtype); -+ if (es == 0) { -+ log::throw_with_log( -+ "io::read_vtk: SCALARS '{}' has dtype '{}' which carbon does not map back", rec.name, -+ rec.vtk_dtype); -+ } -+ in.seekg(rec.payload_offset + static_cast(point_count) * -+ static_cast(rec.components) * -+ static_cast(es)); -+ out_fields.push_back(std::move(rec)); -+ const int next_c = in.peek(); // optional trailing newline after the payload -+ if (next_c == '\n' || next_c == '\r') { -+ in.get(); -+ if (next_c == '\r' && in.peek() == '\n') { -+ in.get(); -+ } -+ } -+ } -+} -+ -+void -+read_vtk_box_field_payload(std::istream& in, -+ size_t element_size, -+ int components, -+ const VtkBox& box, -+ const std::vector& pieces) { -+ if (box.empty()) { -+ return; -+ } -+ int64_t cells = 0; -+ for (const auto& p : pieces) { -+ cells += p.nx * p.ny * p.nz; -+ if (p.nx != box.dims[0] || p.ny != box.dims[1]) { -+ log::throw_with_log( -+ "io::read_vtk: piece ({}x{}) does not match the shard box ({}x{})", p.nx, p.ny, -+ box.dims[0], box.dims[1]); -+ } -+ } -+ if (cells != box.points()) { -+ log::throw_with_log( -+ "io::read_vtk: pieces hold {} cells but the shard box has {}", cells, box.points()); -+ } -+ switch (element_size) { -+ case 1: -+ read_payload<1>(in, components, pieces); -+ break; -+ case 2: -+ read_payload<2>(in, components, pieces); -+ break; -+ case 4: -+ read_payload<4>(in, components, pieces); -+ break; -+ case 8: -+ read_payload<8>(in, components, pieces); -+ break; -+ default: -+ log::throw_with_log("io::read_vtk: unsupported element size {}", -+ element_size); -+ } -+} -+ -+// ================================================================================================ -+// Session -+// ================================================================================================ -+ -+struct VtkBoxSession::Impl { -+ std::string path; -+ bool for_write = false; -+ std::uint32_t num_fields_recorded = 0; -+ VtkBox box; -+ std::ofstream writer; -+ std::ifstream reader; -+ std::vector read_fields; -+ size_t read_fields_cursor = 0; -+}; -+ -+VtkBoxSession::VtkBoxSession() noexcept = default; -+VtkBoxSession::~VtkBoxSession() = default; -+VtkBoxSession::VtkBoxSession(VtkBoxSession&&) noexcept = default; -+auto -+VtkBoxSession::operator=(VtkBoxSession&&) noexcept -> VtkBoxSession& = default; -+ -+auto -+VtkBoxSession::shard_path(std::string_view base, -+ const DenseDistributed& grid) -> std::string { -+ return shard_path_of(base, grid); -+} -+ -+void -+VtkBoxSession::open_for_write(std::string_view path, -+ const DenseDistributed& grid, -+ std::uint32_t /*num_fields*/) { -+ impl_ = std::make_unique(); -+ impl_->path = shard_path_of(path, grid); -+ impl_->for_write = true; -+ impl_->box = vtk_box_of(grid); -+ impl_->writer.open(impl_->path, std::ios::binary | std::ios::trunc); -+ if (!impl_->writer) { -+ log::throw_with_log("io::write_vtk: failed to open '{}' for writing", -+ impl_->path); -+ } -+ write_vtk_box_header(impl_->writer, impl_->box); -+} -+ -+void -+VtkBoxSession::write_field(std::string_view name, -+ const char* dtype_tag, -+ size_t element_size, -+ int components, -+ const std::vector& pieces) { -+ if (impl_ == nullptr || !impl_->for_write) { -+ log::throw_with_log("io::write_vtk: session is not in a writable state"); -+ } -+ write_vtk_box_field(impl_->writer, name, dtype_tag, element_size, components, impl_->box, pieces); -+ ++impl_->num_fields_recorded; -+} -+ -+void -+VtkBoxSession::open_for_read(std::string_view path, -+ const DenseDistributed& grid) { -+ impl_ = std::make_unique(); -+ impl_->path = shard_path_of(path, grid); -+ impl_->for_write = false; -+ impl_->box = vtk_box_of(grid); -+ impl_->reader.open(impl_->path, std::ios::binary); -+ if (!impl_->reader) { -+ log::throw_with_log("io::read_vtk: failed to open '{}' for reading", -+ impl_->path); -+ } -+ parse_vtk_box_header(impl_->reader, impl_->path, impl_->box, impl_->read_fields); -+} -+ -+void -+VtkBoxSession::read_field(std::string_view /*name*/, -+ const char* dtype_tag, -+ size_t element_size, -+ int components, -+ const std::vector& pieces) { -+ if (impl_ == nullptr || impl_->for_write) { -+ log::throw_with_log("io::read_vtk: session is not in a readable state"); -+ } -+ if (impl_->read_fields_cursor >= impl_->read_fields.size()) { -+ log::throw_with_log( -+ "io::read_vtk: more fields requested than '{}' contains", impl_->path); -+ } -+ // Fields bind by ordinal (names differ between writers). -+ const auto& rec = impl_->read_fields[impl_->read_fields_cursor++]; -+ const char* expected_kw = vtk_keyword_from_native_tag(dtype_tag); -+ if (expected_kw == nullptr || rec.vtk_dtype != expected_kw) { -+ log::throw_with_log( -+ "io::read_vtk: field {} dtype '{}' does not match bound carbon dtype '{}' in '{}'", -+ rec.name, rec.vtk_dtype, (expected_kw != nullptr ? expected_kw : "?"), impl_->path); -+ } -+ if (rec.components != components) { -+ log::throw_with_log( -+ "io::read_vtk: field {} has {} components but the bound Field has {}", rec.name, -+ rec.components, components); -+ } -+ impl_->reader.clear(); -+ impl_->reader.seekg(rec.payload_offset); -+ if (!impl_->reader.good()) { -+ log::throw_with_log( -+ "io::read_vtk: seek to the payload of '{}' failed in '{}'", rec.name, impl_->path); -+ } -+ read_vtk_box_field_payload(impl_->reader, element_size, components, impl_->box, pieces); -+} -+ -+auto -+VtkBoxSession::num_fields() const noexcept -> std::uint32_t { -+ if (impl_ == nullptr) { -+ return 0U; -+ } -+ return impl_->for_write ? impl_->num_fields_recorded -+ : static_cast(impl_->read_fields.size()); -+} -+ -+} // namespace carbon::io::detail -+ -+namespace carbon::io { -+ -+auto -+write_vtk_multiblock_index(std::string_view base, -+ const DenseDistributed& grid) -> void { -+#ifdef CARBON_HAVE_MPI_NCCL -+ const auto* dist = grid.system().distributed(); -+ if (dist == nullptr) { -+ return; // single process: the shard at is the whole dataset -+ } -+ const int world_size = dist->world_size(); -+ if (world_size <= 1 || dist->world_rank() != 0) { -+ return; -+ } -+ -+ // Which ranks own cells? Every rank's owned box follows from the global split alone, so the -+ // index needs no communication. Ranks with an empty box wrote a placeholder shard that is not -+ // listed (there is nothing to display). -+ const ProcessGrid& pg = grid.process_grid(); -+ const int64_3d global = grid.global_extent(); -+ std::vector listed; -+ for (int r = 0; r < world_size; ++r) { -+ bool owns = true; -+ if (pg.world_size() == world_size) { -+ const auto chunk = ::carbon::detail::dense_distributed::rank_chunk( -+ global, pg, pg.coords_of(r), int64_3d{0, 0, 0}); -+ owns = chunk.owned.x > 0 && chunk.owned.y > 0 && chunk.owned.z > 0; -+ } -+ if (owns) { -+ listed.push_back(r); -+ } -+ } -+ -+ const std::filesystem::path base_path(std::string{base}); -+ const std::filesystem::path master_path = base_path.string() + ".vtm"; -+ const std::filesystem::path base_filename = base_path.filename(); -+ -+ std::ofstream out(master_path, std::ios::binary | std::ios::trunc); -+ if (!out) { -+ log::throw_with_log( -+ "io::write_vtk_multiblock_index: failed to open '{}' for writing", master_path.string()); -+ } -+ out << "\n"; -+ out << "\n"; -+ out << " \n"; -+ int block = 0; -+ for (const int r : listed) { -+ out << " \n"; -+ out << " \n"; -+ out << " \n"; -+ } -+ out << " \n"; -+ out << "\n"; -+ if (!out.good()) { -+ log::throw_with_log("io::write_vtk_multiblock_index: write to '{}' failed", -+ master_path.string()); -+ } -+#else -+ (void)base; -+ (void)grid; -+#endif -+} -+ -+} // namespace carbon::io -diff --git a/tests/test_dense_distributed_dist.cu b/tests/test_dense_distributed_dist.cu -index ddb48a0..332abdd 100644 ---- a/tests/test_dense_distributed_dist.cu -+++ b/tests/test_dense_distributed_dist.cu -@@ -25,7 +25,15 @@ - // neighbour is outside an open boundary) is compiled into a Skeleton, so the halo kernel is - // auto-inserted from read_stencil and DenseDistributed::Span / Partition run on the device. - // Run once without overlap and once with OverlapMode::Standard, which splits the kernel into --// Internal + Boundary launches and therefore exercises those Span views for real. -+// Internal + Boundary launches and therefore exercises those Span views for real. (For pencil -+// and brick the Boundary launch is the compact shell, not the full owned extent.) -+// -+// 3. VTK shard I/O. A 3-component float field goes host -> device -> host, is written with -+// io::write_vtk (one `.rank` shard per rank) plus the `.vtm` index, and read back with -+// io::read_vtk into a second field. Each rank checks its own shard header against its owned box -+// (DIMENSIONS / ORIGIN), every owned cell after the round trip, that halo cells were not -+// touched, and rank 0 checks that the index lists every rank. Files are written to the -+// working directory (like test_io_dist) and removed afterwards. - - #include - #include -@@ -34,6 +42,7 @@ - #include - #include - #include -+#include - #include - #include - #include -@@ -47,7 +56,10 @@ - #include - #include - #include -+#include -+#include - #include -+#include - #include - #include - #include -@@ -470,6 +482,164 @@ run_stencil(carbon::System& sys, - return true; - } - -+// ------------------------------------------------------------------------------------------------ -+// Check 3: VTK shard I/O for DenseDistributed (write_vtk / read_vtk / multiblock index). -+// ------------------------------------------------------------------------------------------------ -+ -+[[nodiscard]] auto -+run_vtk(carbon::System& sys, -+ int rank, -+ int world, -+ const ProcessGrid& pg, -+ BoundaryModeDistributed mode, -+ const std::string& label, -+ const int64_3d& global) -> bool { -+ const std::string base = "carbon_test_dense_distributed_vtk_" + label; -+ const std::string shard = base + ".rank" + std::to_string(rank); -+ const std::string index = base + ".vtm"; -+ bool ok = true; -+ try { -+ DenseDistributed grid(sys, global, pg, six_point(), mode); -+ const auto& span = grid.spans()[0]; -+ const int64_3d halo = span.halo(); -+ const int64_3d owned = span.logic_extent(); -+ const int64_3d haloed = span.haloed_extent(); -+ const int64_t pitch = span.xy_slab_elements(); -+ const int64_t per_comp = span.linear_storage_elements(); -+ constexpr int kComps = 3; -+ constexpr float kSentinelIn = -1.0F; -+ constexpr float kSentinelOut = -2.0F; -+ -+ auto f = grid.template newField(carbon::MemorySide::HostDevice, "pop"); -+ auto g = grid.template newField(carbon::MemorySide::HostDevice, "pop_in"); -+ const auto is_owned_cell = [&](int64_t x, int64_t y, int64_t z) -> bool { -+ return x >= halo.x && x < halo.x + owned.x && y >= halo.y && y < halo.y + owned.y && -+ z >= halo.z && z < halo.z + owned.z; -+ }; -+ { -+ float* hf = f.cpu_buffers()[0].data(); -+ float* hg = g.cpu_buffers()[0].data(); -+ for (int64_t z = 0; z < haloed.z; ++z) { -+ for (int64_t y = 0; y < haloed.y; ++y) { -+ for (int64_t x = 0; x < haloed.x; ++x) { -+ const int64_3d gl = span.global_location(span.make_idx(x, y, z)); -+ const int64_t off = z * pitch + y * haloed.x + x; -+ for (int c = 0; c < kComps; ++c) { -+ hf[c * per_comp + off] = is_owned_cell(x, y, z) -+ ? static_cast(encode(gl.x, gl.y, gl.z, c)) -+ : kSentinelIn; -+ hg[c * per_comp + off] = kSentinelOut; -+ } -+ } -+ } -+ } -+ } -+ // host -> device -> host, so the field written is what a real run would download -+ carbon::Stream stream = sys.stream(); -+ carbon::Transfer(sys, f.cpu_buffers(), f.gpu_buffers())(stream); -+ if (!sync_all(stream, "vtk upload")) { -+ return false; -+ } -+ { -+ float* hf = f.cpu_buffers()[0].data(); -+ for (size_t i = 0; i < f.cpu_buffers()[0].size(); ++i) { -+ hf[i] = 0.0F; -+ } -+ } -+ carbon::Transfer(sys, f.gpu_buffers(), f.cpu_buffers())(stream); -+ if (!sync_all(stream, "vtk download")) { -+ return false; -+ } -+ -+ carbon::io::write_vtk(base, grid, f); -+ carbon::io::write_vtk_multiblock_index(base, grid); -+ -+ // --- this rank's shard header must describe its owned box ---------------------------------- -+ { -+ std::ifstream in(shard, std::ios::binary); -+ std::string line; -+ int64_t dims[3] = {-1, -1, -1}; -+ int64_t org[3] = {-1, -1, -1}; -+ while (std::getline(in, line)) { -+ std::istringstream ls(line); -+ std::string head; -+ ls >> head; -+ if (head == "DIMENSIONS") { -+ ls >> dims[0] >> dims[1] >> dims[2]; -+ } else if (head == "ORIGIN") { -+ ls >> org[0] >> org[1] >> org[2]; -+ } else if (head == "SCALARS") { -+ break; -+ } -+ } -+ const int64_3d o0 = span.global_location(span.make_idx(halo.x, halo.y, halo.z)); -+ if (dims[0] != owned.x || dims[1] != owned.y || dims[2] != owned.z || org[0] != o0.x || -+ org[1] != o0.y || org[2] != o0.z) { -+ CARBON_LOG_ERROR( -+ "test_dense_distributed_dist[{}]: rank {} shard header DIMENSIONS=({},{},{}) " -+ "ORIGIN=({},{},{}) want owned=({},{},{}) origin=({},{},{})", -+ label, rank, dims[0], dims[1], dims[2], org[0], org[1], org[2], owned.x, owned.y, -+ owned.z, o0.x, o0.y, o0.z); -+ ok = false; -+ } -+ } -+ -+ // --- rank 0's index lists every rank (all own cells for this extent) ------------------------- -+ if (rank == 0) { -+ std::ifstream in(index); -+ const std::string text((std::istreambuf_iterator(in)), -+ std::istreambuf_iterator()); -+ if (text.find("vtkMultiBlockDataSet") == std::string::npos) { -+ CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: missing/invalid {}", label, index); -+ ok = false; -+ } -+ for (int r = 0; r < world; ++r) { -+ if (text.find("name=\"rank" + std::to_string(r) + "\"") == std::string::npos) { -+ CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: index does not list rank {}", label, -+ r); -+ ok = false; -+ } -+ } -+ } -+ -+ // --- read back into a fresh field: owned == written, halo untouched ---------------------------- -+ carbon::io::read_vtk(base, grid, g); -+ size_t mismatches = 0; -+ const float* hg = g.cpu_buffers()[0].data(); -+ for (int64_t z = 0; z < haloed.z; ++z) { -+ for (int64_t y = 0; y < haloed.y; ++y) { -+ for (int64_t x = 0; x < haloed.x; ++x) { -+ const int64_3d gl = span.global_location(span.make_idx(x, y, z)); -+ const int64_t off = z * pitch + y * haloed.x + x; -+ for (int c = 0; c < kComps; ++c) { -+ const float want = is_owned_cell(x, y, z) -+ ? static_cast(encode(gl.x, gl.y, gl.z, c)) -+ : kSentinelOut; -+ if (hg[c * per_comp + off] != want) { -+ ++mismatches; -+ } -+ } -+ } -+ } -+ } -+ if (mismatches != 0U) { -+ CARBON_LOG_ERROR( -+ "test_dense_distributed_dist[{}]: rank {} VTK round trip has {} wrong values", label, -+ rank, mismatches); -+ ok = false; -+ } -+ } catch (const std::exception& e) { -+ CARBON_LOG_ERROR("test_dense_distributed_dist[{}]: VTK I/O failed: {}", label, e.what()); -+ ok = false; -+ } -+ std::error_code ec; -+ std::filesystem::remove(shard, ec); -+ if (rank == 0) { -+ std::filesystem::remove(index, ec); -+ } -+ return ok; -+} -+ - struct Case { - ProcessGrid pg; - BoundaryModeDistributed mode; -@@ -540,7 +710,8 @@ main() { - !run_stencil(sys, rank, c.pg, c.mode, carbon::OverlapMode::None, - std::string(c.label) + "/stencil", global) || - !run_stencil(sys, rank, c.pg, c.mode, carbon::OverlapMode::Standard, -- std::string(c.label) + "/stencil-overlap", global)) { -+ std::string(c.label) + "/stencil-overlap", 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 079dcd6..21a52b4 100644 ---- a/tests/test_dense_distributed_host.cpp -+++ b/tests/test_dense_distributed_host.cpp -@@ -7,6 +7,10 @@ - // hand-written expectations, the owned boxes must tile the global domain exactly once, and - // the resulting Span must iterate (Standard, Internal + Boundary) and resolve - // neighbours (open vs periodic) correctly. -+// Part D VTK shard I/O (io::detail stream-level writer/reader behind write_vtk / read_vtk for -+// DenseDistributed): byte-level check of the legacy BINARY payload with an independent -+// decoder, library round trip that must leave halo cells untouched, shard boxes that tile -+// the domain exactly once, and the placeholder shard of a rank that owns no cells. - // Part C correctness of the full X -> Y -> Z staged halo exchange on an emulated multi-rank world - // (corners/edges, periodic wraps, uneven splits, self-wrap), driven by the production - // plan builder and checked against the run-based builder (kept as the oracle) and against -@@ -20,16 +24,22 @@ - #include - #include - #include -+#include -+#include - #include - #include - - #include - #include -+#include - #include - #include - #include -+#include - #include - #include -+#include -+#include - #include - #include - -@@ -704,6 +714,23 @@ 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) { -+ // 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 -+ // padded tail is exactly the invalid threads. -+ const auto pos = [](int64_t v) { -+ return v > 0 ? v : 0; -+ }; -+ const int64_t owned_cells = ch.owned.x * ch.owned.y * ch.owned.z; -+ const int64_t internal_cells = pos(ch.owned.x - 2 * halo.x) * -+ pos(ch.owned.y - 2 * halo.y) * -+ pos(ch.owned.z - 2 * halo.z); -+ const int64_t shell = owned_cells - internal_cells; -+ CHECK(e.z == 1 || shell == 0); -+ CHECK(e.x * e.y * e.z >= shell); -+ CHECK(e.x * e.y * e.z < shell + 128); -+ } -+ int64_t valid_threads = 0; - for (int64_t iz = 0; iz < e.z; ++iz) { - for (int64_t iy = 0; iy < e.y; ++iy) { - for (int64_t ix = 0; ix < e.x; ++ix) { -@@ -711,6 +738,7 @@ check_geometry(const GeomCase& c, - if (!v.valid) { - continue; - } -+ ++valid_threads; - const int64_3d cell = v.idx.cell(); - const int64_t lx = cell.x - halo.x; - const int64_t ly = cell.y - halo.y; -@@ -721,6 +749,15 @@ check_geometry(const GeomCase& c, - } - } - } -+ if (view == carbon::DataView::Boundary && !legacy_slab) { -+ // Every valid Boundary thread is a distinct shell cell; the rest of the box is padding. -+ const auto pos = [](int64_t v) { -+ return v > 0 ? v : 0; -+ }; -+ CHECK(valid_threads == ch.owned.x * ch.owned.y * ch.owned.z - -+ pos(ch.owned.x - 2 * halo.x) * pos(ch.owned.y - 2 * halo.y) * -+ pos(ch.owned.z - 2 * halo.z)); -+ } - } - for (const int m : mark) { - CHECK(m == 1); -@@ -820,6 +857,269 @@ part_b_geometry(size_t& cells, - return cases.size(); - } - -+// ------------------------------------------------------------------------------------------------ -+// Part D: VTK shard I/O for DenseDistributed. -+// ------------------------------------------------------------------------------------------------ -+ -+namespace vtk = carbon::io::detail; -+ -+// Injective for extents < 16 and up to 3 components, and it fits in int16. -+auto -+vtk_value(int64_t x, -+ int64_t y, -+ int64_t z, -+ int c) -> int { -+ return static_cast(x + 16 * y + 256 * z + 4096 * c); -+} -+ -+// Independent big-endian decoder (does not use the library's swap code). -+template -+auto -+decode_be(const unsigned char* p) -> T { -+ unsigned char b[sizeof(T)]; -+ for (size_t i = 0; i < sizeof(T); ++i) { -+ b[i] = p[sizeof(T) - 1 - i]; // BE on the wire -> LE host (this test runs on LE hosts) -+ } -+ T v; -+ std::memcpy(&v, b, sizeof(T)); -+ return v; -+} -+ -+struct VtkCase { -+ const char* name; -+ int px, py, pz; -+ BoundaryModeDistributed bm; -+ int64_t gx, gy, gz; -+}; -+ -+template -+auto -+vtk_roundtrip_case(const VtkCase& c, -+ int comps, -+ std::vector& cover, -+ size_t& shards, -+ size_t& empty_shards, -+ size_t& points) -> void { -+ g_ctx = std::string("part D ") + c.name + " T" + std::to_string(sizeof(T)) + " c" + -+ std::to_string(comps); -+ static_assert(std::endian::native == std::endian::little, "decoder assumes a little-endian host"); -+ const ProcessGrid pg = ProcessGrid::custom(c.px * c.py * c.pz, c.px, c.py, c.pz); -+ 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 int64_3d global{c.gx, c.gy, c.gz}; -+ const int64_3d halo = dd::halo_extent(pg, c.bm, stencil); -+ const char* tag = -+ sizeof(T) == 2 ? "i16\0\0\0\0" : (sizeof(T) == 4 ? "i32\0\0\0\0" : "f64\0\0\0\0"); -+ const char* kw = sizeof(T) == 2 ? "short" : (sizeof(T) == 4 ? "int" : "double"); -+ -+ for (int32_t r = 0; r < pg.world_size(); ++r) { -+ const dd::RankChunk ch = dd::rank_chunk(global, pg, pg.coords_of(r), halo); -+ const int64_t per_comp = ch.xy_pitch * ch.haloed.z; -+ const T sentinel = static_cast(-777); -+ std::vector buf(static_cast(per_comp) * static_cast(comps), sentinel); -+ const int64_3d own0{ch.offset.x + halo.x, ch.offset.y + halo.y, ch.offset.z + halo.z}; -+ for (int64_t z = 0; z < ch.owned.z; ++z) { -+ for (int64_t y = 0; y < ch.owned.y; ++y) { -+ for (int64_t x = 0; x < ch.owned.x; ++x) { -+ for (int k = 0; k < comps; ++k) { -+ const int64_t off = -+ (halo.z + z) * ch.xy_pitch + (halo.y + y) * ch.haloed.x + halo.x + x; -+ buf[static_cast(k * per_comp + off)] = -+ static_cast(vtk_value(own0.x + x, own0.y + y, own0.z + z, k)); -+ } -+ } -+ } -+ } -+ -+ vtk::VtkBox box; -+ box.origin[0] = own0.x; -+ box.origin[1] = own0.y; -+ box.origin[2] = own0.z; -+ const bool owns = ch.owned.x > 0 && ch.owned.y > 0 && ch.owned.z > 0; -+ if (owns) { -+ box.dims[0] = ch.owned.x; -+ box.dims[1] = ch.owned.y; -+ box.dims[2] = ch.owned.z; -+ } -+ std::vector pieces; -+ if (owns) { -+ vtk::VtkBoxPiece p; -+ p.start = buf.data() + halo.z * ch.xy_pitch + halo.y * ch.haloed.x + halo.x; -+ p.nx = ch.owned.x; -+ p.ny = ch.owned.y; -+ p.nz = ch.owned.z; -+ p.row_stride = ch.haloed.x; -+ p.plane_pitch = ch.xy_pitch; -+ p.comp_stride = per_comp; -+ pieces.push_back(p); -+ } -+ -+ std::ostringstream os; -+ vtk::write_vtk_box_header(os, box); -+ vtk::write_vtk_box_field(os, "my field", tag, sizeof(T), comps, box, pieces); -+ const std::string bytes = os.str(); -+ ++shards; -+ -+ // --- independent parse of the text header ------------------------------------------------- -+ std::istringstream hs(bytes); -+ std::string line; -+ int64_t dims[3] = {-1, -1, -1}; -+ int64_t org[3] = {-1, -1, -1}; -+ int64_t npts = -1; -+ std::string scal_name; -+ std::string scal_type; -+ int scal_comps = -1; -+ size_t payload_at = 0; -+ while (std::getline(hs, line)) { -+ std::istringstream ls(line); -+ std::string head; -+ ls >> head; -+ if (head == "DIMENSIONS") { -+ ls >> dims[0] >> dims[1] >> dims[2]; -+ } else if (head == "ORIGIN") { -+ ls >> org[0] >> org[1] >> org[2]; -+ } else if (head == "POINT_DATA") { -+ ls >> npts; -+ } else if (head == "SCALARS") { -+ ls >> scal_name >> scal_type >> scal_comps; -+ } else if (head == "LOOKUP_TABLE") { -+ payload_at = static_cast(hs.tellg()); -+ break; -+ } -+ } -+ CHECK(scal_name == "my_field"); // whitespace in the label is made a single token -+ CHECK(scal_type == kw); -+ CHECK(scal_comps == comps); -+ if (!owns) { -+ // Placeholder shard: valid header, no payload, flagged as empty in the title. -+ ++empty_shards; -+ CHECK(dims[0] == 0 && dims[1] == 0 && dims[2] == 0 && npts == 0); -+ CHECK(bytes.size() == payload_at + 1U); // just the newline that ends the SCALARS block -+ CHECK(bytes.find("empty") != std::string::npos); -+ } else { -+ CHECK(dims[0] == ch.owned.x && dims[1] == ch.owned.y && dims[2] == ch.owned.z); -+ CHECK(org[0] == own0.x && org[1] == own0.y && org[2] == own0.z); -+ CHECK(npts == ch.owned.x * ch.owned.y * ch.owned.z); -+ const size_t payload_bytes = -+ static_cast(npts) * static_cast(comps) * sizeof(T); -+ CHECK(bytes.size() == payload_at + payload_bytes + 1U); -+ const auto* raw = reinterpret_cast(bytes.data()) + payload_at; -+ for (int64_t z = 0; z < dims[2]; ++z) { -+ for (int64_t y = 0; y < dims[1]; ++y) { -+ for (int64_t x = 0; x < dims[0]; ++x) { -+ const int64_t pt = (z * dims[1] + y) * dims[0] + x; -+ for (int k = 0; k < comps; ++k) { -+ const T got = -+ decode_be(raw + (static_cast(pt) * static_cast(comps) + -+ static_cast(k)) * -+ sizeof(T)); -+ CHECK(got == static_cast(vtk_value(org[0] + x, org[1] + y, org[2] + z, k))); -+ } -+ } -+ } -+ // tiling bookkeeping (uses only what the header says) -+ } -+ for (int64_t z = 0; z < dims[2]; ++z) { -+ for (int64_t y = 0; y < dims[1]; ++y) { -+ for (int64_t x = 0; x < dims[0]; ++x) { -+ cover[static_cast(((org[2] + z) * c.gy + (org[1] + y)) * c.gx + org[0] + x)] += -+ 1; -+ } -+ } -+ } -+ points += static_cast(npts); -+ } -+ -+ // --- library round trip: owned cells restored, halo cells untouched ------------------------ -+ std::istringstream in(bytes); -+ std::vector recs; -+ vtk::parse_vtk_box_header(in, "mem", box, recs); -+ CHECK(recs.size() == 1U); -+ CHECK(recs[0].components == comps && recs[0].vtk_dtype == kw); -+ const T sentinel2 = static_cast(-555); -+ std::vector back(buf.size(), sentinel2); -+ std::vector mut; -+ if (owns) { -+ vtk::VtkBoxPieceMut m; -+ m.start = back.data() + halo.z * ch.xy_pitch + halo.y * ch.haloed.x + halo.x; -+ m.nx = ch.owned.x; -+ m.ny = ch.owned.y; -+ m.nz = ch.owned.z; -+ m.row_stride = ch.haloed.x; -+ m.plane_pitch = ch.xy_pitch; -+ m.comp_stride = per_comp; -+ mut.push_back(m); -+ } -+ in.clear(); -+ in.seekg(recs[0].payload_offset); -+ vtk::read_vtk_box_field_payload(in, sizeof(T), comps, box, mut); -+ for (int64_t z = 0; z < ch.haloed.z; ++z) { -+ for (int64_t y = 0; y < ch.haloed.y; ++y) { -+ for (int64_t x = 0; x < ch.haloed.x; ++x) { -+ const bool in_owned = x >= halo.x && x < halo.x + ch.owned.x && y >= halo.y && -+ y < halo.y + ch.owned.y && z >= halo.z && z < halo.z + ch.owned.z; -+ for (int k = 0; k < comps; ++k) { -+ const size_t i = -+ static_cast(k * per_comp + z * ch.xy_pitch + y * ch.haloed.x + x); -+ CHECK(in_owned ? back[i] == buf[i] : back[i] == sentinel2); -+ } -+ } -+ } -+ } -+ -+ // --- a shard from a different box must be rejected ----------------------------------------- -+ if (owns) { -+ vtk::VtkBox other = box; -+ other.origin[0] += 1; -+ std::istringstream in2(bytes); -+ std::vector recs2; -+ bool threw = false; -+ carbon::log::set_level(spdlog::level::off); // the library logs the (expected) rejection -+ try { -+ vtk::parse_vtk_box_header(in2, "mem", other, recs2); -+ } catch (const std::invalid_argument&) { -+ threw = true; -+ } -+ carbon::log::set_level(spdlog::level::info); -+ CHECK(threw); -+ } -+ } -+} -+ -+auto -+part_d_vtk(size_t& shards, -+ size_t& empty_shards, -+ size_t& points) -> size_t { -+ constexpr auto kO = BoundaryModeDistributed::Open; -+ constexpr auto kX = BoundaryModeDistributed::PeriodicX; -+ constexpr auto kZ = BoundaryModeDistributed::PeriodicZ; -+ const std::vector cases = { -+ {"slab", 1, 1, 4, kO, 6, 5, 9}, -+ {"slab-periodicZ", 1, 1, 3, kZ, 5, 4, 7}, -+ {"pencil", 1, 2, 2, kO, 6, 7, 8}, -+ {"pencil-periodicX", 1, 2, 2, kX, 5, 6, 4}, -+ {"brick-uneven", 3, 2, 2, kO, 8, 5, 6}, -+ {"brick-thin", 2, 2, 2, kX | kZ, 3, 3, 3}, -+ // 2 layers over 4 z-parts and 1 over 2 y-parts: half of the ranks own no cells. -+ {"brick-empty-ranks", 2, 2, 4, kO, 3, 1, 2}, -+ }; -+ for (const VtkCase& c : cases) { -+ std::vector cover(static_cast(c.gx * c.gy * c.gz), 0); -+ vtk_roundtrip_case(c, 2, cover, shards, empty_shards, points); -+ for (const int m : cover) { -+ CHECK(m == 1); // shard boxes tile the global domain exactly once -+ } -+ // Other element sizes / component counts (tiling already shown above; reuse a scratch map). -+ std::vector scratch32(cover.size(), 0); -+ vtk_roundtrip_case(c, 3, scratch32, shards, empty_shards, points); -+ std::vector scratch64(cover.size(), 0); -+ vtk_roundtrip_case(c, 1, scratch64, shards, empty_shards, points); -+ } -+ CHECK(empty_shards > 0U); // the placeholder path must actually be exercised -+ return cases.size(); -+} -+ - struct Scenario { - const char* name; - int px, py, pz; -@@ -900,6 +1200,13 @@ main() { - std::printf("geometry cases=%zu owned cells checked=%zu neighbour reads checked=%zu\n", - geom_cases, geom_cells, geom_neighbours); - -+ size_t vtk_shards = 0; -+ size_t vtk_empty = 0; -+ size_t vtk_points = 0; -+ const size_t vtk_cases = part_d_vtk(vtk_shards, vtk_empty, vtk_points); -+ std::printf("vtk cases=%zu shards=%zu (placeholders=%zu) points verified=%zu\n", vtk_cases, -+ vtk_shards, vtk_empty, vtk_points); -+ - std::vector sc; - const BoundaryModeDistributed modes[] = { - kOpen, kPX, kPY, kPZ, bm_or(kPX, kPZ), bm_or(bm_or(kPX, kPY), kPZ)}; diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 1f026382..aed1f09d 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6153,3 +6153,16 @@ This unblocked the matrix on this host: the `sycl` and `hip-nvidia` images build follows it in FIFO order and the Internal half overlaps on stream 0. The stencil's Internal half still waits on the producer's Boundary half (it reads boundary-band cells), and the anchor-start fork is load-bearing again because the Boundary half opens the halo stream. +- **2026-11 — `LatticeDistributed` halo semantic and XML `.vti` shards.** + `StencilSemantic::LatticeDistributed` exchanges both nonzero signs of a face-normal + velocity on every decomposed face (zero-normal components still excluded). This keeps + wall bounce-back reads of `opp(q)` valid across rank boundaries on brick/pencil grids; + `Lattice` remains the cheaper one-sided semantic. `Halo` / `HaloDisg` treat it as + bidirectional Z. The distributed LBM benchmark selects it only when the + `DenseDistributed` process grid is split on X or Y, so slab layouts keep `Lattice`. + The distributed VTK writer now emits XML ImageData `.vti` shards with inline + base64 little-endian binary payloads and a `.vtm` index that references them; the + legacy stream-level helpers stay for the host tests. Inline binary is used because + VTK 9.2's XML parser rejects raw appended blocks above its small line buffer. The + base64 is emitted as one line: VTK's inline reader truncates large line-wrapped + blocks. The old experimental `io_vtk_distributed_wrong.cpp` was removed. diff --git a/include/carbon/detail/halo_build.h b/include/carbon/detail/halo_build.h index 0e2dc86c..dd26c8e7 100644 --- a/include/carbon/detail/halo_build.h +++ b/include/carbon/detail/halo_build.h @@ -68,19 +68,21 @@ namespace carbon::detail::halo_build { /** * Phase 1 (semantic): reject unrecognised @c StencilSemantic values. * - * Both halo families accept @c Standard and @c Lattice ; any other - * enum value indicates a memory-corruption-style misuse and gets a - * pointed diagnostic. @p family_tag is prepended to the log message - * so the user sees @c "Halo:" or @c "HaloDisg:" depending on the - * caller — same shape as the original inline checks. + * Both halo families accept @c Standard , @c Lattice , and + * @c LatticeDistributed ; any other enum value indicates a + * memory-corruption-style misuse and gets a pointed diagnostic. + * @p family_tag is prepended to the log message so the user sees + * @c "Halo:" or @c "HaloDisg:" depending on the caller — same shape as + * the original inline checks. * - * @throws std::invalid_argument when @p semantic is neither - * @c Standard nor @c Lattice . + * @throws std::invalid_argument when @p semantic is not one of the three + * supported values. */ inline auto validate_stencil_semantic(StencilSemantic semantic, const char* family_tag) -> void { - if (semantic != StencilSemantic::Standard && semantic != StencilSemantic::Lattice) { + if (semantic != StencilSemantic::Standard && semantic != StencilSemantic::Lattice && + semantic != StencilSemantic::LatticeDistributed) { log::throw_with_log("{}: unrecognised StencilSemantic (got {})", family_tag, static_cast(semantic)); } diff --git a/include/carbon/detail/io_vtk.inl b/include/carbon/detail/io_vtk.inl index 632d8529..b14eedfa 100644 --- a/include/carbon/detail/io_vtk.inl +++ b/include/carbon/detail/io_vtk.inl @@ -161,10 +161,11 @@ write_vtk(std::string_view path, * distributed handle this function uses to enumerate world * size on rank 0. * - * Note: ParaView's @c .pvti format would offer spatial merging across - * pieces but requires the shards to be in the XML @c .vti format which - * carbon does not currently emit; @c .vtm is the next-best generic - * "load all pieces in one go" wrapper and works with the legacy shards. + * Note: this Dense path still writes legacy @c .vtk shards. The + * @c DenseDistributed path emits XML ImageData @c .vti shards and wraps + * them in the same @c .vtm index. ParaView's @c .pvti format would offer + * spatial merging across pieces, but @c .vtm is the generic wrapper that + * works with both shard families. */ CARBON_API auto write_vtk_multiblock_index(std::string_view base, diff --git a/include/carbon/detail/io_vtk_distributed.inl b/include/carbon/detail/io_vtk_distributed.inl index 33fc51ab..5381166d 100644 --- a/include/carbon/detail/io_vtk_distributed.inl +++ b/include/carbon/detail/io_vtk_distributed.inl @@ -1,31 +1,38 @@ -// io_vtk_distributed.inl — VTK legacy backend for carbon::DenseDistributed, split out of +// io_vtk_distributed.inl — VTK XML backend for carbon::DenseDistributed, split out of // . Tail include of io.h (see io_vtk.inl for the include-context contract); not a // standalone header. // -// Same on-disk format as the Dense backend (legacy BINARY STRUCTURED_POINTS, one `.rank` shard -// per rank under MPI, `.vtm` multiblock index written by rank 0), generalised from "full XY -// planes, z-slab" to "the rank's owned bounding box": +// One XML ImageData `.vti` shard per rank under MPI, plus a `.vtm` multiblock index written by +// rank 0. Geometry is the rank's owned bounding box, generalised from "full XY planes, z-slab": // -// # vtk DataFile Version 3.0 -// carbon dense field shard -// BINARY -// DATASET STRUCTURED_POINTS -// DIMENSIONS // the rank's owned box (halo excluded) -// ORIGIN // global index of the box's first cell -// SPACING 1 1 1 // index space, same as the Dense writer -// POINT_DATA -// SCALARS -// LOOKUP_TABLE default -// +// +// +// +// +// +// +// +// +// +// +// // -// A rank that owns no cells (global extent smaller than the process grid on some axis) writes a -// placeholder shard: valid header with `DIMENSIONS 0 0 0` / `POINT_DATA 0` and each SCALARS -// header without payload, so every rank leaves exactly one file. The `.vtm` index lists only the -// non-empty shards (there is nothing to display for the others). +// Each inline block is base64-encoded and starts with an 8-byte little-endian byte count, +// followed by the little-endian component-fastest payload (x fastest, then y, then z). The +// base64 is written as one line: VTK's inline reader mishandles wrapped blocks once the payload +// grows past a few MiB. Inline binary avoids the VTK 9.2 XML parser's raw-appended-data buffer +// limit while remaining a normal VTK XML file. A rank +// that owns no cells writes a valid empty shard; the `.vtm` index lists only the non-empty +// shards. // -// Index space (SPACING 1, ORIGIN in cells) is deliberate: it is what the Dense writer/reader use, +// Index space (Spacing 1, Origin in cells) is deliberate: it is what the Dense writer/reader use, // costs nothing extra to write, and keeps shards of both grid families interchangeable in // ParaView. The span's physical origin/spacing are not applied. +// +// The legacy stream-level helpers below are retained for the host VTK tests. The session itself +// uses the XML helpers in io_vtk_distributed.cpp. namespace detail { /** Pointer-parametrised block of owned cells inside a haloed per-GPU buffer. */ @@ -62,7 +69,7 @@ struct VtkBox { } }; -/** Per-SCALARS record found while parsing a shard header. */ +/** Per-DataArray record found while parsing a shard header. */ struct VtkBoxFieldRecord { std::string name; std::string vtk_dtype; @@ -143,6 +150,11 @@ public: size_t element_size, int components, const std::vector& pieces); + + /** Finish a writable session: close PointData/ImageData/VTKFile. Idempotent. */ + void + finalize(); + void read_field(std::string_view name, const char* dtype_tag, @@ -241,8 +253,8 @@ collect_vtk_pieces_mut(const DenseDistributed& grid, } // namespace detail /** - * Write @p fields (host mirrors, halo excluded) of @p grid as one legacy BINARY VTK shard per - * rank (`.rank` under MPI, `` otherwise). Works for every decomposition + * Write @p fields (host mirrors, halo excluded) of @p grid as one XML ImageData `.vti` shard per + * rank (`.rank.vti` under MPI, `.vti` otherwise). Works for every decomposition * (slab / pencil / brick). Download device data to the host mirror first. Call * @ref write_vtk_multiblock_index afterwards (any rank may call it; rank 0 writes) to get a * single `.vtm` that ParaView opens as one multiblock dataset. @@ -269,11 +281,12 @@ write_vtk(std::string_view path, ++i; }(), ...); + sess.finalize(); } /** - * Read @p fields of @p grid from the shard @ref write_vtk wrote for this rank. DIMENSIONS and - * ORIGIN must match this rank's owned box; fields bind by ordinal. Only owned cells are touched + * Read @p fields of @p grid from the shard @ref write_vtk wrote for this rank. WholeExtent and + * Origin must match this rank's owned box; fields bind by ordinal. Only owned cells are touched * (halo cells keep their contents). */ template diff --git a/include/carbon/halo.h b/include/carbon/halo.h index 0930a1ba..30e97201 100644 --- a/include/carbon/halo.h +++ b/include/carbon/halo.h @@ -145,7 +145,7 @@ class Halo { * * - @c stencil.size() must equal @c Components . * - @c stencil.radius() must be @c <= halo_z (the available halo thickness). - * - @p semantic must be one of @c Standard / @c Lattice . + * - @p semantic must be one of @c Standard / @c Lattice / @c LatticeDistributed . * * @throws std::invalid_argument on any of the above failing. */ @@ -387,7 +387,7 @@ Halo(Components)) { log::throw_with_log( "Halo(lattice): stencil.size() = {} but Components = {}; the lattice halo pairs " @@ -404,17 +404,22 @@ Halo bool { if (semantic_ == StencilSemantic::Standard) { return true; } - return stencil_.points()[static_cast(c)].z > 0; + const int64_t z = stencil_.points()[static_cast(c)].z; + return bidirectional_z ? z != 0 : z > 0; }; auto active_down = [&](int c) noexcept -> bool { if (semantic_ == StencilSemantic::Standard) { return true; } - return stencil_.points()[static_cast(c)].z < 0; + const int64_t z = stencil_.points()[static_cast(c)].z; + return bidirectional_z ? z != 0 : z < 0; }; // Host-only fields (MemorySide::Host) carry no GPU buffers; the host_intra_ diff --git a/include/carbon/halo_disg.h b/include/carbon/halo_disg.h index 2c9eb0b8..7593619d 100644 --- a/include/carbon/halo_disg.h +++ b/include/carbon/halo_disg.h @@ -115,7 +115,7 @@ class HaloDisg { * - @c stencil.radius() must be @c <= 1 (the disg layout pins ghost / boundary radius * to 1; lattices like Q39 / Q125 with radius @c >= 2 need extending the disg * region count first). - * - @p semantic must be one of @c Standard / @c Lattice . + * - @p semantic must be one of @c Standard / @c Lattice / @c LatticeDistributed . * * @throws std::invalid_argument on any of the above failing. */ @@ -284,6 +284,8 @@ enum class TransferDir : int { * direction of a lattice halo. Standard semantic always returns the single run * @c [0, Components) ; lattice semantic walks @c stencil.points() and emits one * @c CardinalityRun per maximal run of consecutive same-sign-z populations. + * LatticeDistributed treats both directions as bidirectional z and emits runs + * over every population with @c c_z != 0 . */ template [[nodiscard]] inline auto @@ -295,6 +297,7 @@ runs_for_direction(StencilSemantic semantic, runs.push_back({0, Components}); return runs; } + const bool bidirectional_z = semantic == StencilSemantic::LatticeDistributed; // Lattice: walk cardinalities and emit one run per maximal active stretch. int j_start = -1; int j_len = 0; @@ -306,7 +309,8 @@ runs_for_direction(StencilSemantic semantic, }; for (int j = 0; j < Components; ++j) { const auto& s = stencil.points()[static_cast(j)]; - const bool active = (dir == TransferDir::Up) ? (s.z > 0) : (s.z < 0); + const bool active = + bidirectional_z ? (s.z != 0) : ((dir == TransferDir::Up) ? (s.z > 0) : (s.z < 0)); if (active) { if (j_len == 0) { j_start = j; @@ -343,7 +347,7 @@ HaloDisg(Components)) { log::throw_with_log( "HaloDisg(lattice): stencil.size() = {} but Components = {}; the lattice halo pairs " @@ -401,7 +405,8 @@ HaloDisg intra; diff --git a/include/carbon/halo_distributed.h b/include/carbon/halo_distributed.h index a6017c05..ae4605a8 100644 --- a/include/carbon/halo_distributed.h +++ b/include/carbon/halo_distributed.h @@ -155,7 +155,7 @@ class HaloDistributed { * * - @c stencil.size() must equal @c Components . * - @c stencil.radius() must be @c <= the corresponding per-axis halo thickness. - * - @p semantic must be one of @c Standard / @c Lattice . + * - @p semantic must be one of @c Standard / @c Lattice / @c LatticeDistributed . * * @throws std::invalid_argument on any of the above failing. */ @@ -565,7 +565,7 @@ HaloDistributed(Components)) { log::throw_with_log( "HaloDistributed(lattice): stencil.size() = {} but Components = {}; the lattice halo " @@ -601,7 +601,7 @@ HaloDistributed(Components)) { log::throw_with_log( "HaloDistributed(lattice): stencil.size() = {} but Components = {}; the lattice halo " @@ -619,17 +619,22 @@ HaloDistributed bool { if (semantic_ == StencilSemantic::Standard) { return true; } - return stencil_.points()[static_cast(c)].z > 0; + const int64_t z = stencil_.points()[static_cast(c)].z; + return bidirectional_z ? z != 0 : z > 0; }; auto active_down = [&](int c) noexcept -> bool { if (semantic_ == StencilSemantic::Standard) { return true; } - return stencil_.points()[static_cast(c)].z < 0; + const int64_t z = stencil_.points()[static_cast(c)].z; + return bidirectional_z ? z != 0 : z < 0; }; // Host-only fields (MemorySide::Host) carry no GPU buffers; the host_intra_ @@ -836,11 +841,15 @@ HaloDistributed(c)], axis); }; + const bool bidirectional = semantic_ == StencilSemantic::LatticeDistributed; const auto active_send = [&](int c, Axis axis, AxisSide side) -> bool { if (semantic_ == StencilSemantic::Standard) { return true; } const int64_t v = velocity(c, axis); + if (bidirectional) { + return v != 0; + } return side == AxisSide::Upper ? v > 0 : v < 0; }; @@ -849,6 +858,9 @@ HaloDistributed 0; }; diff --git a/include/carbon/kernel.h b/include/carbon/kernel.h index d681f489..7df03b0a 100644 --- a/include/carbon/kernel.h +++ b/include/carbon/kernel.h @@ -312,7 +312,8 @@ struct KernelLoader { /** * @brief Stencil read with explicit halo semantic — same as @ref read_stencil but * the auto-inserted halo uses @p stencil and @p semantic (e.g. - * @c StencilSemantic::Lattice for LBM populations). Mirrors Neon's + * @c StencilSemantic::Lattice for LBM populations; use @c LatticeDistributed on + * multi-axis decompositions). Mirrors Neon's * @c Loader::load(field, Pattern::STENCIL, stencilSemantic) . * * @p stencil must be index-aligned with the field's @c Components when diff --git a/include/carbon/stencil.h b/include/carbon/stencil.h index 0369b823..61884318 100644 --- a/include/carbon/stencil.h +++ b/include/carbon/stencil.h @@ -22,12 +22,31 @@ namespace carbon { * z-slab boundary — for D3Q19 that's 5/19, for D3Q27 9/27. Carries an additional * pre-condition: @c stencil.size() must equal the field's @c Components and entries are * paired by index @c (population q ↔ stencil.points()[q]) . + * + * @c LatticeDistributed is the multi-axis / distributed variant: every decomposed face + * exchanges both nonzero signs of its normal velocity component, so a wall bounce-back + * that reads @c opp(q) from a wall cell across a rank boundary still finds it. Components + * with zero normal velocity cannot cross the face and are not exchanged. On a z-only + * layout this degenerates to bidirectional z. It is more expensive than @c Lattice but + * still cheaper than @c Standard for D3Q19 / D3Q27 cubic decompositions. Carries the same + * stencil-size pre-condition as @c Lattice . */ enum struct StencilSemantic : int { Standard = 0, - Lattice = 1 + Lattice = 1, + LatticeDistributed = 2 }; +/** + * @return @c true for either lattice-population semantic (@c Lattice or + * @c LatticeDistributed). Used by halo constructors to apply the common + * stencil-size / radius validation. + */ +[[nodiscard]] constexpr auto +is_lattice_semantic(StencilSemantic semantic) noexcept -> bool { + return semantic == StencilSemantic::Lattice || semantic == StencilSemantic::LatticeDistributed; +} + [[nodiscard]] CARBON_API auto to_string(StencilSemantic semantic) noexcept -> std::string_view; diff --git a/src/io_vtk_distributed.cpp b/src/io_vtk_distributed.cpp index 2beb19a5..e1b2cf3b 100644 --- a/src/io_vtk_distributed.cpp +++ b/src/io_vtk_distributed.cpp @@ -1,10 +1,10 @@ -// VTK legacy backend for carbon::DenseDistributed (slab / pencil / brick). See +// VTK XML backend for carbon::DenseDistributed (slab / pencil / brick). See // include/carbon/detail/io_vtk_distributed.inl for the on-disk format and the public surface. // // The helpers below (byte order, dtype keywords, header parsing) intentionally mirror the Dense // backend in io_vtk.cpp instead of sharing it, so the Dense path stays byte-for-byte untouched. -// What differs is the geometry: a shard is the rank's owned *box* (DIMENSIONS = owned extent, -// ORIGIN = global index of its first cell) and rows are read/written with the real haloed row +// What differs is the geometry: a shard is the rank's owned *box* (WholeExtent = owned extent, +// Origin = global index of its first cell) and rows are read/written with the real haloed row // stride instead of assuming full-width XY planes. #include @@ -17,7 +17,9 @@ #endif #include +#include #include +#include #include #include #include @@ -29,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -118,6 +121,43 @@ element_size_of_keyword(const std::string& kw) noexcept -> size_t { return 0; } +/** Map a carbon native dtype tag to the VTK XML keyword; null if unknown. */ +[[nodiscard]] auto +vtk_xml_keyword_from_native_tag(const char* tag) noexcept -> const char* { + const std::string_view t(tag, 8); + if (t.starts_with("f32")) { + return "Float32"; + } + if (t.starts_with("f64")) { + return "Float64"; + } + if (t.starts_with("i8")) { + return "Int8"; + } + if (t.starts_with("u8")) { + return "UInt8"; + } + if (t.starts_with("i16")) { + return "Int16"; + } + if (t.starts_with("u16")) { + return "UInt16"; + } + if (t.starts_with("i32")) { + return "Int32"; + } + if (t.starts_with("u32")) { + return "UInt32"; + } + if (t.starts_with("i64")) { + return "Int64"; + } + if (t.starts_with("u64")) { + return "UInt64"; + } + return nullptr; +} + void rtrim_inplace(std::string& s) noexcept { while (!s.empty() && (s.back() == '\r' || s.back() == ' ' || s.back() == '\t')) { @@ -137,19 +177,64 @@ sanitize_name(std::string_view name) -> std::string { return out.empty() ? std::string("field") : out; } +[[nodiscard]] auto +xml_escape(std::string_view value) -> std::string { + std::string out; + out.reserve(value.size()); + for (const char c : value) { + switch (c) { + case '&': + out += "&"; + break; + case '<': + out += "<"; + break; + case '>': + out += ">"; + break; + case '"': + out += """; + break; + case '\'': + out += "'"; + break; + default: + out.push_back(c); + break; + } + } + return out; +} + +[[nodiscard]] auto +xml_attribute(std::string_view tag, + std::string_view key) -> std::string { + const std::string needle = std::string(key) + "=\""; + const size_t begin = tag.find(needle); + if (begin == std::string_view::npos) { + return {}; + } + const size_t value_begin = begin + needle.size(); + const size_t end = tag.find('"', value_begin); + if (end == std::string_view::npos) { + return {}; + } + return std::string(tag.substr(value_begin, end - value_begin)); +} + [[nodiscard]] auto shard_path_of(std::string_view base, const DenseDistributed& grid) -> std::string { #ifdef CARBON_HAVE_MPI_NCCL if (grid.system().distributed() != nullptr) { std::ostringstream oss; - oss << base << ".rank" << grid.system().distributed()->world_rank()<<".vtk"; + oss << base << ".rank" << grid.system().distributed()->world_rank() << ".vti"; return oss.str(); } #else (void)grid; #endif - return std::string(base); + return std::string(base) + ".vti"; } [[nodiscard]] auto @@ -308,6 +393,316 @@ read_payload(std::istream& in, } } +template +void +write_payload_le(std::ostream& out, + int comps, + const std::vector& pieces) { + size_t total_bytes = 0; + size_t max_row_bytes = 0; + for (const auto& p : pieces) { + const size_t row = static_cast(p.nx) * static_cast(comps) * ES; + total_bytes += row * static_cast(p.ny) * static_cast(p.nz); + max_row_bytes = std::max(max_row_bytes, row); + } + if (total_bytes == 0) { + return; + } + std::vector block(std::max(std::min(total_bytes, kBlockBytes), max_row_bytes)); + size_t used = 0; + const auto flush = [&] { + if (used == 0) { + return; + } + if (!host_is_little_endian()) { + swap_run(block.data(), used / ES); + } + out.write(reinterpret_cast(block.data()), static_cast(used)); + used = 0; + }; + for (const auto& p : pieces) { + const size_t row_bytes = static_cast(p.nx) * static_cast(comps) * ES; + for (int64_t z = 0; z < p.nz; ++z) { + for (int64_t y = 0; y < p.ny; ++y) { + if (used + row_bytes > block.size()) { + flush(); + } + gather_row(block.data() + used, row_ptr(p, ES, z, y), p.nx, comps, p.comp_stride); + used += row_bytes; + } + } + } + flush(); +} + +template +void +read_payload_le(std::istream& in, + int comps, + const std::vector& pieces) { + size_t max_row_bytes = 0; + size_t total_bytes = 0; + for (const auto& p : pieces) { + const size_t row = static_cast(p.nx) * static_cast(comps) * ES; + max_row_bytes = std::max(max_row_bytes, row); + total_bytes += row * static_cast(p.ny) * static_cast(p.nz); + } + if (total_bytes == 0) { + return; + } + std::vector block(std::max(std::min(total_bytes, kBlockBytes), max_row_bytes)); + for (const auto& p : pieces) { + const size_t row_bytes = static_cast(p.nx) * static_cast(comps) * ES; + const int64_t rows_total = p.ny * p.nz; + const int64_t rows_per_block = static_cast(block.size() / row_bytes); + for (int64_t r0 = 0; r0 < rows_total; r0 += rows_per_block) { + const int64_t rows = std::min(rows_per_block, rows_total - r0); + const size_t bytes = static_cast(rows) * row_bytes; + in.read(reinterpret_cast(block.data()), static_cast(bytes)); + if (!in.good()) { + log::throw_with_log( + "io::read_vtk: short read in inline binary payload (row {} of {})", r0, rows_total); + } + if (!host_is_little_endian()) { + swap_run(block.data(), bytes / ES); + } + for (int64_t i = 0; i < rows; ++i) { + const int64_t r = r0 + i; + scatter_row(row_ptr(p, ES, r / p.ny, r % p.ny), + block.data() + static_cast(i) * row_bytes, p.nx, comps, + p.comp_stride); + } + } + } +} + +void +write_u64_le(std::ostream& out, + std::uint64_t value) { + std::uint8_t bytes[8]; + if (host_is_little_endian()) { + std::memcpy(bytes, &value, sizeof(value)); + } else { + for (size_t i = 0; i < 8U; ++i) { + bytes[i] = static_cast(value >> (8U * i)); + } + } + out.write(reinterpret_cast(bytes), sizeof(bytes)); +} + +[[nodiscard]] auto +read_u64_le(std::istream& in, + std::string_view path) -> std::uint64_t { + std::uint8_t bytes[8]; + in.read(reinterpret_cast(bytes), sizeof(bytes)); + if (!in.good()) { + log::throw_with_log( + "io::read_vtk: short read while reading the inline binary block size in '{}'", path); + } + std::uint64_t value = 0; + if (host_is_little_endian()) { + std::memcpy(&value, bytes, sizeof(value)); + } else { + for (size_t i = 0; i < 8U; ++i) { + value |= static_cast(bytes[i]) << (8U * i); + } + } + return value; +} + +/** Stream buffer that base64-encodes bytes into @p out as one unwrapped line. */ +class Base64EncodeBuf final : public std::streambuf { +public: + explicit Base64EncodeBuf(std::ostream& out) noexcept + : out_(out) {} + +protected: + auto + xsputn(const char* s, + std::streamsize n) -> std::streamsize override { + for (std::streamsize i = 0; i < n; ++i) { + in_[in_len_++] = static_cast(s[i]); + if (in_len_ == in_.size()) { + emit(in_.size()); + in_len_ = 0; + } + } + return n; + } + + auto + overflow(int_type ch) -> int_type override { + if (!traits_type::eq_int_type(ch, traits_type::eof())) { + const char c = traits_type::to_char_type(ch); + (void)xsputn(&c, 1); + } + return traits_type::not_eof(ch); + } + + auto + sync() -> int override { + if (in_len_ != 0) { + emit(in_len_); + in_len_ = 0; + } + return out_.good() ? 0 : -1; + } + +private: + void + emit(size_t n) { + static constexpr char kTable[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + const std::uint8_t b0 = in_[0]; + const std::uint8_t b1 = n > 1 ? in_[1] : 0; + const std::uint8_t b2 = n > 2 ? in_[2] : 0; + char quad[4]; + quad[0] = kTable[b0 >> 2]; + quad[1] = kTable[((b0 & 0x03U) << 4U) | (b1 >> 4U)]; + quad[2] = n > 1 ? kTable[((b1 & 0x0fU) << 2U) | (b2 >> 6U)] : '='; + quad[3] = n > 2 ? kTable[b2 & 0x3fU] : '='; + out_.write(quad, 4); + } + + std::ostream& out_; + std::array in_{}; + size_t in_len_ = 0; +}; + +/** Stream buffer that base64-decodes the inline DataArray body from @p in. */ +class Base64DecodeBuf final : public std::streambuf { +public: + explicit Base64DecodeBuf(std::istream& in) + : in_(in) { + setg(nullptr, nullptr, nullptr); + } + +protected: + auto + underflow() -> int_type override { + if (gptr() < egptr()) { + return traits_type::to_int_type(*gptr()); + } + out_len_ = 0; + while (out_len_ == 0) { + const int v = next_value(); + if (v < 0) { + return traits_type::eof(); + } + quad_[quad_len_++] = v; + if (quad_len_ == quad_.size()) { + decode_quad(); + quad_len_ = 0; + } + } + setg(reinterpret_cast(out_.data()), reinterpret_cast(out_.data()), + reinterpret_cast(out_.data() + out_len_)); + return traits_type::to_int_type(out_[0]); + } + +private: + static constexpr int kPad = 64; + static constexpr int kEnd = -1; + + auto + next_value() -> int { + if (!error_.empty()) { + return kEnd; + } + for (;;) { + char c = 0; + if (!in_.get(c)) { + if (quad_len_ != 0) { + fail("truncated base64 quartet"); + } + return kEnd; + } + const auto u = static_cast(c); + if (std::isspace(u) != 0) { + continue; + } + if (c == '<') { + if (quad_len_ != 0) { + fail("truncated base64 quartet"); + } + return kEnd; + } + if (c == '=') { + if (quad_len_ < 2) { + fail("misplaced base64 padding"); + } + return kPad; + } + const int v = decode_char(u); + if (v < 0) { + fail("invalid base64 character"); + return kEnd; + } + return v; + } + } + + static auto + decode_char(unsigned char c) noexcept -> int { + if (c >= 'A' && c <= 'Z') { + return static_cast(c - 'A'); + } + if (c >= 'a' && c <= 'z') { + return static_cast(c - 'a') + 26; + } + if (c >= '0' && c <= '9') { + return static_cast(c - '0') + 52; + } + if (c == '+') { + return 62; + } + if (c == '/') { + return 63; + } + return -1; + } + + void + decode_quad() { + const bool pad2 = quad_[2] == kPad; + const bool pad3 = quad_[3] == kPad; + if (quad_[0] == kPad || quad_[1] == kPad || (pad2 && !pad3)) { + fail("misplaced base64 padding"); + return; + } + out_[0] = static_cast((quad_[0] << 2) | (quad_[1] >> 4)); + out_len_ = 1; + if (!pad2) { + out_[1] = static_cast(((quad_[1] & 0x0f) << 4) | (quad_[2] >> 2)); + out_len_ = 2; + if (!pad3) { + out_[2] = static_cast(((quad_[2] & 0x03) << 6) | quad_[3]); + out_len_ = 3; + } + } + if (pad2 || pad3) { + padded_ = true; + } else if (padded_) { + fail("base64 data after padding"); + } + } + + void + fail(const char* what) { + if (error_.empty()) { + error_ = std::string(what); + } + } + + std::istream& in_; + std::array quad_{}; + size_t quad_len_ = 0; + std::array out_{}; + size_t out_len_ = 0; + bool padded_ = false; + std::string error_; +}; + } // namespace // ================================================================================================ @@ -646,6 +1041,280 @@ read_vtk_box_field_payload(std::istream& in, } } +// ---- XML ImageData + inline-binary building blocks ----------------------------------------- + +void +validate_pieces_for_box(std::string_view name, + int64_t cells, + int components, + const VtkBox& box, + const std::vector& pieces) { + if (components < 1 || components > 4) { + log::throw_with_log( + "io::write_vtk: field '{}' has {} components (VTK XML supports 1..4 here)", name, + components); + } + if (!box.empty()) { + if (cells != box.points()) { + log::throw_with_log( + "io::write_vtk: field '{}' pieces hold {} cells but the shard box has {}", name, cells, + box.points()); + } + for (const auto& p : pieces) { + if (p.nx != box.dims[0] || p.ny != box.dims[1]) { + log::throw_with_log( + "io::write_vtk: field '{}' piece ({}x{}) does not match the shard box ({}x{})", name, + p.nx, p.ny, box.dims[0], box.dims[1]); + } + } + } +} + +void +write_vti_box_header(std::ostream& out, + const VtkBox& box) { + const bool empty = box.empty(); + const int64_t nx = empty ? 0 : box.dims[0]; + const int64_t ny = empty ? 0 : box.dims[1]; + const int64_t nz = empty ? 0 : box.dims[2]; + out << "\n"; + out << "\n"; + out << " \n"; + out << " \n"; + out << " \n"; + if (!out.good()) { + log::throw_with_log("io::write_vtk: failed to write the shard header"); + } +} + +void +write_vti_box_field_begin(std::ostream& out, + std::string_view name, + const char* dtype_tag, + int components) { + const char* kw = vtk_xml_keyword_from_native_tag(dtype_tag); + if (kw == nullptr) { + log::throw_with_log( + "io::write_vtk: field '{}' has a dtype VTK XML cannot express", name); + } + out << " \n"; + if (!out.good()) { + log::throw_with_log("io::write_vtk: failed to write field metadata"); + } +} + +void +write_vti_box_footer(std::ostream& out) { + out << " \n"; + out << " \n"; + out << " \n"; + out << "\n"; + if (!out.good()) { + log::throw_with_log("io::write_vtk: failed to write the shard footer"); + } +} + +[[nodiscard]] auto +parse_u64_attribute(std::string_view tag, + std::string_view key, + std::string_view path) -> std::uint64_t { + const std::string text = xml_attribute(tag, key); + if (text.empty()) { + log::throw_with_log("io::read_vtk: '{}' is missing attribute '{}'", + path, key); + } + try { + size_t used = 0; + const auto value = std::stoull(text, &used); + if (used != text.size()) { + throw std::invalid_argument("trailing characters"); + } + return value; + } catch (const std::exception&) { + log::throw_with_log( + "io::read_vtk: '{}' has a non-numeric '{}' attribute ('{}')", path, key, text); + } +} + +void +parse_vti_box_header(std::istream& in, + std::string_view path, + const VtkBox& expected, + std::vector& out_fields) { + int64_t whole[6] = {0, -1, 0, -1, 0, -1}; + int64_t origin[3] = {0, 0, 0}; + double spacing[3] = {1.0, 1.0, 1.0}; + bool saw_vtk_file = false; + bool saw_image_data = false; + bool saw_point_data = false; + bool in_point_data = false; + + std::string line; + while (std::getline(in, line)) { + rtrim_inplace(line); + if (line.find("( + "io::read_vtk: '{}' is not a VTK XML ImageData file", path); + } + if (xml_attribute(line, "byte_order") != "LittleEndian") { + log::throw_with_log( + "io::read_vtk: '{}' must use little-endian byte order", path); + } + if (xml_attribute(line, "header_type") != "UInt64") { + log::throw_with_log( + "io::read_vtk: '{}' must use UInt64 inline-binary headers", path); + } + } else if (line.find("> whole[0] >> whole[1] >> whole[2] >> whole[3] >> whole[4] >> whole[5])) { + log::throw_with_log( + "io::read_vtk: '{}' has a bad WholeExtent attribute ('{}')", path, extent); + } + const std::string org = xml_attribute(line, "Origin"); + std::istringstream os(org); + if (!(os >> origin[0] >> origin[1] >> origin[2])) { + log::throw_with_log( + "io::read_vtk: '{}' has a bad Origin attribute ('{}')", path, org); + } + const std::string sp = xml_attribute(line, "Spacing"); + std::istringstream ss(sp); + if (!(ss >> spacing[0] >> spacing[1] >> spacing[2])) { + log::throw_with_log( + "io::read_vtk: '{}' has a bad Spacing attribute ('{}')", path, sp); + } + } else if (line.find("") != std::string::npos) { + in_point_data = false; + break; + } else if (in_point_data && line.find("( + "io::read_vtk: '{}' contains a DataArray that is not inline binary", path); + } + VtkBoxFieldRecord rec; + rec.name = xml_attribute(line, "Name"); + rec.vtk_dtype = xml_attribute(line, "type"); + rec.components = static_cast(parse_u64_attribute(line, "NumberOfComponents", path)); + rec.payload_offset = in.tellg(); + if (rec.payload_offset == std::streampos(-1)) { + log::throw_with_log( + "io::read_vtk: failed to locate the inline payload of '{}' in '{}'", rec.name, path); + } + if (rec.components < 1 || rec.components > 4) { + log::throw_with_log( + "io::read_vtk: DataArray '{}' has components={} (supported: 1..4)", rec.name, + rec.components); + } + out_fields.push_back(std::move(rec)); + } else if (line.find("( + "io::read_vtk: '{}' uses appended data; carbon reads inline binary only", path); + } + } + if (!saw_vtk_file || !saw_image_data || !saw_point_data) { + log::throw_with_log( + "io::read_vtk: '{}' is missing VTKFile/ImageData/PointData", path); + } + + const bool want_empty = expected.empty(); + if (!want_empty) { + if (whole[0] != 0 || whole[1] != expected.dims[0] - 1 || whole[2] != 0 || + whole[3] != expected.dims[1] - 1 || whole[4] != 0 || + whole[5] != expected.dims[2] - 1) { + log::throw_with_log( + "io::read_vtk: '{}' WholeExtent ({}, {}, {}, {}, {}, {}) does not match this rank's " + "owned box ({}, {}, {})", + path, whole[0], whole[1], whole[2], whole[3], whole[4], whole[5], expected.dims[0], + expected.dims[1], expected.dims[2]); + } + } + if (origin[0] != expected.origin[0] || origin[1] != expected.origin[1] || + origin[2] != expected.origin[2]) { + log::throw_with_log( + "io::read_vtk: '{}' Origin ({}, {}, {}) does not match this rank's box origin ({}, {}, {})", + path, origin[0], origin[1], origin[2], expected.origin[0], expected.origin[1], + expected.origin[2]); + } + if (spacing[0] != 1.0 || spacing[1] != 1.0 || spacing[2] != 1.0) { + log::throw_with_log( + "io::read_vtk: '{}' Spacing ({}, {}, {}) is non-unit; carbon uses integer voxel " + "coordinates", + path, spacing[0], spacing[1], spacing[2]); + } +} + +void +read_vti_box_field_payload(std::istream& in, + std::string_view path, + const VtkBoxFieldRecord& record, + size_t element_size, + int components, + const VtkBox& box, + const std::vector& pieces) { + if (box.empty()) { + return; + } + int64_t cells = 0; + for (const auto& p : pieces) { + cells += p.nx * p.ny * p.nz; + if (p.nx != box.dims[0] || p.ny != box.dims[1]) { + log::throw_with_log( + "io::read_vtk: piece ({}x{}) does not match the shard box ({}x{})", p.nx, p.ny, + box.dims[0], box.dims[1]); + } + } + if (cells != box.points()) { + log::throw_with_log( + "io::read_vtk: pieces hold {} cells but the shard box has {}", cells, box.points()); + } + in.clear(); + in.seekg(record.payload_offset); + if (!in.good()) { + log::throw_with_log( + "io::read_vtk: seek to the inline payload of '{}' failed in '{}'", record.name, path); + } + Base64DecodeBuf decoded(in); + std::istream encoded(&decoded); + const auto expected_bytes = static_cast(cells) * + static_cast(components) * + static_cast(element_size); + const auto got_bytes = read_u64_le(encoded, path); + if (got_bytes != expected_bytes) { + log::throw_with_log( + "io::read_vtk: inline block for '{}' is {} bytes, expected {} in '{}'", record.name, + got_bytes, expected_bytes, path); + } + switch (element_size) { + case 1: + read_payload_le<1>(encoded, components, pieces); + break; + case 2: + read_payload_le<2>(encoded, components, pieces); + break; + case 4: + read_payload_le<4>(encoded, components, pieces); + break; + case 8: + read_payload_le<8>(encoded, components, pieces); + break; + default: + log::throw_with_log("io::read_vtk: unsupported element size {}", + element_size); + } +} + // ================================================================================================ // Session // ================================================================================================ @@ -657,12 +1326,19 @@ struct VtkBoxSession::Impl { VtkBox box; std::ofstream writer; std::ifstream reader; + bool finalized = false; std::vector read_fields; size_t read_fields_cursor = 0; }; VtkBoxSession::VtkBoxSession() noexcept = default; -VtkBoxSession::~VtkBoxSession() = default; +VtkBoxSession::~VtkBoxSession() { + try { + finalize(); + } catch (...) { + // Destructors must not throw; write_vtk calls finalize() explicitly to surface I/O failures. + } +} VtkBoxSession::VtkBoxSession(VtkBoxSession&&) noexcept = default; auto VtkBoxSession::operator=(VtkBoxSession&&) noexcept -> VtkBoxSession& = default; @@ -686,7 +1362,7 @@ VtkBoxSession::open_for_write(std::string_view path, log::throw_with_log("io::write_vtk: failed to open '{}' for writing", impl_->path); } - write_vtk_box_header(impl_->writer, impl_->box); + write_vti_box_header(impl_->writer, impl_->box); } void @@ -698,10 +1374,52 @@ VtkBoxSession::write_field(std::string_view name, if (impl_ == nullptr || !impl_->for_write) { log::throw_with_log("io::write_vtk: session is not in a writable state"); } - write_vtk_box_field(impl_->writer, name, dtype_tag, element_size, components, impl_->box, pieces); + int64_t cells = 0; + for (const auto& p : pieces) { + cells += p.nx * p.ny * p.nz; + } + validate_pieces_for_box(name, cells, components, impl_->box, pieces); + write_vti_box_field_begin(impl_->writer, name, dtype_tag, components); + const auto bytes = static_cast(cells) * + static_cast(components) * + static_cast(element_size); + Base64EncodeBuf encoded_buf(impl_->writer); + std::ostream encoded(&encoded_buf); + write_u64_le(encoded, bytes); + switch (element_size) { + case 1: + write_payload_le<1>(encoded, components, pieces); + break; + case 2: + write_payload_le<2>(encoded, components, pieces); + break; + case 4: + write_payload_le<4>(encoded, components, pieces); + break; + case 8: + write_payload_le<8>(encoded, components, pieces); + break; + default: + log::throw_with_log("io::write_vtk: unsupported element size {}", + element_size); + } + encoded.flush(); + impl_->writer << "\n \n"; + if (!impl_->writer.good()) { + log::throw_with_log("io::write_vtk: failed to write field payload"); + } ++impl_->num_fields_recorded; } +void +VtkBoxSession::finalize() { + if (impl_ == nullptr || !impl_->for_write || impl_->finalized) { + return; + } + write_vti_box_footer(impl_->writer); + impl_->finalized = true; +} + void VtkBoxSession::open_for_read(std::string_view path, const DenseDistributed& grid) { @@ -714,7 +1432,7 @@ VtkBoxSession::open_for_read(std::string_view path, log::throw_with_log("io::read_vtk: failed to open '{}' for reading", impl_->path); } - parse_vtk_box_header(impl_->reader, impl_->path, impl_->box, impl_->read_fields); + parse_vti_box_header(impl_->reader, impl_->path, impl_->box, impl_->read_fields); } void @@ -732,7 +1450,7 @@ VtkBoxSession::read_field(std::string_view /*name*/, } // Fields bind by ordinal (names differ between writers). const auto& rec = impl_->read_fields[impl_->read_fields_cursor++]; - const char* expected_kw = vtk_keyword_from_native_tag(dtype_tag); + const char* expected_kw = vtk_xml_keyword_from_native_tag(dtype_tag); if (expected_kw == nullptr || rec.vtk_dtype != expected_kw) { log::throw_with_log( "io::read_vtk: field {} dtype '{}' does not match bound carbon dtype '{}' in '{}'", @@ -743,13 +1461,8 @@ VtkBoxSession::read_field(std::string_view /*name*/, "io::read_vtk: field {} has {} components but the bound Field has {}", rec.name, rec.components, components); } - impl_->reader.clear(); - impl_->reader.seekg(rec.payload_offset); - if (!impl_->reader.good()) { - log::throw_with_log( - "io::read_vtk: seek to the payload of '{}' failed in '{}'", rec.name, impl_->path); - } - read_vtk_box_field_payload(impl_->reader, element_size, components, impl_->box, pieces); + read_vti_box_field_payload(impl_->reader, impl_->path, rec, element_size, components, + impl_->box, pieces); } auto @@ -813,8 +1526,8 @@ write_vtk_multiblock_index(std::string_view base, int block = 0; for (const int r : listed) { out << " \n"; - out << " \n"; + out << " \n"; out << " \n"; } out << " \n"; diff --git a/src/io_vtk_distributed_wrong.cpp b/src/io_vtk_distributed_wrong.cpp deleted file mode 100644 index c9abce68..00000000 --- a/src/io_vtk_distributed_wrong.cpp +++ /dev/null @@ -1,881 +0,0 @@ -// VTK XML (vti) backend for carbon::DenseDistributed (slab / pencil / brick). -// See include/carbon/detail/io_vtk_distributed.inl for the public surface. - -#include -#include -#include -#include - -#ifdef CARBON_HAVE_MPI_NCCL -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace carbon::io::detail { - -namespace { - -namespace dd = ::carbon::detail::dense_distributed; - -/** Staging block for payload I/O: rows are batched so the stream sees few, large transfers. */ -constexpr size_t kBlockBytes = size_t{4} << 20; - -[[nodiscard]] constexpr auto -host_is_little_endian() noexcept -> bool { - return std::endian::native == std::endian::little; -} - -/** Reverse the bytes of @p n consecutive @c ES -byte elements (legacy VTK payloads are BE). */ -template -void -swap_run(std::uint8_t* p, - size_t n) noexcept { - if constexpr (ES > 1) { - for (size_t i = 0; i < n; ++i) { - std::uint8_t* e = p + i * ES; - for (size_t k = 0; k < ES / 2; ++k) { - std::swap(e[k], e[ES - 1 - k]); - } - } - } -} - -/** Map a carbon native dtype tag (8-char, NUL padded) to the VTK legacy keyword; null if unknown. */ -[[nodiscard]] auto -vtk_keyword_from_native_tag(const char* tag) noexcept -> const char* { - const std::string_view t(tag, 8); - if (t.starts_with("f32")) { - return "float"; - } - if (t.starts_with("f64")) { - return "double"; - } - if (t.starts_with("i8")) { - return "char"; - } - if (t.starts_with("u8")) { - return "unsigned_char"; - } - if (t.starts_with("i16")) { - return "short"; - } - if (t.starts_with("u16")) { - return "unsigned_short"; - } - if (t.starts_with("i32")) { - return "int"; - } - if (t.starts_with("u32")) { - return "unsigned_int"; - } - if (t.starts_with("i64")) { - return "vtktypeint64"; - } - if (t.starts_with("u64")) { - return "vtktypeuint64"; - } - return nullptr; -} - -/** Map a carbon native dtype tag to the VTK XML keyword; null if unknown. */ -[[nodiscard]] auto -vtk_xml_keyword_from_native_tag(const char* tag) noexcept -> const char* { - const std::string_view t(tag, 8); - if (t.starts_with("f32")) return "Float32"; - if (t.starts_with("f64")) return "Float64"; - if (t.starts_with("i8")) return "Int8"; - if (t.starts_with("u8")) return "UInt8"; - if (t.starts_with("i16")) return "Int16"; - if (t.starts_with("u16")) return "UInt16"; - if (t.starts_with("i32")) return "Int32"; - if (t.starts_with("u32")) return "UInt32"; - if (t.starts_with("i64")) return "Int64"; - if (t.starts_with("u64")) return "UInt64"; - return nullptr; -} - -[[nodiscard]] auto -element_size_of_keyword(const std::string& kw) noexcept -> size_t { - if (kw == "char" || kw == "unsigned_char" || kw == "Int8" || kw == "UInt8") return 1; - if (kw == "short" || kw == "unsigned_short" || kw == "Int16" || kw == "UInt16") return 2; - if (kw == "int" || kw == "unsigned_int" || kw == "float" || kw == "Int32" || kw == "UInt32" || kw == "Float32") return 4; - if (kw == "double" || kw == "vtktypeint64" || kw == "vtktypeuint64" || kw == "long" || - kw == "unsigned_long" || kw == "Int64" || kw == "UInt64" || kw == "Float64") return 8; - return 0; -} - -void -rtrim_inplace(std::string& s) noexcept { - while (!s.empty() && (s.back() == '\r' || s.back() == ' ' || s.back() == '\t')) { - s.pop_back(); - } -} - -/** Legacy SCALARS names are whitespace-delimited tokens: make the label a single token. */ -[[nodiscard]] auto -sanitize_name(std::string_view name) -> std::string { - std::string out(name); - for (char& c : out) { - if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\"' || c == '<' || c == '>') { - c = '_'; - } - } - return out.empty() ? std::string("field") : out; -} - -[[nodiscard]] auto -shard_path_of(std::string_view base, - const DenseDistributed& grid) -> std::string { -#ifdef CARBON_HAVE_MPI_NCCL - if (grid.system().distributed() != nullptr) { - std::ostringstream oss; - oss << base << ".rank" << grid.system().distributed()->world_rank() << ".vti"; - return oss.str(); - } -#else - (void)grid; -#endif - return std::string(base) + ".vti"; -} - -[[nodiscard]] auto -pieces_cells(const std::vector& pieces) -> int64_t { - int64_t n = 0; - for (const auto& p : pieces) { - n += p.nx * p.ny * p.nz; - } - return n; -} - -// ---- payload gather / scatter (compile-time element size) ---------------------------------- - -/** One owned row of @p nx cells -> interleaved (component-fastest) record bytes. */ -template -void -gather_row(std::uint8_t* dst, - const std::uint8_t* src, - int64_t nx, - int comps, - int64_t comp_stride_elems) noexcept { - if (comps == 1) { - std::memcpy(dst, src, static_cast(nx) * ES); - return; - } - const size_t stride = static_cast(comps) * ES; - for (int c = 0; c < comps; ++c) { - const std::uint8_t* s = src + static_cast(c * comp_stride_elems) * ES; - std::uint8_t* d = dst + static_cast(c) * ES; - for (int64_t x = 0; x < nx; ++x) { - std::memcpy(d + static_cast(x) * stride, s + static_cast(x) * ES, ES); - } - } -} - -/** Interleaved record bytes -> one owned row (inverse of @ref gather_row). */ -template -void -scatter_row(std::uint8_t* dst, - const std::uint8_t* src, - int64_t nx, - int comps, - int64_t comp_stride_elems) noexcept { - if (comps == 1) { - std::memcpy(dst, src, static_cast(nx) * ES); - return; - } - const size_t stride = static_cast(comps) * ES; - for (int c = 0; c < comps; ++c) { - std::uint8_t* d = dst + static_cast(c * comp_stride_elems) * ES; - const std::uint8_t* s = src + static_cast(c) * ES; - for (int64_t x = 0; x < nx; ++x) { - std::memcpy(d + static_cast(x) * ES, s + static_cast(x) * stride, ES); - } - } -} - -[[nodiscard]] inline auto -row_ptr(const VtkBoxPiece& p, - size_t es, - int64_t z, - int64_t y) noexcept -> const std::uint8_t* { - return static_cast(p.start) + - static_cast(z * p.plane_pitch + y * p.row_stride) * es; -} - -[[nodiscard]] inline auto -row_ptr(const VtkBoxPieceMut& p, - size_t es, - int64_t z, - int64_t y) noexcept -> std::uint8_t* { - return static_cast(p.start) + - static_cast(z * p.plane_pitch + y * p.row_stride) * es; -} - -// --- LEGACY PAYLOAD HELPERS (Required for tests) --- - -template -void -write_payload(std::ostream& out, - int comps, - const std::vector& pieces) { - size_t total_bytes = 0; - size_t max_row_bytes = 0; - for (const auto& p : pieces) { - const size_t row = static_cast(p.nx) * static_cast(comps) * ES; - total_bytes += row * static_cast(p.ny) * static_cast(p.nz); - max_row_bytes = std::max(max_row_bytes, row); - } - if (total_bytes == 0) { - return; - } - std::vector block(std::max(std::min(total_bytes, kBlockBytes), max_row_bytes)); - size_t used = 0; - const auto flush = [&] { - if (used == 0) { - return; - } - if (host_is_little_endian()) { - swap_run(block.data(), used / ES); - } - out.write(reinterpret_cast(block.data()), static_cast(used)); - used = 0; - }; - for (const auto& p : pieces) { - const size_t row_bytes = static_cast(p.nx) * static_cast(comps) * ES; - for (int64_t z = 0; z < p.nz; ++z) { - for (int64_t y = 0; y < p.ny; ++y) { - if (used + row_bytes > block.size()) { - flush(); - } - gather_row(block.data() + used, row_ptr(p, ES, z, y), p.nx, comps, p.comp_stride); - used += row_bytes; - } - } - } - flush(); -} - -template -void -read_payload(std::istream& in, - int comps, - const std::vector& pieces) { - size_t max_row_bytes = 0; - size_t total_bytes = 0; - for (const auto& p : pieces) { - const size_t row = static_cast(p.nx) * static_cast(comps) * ES; - max_row_bytes = std::max(max_row_bytes, row); - total_bytes += row * static_cast(p.ny) * static_cast(p.nz); - } - if (total_bytes == 0) { - return; - } - std::vector block(std::max(std::min(total_bytes, kBlockBytes), max_row_bytes)); - for (const auto& p : pieces) { - const size_t row_bytes = static_cast(p.nx) * static_cast(comps) * ES; - const int64_t rows_total = p.ny * p.nz; - const int64_t rows_per_block = static_cast(block.size() / row_bytes); - for (int64_t r0 = 0; r0 < rows_total; r0 += rows_per_block) { - const int64_t rows = std::min(rows_per_block, rows_total - r0); - const size_t bytes = static_cast(rows) * row_bytes; - in.read(reinterpret_cast(block.data()), static_cast(bytes)); - if (!in.good()) { - log::throw_with_log( - "io::read_vtk: short read in payload (row {} of {})", r0, rows_total); - } - if (host_is_little_endian()) { - swap_run(block.data(), bytes / ES); - } - for (int64_t i = 0; i < rows; ++i) { - const int64_t r = r0 + i; - scatter_row(row_ptr(p, ES, r / p.ny, r % p.ny), - block.data() + static_cast(i) * row_bytes, p.nx, comps, - p.comp_stride); - } - } - } -} - -// --- XML PAYLOAD HELPERS --- - -template -void -write_xml_payload_to_buffer(std::uint8_t* dst, - int comps, - const std::vector& pieces) { - size_t used = 0; - for (const auto& p : pieces) { - const size_t row_bytes = static_cast(p.nx) * static_cast(comps) * ES; - for (int64_t z = 0; z < p.nz; ++z) { - for (int64_t y = 0; y < p.ny; ++y) { - gather_row(dst + used, row_ptr(p, ES, z, y), p.nx, comps, p.comp_stride); - used += row_bytes; - } - } - } -} - -} // namespace - -// ================================================================================================ -// Box geometry -// ================================================================================================ - -auto -vtk_box_of(const DenseDistributed& grid) -> VtkBox { - VtkBox box; - const auto& spans = grid.spans(); - if (spans.empty()) { - return box; - } - const auto owned_origin = [](const auto& span) -> int64_3d { - const int64_3d o = span.offset(); - const int64_3d h = span.halo(); - return int64_3d{o.x + h.x, o.y + h.y, o.z + h.z}; - }; - const int64_3d first = owned_origin(spans.front()); - box.origin[0] = first.x; - box.origin[1] = first.y; - box.origin[2] = first.z; - - int64_t z_total = 0; - int64_3d prev_origin{}; - int64_t prev_nz = 0; - bool have_prev = false; - int64_t nx = 0; - int64_t ny = 0; - for (const auto& span : spans) { - const int64_3d owned = span.logic_extent(); - if (owned.x <= 0 || owned.y <= 0 || owned.z <= 0) { - continue; - } - const int64_3d o = owned_origin(span); - if (!have_prev) { - nx = owned.x; - ny = owned.y; - box.origin[0] = o.x; - box.origin[1] = o.y; - box.origin[2] = o.z; - } else if (owned.x != nx || owned.y != ny || o.x != prev_origin.x || o.y != prev_origin.y || - o.z != prev_origin.z + prev_nz) { - log::throw_with_log( - "io::vtk: the local spans of this DenseDistributed do not form a single box (only a " - "z-stacked slab can span several local GPUs)"); - } - z_total += owned.z; - prev_origin = o; - prev_nz = owned.z; - have_prev = true; - } - if (have_prev) { - box.dims[0] = nx; - box.dims[1] = ny; - box.dims[2] = z_total; - } - return box; -} - -// ================================================================================================ -// Stream-level building blocks (Legacy - required for tests) -// ================================================================================================ - -void -write_vtk_box_header(std::ostream& out, - const VtkBox& box) { - const bool empty = box.empty(); - out << "# vtk DataFile Version 3.0\n"; - out << (empty ? "carbon dense field shard (empty: this rank owns no cells)\n" : "carbon dense field shard\n"); - out << "BINARY\n"; - out << "DATASET STRUCTURED_POINTS\n"; - out << "DIMENSIONS " << (empty ? 0 : box.dims[0]) << ' ' << (empty ? 0 : box.dims[1]) << ' ' << (empty ? 0 : box.dims[2]) << '\n'; - out << "ORIGIN " << box.origin[0] << ' ' << box.origin[1] << ' ' << box.origin[2] << '\n'; - out << "SPACING 1 1 1\n"; - out << "POINT_DATA " << box.points() << '\n'; - if (!out.good()) log::throw_with_log("io::write_vtk: failed to write the shard header"); -} - -void -write_vtk_box_field(std::ostream& out, - std::string_view name, - const char* dtype_tag, - size_t element_size, - int components, - const VtkBox& box, - const std::vector& pieces) { - const char* kw = vtk_keyword_from_native_tag(dtype_tag); - if (kw == nullptr) log::throw_with_log("io::write_vtk: dtype error"); - if (components < 1 || components > 4) log::throw_with_log("io::write_vtk: components error"); - - out << "SCALARS " << sanitize_name(name) << ' ' << kw << ' ' << components << '\n'; - out << "LOOKUP_TABLE default\n"; - if (!box.empty()) { - switch (element_size) { - case 1: write_payload<1>(out, components, pieces); break; - case 2: write_payload<2>(out, components, pieces); break; - case 4: write_payload<4>(out, components, pieces); break; - case 8: write_payload<8>(out, components, pieces); break; - default: log::throw_with_log("io::write_vtk: unsupported size"); - } - } - out << '\n'; -} - -void -parse_vtk_box_header(std::istream& in, - std::string_view path, - const VtkBox& expected, - std::vector& out_fields) { - const auto next_line = [&](bool strict) -> std::string { - std::string line; - if (!std::getline(in, line)) { - if (strict) log::throw_with_log("io::read_vtk: header ended"); - return {}; - } - rtrim_inplace(line); - return line; - }; - - const auto magic = next_line(true); - if (magic.rfind("# vtk DataFile Version", 0) != 0) log::throw_with_log("io::read_vtk: bad magic"); - next_line(true); // title - if (next_line(true) != "BINARY") log::throw_with_log("io::read_vtk: not BINARY"); - if (next_line(true) != "DATASET STRUCTURED_POINTS") log::throw_with_log("io::read_vtk: not STRUCTURED_POINTS"); - - int64_t dims[3] = {0, 0, 0}; - int64_t origin[3] = {0, 0, 0}; - double spacing[3] = {1.0, 1.0, 1.0}; - int64_t point_count = -1; - while (point_count < 0) { - const auto cur = next_line(true); - if (cur.empty()) continue; - std::istringstream iss(cur); - std::string head; - iss >> head; - if (head == "DIMENSIONS") iss >> dims[0] >> dims[1] >> dims[2]; - else if (head == "ORIGIN") iss >> origin[0] >> origin[1] >> origin[2]; - else if (head == "SPACING" || head == "ASPECT_RATIO") iss >> spacing[0] >> spacing[1] >> spacing[2]; - else if (head == "POINT_DATA") iss >> point_count; - else log::throw_with_log("io::read_vtk: unexpected header"); - } - - while (in) { - const auto cur = next_line(false); - if (cur.empty()) { - if (in.eof()) break; - continue; - } - std::istringstream iss(cur); - std::string head; - iss >> head; - if (head != "SCALARS") log::throw_with_log("io::read_vtk: expected SCALARS"); - VtkBoxFieldRecord rec; - iss >> rec.name >> rec.vtk_dtype; - rec.components = 1; - iss >> rec.components; - next_line(true); // LOOKUP_TABLE - rec.payload_offset = in.tellg(); - const size_t es = element_size_of_keyword(rec.vtk_dtype); - in.seekg(rec.payload_offset + static_cast(point_count * rec.components * es)); - out_fields.push_back(std::move(rec)); - const int next_c = in.peek(); - if (next_c == '\n' || next_c == '\r') { - in.get(); - if (next_c == '\r' && in.peek() == '\n') in.get(); - } - } -} - -void -read_vtk_box_field_payload(std::istream& in, - size_t element_size, - int components, - const VtkBox& box, - const std::vector& pieces) { - if (box.empty()) return; - switch (element_size) { - case 1: read_payload<1>(in, components, pieces); break; - case 2: read_payload<2>(in, components, pieces); break; - case 4: read_payload<4>(in, components, pieces); break; - case 8: read_payload<8>(in, components, pieces); break; - default: log::throw_with_log("io::read_vtk: bad size"); - } -} - -// ================================================================================================ -// Stream-level building blocks (XML - used by VtkBoxSession) -// ================================================================================================ - -void -write_vtk_xml_box_header(std::ostream& out, - const VtkBox& box) { - out << "\n"; - out << "\n"; - const bool empty = box.empty(); - if (empty) { - out << " \n"; - out << " \n"; - } else { - out << " \n"; - out << " \n"; - } - out << " \n"; -} - -void -write_vtk_xml_box_field(std::ostream& out, - std::string_view name, - const char* dtype_tag, - size_t element_size, - int components, - const VtkBox& box, - const std::vector& pieces) { - const char* kw = vtk_xml_keyword_from_native_tag(dtype_tag); - if (kw == nullptr) log::throw_with_log("io::write_vtk: bad xml dtype"); - - out << " \n"; - - if (!box.empty()) { - size_t payload_bytes = static_cast(box.points()) * components * element_size; - std::vector raw_data(payload_bytes); - - switch (element_size) { - case 1: write_xml_payload_to_buffer<1>(raw_data.data(), components, pieces); break; - case 2: write_xml_payload_to_buffer<2>(raw_data.data(), components, pieces); break; - case 4: write_xml_payload_to_buffer<4>(raw_data.data(), components, pieces); break; - case 8: write_xml_payload_to_buffer<8>(raw_data.data(), components, pieces); break; - default: log::throw_with_log("io::write_vtk: bad size"); - } - - if (element_size == 4) { - const float* fdata = reinterpret_cast(raw_data.data()); - size_t n = payload_bytes / 4; - for (size_t i = 0; i < n; ++i) { - out << fdata[i] << " "; - if (i % 10 == 9) out << "\n"; - } - } else if (element_size == 8) { - const double* ddata = reinterpret_cast(raw_data.data()); - size_t n = payload_bytes / 8; - for (size_t i = 0; i < n; ++i) { - out << ddata[i] << " "; - if (i % 10 == 9) out << "\n"; - } - } else { - for (size_t i = 0; i < payload_bytes; ++i) { - out << static_cast(raw_data[i]) << " "; - if (i % 10 == 9) out << "\n"; - } - } - } - out << "\n \n"; -} - -void -parse_vtk_xml_box_header(std::istream& in, - std::string_view path, - const VtkBox& expected, - std::vector& out_fields) { - std::string line; - auto get_attr = [](const std::string& s, const std::string& key) -> std::string { - std::string k = key + "=\""; - auto pos = s.find(k); - if (pos == std::string::npos) return ""; - pos += k.size(); - auto end = s.find("\"", pos); - return s.substr(pos, end - pos); - }; - - while (std::getline(in, line)) { - if (line.find("> e0 >> e1 >> e2 >> e3 >> e4 >> e5) { - dims[0] = e1 - e0 + 1; - dims[1] = e3 - e2 + 1; - dims[2] = e5 - e4 + 1; - } - - std::stringstream ss_org(origin_str); - ss_org >> origin[0] >> origin[1] >> origin[2]; - - const bool want_empty = expected.empty(); - const int64_t want_dims[3] = {want_empty ? 0 : expected.dims[0], - want_empty ? 0 : expected.dims[1], - want_empty ? 0 : expected.dims[2]}; - if (dims[0] != want_dims[0] || dims[1] != want_dims[1] || dims[2] != want_dims[2]) { - log::throw_with_log( - "io::read_vtk: '{}' DIMENSIONS ({}, {}, {}) do not match this rank's owned box ({}, {}, {})", - path, dims[0], dims[1], dims[2], want_dims[0], want_dims[1], want_dims[2]); - } - if (origin[0] != expected.origin[0] || origin[1] != expected.origin[1] || origin[2] != expected.origin[2]) { - log::throw_with_log( - "io::read_vtk: '{}' ORIGIN ({}, {}, {}) does not match this rank's box origin ({}, {}, {})", - path, origin[0], origin[1], origin[2], expected.origin[0], expected.origin[1], expected.origin[2]); - } - } else if (line.find("") != std::string::npos) break; - } - } - } -} - -void -read_vtk_xml_box_field_payload(std::istream& in, - size_t element_size, - int components, - const VtkBox& box, - const std::vector& pieces) { - if (box.empty()) return; - size_t total_elements = static_cast(box.points()) * components; - std::vector fdata(total_elements); - for (size_t i = 0; i < total_elements; ++i) { - in >> fdata[i]; - } - - size_t offset = 0; - for (const auto& p : pieces) { - const size_t row_bytes = static_cast(p.nx) * static_cast(components) * element_size; - for (int64_t z = 0; z < p.nz; ++z) { - for (int64_t y = 0; y < p.ny; ++y) { - std::memcpy(row_ptr(p, element_size, z, y), fdata.data() + offset, row_bytes); - offset += p.nx * components; - } - } - } -} - -// ================================================================================================ -// Session -// ================================================================================================ - -struct VtkBoxSession::Impl { - std::string path; - bool for_write = false; - std::uint32_t num_fields_recorded = 0; - VtkBox box; - std::ofstream writer; - std::ifstream reader; - std::vector read_fields; - size_t read_fields_cursor = 0; - - void finalize() { - if (!writer.is_open()) return; - writer << " \n"; - writer << " \n"; - writer << " \n"; - writer << "\n"; - writer.flush(); - if (!writer.good()) { - log::throw_with_log("io::write_vtk: failed to finalize the shard"); - } - writer.close(); - } -}; - -VtkBoxSession::VtkBoxSession() noexcept = default; -VtkBoxSession::~VtkBoxSession() { - if (impl_ && impl_->for_write) { - impl_->finalize(); - } -} -VtkBoxSession::VtkBoxSession(VtkBoxSession&&) noexcept = default; -auto -VtkBoxSession::operator=(VtkBoxSession&&) noexcept -> VtkBoxSession& = default; - -auto -VtkBoxSession::shard_path(std::string_view base, - const DenseDistributed& grid) -> std::string { - return shard_path_of(base, grid); -} - -void -VtkBoxSession::open_for_write(std::string_view path, - const DenseDistributed& grid, - std::uint32_t /*num_fields*/) { - if (impl_ && impl_->for_write) { - impl_->finalize(); - } - impl_ = std::make_unique(); - impl_->path = shard_path_of(path, grid); - impl_->for_write = true; - impl_->box = vtk_box_of(grid); - impl_->writer.open(impl_->path, std::ios::binary | std::ios::trunc); - if (!impl_->writer) { - log::throw_with_log("io::write_vtk: failed to open '{}' for writing", - impl_->path); - } - write_vtk_xml_box_header(impl_->writer, impl_->box); -} - -void -VtkBoxSession::write_field(std::string_view name, - const char* dtype_tag, - size_t element_size, - int components, - const std::vector& pieces) { - if (impl_ == nullptr || !impl_->for_write) { - log::throw_with_log("io::write_vtk: session is not in a writable state"); - } - write_vtk_xml_box_field(impl_->writer, name, dtype_tag, element_size, components, impl_->box, pieces); - ++impl_->num_fields_recorded; -} - -void -VtkBoxSession::open_for_read(std::string_view path, - const DenseDistributed& grid) { - impl_ = std::make_unique(); - impl_->path = shard_path_of(path, grid); - impl_->for_write = false; - impl_->box = vtk_box_of(grid); - impl_->reader.open(impl_->path, std::ios::binary); - if (!impl_->reader) { - log::throw_with_log("io::read_vtk: failed to open '{}' for reading", - impl_->path); - } - parse_vtk_xml_box_header(impl_->reader, impl_->path, impl_->box, impl_->read_fields); -} - -void -VtkBoxSession::read_field(std::string_view /*name*/, - const char* dtype_tag, - size_t element_size, - int components, - const std::vector& pieces) { - if (impl_ == nullptr || impl_->for_write) { - log::throw_with_log("io::read_vtk: session is not in a readable state"); - } - if (impl_->read_fields_cursor >= impl_->read_fields.size()) { - log::throw_with_log( - "io::read_vtk: more fields requested than '{}' contains", impl_->path); - } - const auto& rec = impl_->read_fields[impl_->read_fields_cursor++]; - const char* expected_kw = vtk_xml_keyword_from_native_tag(dtype_tag); - if (expected_kw == nullptr || rec.vtk_dtype != expected_kw) { - log::throw_with_log( - "io::read_vtk: field {} dtype '{}' does not match bound carbon dtype '{}' in '{}'", - rec.name, rec.vtk_dtype, (expected_kw != nullptr ? expected_kw : "?"), impl_->path); - } - if (rec.components != components) { - log::throw_with_log( - "io::read_vtk: field {} has {} components but the bound Field has {}", rec.name, - rec.components, components); - } - impl_->reader.clear(); - impl_->reader.seekg(rec.payload_offset); - if (!impl_->reader.good()) { - log::throw_with_log( - "io::read_vtk: seek to the payload of '{}' failed in '{}'", rec.name, impl_->path); - } - read_vtk_xml_box_field_payload(impl_->reader, element_size, components, impl_->box, pieces); -} - -auto -VtkBoxSession::num_fields() const noexcept -> std::uint32_t { - if (impl_ == nullptr) { - return 0U; - } - return impl_->for_write ? impl_->num_fields_recorded - : static_cast(impl_->read_fields.size()); -} - -} // namespace carbon::io::detail - -namespace carbon::io { - -auto -write_vtk_multiblock_index(std::string_view base, - const DenseDistributed& grid) -> void { -#ifdef CARBON_HAVE_MPI_NCCL - const auto* dist = grid.system().distributed(); - if (dist == nullptr) { - return; - } - const int world_size = dist->world_size(); - if (world_size <= 1 || dist->world_rank() != 0) { - return; - } - - const ProcessGrid& pg = grid.process_grid(); - const int64_3d global = grid.global_extent(); - std::vector listed; - for (int r = 0; r < world_size; ++r) { - bool owns = true; - if (pg.world_size() == world_size) { - const auto chunk = ::carbon::detail::dense_distributed::rank_chunk( - global, pg, pg.coords_of(r), int64_3d{0, 0, 0}); - owns = chunk.owned.x > 0 && chunk.owned.y > 0 && chunk.owned.z > 0; - } - if (owns) { - listed.push_back(r); - } - } - - const std::filesystem::path base_path(std::string{base}); - const std::filesystem::path master_path = base_path.string() + ".vtm"; - const std::filesystem::path base_filename = base_path.filename(); - - std::ofstream out(master_path, std::ios::binary | std::ios::trunc); - if (!out) { - log::throw_with_log( - "io::write_vtk_multiblock_index: failed to open '{}' for writing", master_path.string()); - } - out << "\n"; - out << "\n"; - out << " \n"; - int block = 0; - for (const int r : listed) { - out << " \n"; - out << " \n"; - out << " \n"; - } - out << " \n"; - out << "\n"; - if (!out.good()) { - log::throw_with_log("io::write_vtk_multiblock_index: write to '{}' failed", - master_path.string()); - } -#else - (void)base; - (void)grid; -#endif -} - -} // namespace carbon::io \ No newline at end of file diff --git a/src/stencil.cpp b/src/stencil.cpp index f40aeade..84b3b875 100644 --- a/src/stencil.cpp +++ b/src/stencil.cpp @@ -146,6 +146,8 @@ to_string(StencilSemantic semantic) noexcept -> std::string_view { return "standard"; case StencilSemantic::Lattice: return "lattice"; + case StencilSemantic::LatticeDistributed: + return "lattice-distributed"; } return "unknown"; } diff --git a/tests/test_dense_distributed_dist.cu b/tests/test_dense_distributed_dist.cu index 332abdd3..a98a791a 100644 --- a/tests/test_dense_distributed_dist.cu +++ b/tests/test_dense_distributed_dist.cu @@ -29,11 +29,11 @@ // and brick the Boundary launch is the compact shell, not the full owned extent.) // // 3. VTK shard I/O. A 3-component float field goes host -> device -> host, is written with -// io::write_vtk (one `.rank` shard per rank) plus the `.vtm` index, and read back with -// io::read_vtk into a second field. Each rank checks its own shard header against its owned box -// (DIMENSIONS / ORIGIN), every owned cell after the round trip, that halo cells were not -// touched, and rank 0 checks that the index lists every rank. Files are written to the -// working directory (like test_io_dist) and removed afterwards. +// io::write_vtk (one XML `.rank.vti` shard per rank) plus the `.vtm` index, and read back +// with io::read_vtk into a second field. Each rank checks its own shard WholeExtent / Origin +// against its owned box, every owned cell after the round trip, that halo cells were not +// touched, and rank 0 checks that the index lists every rank. Files are written to the working +// directory (like test_io_dist) and removed afterwards. #include #include @@ -121,6 +121,22 @@ six_point() -> carbon::Stencil { /*remove_center=*/true); } +[[nodiscard]] auto +xml_attribute(std::string_view tag, + std::string_view key) -> std::string { + const std::string needle = std::string(key) + "=\""; + const size_t begin = tag.find(needle); + if (begin == std::string_view::npos) { + return {}; + } + const size_t value_begin = begin + needle.size(); + const size_t end = tag.find('"', value_begin); + if (end == std::string_view::npos) { + return {}; + } + return std::string(tag.substr(value_begin, end - value_begin)); +} + /** Wrap @p v into [0, n) if @p periodic; return false when it is outside an open axis. */ [[nodiscard]] auto wrap_axis(int64_t v, @@ -149,7 +165,8 @@ run_halo_once(carbon::System& sys, const ProcessGrid& pg, BoundaryModeDistributed mode, const char* label, - const int64_3d& global) -> bool { + const int64_3d& global, + carbon::StencilSemantic semantic = carbon::StencilSemantic::Standard) -> bool { const int32_3d dims = pg.dims(); const int32_3d coords = pg.coords_of(rank); const carbon::Stencil stencil = six_point(); @@ -236,7 +253,7 @@ run_halo_once(carbon::System& sys, return false; } - carbon::HaloDistributed exchange(field); + carbon::HaloDistributed exchange(field, stencil, semantic); // A multi-rank layout always needs cross-rank transfers (X/Y faces fan out into several runs, so // the exact count is geometry dependent; correctness is enforced by the cell comparison below). if (exchange.pair_count() != 0U || exchange.dist_entry_count() == 0U || @@ -287,10 +304,37 @@ run_halo_once(carbon::System& sys, wrap_axis(g.y, global.y, carbon::is_periodic(mode, Axis::Y), wy) && wrap_axis(g.z, global.z, carbon::is_periodic(mode, Axis::Z), wz); const bool owned_cell = is_owned_cell(x, y, z); + const bool halo_x = x < halo.x || x >= halo.x + owned.x; + const bool halo_y = y < halo.y || y >= halo.y + owned.y; + const bool halo_z = z < halo.z || z >= halo.z + owned.z; + const int halo_axes = static_cast(halo_x) + static_cast(halo_y) + + static_cast(halo_z); + const Axis halo_axis = halo_x ? Axis::X : (halo_y ? Axis::Y : Axis::Z); const int64_t off = z * pitch + y * haloed.x + x; for (int c = 0; c < Components; ++c) { - const int want = - owned_cell ? encode(g.x, g.y, g.z, c) : (inside ? encode(wx, wy, wz, c) : kSentinel); + bool check = true; + int want = kSentinel; + if (owned_cell) { + want = encode(g.x, g.y, g.z, c); + } else if (!inside) { + want = kSentinel; + } else if (semantic == carbon::StencilSemantic::LatticeDistributed) { + // Corners are written by more than one face pass; only face-interior + // halo cells have an unambiguous source for every active component. + if (halo_axes != 1) { + check = false; + } else { + const auto& p = stencil.points()[static_cast(c)]; + const int64_t v = + halo_axis == Axis::X ? p.x : (halo_axis == Axis::Y ? p.y : p.z); + want = v != 0 ? encode(wx, wy, wz, c) : kSentinel; + } + } else { + want = encode(wx, wy, wz, c); + } + if (!check) { + continue; + } const int got = h[c * per_comp + off]; if (got != want) { if (mismatches < 4U) { @@ -325,16 +369,20 @@ run_halo(carbon::System& sys, const ProcessGrid& pg, BoundaryModeDistributed mode, const std::string& label, - const int64_3d& global) -> bool { + const int64_3d& global, + carbon::StencilSemantic semantic = carbon::StencilSemantic::Standard) -> bool { const char* saved = std::getenv("CARBON_HALO_PACK"); const bool had = saved != nullptr; const std::string previous = had ? saved : ""; bool ok = true; for (const bool pack : {true, false}) { ::setenv("CARBON_HALO_PACK", pack ? "1" : "0", 1); - const std::string tagged = - label + "/c" + std::to_string(Components) + (pack ? "/packed" : "/runs"); - ok = run_halo_once(sys, rank, pg, mode, tagged.c_str(), global); + const std::string tagged = label + "/c" + std::to_string(Components) + + (pack ? "/packed" : "/runs") + + (semantic == carbon::StencilSemantic::LatticeDistributed + ? "/lattice-distributed" + : ""); + ok = run_halo_once(sys, rank, pg, mode, tagged.c_str(), global, semantic); if (!ok) { break; } @@ -495,7 +543,7 @@ run_vtk(carbon::System& sys, const std::string& label, const int64_3d& global) -> bool { const std::string base = "carbon_test_dense_distributed_vtk_" + label; - const std::string shard = base + ".rank" + std::to_string(rank); + const std::string shard = base + ".rank" + std::to_string(rank) + ".vti"; const std::string index = base + ".vtm"; bool ok = true; try { @@ -558,28 +606,38 @@ run_vtk(carbon::System& sys, { std::ifstream in(shard, std::ios::binary); std::string line; - int64_t dims[3] = {-1, -1, -1}; + int64_t whole[6] = {-1, -1, -1, -1, -1, -1}; int64_t org[3] = {-1, -1, -1}; while (std::getline(in, line)) { - std::istringstream ls(line); - std::string head; - ls >> head; - if (head == "DIMENSIONS") { - ls >> dims[0] >> dims[1] >> dims[2]; - } else if (head == "ORIGIN") { - ls >> org[0] >> org[1] >> org[2]; - } else if (head == "SCALARS") { + if (line.find("> whole[0] >> whole[1] >> whole[2] >> whole[3] >> whole[4] >> whole[5]; + const std::string origin = xml_attribute(line, "Origin"); + std::istringstream os(origin); + os >> org[0] >> org[1] >> org[2]; break; } } const int64_3d o0 = span.global_location(span.make_idx(halo.x, halo.y, halo.z)); - if (dims[0] != owned.x || dims[1] != owned.y || dims[2] != owned.z || org[0] != o0.x || - org[1] != o0.y || org[2] != o0.z) { + if (whole[0] != 0 || whole[1] != owned.x - 1 || whole[2] != 0 || + whole[3] != owned.y - 1 || whole[4] != 0 || whole[5] != owned.z - 1 || + org[0] != o0.x || org[1] != o0.y || org[2] != o0.z) { + CARBON_LOG_ERROR( + "test_dense_distributed_dist[{}]: rank {} shard WholeExtent=({},{},{},{},{},{}) " + "Origin=({},{},{}) want owned=({},{},{}) origin=({},{},{})", + label, rank, whole[0], whole[1], whole[2], whole[3], whole[4], whole[5], org[0], + org[1], org[2], owned.x, owned.y, owned.z, o0.x, o0.y, o0.z); + ok = false; + } + std::ifstream raw(shard, std::ios::binary); + const std::string text((std::istreambuf_iterator(raw)), + std::istreambuf_iterator()); + if (text.find("format=\"binary\"") == std::string::npos || + text.find("(sys, rank, c.pg, c.mode, c.label, global) || (c.multi_component && !run_halo<3>(sys, rank, c.pg, c.mode, c.label, global)) || + !run_halo<6>(sys, rank, c.pg, c.mode, std::string(c.label) + "/lattice", global, + carbon::StencilSemantic::LatticeDistributed) || !run_stencil(sys, rank, c.pg, c.mode, carbon::OverlapMode::None, std::string(c.label) + "/stencil", global) || !run_stencil(sys, rank, c.pg, c.mode, carbon::OverlapMode::Standard, From 8e9c37e207854fdbe38340e79bfba2abbd5a5dbf Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Thu, 5 Nov 2026 10:13:22 +0100 Subject: [PATCH 09/33] vtk update distributed writing --- docs/CHANGELOG.md | 6 +- include/carbon/detail/io_vtk_distributed.inl | 6 +- src/io_vtk_distributed.cpp | 26 +++--- tests/test_dense_distributed_host.cpp | 93 +++++++++++++++++--- 4 files changed, 103 insertions(+), 28 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index aed1f09d..1fcef2c4 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6165,4 +6165,8 @@ This unblocked the matrix on this host: the `sycl` and `hip-nvidia` images build legacy stream-level helpers stay for the host tests. Inline binary is used because VTK 9.2's XML parser rejects raw appended blocks above its small line buffer. The base64 is emitted as one line: VTK's inline reader truncates large line-wrapped - blocks. The old experimental `io_vtk_distributed_wrong.cpp` was removed. + blocks. Empty shards use `0 -1` extents so VTK reads them as zero-point images. + `dense_distributed_host` now also drives the staged X -> Y -> Z planner with + `LatticeDistributed` on emulated slab / pencil / brick worlds and checks face-interior + halo components in both directions. The old experimental + `io_vtk_distributed_wrong.cpp` was removed. diff --git a/include/carbon/detail/io_vtk_distributed.inl b/include/carbon/detail/io_vtk_distributed.inl index 5381166d..fc6de11a 100644 --- a/include/carbon/detail/io_vtk_distributed.inl +++ b/include/carbon/detail/io_vtk_distributed.inl @@ -23,9 +23,9 @@ // followed by the little-endian component-fastest payload (x fastest, then y, then z). The // base64 is written as one line: VTK's inline reader mishandles wrapped blocks once the payload // grows past a few MiB. Inline binary avoids the VTK 9.2 XML parser's raw-appended-data buffer -// limit while remaining a normal VTK XML file. A rank -// that owns no cells writes a valid empty shard; the `.vtm` index lists only the non-empty -// shards. +// limit while remaining a normal VTK XML file. A rank that owns no cells writes a valid empty +// shard (`WholeExtent` / `Piece Extent` are `0 -1` on every axis); the `.vtm` index lists only +// the non-empty shards. // // Index space (Spacing 1, Origin in cells) is deliberate: it is what the Dense writer/reader use, // costs nothing extra to write, and keeps shards of both grid families interchangeable in diff --git a/src/io_vtk_distributed.cpp b/src/io_vtk_distributed.cpp index e1b2cf3b..a00c1c7b 100644 --- a/src/io_vtk_distributed.cpp +++ b/src/io_vtk_distributed.cpp @@ -1080,12 +1080,12 @@ write_vti_box_header(std::ostream& out, out << "\n"; out << "\n"; - out << " \n"; - out << " \n"; + out << " \n"; out << " \n"; if (!out.good()) { log::throw_with_log("io::write_vtk: failed to write the shard header"); @@ -1229,16 +1229,14 @@ parse_vti_box_header(std::istream& in, } const bool want_empty = expected.empty(); - if (!want_empty) { - if (whole[0] != 0 || whole[1] != expected.dims[0] - 1 || whole[2] != 0 || - whole[3] != expected.dims[1] - 1 || whole[4] != 0 || - whole[5] != expected.dims[2] - 1) { - log::throw_with_log( - "io::read_vtk: '{}' WholeExtent ({}, {}, {}, {}, {}, {}) does not match this rank's " - "owned box ({}, {}, {})", - path, whole[0], whole[1], whole[2], whole[3], whole[4], whole[5], expected.dims[0], - expected.dims[1], expected.dims[2]); - } + if (whole[0] != 0 || whole[1] != (want_empty ? -1 : expected.dims[0] - 1) || whole[2] != 0 || + whole[3] != (want_empty ? -1 : expected.dims[1] - 1) || whole[4] != 0 || + whole[5] != (want_empty ? -1 : expected.dims[2] - 1)) { + log::throw_with_log( + "io::read_vtk: '{}' WholeExtent ({}, {}, {}, {}, {}, {}) does not match this rank's " + "owned box ({}, {}, {})", + path, whole[0], whole[1], whole[2], whole[3], whole[4], whole[5], expected.dims[0], + expected.dims[1], expected.dims[2]); } if (origin[0] != expected.origin[0] || origin[1] != expected.origin[1] || origin[2] != expected.origin[2]) { diff --git a/tests/test_dense_distributed_host.cpp b/tests/test_dense_distributed_host.cpp index 21a52b44..60cd2183 100644 --- a/tests/test_dense_distributed_host.cpp +++ b/tests/test_dense_distributed_host.cpp @@ -14,7 +14,8 @@ // Part C correctness of the full X -> Y -> Z staged halo exchange on an emulated multi-rank world // (corners/edges, periodic wraps, uneven splits, self-wrap), driven by the production // plan builder and checked against the run-based builder (kept as the oracle) and against -// ground truth. +// ground truth. Also covers `LatticeDistributed` face-interior halo components in both +// directions, so the brick/pencil wall-bounce-back fix is exercised without GPUs. // // What it does NOT cover: stream ordering, NCCL/MPI transport and real kernel launches. That is the // job of the dense_distributed_dist test, which runs the real exchange on GPUs. @@ -122,13 +123,15 @@ struct Rank { std::vector stage; }; +enum class Semantic { Standard, Lattice, LatticeDistributed }; + struct World { ProcessGrid pg = ProcessGrid::custom(1, 1, 1, 1); BoundaryModeDistributed bm{BoundaryModeDistributed::Open}; int64_3d global{}; int64_3d halo{}; int comps{1}; - bool lat{false}; + Semantic semantic{Semantic::Standard}; std::vector vel; std::vector ranks; @@ -136,10 +139,13 @@ struct World { active_send(int c, Axis axis, AxisSide side) const -> bool { - if (!lat) { + if (semantic == Semantic::Standard) { return true; } const int v = axis_of(vel[static_cast(c)], axis); + if (semantic == Semantic::LatticeDistributed) { + return v != 0; + } return side == AxisSide::Upper ? v > 0 : v < 0; } @@ -147,10 +153,13 @@ struct World { active_recv(int c, Axis axis, AxisSide side) const -> bool { - if (!lat) { + if (semantic == Semantic::Standard) { return true; } const int v = axis_of(vel[static_cast(c)], axis); + if (semantic == Semantic::LatticeDistributed) { + return v != 0; + } return side == AxisSide::Upper ? v < 0 : v > 0; } }; @@ -190,15 +199,18 @@ make_world(const ProcessGrid& pg, int64_3d halo, int comps, int lattice_q, + bool lattice_distributed, int64_t pitch_pad) -> World { World w; w.pg = pg; w.bm = bm; w.global = global; w.halo = halo; - w.lat = lattice_q != 0; + w.semantic = lattice_q == 0 + ? Semantic::Standard + : (lattice_distributed ? Semantic::LatticeDistributed : Semantic::Lattice); w.vel = lattice(lattice_q); - w.comps = w.lat ? static_cast(w.vel.size()) : comps; + w.comps = w.semantic == Semantic::Standard ? comps : static_cast(w.vel.size()); const int64_3d hh = dd::halo_extent(pg, bm, stencil_from_halo(halo)); for (int32_t r = 0; r < pg.world_size(); ++r) { Rank rk; @@ -386,7 +398,7 @@ needed(const World& w, int64_t lx, int64_t ly, int64_t lz) -> bool { - if (!w.lat) { + if (w.semantic == Semantic::Standard) { return true; } const Vel& v = w.vel[static_cast(c)]; @@ -459,6 +471,56 @@ verify(const World& w, return checked; } +// For LatticeDistributed, face-interior halo cells must carry every component whose velocity is +// nonzero on that face, and must leave zero-normal components untouched. Corners are skipped: +// several face passes may write them, so their source is not unique. +auto +verify_lattice_distributed_faces(const World& w) -> size_t { + size_t checked = 0; + for (size_t i = 0; i < w.ranks.size(); ++i) { + const Rank& rk = w.ranks[i]; + for (int c = 0; c < w.comps; ++c) { + for (int64_t z = 0; z < rk.g.haloed.z; ++z) { + for (int64_t y = 0; y < rk.g.haloed.y; ++y) { + for (int64_t x = 0; x < rk.g.haloed.x; ++x) { + const bool owned = x >= rk.g.halo.x && x < rk.g.halo.x + rk.g.owned.x && + y >= rk.g.halo.y && y < rk.g.halo.y + rk.g.owned.y && + z >= rk.g.halo.z && z < rk.g.halo.z + rk.g.owned.z; + if (owned) { + continue; + } + const bool halo_x = x < rk.g.halo.x || x >= rk.g.halo.x + rk.g.owned.x; + const bool halo_y = y < rk.g.halo.y || y >= rk.g.halo.y + rk.g.owned.y; + const bool halo_z = z < rk.g.halo.z || z >= rk.g.halo.z + rk.g.owned.z; + if (static_cast(halo_x) + static_cast(halo_y) + static_cast(halo_z) != 1) { + continue; + } + const Axis axis = halo_x ? Axis::X : (halo_y ? Axis::Y : Axis::Z); + const size_t idx = static_cast(c * rk.comp_stride + z * rk.g.pitch + + y * rk.g.haloed.x + x); + const uint64_t marker = + kMarker ^ (static_cast(i + 1) << 40) ^ static_cast(idx); + std::array gw{}; + const bool valid = + wrap_global(w, rk.offset.x + x - rk.g.halo.x, rk.offset.y + y - rk.g.halo.y, + rk.offset.z + z - rk.g.halo.z, gw); + const uint64_t got = rk.buf[idx]; + if (!valid) { + CHECK(got == marker); + } else if (axis_of(w.vel[static_cast(c)], axis) != 0) { + CHECK(got == encode(gw[0], gw[1], gw[2], c)); + } else { + CHECK(got == marker); + } + ++checked; + } + } + } + } + } + return checked; +} + // ---- Part A: kernel index math in isolation, all element widths --------------------------- struct Wide16 { uint64_t a, b; @@ -1129,6 +1191,7 @@ struct Scenario { int comps; int lattice_q; int64_t pad; + bool lattice_distributed = false; }; constexpr BoundaryModeDistributed kOpen = BoundaryModeDistributed::Open; @@ -1149,10 +1212,12 @@ run_scenario(const Scenario& s, size_t& z_msgs) -> void { g_ctx = std::string(s.name) + " grid=" + std::to_string(s.px) + "x" + std::to_string(s.py) + "x" + std::to_string(s.pz) + " bm=" + std::to_string(static_cast(s.bm)) + - " lat=" + std::to_string(s.lattice_q) + " pad=" + std::to_string(s.pad); + " lat=" + std::to_string(s.lattice_q) + + " semantic=" + (s.lattice_distributed ? "lattice-distributed" : "lattice-or-standard") + + " pad=" + std::to_string(s.pad); const ProcessGrid pg = ProcessGrid::custom(s.px * s.py * s.pz, s.px, s.py, s.pz); - World packed = - make_world(pg, s.bm, {s.gx, s.gy, s.gz}, {s.hx, s.hy, s.hz}, s.comps, s.lattice_q, s.pad); + World packed = make_world(pg, s.bm, {s.gx, s.gy, s.gz}, {s.hx, s.hy, s.hz}, s.comps, + s.lattice_q, s.lattice_distributed, s.pad); World oracle = packed; // identical start state // Old path: run-based X, Y, Z. @@ -1181,6 +1246,12 @@ run_scenario(const Scenario& s, false); // oracle: right on needed cells (it clobbers exterior halos, by design)... total_checked += verify(packed, &oracle, true, pack_z); // ...and the packed result must match it bit for bit + if (packed.semantic == Semantic::LatticeDistributed) { + const size_t face_checked = verify_lattice_distributed_faces(oracle) + + verify_lattice_distributed_faces(packed); + CHECK(face_checked > 0U); + total_checked += face_checked; + } } } // namespace @@ -1228,6 +1299,8 @@ main() { // Lattice direction filtering (per-axis send/recv component lists). sc.push_back({"d3q19", g.x, g.y, g.z, bm, 11, 9, 10, 1, 1, 1, 0, 19, 0}); sc.push_back({"d3q27", g.x, g.y, g.z, bm, 11, 9, 10, 1, 1, 1, 0, 27, 5}); + sc.push_back({"d3q19-dist", g.x, g.y, g.z, bm, 11, 9, 10, 1, 1, 1, 0, 19, 0, true}); + sc.push_back({"d3q27-dist-pad", g.x, g.y, g.z, bm, 11, 9, 10, 1, 1, 1, 0, 27, 5, true}); } } From 8c16cc18e264886ea1484912bb4ddd5bae3ad393 Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Thu, 5 Nov 2026 17:50:34 +0100 Subject: [PATCH 10/33] Fix spdlog version and render_ray_march.inl for amd gpus --- cmake/CarbonSpdlog.cmake | 2 +- include/carbon/detail/render_ray_march.inl | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/cmake/CarbonSpdlog.cmake b/cmake/CarbonSpdlog.cmake index 94424882..98e08412 100644 --- a/cmake/CarbonSpdlog.cmake +++ b/cmake/CarbonSpdlog.cmake @@ -13,7 +13,7 @@ set(SPDLOG_INSTALL ON CACHE BOOL "" FORCE) FetchContent_Declare( spdlog GIT_REPOSITORY https://github.com/gabime/spdlog.git - GIT_TAG v1.15.0 + GIT_TAG v1.16.0 ) FetchContent_MakeAvailable(spdlog) diff --git a/include/carbon/detail/render_ray_march.inl b/include/carbon/detail/render_ray_march.inl index 09632791..eaf8e07d 100644 --- a/include/carbon/detail/render_ray_march.inl +++ b/include/carbon/detail/render_ray_march.inl @@ -10,6 +10,7 @@ namespace carbon { namespace detail { +/* [[nodiscard]] CARBON_HD constexpr auto ray_inf() noexcept -> float { #ifdef __CUDA_ARCH__ @@ -20,6 +21,19 @@ ray_inf() noexcept -> float { return std::numeric_limits::infinity(); #endif } +*/ + +[[nodiscard]] CARBON_HD constexpr auto +ray_inf() noexcept -> float { +#ifdef __CUDA_ARCH__ + return __int_as_float(0x7f800000); +#elif defined(__HIP_DEVICE_COMPILE__) + return std::numeric_limits::infinity(); +#else + return std::numeric_limits::infinity(); +#endif +} + struct RayMarchSegment { float color_r{0.0F}; From 3c474909075646ce528d934f9e6d6c682c31d3cc Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Thu, 5 Nov 2026 18:16:24 +0100 Subject: [PATCH 11/33] Add only rank=0 printing iteration time --- .../lbm_lid_driven_cavity_distributed.cu | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu b/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu index 7863e758..ae72983c 100644 --- a/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu +++ b/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu @@ -711,8 +711,9 @@ run_benchmark(const Options& opts, } const auto now = Clock::now(); const double elapsed_overall = Seconds(now - overall_started).count(); - CARBON_LOG_INFO("lbm_lid_driven_cavity: iter {}/{} elapsed={:.3f}s", it + 1, opts.iters, - elapsed_overall); + if (world_rank == 0) { + CARBON_LOG_INFO("lbm_lid_driven_cavity: iter {}/{} elapsed={:.3f}s", it + 1, opts.iters,elapsed_overall); + } } CARBON_HALO_NVTX_POP(); From aace22b62b256da36f1d9ebf1bf8defdf91c553c Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:07:02 +0100 Subject: [PATCH 12/33] Fix decomposition check --- docs/CHANGELOG.md | 10 + .../carbon/detail/dense_distributed/layout.h | 36 ++ src/dense.cpp | 33 +- src/dense_disg.cpp | 32 +- src/dense_distributed.cpp | 46 +-- src/dense_distributed_old.cpp | 390 ++++++++++++++++++ tests/test_dense_distributed_host.cpp | 67 ++- 7 files changed, 540 insertions(+), 74 deletions(-) create mode 100644 src/dense_distributed_old.cpp diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 12f931d8..3eb9e5a4 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6185,3 +6185,13 @@ 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). 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/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..5dd46356 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 = @@ -193,37 +198,6 @@ DenseDistributed::init_common_(System system, chunk.halo, boundary_mode_, 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/dense_distributed_old.cpp b/src/dense_distributed_old.cpp new file mode 100644 index 00000000..39b50ea0 --- /dev/null +++ b/src/dense_distributed_old.cpp @@ -0,0 +1,390 @@ +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +namespace { + +using carbon::detail::dense_distributed::split_extent; + +[[nodiscard]] auto +resolve_world_size(const carbon::System& system) -> int { +#ifdef CARBON_HAVE_MPI_NCCL + if (const carbon::Distributed* dist = system.distributed(); dist != nullptr) { + return dist->world_size(); + } +#endif + return static_cast(system.gpu_group().size()); +} + +[[nodiscard]] auto +resolve_world_rank(const carbon::System& system) -> int { +#ifdef CARBON_HAVE_MPI_NCCL + if (const carbon::Distributed* dist = system.distributed(); dist != nullptr) { + return dist->world_rank(); + } +#endif + return 0; +} + +[[nodiscard]] auto +linear_count_for_slab(int64_t nx, + int64_t ny, + size_t nz_slab) -> size_t { + if (nx < 0 || ny < 0) { + carbon::log::throw_with_log( + "DenseDistributed: global x and y extents must be non-negative (nx={}, ny={})", nx, ny); + } + const int64_t nx64 = nx; + const int64_t ny64 = ny; + const int64_t nz64 = static_cast(nz_slab); + if (nz_slab > static_cast(std::numeric_limits::max())) { + carbon::log::throw_with_log( + "DenseDistributed: per-GPU z slab too large (nz_slab={})", nz_slab); + } + const int64_t prod = nx64 * ny64; + if (nx64 != 0 && prod / nx64 != ny64) { + carbon::log::throw_with_log( + "DenseDistributed: x*y overflow (nx={}, ny={})", nx64, ny64); + } + const int64_t line = prod * nz64; + if (prod != 0 && line / prod != nz64) { + carbon::log::throw_with_log( + "DenseDistributed: linear element count overflow (nx={}, ny={}, nz_slab={})", nx64, ny64, + nz_slab); + } + if (line < 0) { + carbon::log::throw_with_log( + "DenseDistributed: negative linear element count (nx={}, ny={}, nz_slab={})", nx64, ny64, + nz_slab); + } + if (static_cast(line) > static_cast(std::numeric_limits::max())) { + carbon::log::throw_with_log( + "DenseDistributed: linear element count too large for size_t (line={})", line); + } + return static_cast(line); +} + +} // namespace + +namespace carbon { +void +DenseDistributed::init_common_(System system, + int64_3d global_extent, + Stencil stencil, + BoundaryModeDistributed boundary_mode, + float32_3d origin, + float spacing, + ProcessGrid process_grid, + std::optional block_override) { + if (!std::isfinite(spacing) || spacing <= 0.0F) { + log::throw_with_log( + "DenseDistributed: spacing must be finite and strictly positive (spacing={})", spacing); + } + if (!std::isfinite(origin.x) || !std::isfinite(origin.y) || !std::isfinite(origin.z)) { + log::throw_with_log( + "DenseDistributed: origin components must be finite (origin=({}, {}, {}))", origin.x, + origin.y, origin.z); + } + if (system.gpu_group().size() == 0U) { + log::throw_with_log( + "DenseDistributed: System has zero GPUs; cannot build a grid (matches the Block / " + "DenseDisg " + "policy -- empty systems fail at the grid ctor rather than at the first newField " + "call, so the diagnostic points at the actual misconfiguration)"); + } + if (global_extent.x < 0 || global_extent.y < 0 || global_extent.z < 0) { + log::throw_with_log( + "DenseDistributed: global x, y, z extents must be non-negative (x={}, y={}, z={})", + global_extent.x, global_extent.y, global_extent.z); + } + + global_ = global_extent; + system_ = std::move(system); + stencil_ = std::move(stencil); + boundary_mode_ = boundary_mode; + origin_ = origin; + spacing_ = spacing; + process_grid_ = std::move(process_grid); + + const size_t local_n = system_.gpu_group().size(); + const int world_size = resolve_world_size(system_); + const int world_rank = resolve_world_rank(system_); + bool distributed = false; + +#ifdef CARBON_HAVE_MPI_NCCL + const Distributed* dist = system_.distributed(); + distributed = dist != nullptr; + if (dist != nullptr) { + if (local_n != 1U) { + log::throw_with_log( + "DenseDistributed: distributed System must own exactly one local GPU per rank (got {}); " + "carbon's " + "distributed model is one rank per GPU", + local_n); + } + if (world_size <= 0 || world_rank < 0 || world_rank >= world_size) { + log::throw_with_log( + "DenseDistributed: invalid Distributed state (world_size={}, world_rank={})", world_size, + world_rank); + } + if (process_grid_.world_size() != world_size) { + log::throw_with_log( + "DenseDistributed: ProcessGrid world_size ({}) does not match Distributed world_size " + "({})", + process_grid_.world_size(), world_size); + } + } else +#endif + { + if (process_grid_.world_size() != static_cast(local_n)) { + log::throw_with_log( + "DenseDistributed: ProcessGrid world_size ({}) does not match local GPU count ({})", + process_grid_.world_size(), local_n); + } + } + + const int32_3d dims = process_grid_.dims(); + if (dims.x <= 0 || dims.y <= 0 || dims.z <= 0) { + log::throw_with_log( + "DenseDistributed: ProcessGrid dimensions must be positive (dims=({}, {}, {}))", dims.x, + dims.y, dims.z); + } + if (local_n > 1U && (dims.x > 1 || dims.y > 1)) { + log::throw_with_log( + "DenseDistributed: single-process Pencil/Brick with multiple local GPUs is not supported; " + "use MPI with one rank per GPU (local GPUs={}, dims=({}, {}, {}))", + local_n, dims.x, dims.y, dims.z); + } + const int32_3d coords = process_grid_.coords_of(world_rank); + 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. + 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))) { + (void)linear_count_for_slab(static_cast(nx), static_cast(ny), nz); + } + } + } + + 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_); + + spans_ = system_.make_vector([&](size_t i) { + const int32_3d gpu_coords = distributed ? coords : process_grid_.coords_of(static_cast(i)); + const detail::dense_distributed::RankChunk chunk = 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_); + }); + + // 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) { + if (block_override.has_value()) { + return *block_override; + } + return dense_make_kernel_block(system_.gpu_group().devices()[i]); + }); + gpu_grid_per_view_[vi] = system_.make_vector([&](size_t i) { + const detail::Gpu& gpu = system_.gpu_group().devices()[i]; + LaunchShape grid; + detail::compute_dense_grid(spans_[i].iter_extent(view), gpu_block_per_view_[vi][i], + gpu.properties().max_threads_per_block, grid); + return grid; + }); + } +} + +DenseDistributed::DenseDistributed(System system, + int64_3d global_extent, + Stencil stencil, + BoundaryModeDistributed boundary_mode, + float32_3d origin, + float spacing, + std::optional block_override) + : DenseDistributed() { + const int world_size = resolve_world_size(system); + const ProcessGrid pg = + world_size > 0 ? ProcessGrid::make(world_size, DecompositionMode::Slab) : ProcessGrid{}; + init_common_(std::move(system), global_extent, std::move(stencil), boundary_mode, origin, spacing, + pg, block_override); +} + +DenseDistributed::DenseDistributed(System system, + int64_3d global_extent, + DecompositionMode decomposition, + Stencil stencil, + BoundaryModeDistributed boundary_mode, + float32_3d origin, + float spacing, + std::optional block_override) + : DenseDistributed() { + const int world_size = resolve_world_size(system); + const ProcessGrid pg = + world_size > 0 ? ProcessGrid::make(world_size, decomposition) : ProcessGrid{}; + init_common_(std::move(system), global_extent, std::move(stencil), boundary_mode, origin, spacing, + pg, block_override); +} + +DenseDistributed::DenseDistributed(System system, + int64_3d global_extent, + ProcessGrid process_grid, + Stencil stencil, + BoundaryModeDistributed boundary_mode, + float32_3d origin, + float spacing, + std::optional block_override) + : DenseDistributed() { + init_common_(std::move(system), global_extent, std::move(stencil), boundary_mode, origin, spacing, + std::move(process_grid), block_override); +} + +auto +DenseDistributed::process_grid() const noexcept -> const ProcessGrid& { + return process_grid_; +} + +auto +DenseDistributed::local_extent(size_t gpu) const -> int64_3d { + if (gpu >= gpu_count()) { + log::throw_with_log( + "DenseDistributed::local_extent: gpu index out of range (gpu={}, gpu_count={})", gpu, + gpu_count()); + } + return spans_[gpu].logic_extent(); +} + +auto +DenseDistributed::linear_elements(size_t gpu) const -> size_t { + if (gpu >= gpu_count()) { + log::throw_with_log( + "DenseDistributed::linear_elements: gpu index out of range (gpu={}, gpu_count={})", gpu, + gpu_count()); + } + const int64_3d owned = spans_[gpu].logic_extent(); + return linear_count_for_slab(owned.x, owned.y, static_cast(owned.z)); +} + +auto +DenseDistributed::global_extent() const noexcept -> const int64_3d& { + return global_; +} + +auto +DenseDistributed::stencil() const noexcept -> const Stencil& { + return stencil_; +} + +auto +DenseDistributed::boundary_mode() const noexcept -> BoundaryModeDistributed { + return boundary_mode_; +} + +auto +DenseDistributed::origin() const noexcept -> float32_3d { + return origin_; +} + +auto +DenseDistributed::spacing() const noexcept -> float { + return spacing_; +} + +auto +DenseDistributed::system() noexcept -> System& { + return system_; +} + +auto +DenseDistributed::system() const noexcept -> const System& { + return system_; +} + +auto +DenseDistributed::gpu_count() const noexcept -> size_t { + return system_.gpu_group().size(); +} + +auto +DenseDistributed::global_slab_count() const noexcept -> size_t { + return global_slab_count_; +} + +auto +DenseDistributed::local_slab_offset() const noexcept -> size_t { + return local_slab_offset_; +} + +auto +DenseDistributed::local_z(size_t gpu) const -> int64_t { + if (gpu >= gpu_count()) { + log::throw_with_log( + "DenseDistributed::local_z: gpu index out of range (gpu={}, gpu_count={})", gpu, + gpu_count()); + } + return spans_[gpu].logic_extent().z; +} + +auto +DenseDistributed::z_offset_global(size_t gpu) const -> int64_t { + if (gpu >= gpu_count()) { + log::throw_with_log( + "DenseDistributed::z_offset_global: gpu index out of range (gpu={}, gpu_count={})", gpu, + gpu_count()); + } + // Span::z_offset() is the start of the lower halo; the first owned layer is halo_z above it. + return spans_[gpu].z_offset() + spans_[gpu].halo_z(); +} + +auto +DenseDistributed::linear_counts_per_gpu() const -> std::vector { + return system_.make_vector([&](size_t i) { + return linear_elements(i); + }); +} + +} // namespace carbon diff --git a/tests/test_dense_distributed_host.cpp b/tests/test_dense_distributed_host.cpp index 60cd2183..2da0921f 100644 --- a/tests/test_dense_distributed_host.cpp +++ b/tests/test_dense_distributed_host.cpp @@ -919,6 +919,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 +1329,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; From cacaa4b8bbeeaf4a5f25432132f0705467affd5d Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:20:53 +0100 Subject: [PATCH 13/33] Add two-band boundary path on dense_distributed iter_extent function of span.h --- docs/CHANGELOG.md | 6 + .../carbon/detail/dense_distributed/span.h | 32 +- src/dense_distributed.cpp | 3 +- src/dense_distributed_old.cpp | 390 ------------------ tests/test_dense_distributed_host.cpp | 13 +- 5 files changed, 41 insertions(+), 403 deletions(-) delete mode 100644 src/dense_distributed_old.cpp diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 3eb9e5a4..e703d8c4 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6195,3 +6195,9 @@ This unblocked the matrix on this host: the `sycl` and `hip-nvidia` images build `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. 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/src/dense_distributed.cpp b/src/dense_distributed.cpp index 5dd46356..0d6683d0 100644 --- a/src/dense_distributed.cpp +++ b/src/dense_distributed.cpp @@ -195,7 +195,8 @@ 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_); }); for (auto view : data_view_options()) { diff --git a/src/dense_distributed_old.cpp b/src/dense_distributed_old.cpp deleted file mode 100644 index 39b50ea0..00000000 --- a/src/dense_distributed_old.cpp +++ /dev/null @@ -1,390 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include - -namespace { - -using carbon::detail::dense_distributed::split_extent; - -[[nodiscard]] auto -resolve_world_size(const carbon::System& system) -> int { -#ifdef CARBON_HAVE_MPI_NCCL - if (const carbon::Distributed* dist = system.distributed(); dist != nullptr) { - return dist->world_size(); - } -#endif - return static_cast(system.gpu_group().size()); -} - -[[nodiscard]] auto -resolve_world_rank(const carbon::System& system) -> int { -#ifdef CARBON_HAVE_MPI_NCCL - if (const carbon::Distributed* dist = system.distributed(); dist != nullptr) { - return dist->world_rank(); - } -#endif - return 0; -} - -[[nodiscard]] auto -linear_count_for_slab(int64_t nx, - int64_t ny, - size_t nz_slab) -> size_t { - if (nx < 0 || ny < 0) { - carbon::log::throw_with_log( - "DenseDistributed: global x and y extents must be non-negative (nx={}, ny={})", nx, ny); - } - const int64_t nx64 = nx; - const int64_t ny64 = ny; - const int64_t nz64 = static_cast(nz_slab); - if (nz_slab > static_cast(std::numeric_limits::max())) { - carbon::log::throw_with_log( - "DenseDistributed: per-GPU z slab too large (nz_slab={})", nz_slab); - } - const int64_t prod = nx64 * ny64; - if (nx64 != 0 && prod / nx64 != ny64) { - carbon::log::throw_with_log( - "DenseDistributed: x*y overflow (nx={}, ny={})", nx64, ny64); - } - const int64_t line = prod * nz64; - if (prod != 0 && line / prod != nz64) { - carbon::log::throw_with_log( - "DenseDistributed: linear element count overflow (nx={}, ny={}, nz_slab={})", nx64, ny64, - nz_slab); - } - if (line < 0) { - carbon::log::throw_with_log( - "DenseDistributed: negative linear element count (nx={}, ny={}, nz_slab={})", nx64, ny64, - nz_slab); - } - if (static_cast(line) > static_cast(std::numeric_limits::max())) { - carbon::log::throw_with_log( - "DenseDistributed: linear element count too large for size_t (line={})", line); - } - return static_cast(line); -} - -} // namespace - -namespace carbon { -void -DenseDistributed::init_common_(System system, - int64_3d global_extent, - Stencil stencil, - BoundaryModeDistributed boundary_mode, - float32_3d origin, - float spacing, - ProcessGrid process_grid, - std::optional block_override) { - if (!std::isfinite(spacing) || spacing <= 0.0F) { - log::throw_with_log( - "DenseDistributed: spacing must be finite and strictly positive (spacing={})", spacing); - } - if (!std::isfinite(origin.x) || !std::isfinite(origin.y) || !std::isfinite(origin.z)) { - log::throw_with_log( - "DenseDistributed: origin components must be finite (origin=({}, {}, {}))", origin.x, - origin.y, origin.z); - } - if (system.gpu_group().size() == 0U) { - log::throw_with_log( - "DenseDistributed: System has zero GPUs; cannot build a grid (matches the Block / " - "DenseDisg " - "policy -- empty systems fail at the grid ctor rather than at the first newField " - "call, so the diagnostic points at the actual misconfiguration)"); - } - if (global_extent.x < 0 || global_extent.y < 0 || global_extent.z < 0) { - log::throw_with_log( - "DenseDistributed: global x, y, z extents must be non-negative (x={}, y={}, z={})", - global_extent.x, global_extent.y, global_extent.z); - } - - global_ = global_extent; - system_ = std::move(system); - stencil_ = std::move(stencil); - boundary_mode_ = boundary_mode; - origin_ = origin; - spacing_ = spacing; - process_grid_ = std::move(process_grid); - - const size_t local_n = system_.gpu_group().size(); - const int world_size = resolve_world_size(system_); - const int world_rank = resolve_world_rank(system_); - bool distributed = false; - -#ifdef CARBON_HAVE_MPI_NCCL - const Distributed* dist = system_.distributed(); - distributed = dist != nullptr; - if (dist != nullptr) { - if (local_n != 1U) { - log::throw_with_log( - "DenseDistributed: distributed System must own exactly one local GPU per rank (got {}); " - "carbon's " - "distributed model is one rank per GPU", - local_n); - } - if (world_size <= 0 || world_rank < 0 || world_rank >= world_size) { - log::throw_with_log( - "DenseDistributed: invalid Distributed state (world_size={}, world_rank={})", world_size, - world_rank); - } - if (process_grid_.world_size() != world_size) { - log::throw_with_log( - "DenseDistributed: ProcessGrid world_size ({}) does not match Distributed world_size " - "({})", - process_grid_.world_size(), world_size); - } - } else -#endif - { - if (process_grid_.world_size() != static_cast(local_n)) { - log::throw_with_log( - "DenseDistributed: ProcessGrid world_size ({}) does not match local GPU count ({})", - process_grid_.world_size(), local_n); - } - } - - const int32_3d dims = process_grid_.dims(); - if (dims.x <= 0 || dims.y <= 0 || dims.z <= 0) { - log::throw_with_log( - "DenseDistributed: ProcessGrid dimensions must be positive (dims=({}, {}, {}))", dims.x, - dims.y, dims.z); - } - if (local_n > 1U && (dims.x > 1 || dims.y > 1)) { - log::throw_with_log( - "DenseDistributed: single-process Pencil/Brick with multiple local GPUs is not supported; " - "use MPI with one rank per GPU (local GPUs={}, dims=({}, {}, {}))", - local_n, dims.x, dims.y, dims.z); - } - const int32_3d coords = process_grid_.coords_of(world_rank); - 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. - 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))) { - (void)linear_count_for_slab(static_cast(nx), static_cast(ny), nz); - } - } - } - - 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_); - - spans_ = system_.make_vector([&](size_t i) { - const int32_3d gpu_coords = distributed ? coords : process_grid_.coords_of(static_cast(i)); - const detail::dense_distributed::RankChunk chunk = 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_); - }); - - // 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) { - if (block_override.has_value()) { - return *block_override; - } - return dense_make_kernel_block(system_.gpu_group().devices()[i]); - }); - gpu_grid_per_view_[vi] = system_.make_vector([&](size_t i) { - const detail::Gpu& gpu = system_.gpu_group().devices()[i]; - LaunchShape grid; - detail::compute_dense_grid(spans_[i].iter_extent(view), gpu_block_per_view_[vi][i], - gpu.properties().max_threads_per_block, grid); - return grid; - }); - } -} - -DenseDistributed::DenseDistributed(System system, - int64_3d global_extent, - Stencil stencil, - BoundaryModeDistributed boundary_mode, - float32_3d origin, - float spacing, - std::optional block_override) - : DenseDistributed() { - const int world_size = resolve_world_size(system); - const ProcessGrid pg = - world_size > 0 ? ProcessGrid::make(world_size, DecompositionMode::Slab) : ProcessGrid{}; - init_common_(std::move(system), global_extent, std::move(stencil), boundary_mode, origin, spacing, - pg, block_override); -} - -DenseDistributed::DenseDistributed(System system, - int64_3d global_extent, - DecompositionMode decomposition, - Stencil stencil, - BoundaryModeDistributed boundary_mode, - float32_3d origin, - float spacing, - std::optional block_override) - : DenseDistributed() { - const int world_size = resolve_world_size(system); - const ProcessGrid pg = - world_size > 0 ? ProcessGrid::make(world_size, decomposition) : ProcessGrid{}; - init_common_(std::move(system), global_extent, std::move(stencil), boundary_mode, origin, spacing, - pg, block_override); -} - -DenseDistributed::DenseDistributed(System system, - int64_3d global_extent, - ProcessGrid process_grid, - Stencil stencil, - BoundaryModeDistributed boundary_mode, - float32_3d origin, - float spacing, - std::optional block_override) - : DenseDistributed() { - init_common_(std::move(system), global_extent, std::move(stencil), boundary_mode, origin, spacing, - std::move(process_grid), block_override); -} - -auto -DenseDistributed::process_grid() const noexcept -> const ProcessGrid& { - return process_grid_; -} - -auto -DenseDistributed::local_extent(size_t gpu) const -> int64_3d { - if (gpu >= gpu_count()) { - log::throw_with_log( - "DenseDistributed::local_extent: gpu index out of range (gpu={}, gpu_count={})", gpu, - gpu_count()); - } - return spans_[gpu].logic_extent(); -} - -auto -DenseDistributed::linear_elements(size_t gpu) const -> size_t { - if (gpu >= gpu_count()) { - log::throw_with_log( - "DenseDistributed::linear_elements: gpu index out of range (gpu={}, gpu_count={})", gpu, - gpu_count()); - } - const int64_3d owned = spans_[gpu].logic_extent(); - return linear_count_for_slab(owned.x, owned.y, static_cast(owned.z)); -} - -auto -DenseDistributed::global_extent() const noexcept -> const int64_3d& { - return global_; -} - -auto -DenseDistributed::stencil() const noexcept -> const Stencil& { - return stencil_; -} - -auto -DenseDistributed::boundary_mode() const noexcept -> BoundaryModeDistributed { - return boundary_mode_; -} - -auto -DenseDistributed::origin() const noexcept -> float32_3d { - return origin_; -} - -auto -DenseDistributed::spacing() const noexcept -> float { - return spacing_; -} - -auto -DenseDistributed::system() noexcept -> System& { - return system_; -} - -auto -DenseDistributed::system() const noexcept -> const System& { - return system_; -} - -auto -DenseDistributed::gpu_count() const noexcept -> size_t { - return system_.gpu_group().size(); -} - -auto -DenseDistributed::global_slab_count() const noexcept -> size_t { - return global_slab_count_; -} - -auto -DenseDistributed::local_slab_offset() const noexcept -> size_t { - return local_slab_offset_; -} - -auto -DenseDistributed::local_z(size_t gpu) const -> int64_t { - if (gpu >= gpu_count()) { - log::throw_with_log( - "DenseDistributed::local_z: gpu index out of range (gpu={}, gpu_count={})", gpu, - gpu_count()); - } - return spans_[gpu].logic_extent().z; -} - -auto -DenseDistributed::z_offset_global(size_t gpu) const -> int64_t { - if (gpu >= gpu_count()) { - log::throw_with_log( - "DenseDistributed::z_offset_global: gpu index out of range (gpu={}, gpu_count={})", gpu, - gpu_count()); - } - // Span::z_offset() is the start of the lower halo; the first owned layer is halo_z above it. - return spans_[gpu].z_offset() + spans_[gpu].halo_z(); -} - -auto -DenseDistributed::linear_counts_per_gpu() const -> std::vector { - return system_.make_vector([&](size_t i) { - return linear_elements(i); - }); -} - -} // namespace carbon diff --git a/tests/test_dense_distributed_host.cpp b/tests/test_dense_distributed_host.cpp index 2da0921f..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); From dca087dc2908ce4f8ffb1a240dc7bae5369a1195 Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:09:38 +0100 Subject: [PATCH 14/33] Add atomic_add fix for hip on amd --- docs/CHANGELOG.md | 11 +++ .../carbon/detail/backend/cudalike/atomic.h | 70 ++++++++++++++++++ .../backend/cudalike/block_reduce_kernel.h | 31 +------- .../cudalike/dense_disg_reduce_kernel.h | 31 +------- .../dense_distributed_reduce_kernel.h | 29 +------- .../backend/cudalike/dense_reduce_kernel.h | 29 +------- .../detail/backend/cudalike/reduce_atomic.h | 38 ++++++++++ include/carbon/detail/reduce_kernel_impl.h | 2 +- include/carbon/reduce.h | 10 +-- tests/test_atomic_host.cpp | 64 ++++++++++++++++- tests/test_reduce_atomic.cu | 72 ++++++++++++++++++- 11 files changed, 265 insertions(+), 122 deletions(-) create mode 100644 include/carbon/detail/backend/cudalike/reduce_atomic.h diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index e703d8c4..c26d7379 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6201,3 +6201,14 @@ This unblocked the matrix on this host: the `sycl` and `hip-nvidia` images build 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. 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..dfeec86b 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 ). diff --git a/include/carbon/detail/backend/cudalike/dense_reduce_kernel.h b/include/carbon/detail/backend/cudalike/dense_reduce_kernel.h index b0dce329..2c621d45 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 ). 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/reduce_kernel_impl.h b/include/carbon/detail/reduce_kernel_impl.h index 62329c74..3e480815 100644 --- a/include/carbon/detail/reduce_kernel_impl.h +++ b/include/carbon/detail/reduce_kernel_impl.h @@ -164,7 +164,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) { diff --git a/include/carbon/reduce.h b/include/carbon/reduce.h index 7c016027..9a3e7962 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, 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_reduce_atomic.cu b/tests/test_reduce_atomic.cu index 8a4fb4d1..72a4af20 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,54 @@ 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; + } + // Invalid: Min + BlockAtomic throws at construction. carbon::ReductionResult bad_dst(sys); bool threw = false; From d26b7ccc42c9401a9b129bc82b092da236bd0555 Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Sat, 7 Nov 2026 11:36:05 +0100 Subject: [PATCH 15/33] Fix sycl adp CPU backend --- CMakeLists.txt | 15 ++ examples/distributed/stencil.cu | 208 +++++++++++++++++++++ include/carbon/cpu.h | 16 +- include/carbon/detail/backend/sycl/event.h | 7 + src/gpu_sycl.cpp | 4 +- src/sycl_device_filter.h | 26 +++ src/sycl_stub.cpp | 8 +- 7 files changed, 278 insertions(+), 6 deletions(-) create mode 100644 examples/distributed/stencil.cu create mode 100644 src/sycl_device_filter.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 9162d81a..728e1f2a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -389,6 +389,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 diff --git a/examples/distributed/stencil.cu b/examples/distributed/stencil.cu new file mode 100644 index 00000000..46c3d14b --- /dev/null +++ b/examples/distributed/stencil.cu @@ -0,0 +1,208 @@ +// scalar_mul_distributed.cu +// +// Minimal correctness test for the 3D domain decomposition of +// carbon::DenseDistributed (slab | pencil | brick). +// +// 1. takes the decomposition type as input: slab | pencil | brick +// 2. builds a carbon::DenseDistributed grid on a 7-point stencil +// (the stencil is what drives the per-axis halo the decomposition honours) +// 3. runs one trivial kernel through carbon::Skeleton: y = a * x +// 4. verifies with a global Sum reduction (rank-invariant): +// SUM(y) == a * N^3 +// which can only hold if the owned cells tile the global domain exactly +// once and the kernel touched every owned cell (no overlap, no gaps). +// +// Usage: +// ./scalar_mul_distributed slab # single process, local GPUs +// mpirun -np 4 ./scalar_mul_distributed pencil # MPI, 4 ranks +// mpirun -np 8 ./scalar_mul_distributed brick --n 128 --scalar 0.25 +// +// Exit code: 0 = PASS, 1 = FAIL. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef CARBON_HAVE_MPI_NCCL +# include +#endif + +#include +#include +#include +#include +#include + +namespace { + +[[nodiscard]] auto +decomposition_mode(std::string_view 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); +} + +} // namespace + +int +main(int argc, +char** argv) { + // ---- CLI: [--n 64] [--scalar 0.5] ------------------------------ + std::string dec = "slab"; + int64_t n = 64; + float scalar = 0.5f; // power of two => the checksum below is exact even in float + 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] [--scalar A]\n"; + return EXIT_SUCCESS; + } + if ((a == "--n" || a == "--scalar") && i + 1 < argc) { + if (a == "--n") { + n = std::stoll(argv[++i]); + } else { + scalar = std::stof(argv[++i]); + } + } else if (a[0] != '-') { + dec = a; + } + } + if (n < 4) { + std::cerr << "error: --n must be >= 4 (got " << n << ")\n"; + return EXIT_FAILURE; + } + const auto dec_mode = decomposition_mode(dec); + + carbon::init(); + if (carbon::device_count() <= 0) { + CARBON_LOG_ERROR("scalar_mul_distributed: no CUDA devices visible"); + return EXIT_FAILURE; + } + + // ---- System bootstrap (same pattern as the LBM benchmark) ------------------------------ +#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()); + const bool use_mpi = false; +#endif + + // ---- 7-point stencil -> per-axis halo for the chosen 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::int64_3d global{n, n, n}; + + // Auto-factorised process grid: + // slab: 1 x 1 x R pencil: 1 x sqrt x sqrt brick: cbrt x cbrt x cbrt + const carbon::ProcessGrid pg = carbon::ProcessGrid::make(world_size, dec_mode); + if (world_rank == 0) { + const auto d = pg.dims(); + CARBON_LOG_INFO("scalar_mul_distributed: N={} decomposition={} process_grid={}x{}x{} " + "world_size={} {}", + n, dec, d.x, d.y, d.z, world_size, use_mpi ? "(mpi+nccl)" : "(in-process)"); + } + + carbon::DenseDistributed grid(sys, global, pg, stencil); + using Span = typename carbon::DenseDistributed::Span; + using Idx = typename carbon::DenseDistributed::Idx; + + auto fIn = grid.template newField(carbon::MemorySide::HostDevice, "x"); + auto fOut = grid.template newField(carbon::MemorySide::HostDevice, "y"); + + // Seed every owned cell with 1.0 (halo cells stay zero-initialised). + fIn.fill_owned_host([](carbon::int64_3d, int) -> float { return 1.0f; }); + { + carbon::Stream s = sys.stream(); + carbon::Transfer(sys, fIn.cpu_buffers(), fIn.gpu_buffers())(s); + s.wait(); + } + + // ---- the kernel: y = a * x on every owned cell ---------------------------------------- + // The *read* side is the exact pattern from the LBM benchmark's checksum kernel + // (loader.read + .read(s, idx, comp)); the write side is its mirror. + carbon::Skeleton sk(sys); + sk.add(carbon::Kernel::map( // (1) builder name TBC against carbon/kernel.h + grid, + [&](carbon::KernelLoader& loader) { + const auto xin = loader.read(fIn); + const auto yout = loader.write(fOut); // (2) TBC + return [xin, yout, scalar] CARBON_HOST_DEVICE(Span s, Idx idx) { + yout.write(s, idx, 0, scalar * xin.read(s, idx, 0)); // (3) TBC + }; + }, + "scalar_mul"); + + try { + sk.compile(); + sk.run(); + sk.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("scalar_mul_distributed: kernel failed: {}", e.what()); + return EXIT_FAILURE; + } + + // ---- verification: global checksum (rank-invariant) ------------------------------------- + // Every owned cell contributes exactly `scalar`, so SUM(y) == a * N^3 iff the owned cells + // tile the global domain exactly once and the kernel ran on all of them. + carbon::ReductionResult sum_y(sys); + carbon::Skeleton chk(sys); + chk.add(carbon::Kernel::reduce( + grid, + [&](carbon::KernelLoader& loader) { + const auto yin = loader.read(fOut); + return [yin] CARBON_HOST_DEVICE(Span s, Idx idx) -> double { + return static_cast(yin.read(s, idx, 0)); + }; + }, + sum_y, carbon::reduce::Sum{}, "checksum_y", /*shared_mem=*/0U)); + try { + chk.compile(); + chk.run(); + chk.wait(); + sum_y.sync(sys.stream()); + sys.stream().wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("scalar_mul_distributed: checksum failed: {}", e.what()); + return EXIT_FAILURE; + } + + const double got = sum_y.host_value(); + const double expected = static_cast(scalar) * static_cast(n) * n * n; + const double rel = std::abs(got - expected) / std::max(1.0, std::abs(expected)); + if (world_rank == 0) { + std::cout << "decomposition=" << dec << " SUM(y)=" << got << " expected=" << expected << '\n'; + } + if (rel > 1e-9) { + CARBON_LOG_ERROR("scalar_mul_distributed: FAIL (decomposition={}) got={} expected={}", dec, + got, expected); + return EXIT_FAILURE; + } + if (world_rank == 0) { + std::cout << "PASS (decomposition=" << dec << " N=" << n << " ranks=" << world_size << ")\n"; + } + return EXIT_SUCCESS; +} \ No newline at end of file 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/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/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) { From f5ec6b233c8f50e0b630ed96ca13f976f29115a2 Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Sat, 7 Nov 2026 16:30:59 +0100 Subject: [PATCH 16/33] Add MPI backend for sycl-cpu offloading --- CMakeLists.txt | 36 ++-- examples/CMakeLists.txt | 6 + examples/distributed/stencil.cu | 208 -------------------- examples/distributed/stencil_axpy.cu | 281 +++++++++++++++++++++++++++ include/carbon/reduce.h | 26 ++- src/communicator.cpp | 21 +- src/communicator_internal.h | 2 + src/dist_reduce.cpp | 26 +++ src/dist_transfer.cpp | 12 +- src/gpu_runtime_compat.h | 42 +++- 10 files changed, 433 insertions(+), 227 deletions(-) delete mode 100644 examples/distributed/stencil.cu create mode 100644 examples/distributed/stencil_axpy.cu diff --git a/CMakeLists.txt b/CMakeLists.txt index 728e1f2a..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}") @@ -484,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 @@ -532,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") @@ -562,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 @@ -602,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/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.cu b/examples/distributed/stencil.cu deleted file mode 100644 index 46c3d14b..00000000 --- a/examples/distributed/stencil.cu +++ /dev/null @@ -1,208 +0,0 @@ -// scalar_mul_distributed.cu -// -// Minimal correctness test for the 3D domain decomposition of -// carbon::DenseDistributed (slab | pencil | brick). -// -// 1. takes the decomposition type as input: slab | pencil | brick -// 2. builds a carbon::DenseDistributed grid on a 7-point stencil -// (the stencil is what drives the per-axis halo the decomposition honours) -// 3. runs one trivial kernel through carbon::Skeleton: y = a * x -// 4. verifies with a global Sum reduction (rank-invariant): -// SUM(y) == a * N^3 -// which can only hold if the owned cells tile the global domain exactly -// once and the kernel touched every owned cell (no overlap, no gaps). -// -// Usage: -// ./scalar_mul_distributed slab # single process, local GPUs -// mpirun -np 4 ./scalar_mul_distributed pencil # MPI, 4 ranks -// mpirun -np 8 ./scalar_mul_distributed brick --n 128 --scalar 0.25 -// -// Exit code: 0 = PASS, 1 = FAIL. - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef CARBON_HAVE_MPI_NCCL -# include -#endif - -#include -#include -#include -#include -#include - -namespace { - -[[nodiscard]] auto -decomposition_mode(std::string_view 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); -} - -} // namespace - -int -main(int argc, -char** argv) { - // ---- CLI: [--n 64] [--scalar 0.5] ------------------------------ - std::string dec = "slab"; - int64_t n = 64; - float scalar = 0.5f; // power of two => the checksum below is exact even in float - 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] [--scalar A]\n"; - return EXIT_SUCCESS; - } - if ((a == "--n" || a == "--scalar") && i + 1 < argc) { - if (a == "--n") { - n = std::stoll(argv[++i]); - } else { - scalar = std::stof(argv[++i]); - } - } else if (a[0] != '-') { - dec = a; - } - } - if (n < 4) { - std::cerr << "error: --n must be >= 4 (got " << n << ")\n"; - return EXIT_FAILURE; - } - const auto dec_mode = decomposition_mode(dec); - - carbon::init(); - if (carbon::device_count() <= 0) { - CARBON_LOG_ERROR("scalar_mul_distributed: no CUDA devices visible"); - return EXIT_FAILURE; - } - - // ---- System bootstrap (same pattern as the LBM benchmark) ------------------------------ -#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()); - const bool use_mpi = false; -#endif - - // ---- 7-point stencil -> per-axis halo for the chosen 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::int64_3d global{n, n, n}; - - // Auto-factorised process grid: - // slab: 1 x 1 x R pencil: 1 x sqrt x sqrt brick: cbrt x cbrt x cbrt - const carbon::ProcessGrid pg = carbon::ProcessGrid::make(world_size, dec_mode); - if (world_rank == 0) { - const auto d = pg.dims(); - CARBON_LOG_INFO("scalar_mul_distributed: N={} decomposition={} process_grid={}x{}x{} " - "world_size={} {}", - n, dec, d.x, d.y, d.z, world_size, use_mpi ? "(mpi+nccl)" : "(in-process)"); - } - - carbon::DenseDistributed grid(sys, global, pg, stencil); - using Span = typename carbon::DenseDistributed::Span; - using Idx = typename carbon::DenseDistributed::Idx; - - auto fIn = grid.template newField(carbon::MemorySide::HostDevice, "x"); - auto fOut = grid.template newField(carbon::MemorySide::HostDevice, "y"); - - // Seed every owned cell with 1.0 (halo cells stay zero-initialised). - fIn.fill_owned_host([](carbon::int64_3d, int) -> float { return 1.0f; }); - { - carbon::Stream s = sys.stream(); - carbon::Transfer(sys, fIn.cpu_buffers(), fIn.gpu_buffers())(s); - s.wait(); - } - - // ---- the kernel: y = a * x on every owned cell ---------------------------------------- - // The *read* side is the exact pattern from the LBM benchmark's checksum kernel - // (loader.read + .read(s, idx, comp)); the write side is its mirror. - carbon::Skeleton sk(sys); - sk.add(carbon::Kernel::map( // (1) builder name TBC against carbon/kernel.h - grid, - [&](carbon::KernelLoader& loader) { - const auto xin = loader.read(fIn); - const auto yout = loader.write(fOut); // (2) TBC - return [xin, yout, scalar] CARBON_HOST_DEVICE(Span s, Idx idx) { - yout.write(s, idx, 0, scalar * xin.read(s, idx, 0)); // (3) TBC - }; - }, - "scalar_mul"); - - try { - sk.compile(); - sk.run(); - sk.wait(); - } catch (const std::exception& e) { - CARBON_LOG_ERROR("scalar_mul_distributed: kernel failed: {}", e.what()); - return EXIT_FAILURE; - } - - // ---- verification: global checksum (rank-invariant) ------------------------------------- - // Every owned cell contributes exactly `scalar`, so SUM(y) == a * N^3 iff the owned cells - // tile the global domain exactly once and the kernel ran on all of them. - carbon::ReductionResult sum_y(sys); - carbon::Skeleton chk(sys); - chk.add(carbon::Kernel::reduce( - grid, - [&](carbon::KernelLoader& loader) { - const auto yin = loader.read(fOut); - return [yin] CARBON_HOST_DEVICE(Span s, Idx idx) -> double { - return static_cast(yin.read(s, idx, 0)); - }; - }, - sum_y, carbon::reduce::Sum{}, "checksum_y", /*shared_mem=*/0U)); - try { - chk.compile(); - chk.run(); - chk.wait(); - sum_y.sync(sys.stream()); - sys.stream().wait(); - } catch (const std::exception& e) { - CARBON_LOG_ERROR("scalar_mul_distributed: checksum failed: {}", e.what()); - return EXIT_FAILURE; - } - - const double got = sum_y.host_value(); - const double expected = static_cast(scalar) * static_cast(n) * n * n; - const double rel = std::abs(got - expected) / std::max(1.0, std::abs(expected)); - if (world_rank == 0) { - std::cout << "decomposition=" << dec << " SUM(y)=" << got << " expected=" << expected << '\n'; - } - if (rel > 1e-9) { - CARBON_LOG_ERROR("scalar_mul_distributed: FAIL (decomposition={}) got={} expected={}", dec, - got, expected); - return EXIT_FAILURE; - } - if (world_rank == 0) { - std::cout << "PASS (decomposition=" << dec << " N=" << n << " ranks=" << world_size << ")\n"; - } - return EXIT_SUCCESS; -} \ No newline at end of file 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/reduce.h b/include/carbon/reduce.h index 9a3e7962..745ab885 100644 --- a/include/carbon/reduce.h +++ b/include/carbon/reduce.h @@ -732,10 +732,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 +777,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/dist_reduce.cpp b/src/dist_reduce.cpp index d9ed377c..655c7259 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); @@ -222,6 +247,7 @@ dist_allreduce_in_place(const System& sys, }); 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; From ebbc5f51f1358a5a9cec7fd4d0577ae0840e09f0 Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Sat, 7 Nov 2026 20:56:12 +0100 Subject: [PATCH 17/33] 3D reducee with docs/reduce-2d-stage1-yz-fix-report.md --- docs/CHANGELOG.md | 12 ++ docs/reduce-2d-stage1-yz-fix-report.md | 190 ++++++++++++++++++ .../dense_distributed_reduce_kernel.h | 23 ++- .../dense_distributed_reduce_launch.h | 46 +---- .../backend/cudalike/dense_reduce_kernel.h | 23 ++- .../backend/cudalike/dense_reduce_launch.h | 46 +---- include/carbon/detail/launch_traits.h | 10 +- include/carbon/detail/reduce_kernel_impl.h | 45 +++-- include/carbon/reduce.h | 16 +- tests/test_dense_distributed_dist.cu | 94 +++++++++ tests/test_reduce_atomic.cu | 21 ++ tests/test_reduce_sum.cu | 85 ++++++++ 12 files changed, 496 insertions(+), 115 deletions(-) create mode 100644 docs/reduce-2d-stage1-yz-fix-report.md diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index c26d7379..34533701 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6212,3 +6212,15 @@ This unblocked the matrix on this host: the `sycl` and `hip-nvidia` images build 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. 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/include/carbon/detail/backend/cudalike/dense_distributed_reduce_kernel.h b/include/carbon/detail/backend/cudalike/dense_distributed_reduce_kernel.h index dfeec86b..a9b1ed7e 100644 --- a/include/carbon/detail/backend/cudalike/dense_distributed_reduce_kernel.h +++ b/include/carbon/detail/backend/cudalike/dense_distributed_reduce_kernel.h @@ -133,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); } @@ -193,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 2c621d45..6a147984 100644 --- a/include/carbon/detail/backend/cudalike/dense_reduce_kernel.h +++ b/include/carbon/detail/backend/cudalike/dense_reduce_kernel.h @@ -133,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); } @@ -193,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/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 3e480815..5aee083b 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 @@ -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) { @@ -671,11 +681,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 745ab885..5ab74562 100644 --- a/include/carbon/reduce.h +++ b/include/carbon/reduce.h @@ -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; }; 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_reduce_atomic.cu b/tests/test_reduce_atomic.cu index 72a4af20..6803ceb9 100644 --- a/tests/test_reduce_atomic.cu +++ b/tests/test_reduce_atomic.cu @@ -226,6 +226,27 @@ main() { 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; } From 543bdd64431dffb11ef3954f8a9024a4293347ce Mon Sep 17 00:00:00 2001 From: Giulio Malenza <90334113+giumal@users.noreply.github.com> Date: Sat, 7 Nov 2026 21:49:18 +0100 Subject: [PATCH 18/33] add split reduction in SYCL --- docs/CHANGELOG.md | 14 ++++++++ include/carbon/detail/reduce_kernel_impl.h | 41 +++++++++++++++++++++- src/dist_reduce.cpp | 14 ++++---- tests/test_skeleton_reduce_split.cu | 16 ++++----- 4 files changed, 70 insertions(+), 15 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 34533701..b6d1461e 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6224,3 +6224,17 @@ This unblocked the matrix on this host: the `sycl` and `hip-nvidia` images build `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/include/carbon/detail/reduce_kernel_impl.h b/include/carbon/detail/reduce_kernel_impl.h index 5aee083b..e86dd64f 100644 --- a/include/carbon/detail/reduce_kernel_impl.h +++ b/include/carbon/detail/reduce_kernel_impl.h @@ -615,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 } diff --git a/src/dist_reduce.cpp b/src/dist_reduce.cpp index 655c7259..20b8d209 100644 --- a/src/dist_reduce.cpp +++ b/src/dist_reduce.cpp @@ -222,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)); }; @@ -233,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 @@ -245,7 +248,6 @@ dist_allreduce_in_place(const System& sys, #endif }); }); - q.wait_and_throw(); #endif #endif // !CARBON_DIST_HOST_MPI } 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 {}", From a9507410f00c966a23219e6e57d2aa61bb1ffb1c Mon Sep 17 00:00:00 2001 From: Massimiliano Meneghin Date: Fri, 6 Nov 2026 03:22:49 -0500 Subject: [PATCH 19/33] Distributed LBM strong-scaling sweep; benchmark --reps, barrier timing, process_grid Add lbm-dist-sweep-run.sh + lbm-dist-sweep.yml (N x GPUs x slab/pencil/brick x NCCL/MPI-P2P x --hp-halo off/on, plus a 1-GPU ref run per N), the plot_dist_scaling.py plotter and data/lbm-dist-sweep/reproduce.sh. The distributed benchmark gains --reps with results.repetitions, timing marks taken after a GPU drain plus Distributed::barrier(), and config.process_grid. lbm_sweep_config.py loaders take optional key/choice tables. Co-authored-by: Cursor --- .../scripts/lbm_sweep_config.py | 43 ++- .../data/lbm-dist-sweep/lbm-dist-sweep.yml | 76 ++++ .../data/lbm-dist-sweep/reproduce.sh | 46 +++ .../lbm_lid_driven_cavity_distributed.cu | 108 +++++- .../scripts/lbm-dist-sweep-run.sh | 248 +++++++++++++ .../scripts/lbm-dist-sweep.yml | 76 ++++ .../scripts/lbm_dist_sweep_config.py | 78 ++++ .../scripts/plotting/plot_dist_scaling.py | 336 ++++++++++++++++++ docs/CHANGELOG.md | 18 + 9 files changed, 1007 insertions(+), 22 deletions(-) create mode 100644 benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep.yml create mode 100755 benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/reproduce.sh create mode 100755 benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep-run.sh create mode 100644 benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep.yml create mode 100755 benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm_dist_sweep_config.py create mode 100755 benchmarks/lbm_lid_driven_cavity_distributed/scripts/plotting/plot_dist_scaling.py diff --git a/benchmarks/lbm_lid_driven_cavity/scripts/lbm_sweep_config.py b/benchmarks/lbm_lid_driven_cavity/scripts/lbm_sweep_config.py index 75e34fc4..038d37ea 100644 --- a/benchmarks/lbm_lid_driven_cavity/scripts/lbm_sweep_config.py +++ b/benchmarks/lbm_lid_driven_cavity/scripts/lbm_sweep_config.py @@ -74,7 +74,7 @@ def _as_list(key: str, v: object) -> list: return [v] -def _parse_value(key: str, kind: str, value: object) -> object: +def _parse_value(key: str, kind: str, value: object, choices: dict[str, set[str]]) -> object: if kind == "int": return _as_int(key, value) if kind == "bool": @@ -98,32 +98,44 @@ def _parse_value(key: str, kind: str, value: object) -> object: for x in items: if not isinstance(x, str) or not pattern.match(x): raise SweepConfigError(f"{key} has an invalid value {x!r}") - if key in CHOICES and x not in CHOICES[key]: - raise SweepConfigError(f"{key} value {x!r} not in {sorted(CHOICES[key])}") + if key in choices and x not in choices[key]: + raise SweepConfigError(f"{key} value {x!r} not in {sorted(choices[key])}") return items if kind == "words" else items[0] -def load_sweep_config(text: str) -> dict[str, object]: - """Validate YAML text; returns every key in ``KEYS``, omitted ones at their default.""" +def load_sweep_config( + text: str, + keys: dict[str, tuple[str, str, object]] = KEYS, + choices: dict[str, set[str]] = CHOICES, +) -> dict[str, object]: + """Validate YAML text; returns every key in ``keys``, omitted ones at their default. + + ``keys`` / ``choices`` default to this sweep's tables; other sweeps (e.g. the + distributed benchmark's) pass their own in the same format. + """ import yaml cfg = yaml.safe_load(text) or {} if not isinstance(cfg, dict): raise SweepConfigError("top level must be a mapping") - out = {key: default for key, (_, _, default) in KEYS.items()} + out = {key: default for key, (_, _, default) in keys.items()} for key, value in cfg.items(): - if key not in KEYS: - raise SweepConfigError(f"unknown key {key!r} (known: {', '.join(KEYS)})") - out[key] = _parse_value(key, KEYS[key][1], value) + if key not in keys: + raise SweepConfigError(f"unknown key {key!r} (known: {', '.join(keys)})") + out[key] = _parse_value(key, keys[key][1], value, choices) return out -def read_sweep_config(path: Path) -> dict[str, object]: +def read_sweep_config( + path: Path, + keys: dict[str, tuple[str, str, object]] = KEYS, + choices: dict[str, set[str]] = CHOICES, +) -> dict[str, object]: """Load a sweep YAML file; the path must be an existing ``.yml`` / ``.yaml`` file.""" path = Path(path).resolve() if path.suffix not in (".yml", ".yaml") or not path.is_file(): raise SweepConfigError(f"not a .yml/.yaml file: {path}") - return load_sweep_config(path.read_text()) + return load_sweep_config(path.read_text(), keys, choices) def series_prefixes(cfg: dict[str, object]) -> list[tuple[str, str, str, str]]: @@ -151,13 +163,16 @@ def _shell_value(kind: str, value: object) -> str: return str(value) -def main() -> int: +def main( + keys: dict[str, tuple[str, str, object]] = KEYS, + choices: dict[str, set[str]] = CHOICES, +) -> int: try: - cfg = load_sweep_config(os.environ.get("LBM_SWEEP_CONFIG", "")) + cfg = load_sweep_config(os.environ.get("LBM_SWEEP_CONFIG", ""), keys, choices) except SweepConfigError as e: sys.stderr.write(f"error: config: {e}\n") return 1 - for key, (var, kind, _) in KEYS.items(): + for key, (var, kind, _) in keys.items(): print(f"{var}={_shell_value(kind, cfg[key])}") return 0 diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep.yml b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep.yml new file mode 100644 index 00000000..23e62de6 --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/lbm-dist-sweep.yml @@ -0,0 +1,76 @@ +# Sweep configuration for lbm-dist-sweep-run.sh and its plotter. +# +# ./benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep-run.sh \ +# benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep.yml +# python3 benchmarks/lbm_lid_driven_cavity_distributed/scripts/plotting/plot_dist_scaling.py \ +# --config benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep.yml +# +# Every run uses --grid dense_distributed under mpiexec, one rank per GPU. +# Every key is optional; omitted keys use the script defaults, and an env var +# of the same name in upper case (CONFIGS, SIZES, GPUS_LIST, ...) overrides +# the file. + +# Lattice:collision pairs, each its own series (populations are always fp32): +# q19:bgk D3Q19 + BGK +# q27:bgk D3Q27 + BGK +# q27:kbc D3Q27 + KBC (KBC is only implemented for D3Q27) +configs: [q19:bgk] + +# Domain edge lengths N: a list, or an inclusive {start, stop, step} range. +sizes: {start: 256, stop: 512, step: 64} + +# GPU counts (= MPI ranks). The 1-GPU point is a single "ref" run per size +# (every decomposition is 1x1x1 there) and is the efficiency baseline. +# ProcessGrid factorises the rank count, so for prime counts (2, 3, 5, 7) +# pencil and brick fall back to a slab, and brick at 4 is a pencil; the +# plots print the process grid under each GPU count. +gpus: {start: 1, stop: 8, step: 1} + +# Process decompositions, one plot panel each: +# slab split z +# pencil split y and z +# brick split x, y and z +decompositions: [slab, pencil, brick] + +# Halo transports, one curve each: +# mpi NCCL (default) +# mpip2p MPI point-to-point (CARBON_DIST_TRANSPORT=mpi) +transports: [mpi] + +# Halo stream priority, one curve each: off = normal priority, on = --hp-halo +# (Skeleton halo_stream_priority = High). Only meaningful with overlap != none. +hp_halo: ["off", "on"] + +# Skeleton OCC mode of every run: none, standard, extended, twoway-extended. +overlap: standard + +# Timing: warmup untimed solver steps, then reps repetitions of +# iters_per_rep solver steps, each closed by a GPU drain and an MPI barrier. +warmup: 400 +iters_per_rep: 1000 +reps: 5 + +# CUDA compute capability the binary is compiled for +# (CMAKE_CUDA_ARCHITECTURES). auto detects it from the GPUs via nvidia-smi. +# Changing it needs a rebuild, so keep skip_build: false for that run. +sm_arch: auto + +# Docker image that builds the binary and does every run. Its NCCL must match +# the host driver: carbon-cuda:local ships an NCCL that needs driver >= 580, +# carbon-cuda-nccl-pinned:local pins NCCL 2.27.7 (CUDA 12.2). +image: carbon-cuda-nccl-pinned:local + +# CUDA+MPI build tree, relative to the carbon repo root. Kept apart from the +# single-process sweep's build-mpi/, which is configured in another image. +build_dir: build-dist + +# Report prefix and output folder: +# benchmarks/lbm_lid_driven_cavity_distributed/data//json/ +prefix: lbm-dist-sweep + +# true reuses the existing build tree; false (re)builds it first. +skip_build: false +# true redoes runs whose JSON already exists; false skips them (resume). +force: true +# Per-run timeout in seconds; a hung run is logged in failed.txt. +run_timeout: 1800 diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/reproduce.sh b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/reproduce.sh new file mode 100755 index 00000000..00261376 --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/reproduce.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# +# benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/reproduce.sh +# +# Reproduces this result set: runs the sweep described by lbm-dist-sweep.yml +# (the frozen copy next to this script) and renders every plot in this folder. +# +# D3Q19 + BGK, fp32, --grid dense_distributed, --overlap standard; +# N = 256..512 step 64; 1..8 GPUs (one MPI rank each); slab, pencil and +# brick decompositions; NCCL halos with --hp-halo off and on; +# 400 warmup steps, then 5 timed repetitions of 1000 solver steps. +# +# Usage: +# ./benchmarks/lbm_lid_driven_cavity_distributed/data/lbm-dist-sweep/reproduce.sh [--plot-only] +# +# (no flag) build build-dist/ in Docker, redo every run (force: true +# overwrites json/), then plot; takes about two hours on 8 GPUs +# --plot-only only re-render the PNGs from the reports already in json/ +# +# Needs docker with the NVIDIA container toolkit, the image named in the yml, +# and python3 with PyYAML and matplotlib. Run it from tmux (or similar) because +# the sweep outlives an SSH session. + +set -euo pipefail + +plot_only=0 +case "${1:-}" in + "") ;; + --plot-only) plot_only=1 ;; + *) + echo "usage: $0 [--plot-only]" >&2 + exit 2 + ;; +esac + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +repo_root="$(cd "${here}/../../../.." && pwd)" +scripts="${repo_root}/benchmarks/lbm_lid_driven_cavity_distributed/scripts" +config="${here}/lbm-dist-sweep.yml" + +if [[ "${plot_only}" -eq 0 ]]; then + "${scripts}/lbm-dist-sweep-run.sh" "${config}" +fi + +python3 "${scripts}/plotting/plot_dist_scaling.py" --config "${config}" --output-dir "${here}" +echo "==> plots written to ${here}" diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu b/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu index 4486cad6..7dd74c4b 100644 --- a/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu +++ b/benchmarks/lbm_lid_driven_cavity_distributed/lbm_lid_driven_cavity_distributed.cu @@ -55,6 +55,7 @@ #include +#include #include #include #include @@ -108,6 +109,7 @@ struct Options { int64_t n = 128; int64_t iters = 1000; int64_t warmup = 100; + int64_t reps = 1; double re = 100.0; double ulb = 0.05; bool ulb_set = false; @@ -175,6 +177,10 @@ build_cli(Options& opts) -> clipp::group { "Total iterations including warmup (default 1000)", (option("--warmup") & integer("warmup", opts.warmup)) % "Warmup iterations excluded from timing (default 100)", + (option("--reps") & integer("reps", opts.reps)) % + "Split the timed iterations into N equal repetitions, each closed by a GPU drain " + "and (under MPI) a barrier, and report per-repetition MLUPS plus " + "mean/min/max/stddev (default 1). Timed iterations must divide by N.", (option("--re") & number("re", opts.re)) % "Reynolds number (default 1e2)", (option("--ulb") & number("ulb", opts.ulb).set(opts.ulb_set)) % "Override lid velocity in lattice units (default 0.05)", @@ -257,6 +263,12 @@ parse_cli(int argc, << " for iters=" << opts.iters << ")\n"; return false; } + const int64_t timed_iters = opts.no_warmup_skip ? opts.iters : opts.iters - opts.warmup; + if (opts.reps < 1 || timed_iters % opts.reps != 0) { + std::cerr << "lbm_lid_driven_cavity: --reps must be >= 1 and divide the " << timed_iters + << " timed iterations (got " << opts.reps << ")\n"; + return false; + } if (opts.lattice != "q19" && opts.lattice != "q27") { std::cerr << "lbm_lid_driven_cavity: --lattice must be q19 or q27 (got '" << opts.lattice << "')\n"; @@ -683,22 +695,50 @@ run_benchmark(const Options& opts, using Clock = std::chrono::steady_clock; using Seconds = std::chrono::duration; const int64_t timed_start = opts.no_warmup_skip ? 0 : opts.warmup; + const int64_t iters_per_rep = (opts.iters - timed_start) / opts.reps; + + // Every timing mark is taken after all ranks drained, so rank 0's window spans the + // slowest rank and the reported MLUPS is a true global figure. + auto drain_all_ranks = [&]() { + sk_ab.wait(); + sk_ba.wait(); +#ifdef CARBON_HAVE_MPI_NCCL + if (use_mpi) { + distributed->barrier(); + } +#endif + }; Clock::time_point timing_started{}; + Clock::time_point rep_started{}; Clock::time_point overall_started = Clock::now(); bool timing_running = false; + std::vector rep_seconds; + rep_seconds.reserve(static_cast(opts.reps)); for (int64_t it = 0; it < opts.iters; ++it) { + if (it > timed_start && (it - timed_start) % iters_per_rep == 0) { + try { + drain_all_ranks(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("lbm_lid_driven_cavity: repetition drain failed at iter {}: {}", it, + e.what()); + return EXIT_FAILURE; + } + const auto now = Clock::now(); + rep_seconds.push_back(Seconds(now - rep_started).count()); + rep_started = now; + } if (it == timed_start) { try { - sk_ab.wait(); - sk_ba.wait(); + drain_all_ranks(); } catch (const std::exception& e) { CARBON_LOG_ERROR("lbm_lid_driven_cavity: pre-timing drain failed at iter {}: {}", it, e.what()); return EXIT_FAILURE; } timing_started = Clock::now(); + rep_started = timing_started; timing_running = true; if (!opts.no_warmup_skip) { CARBON_LOG_INFO("lbm_lid_driven_cavity: warmup complete ({} iters), starting timing window", @@ -733,8 +773,7 @@ run_benchmark(const Options& opts, } try { - sk_ab.wait(); - sk_ba.wait(); + drain_all_ranks(); } catch (const std::exception& e) { CARBON_LOG_ERROR("lbm_lid_driven_cavity: final sync failed: {}", e.what()); return EXIT_FAILURE; @@ -754,10 +793,32 @@ run_benchmark(const Options& opts, const double mlups = (cells_per_iter * static_cast(timed_iters)) / (1.0e6 * timing_seconds); const double overall_seconds = Seconds(timing_ended - overall_started).count(); + rep_seconds.push_back(Seconds(timing_ended - rep_started).count()); - // Under MPI all ranks measure the same `cells_per_iter` (= global N^3) and - // run lock-step (halo exchanges synchronise them), so each rank's `mlups` - // is the global throughput up to small per-rank timing noise. Print only on + std::vector rep_mlups; + rep_mlups.reserve(rep_seconds.size()); + for (const double s : rep_seconds) { + rep_mlups.push_back((cells_per_iter * static_cast(iters_per_rep)) / (1.0e6 * s)); + } + double rep_mlups_mean = 0.0; + double rep_mlups_min = rep_mlups.front(); + double rep_mlups_max = rep_mlups.front(); + for (const double m : rep_mlups) { + rep_mlups_mean += m; + rep_mlups_min = std::min(rep_mlups_min, m); + rep_mlups_max = std::max(rep_mlups_max, m); + } + rep_mlups_mean /= static_cast(rep_mlups.size()); + double rep_mlups_var = 0.0; + for (const double m : rep_mlups) { + rep_mlups_var += (m - rep_mlups_mean) * (m - rep_mlups_mean); + } + const double rep_mlups_stddev = + rep_mlups.size() > 1 ? std::sqrt(rep_mlups_var / static_cast(rep_mlups.size() - 1)) + : 0.0; + + // Under MPI all ranks measure the same `cells_per_iter` (= global N^3) between the + // same barriers, so each rank's `mlups` is the global throughput. Print only on // rank 0 to keep the scrape-friendly headline single-shot. `total_gpu_count` // is the world size under MPI (one rank per GPU) and the local GPU count // otherwise; `local_gpu_count` stays useful on multi-GPU single-process runs. @@ -774,6 +835,12 @@ run_benchmark(const Options& opts, << " ranks=" << world_size << " decomposition=" << decomposition_mode_name(dec_mode) << " lattice=" << lattice_name << " collision=" << collision_name << (use_mpi ? " transport=mpi+nccl" : "") << ")" << '\n'; + if (opts.reps > 1) { + CARBON_LOG_INFO( + "lbm_lid_driven_cavity: {} repetitions x {} iters => MLUPS mean={:.2f} min={:.2f} " + "max={:.2f} stddev={:.2f}", + opts.reps, iters_per_rep, rep_mlups_mean, rep_mlups_min, rep_mlups_max, rep_mlups_stddev); + } } // Optional grid-family parity checksum: Sum-reduce the whole final population @@ -924,10 +991,17 @@ run_benchmark(const Options& opts, out << " \"n\": " << opts.n << ",\n"; out << " \"iters\": " << opts.iters << ",\n"; out << " \"warmup\": " << opts.warmup << ",\n"; + out << " \"reps\": " << opts.reps << ",\n"; out << " \"lattice\": \"" << json_escape(lattice_name) << "\",\n"; out << " \"collision\": \"" << json_escape(collision_name) << "\",\n"; out << " \"grid\": \"" << json_escape(opts.grid) << "\",\n"; out << " \"decomposition\": \"" << decomposition_mode_name(dec_mode) << "\",\n"; + if (pg) { + const carbon::int32_3d dims = pg->dims(); + out << " \"process_grid\": [" << dims.x << ", " << dims.y << ", " << dims.z << "],\n"; + } else { + out << " \"process_grid\": null,\n"; + } out << " \"q\": " << Lattice::Q << ",\n"; out << " \"re\": " << opts.re << ",\n"; out << " \"ulb\": " << ulb << ",\n"; @@ -980,7 +1054,25 @@ run_benchmark(const Options& opts, out << " \"cells_per_iter\": " << static_cast(cells_per_iter) << ",\n"; out << " \"mlups\": " << mlups << ",\n"; out << " \"mlups_per_gpu\": " << (mlups / static_cast(total_gpu_count)) << ",\n"; - out << " \"effective_bandwidth_gb_s\": " << effective_bandwidth_gb_s << "\n"; + out << " \"effective_bandwidth_gb_s\": " << effective_bandwidth_gb_s << ",\n"; + out << " \"repetitions\": {\n"; + out << " \"count\": " << opts.reps << ",\n"; + out << " \"iters_per_rep\": " << iters_per_rep << ",\n"; + out << " \"seconds\": ["; + for (size_t i = 0; i < rep_seconds.size(); ++i) { + out << (i == 0 ? "" : ", ") << rep_seconds[i]; + } + out << "],\n"; + out << " \"mlups\": ["; + for (size_t i = 0; i < rep_mlups.size(); ++i) { + out << (i == 0 ? "" : ", ") << rep_mlups[i]; + } + out << "],\n"; + out << " \"mlups_mean\": " << rep_mlups_mean << ",\n"; + out << " \"mlups_min\": " << rep_mlups_min << ",\n"; + out << " \"mlups_max\": " << rep_mlups_max << ",\n"; + out << " \"mlups_stddev\": " << rep_mlups_stddev << "\n"; + out << " }\n"; out << " }\n"; out << "}\n"; out.close(); diff --git a/benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep-run.sh b/benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep-run.sh new file mode 100755 index 00000000..230bedce --- /dev/null +++ b/benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep-run.sh @@ -0,0 +1,248 @@ +#!/usr/bin/env bash +# +# benchmarks/lbm_lid_driven_cavity_distributed/scripts/lbm-dist-sweep-run.sh +# +# Strong-scaling sweep of the distributed LBM benchmark on one multi-GPU node: +# lattice/collision x domain size x GPU count x decomposition x transport x +# halo priority. Builds the CUDA+MPI Release tree inside Docker and does one +# `mpiexec -n G` run per combination (one rank per GPU, --grid +# dense_distributed, --overlap OVERLAP). +# +# decompositions slab (split z), pencil (y, z), brick (x, y, z) +# transports mpi = NCCL; mpip2p = MPI point-to-point (CARBON_DIST_TRANSPORT=mpi) +# hp_halo off = normal halo stream; on = --hp-halo (high-priority halo stream) +# +# At G=1 every decomposition is 1x1x1 and there is no halo exchange, so each +# (series, N) gets a single `ref` run instead (mpiexec -n 1, hp-halo off): it +# is the efficiency baseline and the 1-GPU point of every curve. +# +# Timing: after WARMUP solver steps, each run times REPS repetitions of +# ITERS_PER_REP solver steps (binary --reps); every repetition ends with a GPU +# drain and an MPI barrier, so rank 0's clock covers the slowest rank. +# results.mlups is the MLUPS over all timed steps (what the plotter reads); +# results.repetitions holds the per-repetition MLUPS; config.process_grid the +# rank grid ProcessGrid actually chose. +# +# Reports are named +# ---fp32-