From 10b75b504e3a3f8f4e21671a263ba7ac3d1676ab Mon Sep 17 00:00:00 2001 From: Ryan Pepper Date: Tue, 10 Nov 2026 10:52:12 +0000 Subject: [PATCH 01/10] Add per-face boundary condition types for DenseDistributed New carbon/boundary_condition_distributed.h: BoundaryConditions (six faces, each BcKind::{None, Dirichlet, Neumann} plus one constant scalar; Neumann is the outward-normal derivative). Trivially copyable and constexpr so it can ride inside the by-value kernel Span. Header only and not yet used anywhere, so behaviour is unchanged. --- .../carbon/boundary_condition_distributed.h | 127 ++++++++++++++++++ include/carbon/carbon.h | 1 + 2 files changed, 128 insertions(+) create mode 100644 include/carbon/boundary_condition_distributed.h diff --git a/include/carbon/boundary_condition_distributed.h b/include/carbon/boundary_condition_distributed.h new file mode 100644 index 00000000..81ee6eb5 --- /dev/null +++ b/include/carbon/boundary_condition_distributed.h @@ -0,0 +1,127 @@ +#pragma once + +#include + +#include + +namespace carbon { + +/** + * Kind of boundary condition applied on one face of a @ref DenseDistributed grid. + * + * Opt-in: a face with @ref BcKind::None keeps the historical behaviour of an open face + * (out-of-domain reads report @c valid = false through @c Partition::neighbour). + */ +enum class BcKind : std::uint8_t { + /** No boundary condition on this face (default). */ + None = 0, + + /** Fixed value @c u = g on the boundary node. */ + Dirichlet = 1, + + /** Fixed outward-normal derivative @c du/dn = g on the boundary node. */ + Neumann = 2, +}; + +/** One of the six faces of the global box. "Low" is the face at coordinate 0, "High" at extent-1. */ +enum class Face : std::uint8_t { + XLow = 0, + XHigh = 1, + YLow = 2, + YHigh = 3, + ZLow = 4, + ZHigh = 5, +}; + +/** Number of faces of the global box. */ +inline constexpr int kFaceCount = 6; + +/** + * Boundary condition on a single face: a kind and one constant scalar. + * + * For @ref BcKind::Dirichlet, @c value is the field value @c g on the boundary node. + * For @ref BcKind::Neumann, @c value is the @b outward-normal derivative @c du/dn (the normal + * points out of the domain), so the same sign convention holds on low and high faces. + */ +struct FaceBc { + BcKind kind{BcKind::None}; + double value{0.0}; +}; + +/** Dirichlet condition @c u = g. */ +[[nodiscard]] constexpr auto +dirichlet(double g) noexcept -> FaceBc { + return FaceBc{BcKind::Dirichlet, g}; +} + +/** Neumann condition with outward-normal derivative @c du/dn = g. */ +[[nodiscard]] constexpr auto +neumann(double g = 0.0) noexcept -> FaceBc { + return FaceBc{BcKind::Neumann, g}; +} + +/** + * Per-face boundary conditions of a @ref DenseDistributed grid. + * + * A trivially-copyable value type (it rides inside the by-value kernel @c Span), constexpr + * throughout. Every face defaults to @ref BcKind::None, so a default-constructed + * @ref BoundaryConditions changes nothing. + * + * @par Node-centred convention + * The boundary lies @b on the first / last in-domain cell (cell @c (0,0,0) sits at the grid + * origin). A read @c k cells outside a BC face is a @b virtual boundary value: it is computed on + * the spot from the in-domain @b mirror cell, @c k cells inside the face (reflection through the + * boundary node), and nothing is stored for it. With @c u_m the mirror cell value and @c h the + * grid spacing: + * - Dirichlet: @c 2*g - u_m + * - Neumann: @c u_m + 2*k*h*g + * + * The boundary node itself is not set by the grid; the solver pins or solves it. + * + * @par Not combinable with periodic axes + * A BC on an axis that is periodic in @ref BoundaryModeDistributed is rejected when the grid is + * constructed. + * + * @code + * auto bc = carbon::BoundaryConditions::none() + * .with(carbon::Face::XLow, carbon::neumann()) + * .with(carbon::Face::ZHigh, carbon::dirichlet(-1.0)); + * @endcode + */ +struct BoundaryConditions { + FaceBc faces[kFaceCount]{}; + + /** No boundary condition on any face. */ + [[nodiscard]] static constexpr auto + none() noexcept -> BoundaryConditions { + return BoundaryConditions{}; + } + + /** Copy of @c *this with @p face set to @p bc. */ + [[nodiscard]] constexpr auto + with(Face face, + FaceBc bc) const noexcept -> BoundaryConditions { + BoundaryConditions out = *this; + out.faces[static_cast(face)] = bc; + return out; + } + + /** Condition on @p face. */ + [[nodiscard]] constexpr CARBON_HD auto + at(Face face) const noexcept -> const FaceBc& { + return faces[static_cast(face)]; + } + + /** True when at least one face carries a condition. */ + [[nodiscard]] constexpr CARBON_HD auto + any() const noexcept -> bool { + for (const FaceBc& f : faces) { + if (f.kind != BcKind::None) { + return true; + } + } + return false; + } +}; + +} // namespace carbon diff --git a/include/carbon/carbon.h b/include/carbon/carbon.h index 55636c2f..2b9bf29f 100644 --- a/include/carbon/carbon.h +++ b/include/carbon/carbon.h @@ -22,6 +22,7 @@ device_count() noexcept -> int; } // namespace carbon +#include #include #include #include From d6f3d7038cd00b397f1f36e52bc18f7958bdeab4 Mon Sep 17 00:00:00 2001 From: Ryan Pepper Date: Tue, 10 Nov 2026 10:52:12 +0000 Subject: [PATCH 02/10] Add Span boundary conditions and Partition::neighbour_bc Span carries a BoundaryConditions block (default none) and gains neighbour_idx_bc, a sibling of neighbour_idx that checks the global domain before the buffer, because a single-rank open axis has no halo storage. A read across a face with a condition resolves to the in-domain mirror cell, and Partition::neighbour_bc turns it into a virtual boundary value (node-centred: Dirichlet 2g - u_m, Neumann u_m + 2*k*h*g). Edge and corner reads and faces without a condition stay invalid. Opt-in: neighbour, read_pull and Cursor are unchanged. Span now static_asserts that it stays trivially copyable. test_dense_distributed_bc_host (no GPU, no MPI) checks that neighbour_bc equals neighbour when no conditions are set, matches an independent per-cell oracle on emulated slab / pencil / brick worlds at radius 1 and 2 including mixed periodic axes, reproduces linear fields exactly, and keeps the documented limits. --- .../detail/dense_distributed/partition.h | 44 ++ .../carbon/detail/dense_distributed/span.h | 166 +++++- tests/CMakeLists.txt | 4 + tests/README.md | 1 + tests/test_dense_distributed_bc_host.cpp | 528 ++++++++++++++++++ 5 files changed, 739 insertions(+), 4 deletions(-) create mode 100644 tests/test_dense_distributed_bc_host.cpp diff --git a/include/carbon/detail/dense_distributed/partition.h b/include/carbon/detail/dense_distributed/partition.h index 8c21e417..31d08415 100644 --- a/include/carbon/detail/dense_distributed/partition.h +++ b/include/carbon/detail/dense_distributed/partition.h @@ -9,6 +9,7 @@ #include #include +#include namespace carbon::detail::dense_distributed { @@ -230,6 +231,49 @@ class Partition { return NeighbourValue{ptr_[span.linear_offset(r.idx, component_id)], true}; } + /** + * Boundary-condition-aware neighbour read: like @ref neighbour, but an out-of-domain read across + * a face that carries a @ref BoundaryConditions entry returns a @b virtual boundary value + * instead of @c valid = false. Nothing is stored for that value; it is computed from the + * in-domain mirror cell (see @ref neighbour_idx_bc and @c BoundaryConditions): + * - Dirichlet @c u = g : @c 2*g - u_mirror + * - Neumann @c du/dn = g (outward) : @c u_mirror + 2*k*h*g + * + * @c valid is @c true for interior reads and for virtual boundary reads. With no boundary + * conditions configured this returns exactly what @ref neighbour returns. Reads out of domain + * across two or more BC faces at once (edge / corner) return @c valid = false in this version. + * + * Opt-in by design: @ref neighbour, @ref read_pull and @ref cursor are unchanged, so existing + * kernels (and their generated code) are not affected. All components of a multi-component + * field receive the same scalar @c g. Requires a floating-point element type. + */ + [[nodiscard]] CARBON_HD constexpr auto + neighbour_bc(const Span& span, + const Idx& idx, + int8_3d offset, + int component_id) const noexcept -> NeighbourValue { + static_assert(std::is_floating_point_v, + "Partition::neighbour_bc computes virtual boundary values and needs a " + "floating-point element type"); + const NeighbourIdxBc r = neighbour_idx_bc(span, idx, offset); + if (r.kind == NeighbourKindBc::Invalid) { + return {}; + } + const T mirror = ptr_[span.linear_offset(r.idx, component_id)]; + if (r.kind == NeighbourKindBc::Interior) { + return NeighbourValue{mirror, true}; + } + const FaceBc& fbc = span.boundary_conditions().at(r.face); + const T g = static_cast(fbc.value); + if (fbc.kind == BcKind::Dirichlet) { + return NeighbourValue{static_cast(2) * g - mirror, true}; + } + // Neumann (the only other kind that neighbour_idx_bc reports as Boundary). + return NeighbourValue{ + mirror + static_cast(2) * static_cast(r.k) * static_cast(span.spacing()) * g, + 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 diff --git a/include/carbon/detail/dense_distributed/span.h b/include/carbon/detail/dense_distributed/span.h index 636006cf..51ea0dfb 100644 --- a/include/carbon/detail/dense_distributed/span.h +++ b/include/carbon/detail/dense_distributed/span.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -8,6 +9,9 @@ #include +#include +#include + namespace carbon::detail::dense_distributed { /** @@ -57,6 +61,7 @@ class Span { BoundaryModeDistributed boundary_mode_{BoundaryModeDistributed::Open}; float32_3d origin_{}; float spacing_{1.0F}; + BoundaryConditions boundary_conditions_{}; public: CARBON_HD constexpr Span() noexcept = default; @@ -68,7 +73,8 @@ class Span { int64_3d halo = {}, BoundaryModeDistributed boundary_mode = BoundaryModeDistributed::Open, float32_3d origin = {}, - float spacing = 1.0F) noexcept + float spacing = 1.0F, + BoundaryConditions boundary_conditions = {}) noexcept : haloed_extent_(haloed_extent), global_extent_(global_extent), xy_slab_elements_(xy_slab_elements), @@ -76,7 +82,8 @@ class Span { halo_(halo), boundary_mode_(boundary_mode), origin_(origin), - spacing_(spacing) {} + spacing_(spacing), + boundary_conditions_(boundary_conditions) {} /** * Construct a span over its @b storage (haloed) extent. @@ -96,6 +103,9 @@ class Span { * @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). + * @param boundary_conditions Per-face Dirichlet / Neumann conditions consumed only by + * @c Partition::neighbour_bc . Defaults to none, in which case this + * span behaves exactly as before. */ /** Z-only convenience overload: equivalent to full @c offset={0,0,z_offset} and * @c halo={0,0,halo_z}. */ @@ -106,7 +116,8 @@ class Span { int64_t halo_z = 0, BoundaryModeDistributed boundary_mode = BoundaryModeDistributed::Open, float32_3d origin = {}, - float spacing = 1.0F) noexcept + float spacing = 1.0F, + BoundaryConditions boundary_conditions = {}) noexcept : Span(haloed_extent, global_extent, xy_slab_elements, @@ -118,7 +129,8 @@ class Span { halo_z}, boundary_mode, origin, - spacing) {} + spacing, + boundary_conditions) {} /** Storage extent (includes halo layers on every axis where @ref halo() is non-zero). */ [[nodiscard]] CARBON_HD constexpr auto @@ -251,6 +263,16 @@ class Span { return boundary_mode_; } + /** + * Per-face boundary conditions this span was built with (propagated from the owning + * @c DenseDistributed). All faces are @c BcKind::None unless the grid was constructed with + * conditions; only @c Partition::neighbour_bc reads them. + */ + [[nodiscard]] CARBON_HD constexpr auto + boundary_conditions() const noexcept -> const BoundaryConditions& { + return boundary_conditions_; + } + /** Physical-space origin at global integer cell @c (0,0,0) (cell-corner convention). */ [[nodiscard]] CARBON_HD constexpr auto origin() const noexcept -> float32_3d { @@ -444,6 +466,11 @@ class Span { } }; +// Span is passed by value into every kernel launch (device parameter space), so it must stay +// trivially copyable: no virtuals, no owning members. +static_assert(std::is_trivially_copyable_v, + "dense_distributed::Span is passed by value to kernels and must be trivially copyable"); + [[nodiscard]] CARBON_HD constexpr auto Span::make_idx(int64_t ix, int64_t iy, @@ -578,4 +605,135 @@ neighbour_idx(const Span& span, return NeighbourIdx{Idx(bx, by, bz), true}; } +/** Outcome class of @ref neighbour_idx_bc. */ +enum class NeighbourKindBc : std::uint8_t { + /** Unreachable: out of the buffer, out of domain on a face without a BC, or an edge/corner read. */ + Invalid = 0, + + /** In-buffer, in-domain (or periodic-wrapped) cell: identical to what @ref neighbour_idx returns. */ + Interior = 1, + + /** Out of domain across a BC face: @c idx is the in-domain mirror cell, see @ref NeighbourIdxBc. */ + Boundary = 2, +}; + +/** + * Result of @ref neighbour_idx_bc. + * + * - @c Interior : @c idx is the neighbour cell (same index @ref neighbour_idx would return). + * - @c Boundary : the read lands @c k cells outside @c face. @c idx is the in-domain @b mirror + * cell (@c k cells inside the face, reflected through the boundary node); the caller derives + * the virtual boundary value from its content and the face's @ref FaceBc. + * - @c Invalid : nothing reachable. + */ +struct NeighbourIdxBc { + Idx idx{}; + NeighbourKindBc kind{NeighbourKindBc::Invalid}; + ::carbon::Face face{::carbon::Face::XLow}; + int32_t k{0}; +}; + +/** + * Boundary-condition-aware sibling of @ref neighbour_idx (which is left untouched). + * + * Order of checks differs on purpose: the global-domain test per axis runs @b before the buffer + * test, because a single-rank open axis has no halo storage, so an out-of-domain offset is + * necessarily outside the buffer and cannot be recognised as a BC read after a buffer check. + * + * Per-axis classification of the target cell @c g = cell + offset + span.offset(): + * - inside @c [0, global) or on a periodic axis: ordinary (@c Interior-style) axis; + * - outside on a non-periodic axis whose face has @c kind != None: BC axis; + * - outside on a non-periodic axis without a BC: the read is @c Invalid (as for @ref neighbour_idx). + * + * Result: + * - no BC axis: same buffer test and result as @ref neighbour_idx (@c Interior or @c Invalid); + * - exactly one BC axis: @c Boundary with the mirror cell, provided the mirror cell is inside the + * domain and the buffer. The other two axes keep their buffer-local coordinate and must be in + * the buffer; + * - two or more BC axes (edge or corner of the box): @c Invalid. The composition order of mixed + * Dirichlet / Neumann conditions at an edge changes the result, so this is deliberately not + * guessed (documented limitation). + * + * Mirror cell: with @c G the global extent on the BC axis, a read at global coordinate @c g < 0 + * has @c k = -g and mirror global coordinate @c k ; a read at @c g >= G has @c k = g - (G - 1) and + * mirror global coordinate @c (G - 1) - k. For any offset within the stencil radius the mirror is + * within one stencil radius of the reading cell, hence inside the buffer (own halo on a split axis). + */ +[[nodiscard]] CARBON_HD constexpr auto +neighbour_idx_bc(const Span& span, + const Idx& idx, + ::carbon::int8_3d offset) noexcept -> NeighbourIdxBc { + const int64_3d cell = idx.cell(); + const int64_3d haloed = span.haloed_extent(); + const int64_3d global_extent = span.global_extent(); + const int64_3d off = span.offset(); + const BoundaryModeDistributed mode = span.boundary_mode(); + const BoundaryConditions& bc = span.boundary_conditions(); + + const int64_t b[3] = {cell.x + static_cast(offset.x), + cell.y + static_cast(offset.y), + cell.z + static_cast(offset.z)}; + const int64_t haloed_a[3] = {haloed.x, haloed.y, haloed.z}; + const int64_t global_a[3] = {global_extent.x, global_extent.y, global_extent.z}; + const int64_t off_a[3] = {off.x, off.y, off.z}; + const Axis axes[3] = {Axis::X, Axis::Y, Axis::Z}; + const ::carbon::Face low_face[3] = {::carbon::Face::XLow, ::carbon::Face::YLow, + ::carbon::Face::ZLow}; + const ::carbon::Face high_face[3] = {::carbon::Face::XHigh, ::carbon::Face::YHigh, + ::carbon::Face::ZHigh}; + + int bc_axis = -1; + int bc_axis_count = 0; + for (int a = 0; a < 3; ++a) { + const int64_t g = b[a] + off_a[a]; + const bool outside = g < 0 || g >= global_a[a]; + if (!outside || is_periodic(mode, axes[a])) { + continue; + } + const ::carbon::Face f = (g < 0) ? low_face[a] : high_face[a]; + if (bc.at(f).kind == BcKind::None) { + return {}; + } + bc_axis = a; + ++bc_axis_count; + } + + if (bc_axis_count == 0) { + // No BC involved: identical to neighbour_idx (buffer bounds, then valid). + if (b[0] < 0 || b[0] >= haloed_a[0] || b[1] < 0 || b[1] >= haloed_a[1] || b[2] < 0 || + b[2] >= haloed_a[2]) { + return {}; + } + NeighbourIdxBc r; + r.idx = Idx(b[0], b[1], b[2]); + r.kind = NeighbourKindBc::Interior; + return r; + } + if (bc_axis_count > 1) { + return {}; + } + + // Exactly one BC axis: build the mirror cell. + const int64_t g_bc = b[bc_axis] + off_a[bc_axis]; + const int64_t extent = global_a[bc_axis]; + const bool low = g_bc < 0; + const int64_t k = low ? -g_bc : g_bc - (extent - 1); + const int64_t mirror_global = low ? k : (extent - 1) - k; + if (mirror_global < 0 || mirror_global >= extent) { + return {}; + } + int64_t m[3] = {b[0], b[1], b[2]}; + m[bc_axis] = mirror_global - off_a[bc_axis]; + if (m[0] < 0 || m[0] >= haloed_a[0] || m[1] < 0 || m[1] >= haloed_a[1] || m[2] < 0 || + m[2] >= haloed_a[2]) { + return {}; + } + NeighbourIdxBc r; + r.idx = Idx(m[0], m[1], m[2]); + r.kind = NeighbourKindBc::Boundary; + r.face = low ? low_face[bc_axis] : high_face[bc_axis]; + r.k = static_cast(k); + return r; +} + } // namespace carbon::detail::dense_distributed diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ffe81c6e..da32b79a 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -157,6 +157,10 @@ carbon_add_unit_test(halo_coalesce) # 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) +# DenseDistributed per-face boundary conditions (Dirichlet / Neumann), host half: Span and +# Partition::neighbour_bc against an independent oracle on emulated slab / pencil / brick worlds, +# and the guard that no conditions means neighbour_bc == neighbour. No GPU and no MPI. +carbon_add_unit_test(dense_distributed_bc_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. diff --git a/tests/README.md b/tests/README.md index f4ab0ef2..78a3cb54 100644 --- a/tests/README.md +++ b/tests/README.md @@ -22,6 +22,7 @@ completeness. | `test_dynamic_load.cpp` | Smoke-tests dynamic loading of `libcarbon`: `carbon::init()` followed by a version probe through `carbon::info()`. | CPU only | | `test_logging.cpp` | Logging smoke test: `carbon::init()` plus a single `CARBON_LOG_INFO` call to verify the spdlog wiring. | CPU only | | `test_memory_side.cpp` | `MemorySide` enum: count, integer values, `to_string` / `to_int`, stream insertion, exception on out-of-range conversion. | CPU only | +| `test_dense_distributed_bc_host.cpp` | `DenseDistributed` per-face boundary conditions (Dirichlet / Neumann): `neighbour_bc` equals `neighbour` when no conditions are set, matches an independent oracle for every owned cell and offset on emulated slab / pencil / brick worlds (radius 1 and 2, mixed periodic axes), reproduces linear fields exactly, and keeps edge / corner reads invalid. | CPU only | | `test_stencil.cpp` | `Stencil` construction from point lists; verifies radius computation, point storage, and the empty-stencil case. | CPU only | | `test_transfer.cpp` | Host-only `BufferGroup` transfer: builds two single-entry host buffer groups and exercises `Transfer` on the CPU side without touching CUDA. | CPU only | | `test_gpu.cpp` | `device_count()`, `GpuGroup` default construction, multi-allocation buffer groups, `StreamGroup` / `EventGroup` sizing across all visible devices. | Multi-GPU | diff --git a/tests/test_dense_distributed_bc_host.cpp b/tests/test_dense_distributed_bc_host.cpp new file mode 100644 index 00000000..c014cd33 --- /dev/null +++ b/tests/test_dense_distributed_bc_host.cpp @@ -0,0 +1,528 @@ +// Host-side tests for per-face boundary conditions on carbon::DenseDistributed +// (BoundaryConditions, Span::boundary_conditions, neighbour_idx_bc, Partition::neighbour_bc). +// +// No GPU and no MPI: every rank of a process grid is emulated on the host. Each rank gets the Span +// the grid would build (halo_extent + rank_chunk) and a host buffer filled the way a completed halo +// exchange leaves it: in-domain cells (including halo cells that alias a neighbour rank's owned +// cells) hold the analytic global field, periodic halo cells hold the wrapped value, and halo cells +// outside the domain on an open face hold a sentinel that must never be read. +// +// Parts: +// A Regression guard: with no boundary conditions neighbour_bc == neighbour (value and valid) +// for every offset, every layout, every boundary mode. +// B Oracle: with conditions, neighbour_bc matches an independent per-cell reference (restated +// from the maths in boundary_condition_distributed.h) for every owned cell and every offset +// within the stencil radius, on slab / pencil / brick layouts, radius 1 and 2, including +// mixed periodic + condition axes. Also checks the sentinel is never consumed. +// C Analytic: a linear field is reproduced exactly by the Neumann (matching outward derivative) +// and Dirichlet (odd about the boundary value) virtual values, on low and high faces. +// D Documented limits: edge / corner reads and faces without a condition stay invalid. +// E Types: BoundaryConditions builder / accessors, Span stays trivially copyable. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using carbon::Axis; +using carbon::BcKind; +using carbon::BoundaryConditions; +using carbon::BoundaryModeDistributed; +using carbon::DecompositionMode; +using carbon::Face; +using carbon::ProcessGrid; +using carbon::Stencil; +using carbon::detail::dense_distributed::Idx; +using carbon::detail::dense_distributed::Partition; +using carbon::detail::dense_distributed::Span; + +int g_checks = 0; + +#define CHECK(cond, ctx) \ + do { \ + ++g_checks; \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL %s:%d %s [%s]\n", __FILE__, __LINE__, #cond, \ + std::string(ctx).c_str()); \ + std::exit(1); \ + } \ + } while (0) + +constexpr double kSentinel = 1.0e30; + +// Analytic global field (non-trivial in all three axes so mirrored values are distinguishable). +[[nodiscard]] auto +field(int64_t x, + int64_t y, + int64_t z) -> double { + const double fx = static_cast(x); + const double fy = static_cast(y); + const double fz = static_cast(z); + return 1.0 + 0.37 * fx + 0.11 * fy + 0.053 * fz + 0.013 * fx * fy + 0.007 * fy * fz - + 0.003 * fx * fz + 0.0011 * fx * fy * fz; +} + +[[nodiscard]] auto +cross_stencil(int radius) -> Stencil { + std::vector pts; + for (int r = 1; r <= radius; ++r) { + pts.push_back({r, 0, 0}); + pts.push_back({-r, 0, 0}); + pts.push_back({0, r, 0}); + pts.push_back({0, -r, 0}); + pts.push_back({0, 0, r}); + pts.push_back({0, 0, -r}); + } + return Stencil(pts); +} + +[[nodiscard]] auto +mod_pos(int64_t v, + int64_t n) -> int64_t { + const int64_t r = v % n; + return r < 0 ? r + n : r; +} + +// One emulated rank: its Span and a filled host buffer (single component). +struct RankView { + Span span; + std::vector buf; + carbon::int64_3d owned{}; + carbon::int64_3d halo{}; +}; + +[[nodiscard]] auto +build_rank(const carbon::int64_3d& global, + const ProcessGrid& pg, + carbon::int32_3d coords, + BoundaryModeDistributed mode, + const Stencil& stencil, + float spacing, + const BoundaryConditions& bc) -> RankView { + namespace dd = carbon::detail::dense_distributed; + const carbon::int64_3d halo = dd::halo_extent(pg, mode, stencil); + const dd::RankChunk chunk = dd::rank_chunk(global, pg, coords, halo); + RankView rv; + rv.span = Span(chunk.haloed, global, chunk.xy_pitch, chunk.offset, chunk.halo, mode, + carbon::float32_3d{}, spacing, bc); + rv.owned = chunk.owned; + rv.halo = chunk.halo; + rv.buf.assign(static_cast(rv.span.linear_storage_elements()), kSentinel); + const int64_t gdim[3] = {global.x, global.y, global.z}; + const Axis axes[3] = {Axis::X, Axis::Y, Axis::Z}; + for (int64_t bz = 0; bz < chunk.haloed.z; ++bz) { + for (int64_t by = 0; by < chunk.haloed.y; ++by) { + for (int64_t bx = 0; bx < chunk.haloed.x; ++bx) { + const int64_t g[3] = {bx + chunk.offset.x, by + chunk.offset.y, bz + chunk.offset.z}; + int64_t w[3]; + bool fillable = true; + for (int a = 0; a < 3; ++a) { + const bool out = g[a] < 0 || g[a] >= gdim[a]; + if (!out) { + w[a] = g[a]; + } else if (carbon::is_periodic(mode, axes[a])) { + w[a] = mod_pos(g[a], gdim[a]); + } else { + fillable = false; + } + } + if (fillable) { + rv.buf[static_cast(rv.span.linear_offset(Idx(bx, by, bz), 0))] = + field(w[0], w[1], w[2]); + } + } + } + } + return rv; +} + +struct Layout { + std::string name; + ProcessGrid pg; +}; + +[[nodiscard]] auto +layouts() -> std::vector { + return { + {"single(1,1,1)", ProcessGrid::custom(1, 1, 1, 1)}, + {"slab(1,1,2)", ProcessGrid::custom(2, 1, 1, 2)}, + {"slab(1,1,3)", ProcessGrid::custom(3, 1, 1, 3)}, + {"pencil(1,2,2)", ProcessGrid::custom(4, 1, 2, 2)}, + {"pencil(2,1,2)", ProcessGrid::custom(4, 2, 1, 2)}, + {"brick(2,2,2)", ProcessGrid::custom(8, 2, 2, 2)}, + }; +} + +[[nodiscard]] auto +mode_name(BoundaryModeDistributed m) -> std::string { + std::string s; + if (carbon::is_periodic(m, Axis::X)) { + s += "X"; + } + if (carbon::is_periodic(m, Axis::Y)) { + s += "Y"; + } + if (carbon::is_periodic(m, Axis::Z)) { + s += "Z"; + } + return s.empty() ? "open" : "periodic:" + s; +} + +[[nodiscard]] auto +modes() -> std::vector { + using M = BoundaryModeDistributed; + return {M::Open, M::PeriodicZ, M::PeriodicX, M::PeriodicX | M::PeriodicY, + M::PeriodicX | M::PeriodicY | M::PeriodicZ}; +} + +template +void +for_each_rank_cell_offset(const RankView& rv, + const Stencil& stencil, + Fn&& fn) { + const carbon::int32_3d r3 = stencil.radius3(); + for (int64_t iz = 0; iz < rv.owned.z; ++iz) { + for (int64_t iy = 0; iy < rv.owned.y; ++iy) { + for (int64_t ix = 0; ix < rv.owned.x; ++ix) { + const Idx idx(rv.halo.x + ix, rv.halo.y + iy, rv.halo.z + iz); + for (int dz = -r3.z; dz <= r3.z; ++dz) { + for (int dy = -r3.y; dy <= r3.y; ++dy) { + for (int dx = -r3.x; dx <= r3.x; ++dx) { + fn(idx, carbon::int8_3d{static_cast(dx), static_cast(dy), + static_cast(dz)}); + } + } + } + } + } + } +} + +// --------------------------------------------------------------------------------------------- +// Part A: no conditions => neighbour_bc is neighbour. +// --------------------------------------------------------------------------------------------- +void +part_a_regression_guard() { + const carbon::int64_3d global{9, 8, 7}; + for (int radius = 1; radius <= 2; ++radius) { + const Stencil stencil = cross_stencil(radius); + for (const BoundaryModeDistributed mode : modes()) { + for (const Layout& lay : layouts()) { + for (int rank = 0; rank < lay.pg.world_size(); ++rank) { + const std::string ctx = "A r=" + std::to_string(radius) + " " + mode_name(mode) + " " + + lay.name + " rank=" + std::to_string(rank); + const RankView rv = + build_rank(global, lay.pg, lay.pg.coords_of(rank), mode, stencil, 0.5F, + BoundaryConditions::none()); + const Partition part(const_cast(rv.buf.data())); + for_each_rank_cell_offset(rv, stencil, [&](const Idx& idx, carbon::int8_3d off) { + const auto a = part.neighbour(rv.span, idx, off, 0); + const auto b = part.neighbour_bc(rv.span, idx, off, 0); + CHECK(a.valid == b.valid, ctx); + if (a.valid) { + CHECK(a.value == b.value, ctx); + } + }); + } + } + } + } +} + +// --------------------------------------------------------------------------------------------- +// Part B: with conditions, neighbour_bc matches an independent oracle. +// --------------------------------------------------------------------------------------------- +struct Expected { + bool valid{false}; + double value{0.0}; +}; + +[[nodiscard]] auto +oracle(const carbon::int64_3d& global, + BoundaryModeDistributed mode, + const BoundaryConditions& bc, + float spacing, + const int64_t cell_global[3], + carbon::int8_3d off) -> Expected { + const int64_t gdim[3] = {global.x, global.y, global.z}; + const Axis axes[3] = {Axis::X, Axis::Y, Axis::Z}; + const Face low[3] = {Face::XLow, Face::YLow, Face::ZLow}; + const Face high[3] = {Face::XHigh, Face::YHigh, Face::ZHigh}; + const int64_t o[3] = {off.x, off.y, off.z}; + int64_t t[3]; + int bc_axis = -1; + int bc_count = 0; + for (int a = 0; a < 3; ++a) { + t[a] = cell_global[a] + o[a]; + const bool out = t[a] < 0 || t[a] >= gdim[a]; + if (!out) { + continue; + } + if (carbon::is_periodic(mode, axes[a])) { + t[a] = mod_pos(t[a], gdim[a]); + continue; + } + const Face f = t[a] < 0 ? low[a] : high[a]; + if (bc.at(f).kind == BcKind::None) { + return {}; + } + bc_axis = a; + ++bc_count; + } + if (bc_count == 0) { + return {true, field(t[0], t[1], t[2])}; + } + if (bc_count > 1) { + return {}; + } + const bool is_low = t[bc_axis] < 0; + const int64_t k = is_low ? -t[bc_axis] : t[bc_axis] - (gdim[bc_axis] - 1); + int64_t m[3] = {t[0], t[1], t[2]}; + m[bc_axis] = is_low ? k : (gdim[bc_axis] - 1) - k; + const double u_m = field(m[0], m[1], m[2]); + const carbon::FaceBc fbc = bc.at(is_low ? low[bc_axis] : high[bc_axis]); + const double h = static_cast(spacing); + if (fbc.kind == BcKind::Dirichlet) { + return {true, 2.0 * fbc.value - u_m}; + } + return {true, u_m + 2.0 * static_cast(k) * h * fbc.value}; +} + +void +run_oracle_case(const std::string& label, + const carbon::int64_3d& global, + int radius, + BoundaryModeDistributed mode, + const BoundaryConditions& bc) { + const Stencil stencil = cross_stencil(radius); + const float spacing = 0.5F; + for (const Layout& lay : layouts()) { + for (int rank = 0; rank < lay.pg.world_size(); ++rank) { + const std::string ctx = "B " + label + " r=" + std::to_string(radius) + " " + + mode_name(mode) + " " + lay.name + " rank=" + std::to_string(rank); + const RankView rv = build_rank(global, lay.pg, lay.pg.coords_of(rank), mode, stencil, + spacing, bc); + const Partition part(const_cast(rv.buf.data())); + const carbon::int64_3d origin = rv.span.offset(); + for_each_rank_cell_offset(rv, stencil, [&](const Idx& idx, carbon::int8_3d off) { + const carbon::int64_3d c = idx.cell(); + const int64_t cg[3] = {c.x + origin.x, c.y + origin.y, c.z + origin.z}; + const Expected e = oracle(global, mode, bc, spacing, cg, off); + const auto got = part.neighbour_bc(rv.span, idx, off, 0); + CHECK(got.valid == e.valid, ctx); + if (e.valid) { + CHECK(std::fabs(got.value - e.value) <= 1e-12 * (1.0 + std::fabs(e.value)), ctx); + CHECK(std::fabs(got.value) < 1.0e20, ctx + " (sentinel consumed)"); + } + }); + } + } +} + +void +part_b_oracle() { + const carbon::int64_3d global{9, 8, 7}; + using M = BoundaryModeDistributed; + using carbon::dirichlet; + using carbon::neumann; + const BoundaryConditions all_neumann = BoundaryConditions::none() + .with(Face::XLow, neumann(0.0)) + .with(Face::XHigh, neumann(0.75)) + .with(Face::YLow, neumann(-1.25)) + .with(Face::YHigh, neumann(0.0)) + .with(Face::ZLow, neumann(2.0)) + .with(Face::ZHigh, neumann(-0.5)); + const BoundaryConditions mixed = BoundaryConditions::none() + .with(Face::XLow, neumann(0.0)) + .with(Face::XHigh, neumann(0.0)) + .with(Face::YLow, neumann(0.0)) + .with(Face::YHigh, neumann(0.0)) + .with(Face::ZLow, dirichlet(0.0)) + .with(Face::ZHigh, dirichlet(-3.5)); + const BoundaryConditions one_face = BoundaryConditions::none().with(Face::ZHigh, dirichlet(1.0)); + // The octant setup used by the magnetostatics example: symmetry planes and pole face. + const BoundaryConditions octant = BoundaryConditions::none() + .with(Face::XLow, neumann(0.0)) + .with(Face::YLow, neumann(0.0)) + .with(Face::ZLow, dirichlet(0.0)) + .with(Face::ZHigh, dirichlet(-2.0)) + .with(Face::XHigh, neumann(0.0)) + .with(Face::YHigh, neumann(0.0)); + for (int radius = 1; radius <= 2; ++radius) { + run_oracle_case("all_neumann", global, radius, M::Open, all_neumann); + run_oracle_case("mixed", global, radius, M::Open, mixed); + run_oracle_case("one_face", global, radius, M::Open, one_face); + run_oracle_case("octant", global, radius, M::Open, octant); + // Mixed periodic + conditions: periodic axes carry no condition. + run_oracle_case("periodicZ_bcXY", global, radius, M::PeriodicZ, + BoundaryConditions::none() + .with(Face::XLow, neumann(0.0)) + .with(Face::XHigh, dirichlet(1.5)) + .with(Face::YLow, neumann(0.5))); + run_oracle_case("periodicX_bcZ", global, radius, M::PeriodicX, + BoundaryConditions::none() + .with(Face::ZLow, dirichlet(0.25)) + .with(Face::ZHigh, neumann(-1.0)) + .with(Face::YHigh, neumann(0.0))); + run_oracle_case("periodicXY_bcZ", global, radius, M::PeriodicX | M::PeriodicY, + BoundaryConditions::none() + .with(Face::ZLow, neumann(0.0)) + .with(Face::ZHigh, dirichlet(2.0))); + } +} + +// --------------------------------------------------------------------------------------------- +// Part C: a linear field is reproduced exactly (sign convention check). +// --------------------------------------------------------------------------------------------- +void +part_c_analytic() { + // u(i,j,k) = b + ax*x*h + ay*y*h + az*z*h on a single rank, so physical derivatives are ax, ay, az. + const carbon::int64_3d global{8, 8, 8}; + const float h = 0.5F; + const double hd = static_cast(h); + const double b = 3.0; + const double a[3] = {0.8, -1.3, 2.1}; + const auto u = [&](int64_t x, int64_t y, int64_t z) { + return b + a[0] * static_cast(x) * hd + a[1] * static_cast(y) * hd + + a[2] * static_cast(z) * hd; + }; + const Stencil stencil = cross_stencil(2); + namespace dd = carbon::detail::dense_distributed; + const ProcessGrid pg = ProcessGrid::custom(1, 1, 1, 1); + const carbon::int64_3d halo = + dd::halo_extent(pg, BoundaryModeDistributed::Open, stencil); + const dd::RankChunk chunk = dd::rank_chunk(global, pg, {0, 0, 0}, halo); + + // Outward derivative on a low face is -a, on a high face +a. Dirichlet value is u at the face. + const Face low[3] = {Face::XLow, Face::YLow, Face::ZLow}; + const Face high[3] = {Face::XHigh, Face::YHigh, Face::ZHigh}; + BoundaryConditions neu = BoundaryConditions::none(); + BoundaryConditions dir = BoundaryConditions::none(); + const int64_t last = 7; + for (int ax = 0; ax < 3; ++ax) { + neu = neu.with(low[ax], carbon::neumann(-a[ax])).with(high[ax], carbon::neumann(a[ax])); + int64_t lo_c[3] = {3, 3, 3}; + int64_t hi_c[3] = {3, 3, 3}; + lo_c[ax] = 0; + hi_c[ax] = last; + dir = dir.with(low[ax], carbon::dirichlet(u(lo_c[0], lo_c[1], lo_c[2]))) + .with(high[ax], carbon::dirichlet(u(hi_c[0], hi_c[1], hi_c[2]))); + } + for (const BoundaryConditions* bc : {&neu, &dir}) { + Span span(chunk.haloed, global, chunk.xy_pitch, chunk.offset, chunk.halo, + BoundaryModeDistributed::Open, carbon::float32_3d{}, h, *bc); + std::vector buf(static_cast(span.linear_storage_elements()), kSentinel); + for (int64_t z = 0; z < 8; ++z) { + for (int64_t y = 0; y < 8; ++y) { + for (int64_t x = 0; x < 8; ++x) { + buf[static_cast(span.linear_offset(Idx(x + halo.x, y + halo.y, z + halo.z), 0))] = + u(x, y, z); + } + } + } + const Partition part(buf.data()); + const std::string ctx = (bc == &neu) ? "C neumann" : "C dirichlet"; + for (int ax = 0; ax < 3; ++ax) { + for (int k = 1; k <= 2; ++k) { + for (int side = 0; side < 2; ++side) { + // Transverse coordinates (3,3,3) match where the constant Dirichlet value g was sampled. + int64_t c[3] = {3, 3, 3}; + c[ax] = side == 0 ? 0 : last; + int8_t d[3] = {0, 0, 0}; + d[ax] = static_cast(side == 0 ? -k : k); + int64_t t[3] = {c[0] + d[0], c[1] + d[1], c[2] + d[2]}; + const auto got = part.neighbour_bc( + span, Idx(c[0] + halo.x, c[1] + halo.y, c[2] + halo.z), + carbon::int8_3d{d[0], d[1], d[2]}, 0); + CHECK(got.valid, ctx); + // The extrapolated linear field at the outside location. + CHECK(std::fabs(got.value - u(t[0], t[1], t[2])) < 1e-12, ctx); + } + } + } + } +} + +// --------------------------------------------------------------------------------------------- +// Part D: documented limits. +// --------------------------------------------------------------------------------------------- +void +part_d_limits() { + const carbon::int64_3d global{6, 6, 6}; + const Stencil stencil = cross_stencil(1); + const ProcessGrid pg = ProcessGrid::custom(1, 1, 1, 1); + const BoundaryConditions bc = BoundaryConditions::none() + .with(Face::XLow, carbon::neumann()) + .with(Face::ZHigh, carbon::dirichlet(1.0)); + const RankView rv = build_rank(global, pg, {0, 0, 0}, BoundaryModeDistributed::Open, stencil, + 1.0F, bc); + const Partition part(const_cast(rv.buf.data())); + const auto at = [&](int64_t x, int64_t y, int64_t z, int8_t dx, int8_t dy, int8_t dz) { + return part.neighbour_bc(rv.span, Idx(x + rv.halo.x, y + rv.halo.y, z + rv.halo.z), + carbon::int8_3d{dx, dy, dz}, 0); + }; + // Single BC axis: valid. + CHECK(at(0, 2, 2, -1, 0, 0).valid, "D xlow face read"); + CHECK(at(2, 2, 5, 0, 0, 1).valid, "D zhigh face read"); + // Edge (XLow x ZHigh): two BC axes at once. + CHECK(!at(0, 2, 5, -1, 0, 1).valid, "D edge read is invalid"); + // Face without a condition stays invalid (historical open-face behaviour). + CHECK(!at(2, 0, 2, 0, -1, 0).valid, "D ylow has no condition"); + CHECK(!at(5, 2, 2, 1, 0, 0).valid, "D xhigh has no condition"); + // In-domain reads unaffected. + CHECK(at(2, 2, 2, 1, 0, 0).valid, "D interior read"); +} + +// --------------------------------------------------------------------------------------------- +// Part E: types. +// --------------------------------------------------------------------------------------------- +void +part_e_types() { + static_assert(std::is_trivially_copyable_v); + static_assert(std::is_trivially_copyable_v); + static_assert(!BoundaryConditions::none().any()); + constexpr BoundaryConditions bc = BoundaryConditions::none() + .with(Face::XHigh, carbon::neumann(2.0)) + .with(Face::ZLow, carbon::dirichlet(-1.0)); + static_assert(bc.any()); + static_assert(bc.at(Face::XHigh).kind == BcKind::Neumann && bc.at(Face::XHigh).value == 2.0); + static_assert(bc.at(Face::ZLow).kind == BcKind::Dirichlet && bc.at(Face::ZLow).value == -1.0); + static_assert(bc.at(Face::YLow).kind == BcKind::None); + // A default Span carries no conditions; the Z-only overload forwards them. + const Span def; + CHECK(!def.boundary_conditions().any(), "E default span has no conditions"); + const Span z(carbon::int64_3d{4, 4, 6}, carbon::int64_3d{4, 4, 4}, 16, int64_t{0}, int64_t{1}, + BoundaryModeDistributed::Open, carbon::float32_3d{}, 1.0F, bc); + CHECK(z.boundary_conditions().at(Face::ZLow).kind == BcKind::Dirichlet, "E z-only ctor forwards"); +} + +} // namespace + +auto +main() -> int { + part_a_regression_guard(); + std::printf("part A (no conditions == neighbour): ok\n"); + part_b_oracle(); + std::printf("part B (oracle, layouts x radius x modes): ok\n"); + part_c_analytic(); + std::printf("part C (linear field exact): ok\n"); + part_d_limits(); + std::printf("part D (documented limits): ok\n"); + part_e_types(); + std::printf("part E (types): ok\n"); + std::printf("test_dense_distributed_bc_host: %d checks passed\n", g_checks); + return 0; +} From a7ae47b36d8ac49e3d1929728ea98a229ec6ca26 Mon Sep 17 00:00:00 2001 From: Ryan Pepper Date: Tue, 10 Nov 2026 10:52:12 +0000 Subject: [PATCH 03/10] Accept BoundaryConditions in the DenseDistributed constructors Appends a defaulted BoundaryConditions parameter after block_override on all three constructors (source compatible), stores it, exposes boundary_conditions(), and passes it into every per-GPU Span. init_common_ rejects a condition on a periodic axis, on an axis whose extent is not larger than the stencil radius there, and a non-finite value. The grid stays immutable after construction. halo_extent, the layouts and HaloDistributed are not touched. --- include/carbon/dense_distributed.h | 30 +++++++++++-- src/dense_distributed.cpp | 72 ++++++++++++++++++++++++++---- 2 files changed, 90 insertions(+), 12 deletions(-) diff --git a/include/carbon/dense_distributed.h b/include/carbon/dense_distributed.h index 079cea02..72970420 100644 --- a/include/carbon/dense_distributed.h +++ b/include/carbon/dense_distributed.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -122,6 +123,14 @@ class CARBON_API DenseDistributed { * @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. + * @param boundary_conditions Optional per-face Dirichlet / Neumann conditions (see + * @ref BoundaryConditions), consumed only by + * @c Partition::neighbour_bc . Defaults to none, which leaves the grid + * exactly as before. Applies to faces of axes that are not periodic in + * @p boundary_mode; a condition on a periodic axis, on an axis whose + * extent is not larger than the stencil radius on that axis, or with a + * non-finite value throws @c std::invalid_argument. The grid is immutable + * after construction. */ DenseDistributed(System system, int64_3d global_extent, @@ -129,7 +138,8 @@ class CARBON_API DenseDistributed { BoundaryModeDistributed boundary_mode = BoundaryModeDistributed::Open, float32_3d origin = {}, float spacing = 1.0F, - std::optional block_override = std::nullopt); + std::optional block_override = std::nullopt, + BoundaryConditions boundary_conditions = BoundaryConditions::none()); /** * @brief Build a layout by auto-factorizing the world size for @p decomposition. @@ -144,7 +154,8 @@ class CARBON_API DenseDistributed { BoundaryModeDistributed boundary_mode = BoundaryModeDistributed::Open, float32_3d origin = {}, float spacing = 1.0F, - std::optional block_override = std::nullopt); + std::optional block_override = std::nullopt, + BoundaryConditions boundary_conditions = BoundaryConditions::none()); /** * @brief Build a layout from an explicit @p process_grid. @@ -159,7 +170,8 @@ class CARBON_API DenseDistributed { BoundaryModeDistributed boundary_mode = BoundaryModeDistributed::Open, float32_3d origin = {}, float spacing = 1.0F, - std::optional block_override = std::nullopt); + std::optional block_override = std::nullopt, + BoundaryConditions boundary_conditions = BoundaryConditions::none()); /** * @brief Default-construct an empty grid: zero global extent, default @@ -201,6 +213,14 @@ class CARBON_API DenseDistributed { [[nodiscard]] auto boundary_mode() const noexcept -> BoundaryModeDistributed; + /** + * @brief Per-face boundary conditions this grid was constructed with (default: none on every + * face). Propagated to every entry of @ref spans() and read only by + * @c Partition::neighbour_bc . + */ + [[nodiscard]] auto + boundary_conditions() const noexcept -> const BoundaryConditions&; + /** Physical-space origin at global cell @c (0,0,0); same value on every @ref spans entry. */ [[nodiscard]] auto origin() const noexcept -> float32_3d; @@ -564,6 +584,7 @@ class CARBON_API DenseDistributed { System system_; Stencil stencil_{}; BoundaryModeDistributed boundary_mode_{BoundaryModeDistributed::Open}; + BoundaryConditions boundary_conditions_{}; float32_3d origin_{}; float spacing_{1.0F}; // Cross-rank partitioning state. See class doxygen for the model. These are z-coordinate @@ -590,7 +611,8 @@ class CARBON_API DenseDistributed { float32_3d origin, float spacing, ProcessGrid process_grid, - std::optional block_override); + std::optional block_override, + BoundaryConditions boundary_conditions); ProcessGrid process_grid_{}; }; diff --git a/src/dense_distributed.cpp b/src/dense_distributed.cpp index 61cad632..9e753cf9 100644 --- a/src/dense_distributed.cpp +++ b/src/dense_distributed.cpp @@ -78,6 +78,49 @@ linear_count_for_slab(int64_t nx, } // namespace namespace carbon { +namespace { +// Validates a BoundaryConditions spec against the grid it is attached to. A face without a +// condition (BcKind::None) is never checked, so the default spec is always accepted. +void +validate_boundary_conditions(const BoundaryConditions& bc, + BoundaryModeDistributed boundary_mode, + const int64_3d& global_extent, + const Stencil& stencil) { + constexpr const char* kFaceName[kFaceCount] = {"XLow", "XHigh", "YLow", "YHigh", "ZLow", "ZHigh"}; + const Axis axis_of_face[kFaceCount] = {Axis::X, Axis::X, Axis::Y, Axis::Y, Axis::Z, Axis::Z}; + const int64_t extent_of_axis[3] = {global_extent.x, global_extent.y, global_extent.z}; + const int32_3d radius = stencil.radius3(); + const int64_t radius_of_axis[3] = {radius.x, radius.y, radius.z}; + for (int f = 0; f < kFaceCount; ++f) { + const FaceBc& fbc = bc.faces[f]; + if (fbc.kind == BcKind::None) { + continue; + } + const Axis axis = axis_of_face[f]; + const int a = static_cast(axis); + if (is_periodic(boundary_mode, axis)) { + log::throw_with_log( + "DenseDistributed: boundary condition on face {} conflicts with a periodic boundary on " + "that axis; use either a periodic axis or a per-face condition, not both", + kFaceName[f]); + } + if (!std::isfinite(fbc.value)) { + log::throw_with_log( + "DenseDistributed: boundary condition on face {} must have a finite value (got {})", + kFaceName[f], fbc.value); + } + if (extent_of_axis[a] <= radius_of_axis[a]) { + log::throw_with_log( + "DenseDistributed: boundary condition on face {} needs a global extent larger than the " + "stencil radius on that axis so every mirror cell is inside the domain (extent={}, " + "radius={})", + kFaceName[f], extent_of_axis[a], radius_of_axis[a]); + } + } +} + +} // namespace + void DenseDistributed::init_common_(System system, int64_3d global_extent, @@ -86,7 +129,8 @@ DenseDistributed::init_common_(System system, float32_3d origin, float spacing, ProcessGrid process_grid, - std::optional block_override) { + std::optional block_override, + BoundaryConditions boundary_conditions) { if (!std::isfinite(spacing) || spacing <= 0.0F) { log::throw_with_log( "DenseDistributed: spacing must be finite and strictly positive (spacing={})", spacing); @@ -109,10 +153,13 @@ DenseDistributed::init_common_(System system, global_extent.x, global_extent.y, global_extent.z); } + validate_boundary_conditions(boundary_conditions, boundary_mode, global_extent, stencil); + global_ = global_extent; system_ = std::move(system); stencil_ = std::move(stencil); boundary_mode_ = boundary_mode; + boundary_conditions_ = boundary_conditions; origin_ = origin; spacing_ = spacing; process_grid_ = std::move(process_grid); @@ -190,7 +237,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_, origin_, spacing_, + boundary_conditions_); }); // The legacy Slab Boundary is still two z-bands; keep its old overlap guard. @@ -248,13 +296,14 @@ DenseDistributed::DenseDistributed(System system, BoundaryModeDistributed boundary_mode, float32_3d origin, float spacing, - std::optional block_override) + std::optional block_override, + BoundaryConditions boundary_conditions) : 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); + pg, block_override, boundary_conditions); } DenseDistributed::DenseDistributed(System system, @@ -264,13 +313,14 @@ DenseDistributed::DenseDistributed(System system, BoundaryModeDistributed boundary_mode, float32_3d origin, float spacing, - std::optional block_override) + std::optional block_override, + BoundaryConditions boundary_conditions) : 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); + pg, block_override, boundary_conditions); } DenseDistributed::DenseDistributed(System system, @@ -280,10 +330,11 @@ DenseDistributed::DenseDistributed(System system, BoundaryModeDistributed boundary_mode, float32_3d origin, float spacing, - std::optional block_override) + std::optional block_override, + BoundaryConditions boundary_conditions) : DenseDistributed() { init_common_(std::move(system), global_extent, std::move(stencil), boundary_mode, origin, spacing, - std::move(process_grid), block_override); + std::move(process_grid), block_override, boundary_conditions); } auto @@ -327,6 +378,11 @@ DenseDistributed::boundary_mode() const noexcept -> BoundaryModeDistributed { return boundary_mode_; } +auto +DenseDistributed::boundary_conditions() const noexcept -> const BoundaryConditions& { + return boundary_conditions_; +} + auto DenseDistributed::origin() const noexcept -> float32_3d { return origin_; From 43208ef90687a783aebf07363594a8d52ec615c7 Mon Sep 17 00:00:00 2001 From: Ryan Pepper Date: Tue, 10 Nov 2026 10:52:12 +0000 Subject: [PATCH 04/10] Document DenseDistributed boundary conditions AGENTS.md layout list, a dated changelog entry, and a doxygen pointer from BoundaryModeDistributed to the new type. --- AGENTS.md | 2 ++ docs/CHANGELOG.md | 24 ++++++++++++++++++++++ include/carbon/boundary_mode_distributed.h | 4 ++++ 3 files changed, 30 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 89f0b325..38d5d943 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,9 @@ The current focus is a port of Neon's `dGrid` (dense, multi-GPU, Z-partitioned g include/carbon/ Public API (umbrella: carbon/carbon.h) detail/ Internal: GPU/buffer/stream/event wrappers detail/dense/ Dense-grid primitives: idx, span, partition, field, kernel, launch_shape + boundary_condition_distributed.h Per-face Dirichlet / Neumann conditions for DenseDistributed (opt-in, read via Partition::neighbour_bc) boundary_mode.h BoundaryMode enum (Open / PeriodicZ), both honoured end-to-end + boundary_mode_distributed.h BoundaryModeDistributed per-axis periodic bitmask (DenseDistributed) data_view.h DataView enum (Standard / Internal / Boundary) devices.h carbon::get_all_devices() free function distributed.h MPI handle (gated by CARBON_HAVE_MPI_NCCL) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 12f931d8..9c558067 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6185,3 +6185,27 @@ 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 — Per-face boundary conditions on `DenseDistributed` (Dirichlet / Neumann, opt-in).** + An open face used to mean "no boundary condition": `Partition::neighbour` returned + `valid = false` and every solver re-implemented the edge by hand (`cg_poisson` drops the + missing x/y neighbour and counts `n_valid`; the z faces are detected from `!valid`). New + `carbon/boundary_condition_distributed.h` adds `BoundaryConditions` (six faces, each + `BcKind::{None, Dirichlet, Neumann}` plus one constant scalar; Neumann is the outward-normal + derivative) as a trailing defaulted argument of the three `DenseDistributed` constructors, + carried into every per-GPU `Span` (`Span::boundary_conditions()`), and read only by the new + `Partition::neighbour_bc`. A read across a BC face returns a *virtual boundary value* + computed from the in-domain mirror cell (node-centred convention: Dirichlet `2g - u_m`, + Neumann `u_m + 2*k*h*g`, `k` cells outside the face); nothing is stored, so no halo storage + is added on single-rank open axes and `HaloDistributed`, `halo_extent` and the layouts are + untouched. `neighbour_idx_bc` checks the global domain before the buffer (the order + `neighbour_idx` cannot use on an axis without halo storage). Reads out of domain across two + faces at once (edges / corners) stay invalid in this version, as do faces without a + condition. The constructor rejects a condition on a periodic axis, on an axis whose extent + is not larger than the stencil radius there, or with a non-finite value. Nothing existing + changes: with no conditions `neighbour_bc` returns exactly what `neighbour` returns, and + `neighbour`, `read_pull`, `Cursor` and the LBM kernels are not modified. `Span` grows by the + condition block and now has a `static_assert` that it stays trivially copyable. + `dense_distributed_bc_host` (host-only, emulated slab / pencil / brick worlds, radius 1 and + 2, mixed periodic axes) checks the no-condition equivalence, an independent per-cell + oracle, exact reproduction of linear fields on low and high faces, and the documented + limits. `Dense`, `DenseDisg` and `Block` keep `BoundaryMode` and are not covered yet. diff --git a/include/carbon/boundary_mode_distributed.h b/include/carbon/boundary_mode_distributed.h index 55122419..c990fa14 100644 --- a/include/carbon/boundary_mode_distributed.h +++ b/include/carbon/boundary_mode_distributed.h @@ -20,6 +20,10 @@ namespace carbon { * - Halo exchange (@ref HaloDistributed): schedules the wrap pair on every periodic axis and omits * it on an open axis. * + * @note This mask only expresses periodicity. Per-face Dirichlet / Neumann conditions on open + * faces are a separate, opt-in type: see @ref BoundaryConditions and + * @c Partition::neighbour_bc . A condition on a periodic axis is rejected at construction. + * * @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 From 71c7ffae37ca67f73b0407a9a2cccbb19a61ae2b Mon Sep 17 00:00:00 2001 From: Ryan Pepper Date: Tue, 10 Nov 2026 10:53:22 +0000 Subject: [PATCH 05/10] Apply clang-format to the boundary condition changes --- .../carbon/detail/dense_distributed/span.h | 5 ++- tests/test_dense_distributed_bc_host.cpp | 37 +++++++++---------- 2 files changed, 20 insertions(+), 22 deletions(-) diff --git a/include/carbon/detail/dense_distributed/span.h b/include/carbon/detail/dense_distributed/span.h index 51ea0dfb..4d17d8f3 100644 --- a/include/carbon/detail/dense_distributed/span.h +++ b/include/carbon/detail/dense_distributed/span.h @@ -468,8 +468,9 @@ class Span { // Span is passed by value into every kernel launch (device parameter space), so it must stay // trivially copyable: no virtuals, no owning members. -static_assert(std::is_trivially_copyable_v, - "dense_distributed::Span is passed by value to kernels and must be trivially copyable"); +static_assert( + std::is_trivially_copyable_v, + "dense_distributed::Span is passed by value to kernels and must be trivially copyable"); [[nodiscard]] CARBON_HD constexpr auto Span::make_idx(int64_t ix, diff --git a/tests/test_dense_distributed_bc_host.cpp b/tests/test_dense_distributed_bc_host.cpp index c014cd33..8ee9c049 100644 --- a/tests/test_dense_distributed_bc_host.cpp +++ b/tests/test_dense_distributed_bc_host.cpp @@ -51,14 +51,14 @@ using carbon::detail::dense_distributed::Span; int g_checks = 0; -#define CHECK(cond, ctx) \ - do { \ - ++g_checks; \ - if (!(cond)) { \ - std::fprintf(stderr, "FAIL %s:%d %s [%s]\n", __FILE__, __LINE__, #cond, \ - std::string(ctx).c_str()); \ - std::exit(1); \ - } \ +#define CHECK(cond, ctx) \ + do { \ + ++g_checks; \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL %s:%d %s [%s]\n", __FILE__, __LINE__, #cond, \ + std::string(ctx).c_str()); \ + std::exit(1); \ + } \ } while (0) constexpr double kSentinel = 1.0e30; @@ -224,9 +224,8 @@ part_a_regression_guard() { for (int rank = 0; rank < lay.pg.world_size(); ++rank) { const std::string ctx = "A r=" + std::to_string(radius) + " " + mode_name(mode) + " " + lay.name + " rank=" + std::to_string(rank); - const RankView rv = - build_rank(global, lay.pg, lay.pg.coords_of(rank), mode, stencil, 0.5F, - BoundaryConditions::none()); + const RankView rv = build_rank(global, lay.pg, lay.pg.coords_of(rank), mode, stencil, + 0.5F, BoundaryConditions::none()); const Partition part(const_cast(rv.buf.data())); for_each_rank_cell_offset(rv, stencil, [&](const Idx& idx, carbon::int8_3d off) { const auto a = part.neighbour(rv.span, idx, off, 0); @@ -313,8 +312,8 @@ run_oracle_case(const std::string& label, for (int rank = 0; rank < lay.pg.world_size(); ++rank) { const std::string ctx = "B " + label + " r=" + std::to_string(radius) + " " + mode_name(mode) + " " + lay.name + " rank=" + std::to_string(rank); - const RankView rv = build_rank(global, lay.pg, lay.pg.coords_of(rank), mode, stencil, - spacing, bc); + const RankView rv = + build_rank(global, lay.pg, lay.pg.coords_of(rank), mode, stencil, spacing, bc); const Partition part(const_cast(rv.buf.data())); const carbon::int64_3d origin = rv.span.offset(); for_each_rank_cell_offset(rv, stencil, [&](const Idx& idx, carbon::int8_3d off) { @@ -402,8 +401,7 @@ part_c_analytic() { const Stencil stencil = cross_stencil(2); namespace dd = carbon::detail::dense_distributed; const ProcessGrid pg = ProcessGrid::custom(1, 1, 1, 1); - const carbon::int64_3d halo = - dd::halo_extent(pg, BoundaryModeDistributed::Open, stencil); + const carbon::int64_3d halo = dd::halo_extent(pg, BoundaryModeDistributed::Open, stencil); const dd::RankChunk chunk = dd::rank_chunk(global, pg, {0, 0, 0}, halo); // Outward derivative on a low face is -a, on a high face +a. Dirichlet value is u at the face. @@ -444,9 +442,8 @@ part_c_analytic() { int8_t d[3] = {0, 0, 0}; d[ax] = static_cast(side == 0 ? -k : k); int64_t t[3] = {c[0] + d[0], c[1] + d[1], c[2] + d[2]}; - const auto got = part.neighbour_bc( - span, Idx(c[0] + halo.x, c[1] + halo.y, c[2] + halo.z), - carbon::int8_3d{d[0], d[1], d[2]}, 0); + const auto got = part.neighbour_bc(span, Idx(c[0] + halo.x, c[1] + halo.y, c[2] + halo.z), + carbon::int8_3d{d[0], d[1], d[2]}, 0); CHECK(got.valid, ctx); // The extrapolated linear field at the outside location. CHECK(std::fabs(got.value - u(t[0], t[1], t[2])) < 1e-12, ctx); @@ -467,8 +464,8 @@ part_d_limits() { const BoundaryConditions bc = BoundaryConditions::none() .with(Face::XLow, carbon::neumann()) .with(Face::ZHigh, carbon::dirichlet(1.0)); - const RankView rv = build_rank(global, pg, {0, 0, 0}, BoundaryModeDistributed::Open, stencil, - 1.0F, bc); + const RankView rv = + build_rank(global, pg, {0, 0, 0}, BoundaryModeDistributed::Open, stencil, 1.0F, bc); const Partition part(const_cast(rv.buf.data())); const auto at = [&](int64_t x, int64_t y, int64_t z, int8_t dx, int8_t dy, int8_t dz) { return part.neighbour_bc(rv.span, Idx(x + rv.halo.x, y + rv.halo.y, z + rv.halo.z), From 4b88755e5476d450d3543269c511bfeafa12293b Mon Sep 17 00:00:00 2001 From: Ryan Pepper Date: Tue, 10 Nov 2026 13:33:03 +0000 Subject: [PATCH 06/10] Add boundary views, host store and a view-aware neighbour_bc BoundaryView holds, per GPU and per global face, the condition (kind and value, per component) of every stored face cell as raw pointers, so one trivially copyable struct serves host and device. resolve() mirrors neighbour_idx_bc but looks the condition up at the face cell under the target of the read; dirichlet_at() is the pinning query. HostBoundaryStore holds the arrays on the host and decides which part of each face a GPU stores: its owned tangential range widened by the stencil radius, clipped to the domain, nothing for faces it does not touch or on periodic axes. Partition::neighbour_bc gains a templated overload taking a view; the existing overload is unchanged. test_boundary_data_host (no GPU, no MPI) checks equivalence with the constants path, patches and per-component kinds against an independent oracle including diagonal reads, stored ranges and coverage, the pinning helper and validation. --- .../detail/dense_distributed/boundary_store.h | 220 ++++++ .../detail/dense_distributed/boundary_view.h | 205 ++++++ .../detail/dense_distributed/partition.h | 39 ++ tests/CMakeLists.txt | 3 + tests/README.md | 1 + tests/test_boundary_data_host.cpp | 635 ++++++++++++++++++ 6 files changed, 1103 insertions(+) create mode 100644 include/carbon/detail/dense_distributed/boundary_store.h create mode 100644 include/carbon/detail/dense_distributed/boundary_view.h create mode 100644 tests/test_boundary_data_host.cpp diff --git a/include/carbon/detail/dense_distributed/boundary_store.h b/include/carbon/detail/dense_distributed/boundary_store.h new file mode 100644 index 00000000..e8bf6c65 --- /dev/null +++ b/include/carbon/detail/dense_distributed/boundary_store.h @@ -0,0 +1,220 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace carbon::detail::dense_distributed { + +/** + * Range of one face stored on one GPU. Empty (@c count == 0) when the GPU does not touch the face, + * owns no cells, or the face's axis is periodic. + */ +struct FaceRange { + int64_t lo[2]{0, 0}; + int64_t hi[2]{0, 0}; + + [[nodiscard]] auto + cells() const noexcept -> int64_t { + return (hi[0] > lo[0] && hi[1] > lo[1]) ? (hi[0] - lo[0]) * (hi[1] - lo[1]) : 0; + } +}; + +/** + * Which part of global face @p face the chunk described by @p span stores. A pure function of the + * span geometry and the stencil radius @p radius3, so the device and host paths share it. + * + * The chunk touches the low face of an axis iff its owned range starts at 0, and the high face iff + * it ends at the global extent (owned ranges, never haloed ones: a halo reaches outside the domain). + * The stored tangential range is the owned range widened by @p radius3 on each tangential axis and + * clipped to the domain, so a diagonal read across the face finds the cell under its target. On a + * periodic tangential axis the whole axis is stored, because reads there wrap. Faces on a periodic + * axis are never stored (a condition on one is rejected at construction). + */ +[[nodiscard]] inline auto +face_range(const Span& span, + ::carbon::Face face, + const int32_3d& radius3) -> FaceRange { + const int64_3d halo = span.halo(); + const int64_3d off = span.offset(); + const int64_3d own = span.logic_extent(); + const int64_3d ge = span.global_extent(); + const int64_t own_lo[3] = {off.x + halo.x, off.y + halo.y, off.z + halo.z}; + const int64_t own_n[3] = {own.x, own.y, own.z}; + const int64_t ext[3] = {ge.x, ge.y, ge.z}; + const int64_t rad[3] = {radius3.x, radius3.y, radius3.z}; + const Axis axes[3] = {Axis::X, Axis::Y, Axis::Z}; + const BoundaryModeDistributed mode = span.boundary_mode(); + + FaceRange r; + if (own_n[0] <= 0 || own_n[1] <= 0 || own_n[2] <= 0) { + return r; + } + const int a = face_axis(face); + if (is_periodic(mode, axes[a])) { + return r; + } + const int64_t own_hi_a = own_lo[a] + own_n[a]; + const bool touches = face_is_high(face) ? (own_hi_a == ext[a]) : (own_lo[a] == 0); + if (!touches) { + return r; + } + for (int w = 0; w < 2; ++w) { + const int t = tangential_axis(a, w); + if (is_periodic(mode, axes[t])) { + r.lo[w] = 0; + r.hi[w] = ext[t]; + } else { + r.lo[w] = std::max(0, own_lo[t] - rad[t]); + r.hi[w] = std::min(ext[t], own_lo[t] + own_n[t] + rad[t]); + } + } + return r; +} + +/** + * Host-side storage of the face data of one GPU: the condition of every stored face cell, per + * component. Plain @c std::vector storage, so it can be built and tested without a device; the + * device path copies these arrays and builds a @ref BoundaryView over the device pointers. + */ +class HostBoundaryStore { +public: + HostBoundaryStore() = default; + + HostBoundaryStore(const Span& span, + const int32_3d& radius3, + int components) + : components_(components), + radius3_(radius3) { + for (int f = 0; f < ::carbon::kFaceCount; ++f) { + ranges_[f] = face_range(span, static_cast<::carbon::Face>(f), radius3); + const size_t n = static_cast(ranges_[f].cells()) * static_cast(components); + kind_[f].assign(n, static_cast(::carbon::BcKind::None)); + value_[f].assign(n, 0.0); + } + } + + [[nodiscard]] auto + range(::carbon::Face face) const noexcept -> const FaceRange& { + return ranges_[static_cast(face)]; + } + + [[nodiscard]] auto + components() const noexcept -> int { + return components_; + } + + /** + * Visit every stored cell of every face: @p fn(face, global_node, comp) returns the condition. + * @c global_node is the global coordinate of the face cell (the face's own axis at 0 or at + * extent - 1). @p fn must be a deterministic function of its arguments, because a cell stored on + * several GPUs (margins overlap neighbouring chunks) is filled independently on each. + * + * @throws std::invalid_argument if a stored condition has a non-finite value, or sits on a face + * whose axis is not larger than the stencil radius (the mirror cell would be outside the + * domain). + */ + template + void + fill(const int64_3d& global_extent, + Fn&& fn) { + const int64_t ext[3] = {global_extent.x, global_extent.y, global_extent.z}; + for (int f = 0; f < ::carbon::kFaceCount; ++f) { + const FaceRange& r = ranges_[f]; + if (r.cells() == 0) { + continue; + } + const int a = f / 2; + const int t0 = tangential_axis(a, 0); + const int t1 = tangential_axis(a, 1); + const int64_t e0 = r.hi[0] - r.lo[0]; + const int64_t e1 = r.hi[1] - r.lo[1]; + for (int c = 0; c < components_; ++c) { + for (int64_t j = 0; j < e1; ++j) { + for (int64_t i = 0; i < e0; ++i) { + int64_t g[3] = {0, 0, 0}; + g[a] = (f % 2) == 1 ? ext[a] - 1 : 0; + g[t0] = r.lo[0] + i; + g[t1] = r.lo[1] + j; + const ::carbon::FaceBc bc = + fn(static_cast<::carbon::Face>(f), int64_3d{g[0], g[1], g[2]}, c); + if (bc.kind != ::carbon::BcKind::None) { + const int64_t rad[3] = {radius3_.x, radius3_.y, radius3_.z}; + if (!std::isfinite(bc.value)) { + throw std::invalid_argument("boundary data: non-finite value on face " + + std::to_string(f)); + } + if (ext[a] <= rad[a]) { + throw std::invalid_argument( + "boundary data: condition on face " + std::to_string(f) + + " needs a global extent larger than the stencil radius on that axis"); + } + } + const size_t idx = static_cast((c * e1 + j) * e0 + i); + kind_[f][idx] = static_cast(bc.kind); + value_[f][idx] = bc.value; + } + } + } + } + } + + /** Raw access for the device upload. */ + [[nodiscard]] auto + kind_data(::carbon::Face face) const noexcept -> const std::vector& { + return kind_[static_cast(face)]; + } + + [[nodiscard]] auto + value_data(::carbon::Face face) const noexcept -> const std::vector& { + return value_[static_cast(face)]; + } + + /** View over this store's own host arrays (host kernels and tests). */ + [[nodiscard]] auto + host_view() const noexcept -> BoundaryView { + BoundaryView v; + for (int f = 0; f < ::carbon::kFaceCount; ++f) { + if (ranges_[f].cells() == 0) { + continue; + } + v.faces[f] = make_face_view(ranges_[f], kind_[f].data(), value_[f].data(), components_); + } + return v; + } + + /** Face view for arbitrary (for example device) pointers over this store's layout. */ + [[nodiscard]] static auto + make_face_view(const FaceRange& r, + const uint8_t* kind, + const double* value, + int components) noexcept -> BoundaryFaceView { + BoundaryFaceView fv; + fv.kind = kind; + fv.value = value; + fv.lo[0] = r.lo[0]; + fv.lo[1] = r.lo[1]; + fv.hi[0] = r.hi[0]; + fv.hi[1] = r.hi[1]; + fv.components = components; + return fv; + } + +private: + int components_{0}; + int32_3d radius3_{}; + FaceRange ranges_[::carbon::kFaceCount]{}; + std::vector kind_[::carbon::kFaceCount]{}; + std::vector value_[::carbon::kFaceCount]{}; +}; + +} // namespace carbon::detail::dense_distributed diff --git a/include/carbon/detail/dense_distributed/boundary_view.h b/include/carbon/detail/dense_distributed/boundary_view.h new file mode 100644 index 00000000..882c610d --- /dev/null +++ b/include/carbon/detail/dense_distributed/boundary_view.h @@ -0,0 +1,205 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +namespace carbon::detail::dense_distributed { + +/** Axis a face lies on (0 = x, 1 = y, 2 = z). */ +[[nodiscard]] constexpr CARBON_HD auto +face_axis(::carbon::Face face) noexcept -> int { + return static_cast(face) / 2; +} + +/** True for the face at the high end of its axis. */ +[[nodiscard]] constexpr CARBON_HD auto +face_is_high(::carbon::Face face) noexcept -> bool { + return (static_cast(face) % 2) == 1; +} + +/** The two axes tangential to @p axis, in increasing order. */ +[[nodiscard]] constexpr CARBON_HD auto +tangential_axis(int axis, + int which) noexcept -> int { + return which == 0 ? (axis == 0 ? 1 : 0) : (axis == 2 ? 1 : 2); +} + +/** + * Pointer-only, trivially copyable view of one global face on one GPU: the condition (kind, value) + * of every stored face cell, per component. The same struct serves host and device pointers. + * + * A face cell is addressed by its global tangential coordinates @c (t0, t1) (the two axes other + * than the face's own, in increasing order). Only the range @c [lo, hi) is stored: the owned + * tangential range of the chunk plus a margin of one stencil radius, clipped to the domain, so a + * diagonal read across the face finds the cell under its target. A GPU that does not touch the face + * has an empty view (null pointers, zero range) and @ref at reports @c BcKind::None everywhere. + */ +struct BoundaryFaceView { + const uint8_t* kind{nullptr}; + const double* value{nullptr}; + int64_t lo[2]{0, 0}; + int64_t hi[2]{0, 0}; + int32_t components{0}; + + /** Condition at global tangential cell @p t0, @p t1 for @p comp; @c None outside the stored range. */ + [[nodiscard]] constexpr CARBON_HD auto + at(int64_t t0, + int64_t t1, + int comp) const noexcept -> ::carbon::FaceBc { + if (kind == nullptr || comp < 0 || comp >= components || t0 < lo[0] || t0 >= hi[0] || + t1 < lo[1] || t1 >= hi[1]) { + return {}; + } + const int64_t e0 = hi[0] - lo[0]; + const int64_t e1 = hi[1] - lo[1]; + const int64_t i = (static_cast(comp) * e1 + (t1 - lo[1])) * e0 + (t0 - lo[0]); + return ::carbon::FaceBc{static_cast<::carbon::BcKind>(kind[i]), value[i]}; + } +}; + +/** Result of @ref BoundaryView::resolve: like @ref NeighbourIdxBc plus the condition to apply. */ +struct BoundaryResolution { + NeighbourIdxBc where{}; + ::carbon::FaceBc bc{}; +}; + +/** + * The six face views of one GPU. Trivially copyable and pointer-only, so it is captured by value + * into a device lambda next to a @c Partition. + */ +struct BoundaryView { + BoundaryFaceView faces[::carbon::kFaceCount]{}; + + /** + * Data-driven counterpart of @ref neighbour_idx_bc: the condition is looked up in the face data at + * the face cell under the target (its global tangential coordinates) instead of coming from + * @c Span. Interior reads behave exactly as in @ref neighbour_idx. A read out of domain across a + * face with no stored condition at that cell, across two or more faces, or whose mirror cell is + * outside the domain or buffer, is @c Invalid. + */ + [[nodiscard]] constexpr CARBON_HD auto + resolve(const Span& span, + const Idx& idx, + ::carbon::int8_3d offset, + int comp) const noexcept -> BoundaryResolution { + const int64_3d cell = idx.cell(); + const int64_3d haloed = span.haloed_extent(); + const int64_3d global_extent = span.global_extent(); + const int64_3d off = span.offset(); + const BoundaryModeDistributed mode = span.boundary_mode(); + + const int64_t b[3] = {cell.x + static_cast(offset.x), + cell.y + static_cast(offset.y), + cell.z + static_cast(offset.z)}; + const int64_t haloed_a[3] = {haloed.x, haloed.y, haloed.z}; + const int64_t global_a[3] = {global_extent.x, global_extent.y, global_extent.z}; + const int64_t off_a[3] = {off.x, off.y, off.z}; + const Axis axes[3] = {Axis::X, Axis::Y, Axis::Z}; + + int bc_axis = -1; + int bc_axis_count = 0; + for (int a = 0; a < 3; ++a) { + const int64_t g = b[a] + off_a[a]; + if ((g < 0 || g >= global_a[a]) && !is_periodic(mode, axes[a])) { + bc_axis = a; + ++bc_axis_count; + } + } + + BoundaryResolution r; + if (bc_axis_count == 0) { + if (b[0] < 0 || b[0] >= haloed_a[0] || b[1] < 0 || b[1] >= haloed_a[1] || b[2] < 0 || + b[2] >= haloed_a[2]) { + return r; + } + r.where.idx = Idx(b[0], b[1], b[2]); + r.where.kind = NeighbourKindBc::Interior; + return r; + } + if (bc_axis_count > 1) { + return r; + } + + const int64_t g_bc = b[bc_axis] + off_a[bc_axis]; + const int64_t extent = global_a[bc_axis]; + const bool low = g_bc < 0; + const int64_t k = low ? -g_bc : g_bc - (extent - 1); + const int64_t mirror_global = low ? k : (extent - 1) - k; + if (mirror_global < 0 || mirror_global >= extent) { + return r; + } + int64_t m[3] = {b[0], b[1], b[2]}; + m[bc_axis] = mirror_global - off_a[bc_axis]; + if (m[0] < 0 || m[0] >= haloed_a[0] || m[1] < 0 || m[1] >= haloed_a[1] || m[2] < 0 || + m[2] >= haloed_a[2]) { + return r; + } + + const ::carbon::Face face = static_cast<::carbon::Face>(2 * bc_axis + (low ? 0 : 1)); + int64_t t[2]; + for (int w = 0; w < 2; ++w) { + const int ta = tangential_axis(bc_axis, w); + int64_t g = b[ta] + off_a[ta]; + if (is_periodic(mode, axes[ta])) { + g %= global_a[ta]; + g = g < 0 ? g + global_a[ta] : g; + } + t[w] = g; + } + const ::carbon::FaceBc bc = faces[static_cast(face)].at(t[0], t[1], comp); + if (bc.kind == ::carbon::BcKind::None) { + return r; + } + r.where.idx = Idx(m[0], m[1], m[2]); + r.where.kind = NeighbourKindBc::Boundary; + r.where.face = face; + r.where.k = static_cast(k); + r.bc = bc; + return r; + } + + /** + * Pinning query for solvers. True when the cell at @p idx lies on a face whose stored condition + * at that cell is Dirichlet for @p comp; @p value is then the Dirichlet value. A cell on several + * faces (an edge or corner) takes the first Dirichlet face in the order XLow, XHigh, YLow, YHigh, + * ZLow, ZHigh. + */ + [[nodiscard]] constexpr CARBON_HD auto + dirichlet_at(const Span& span, + const Idx& idx, + int comp, + double& value) const noexcept -> bool { + const int64_3d cell = idx.cell(); + const int64_3d off = span.offset(); + const int64_3d ge = span.global_extent(); + const int64_t g[3] = {cell.x + off.x, cell.y + off.y, cell.z + off.z}; + const int64_t ext[3] = {ge.x, ge.y, ge.z}; + for (int f = 0; f < ::carbon::kFaceCount; ++f) { + const int a = f / 2; + const bool high = (f % 2) == 1; + if (g[a] != (high ? ext[a] - 1 : 0)) { + continue; + } + const ::carbon::FaceBc bc = + faces[f].at(g[tangential_axis(a, 0)], g[tangential_axis(a, 1)], comp); + if (bc.kind == ::carbon::BcKind::Dirichlet) { + value = bc.value; + return true; + } + } + return false; + } +}; + +static_assert(std::is_trivially_copyable_v, + "BoundaryFaceView rides in a by-value kernel closure"); +static_assert(std::is_trivially_copyable_v, + "BoundaryView rides in a by-value kernel closure"); + +} // namespace carbon::detail::dense_distributed diff --git a/include/carbon/detail/dense_distributed/partition.h b/include/carbon/detail/dense_distributed/partition.h index 31d08415..32e68d0c 100644 --- a/include/carbon/detail/dense_distributed/partition.h +++ b/include/carbon/detail/dense_distributed/partition.h @@ -274,6 +274,45 @@ class Partition { true}; } + /** + * Like @ref neighbour_bc, but the condition comes from @p view (a @c BoundaryView) instead of the + * grid: it is looked up per face cell and per component, at the face cell under the target of the + * read, so it can vary across a face and differ between fields and components. The formulas are + * the same: Dirichlet @c 2*g - u_mirror, Neumann @c u_mirror + 2*k*h*g. + * + * Reads with no stored condition at that cell, across two or more faces, or interior reads that + * leave the buffer return @c valid = false, as for @ref neighbour. Additive and opt-in: the + * overload without a view is unchanged. @p comp indexes both the field component and the boundary + * data component, so the boundary data needs at least as many components as the field. + */ + template + [[nodiscard]] CARBON_HD constexpr auto + neighbour_bc(const Span& span, + const View& view, + const Idx& idx, + int8_3d offset, + int component_id) const noexcept -> NeighbourValue { + static_assert(std::is_floating_point_v, + "Partition::neighbour_bc computes virtual boundary values and needs a " + "floating-point element type"); + const auto res = view.resolve(span, idx, offset, component_id); + if (res.where.kind == NeighbourKindBc::Invalid) { + return {}; + } + const T mirror = ptr_[span.linear_offset(res.where.idx, component_id)]; + if (res.where.kind == NeighbourKindBc::Interior) { + return NeighbourValue{mirror, true}; + } + const T g = static_cast(res.bc.value); + if (res.bc.kind == BcKind::Dirichlet) { + return NeighbourValue{static_cast(2) * g - mirror, true}; + } + return NeighbourValue{ + static_cast(mirror + static_cast(2) * static_cast(res.where.k) * + static_cast(span.spacing()) * g), + 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 diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index da32b79a..b88de10f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -161,6 +161,9 @@ carbon_add_unit_test(dense_distributed_host) # Partition::neighbour_bc against an independent oracle on emulated slab / pencil / brick worlds, # and the guard that no conditions means neighbour_bc == neighbour. No GPU and no MPI. carbon_add_unit_test(dense_distributed_bc_host) +# Spatially varying boundary data (BoundaryData views, HostBoundaryStore, Partition::neighbour_bc with +# a view) on emulated slab / pencil / brick worlds against an independent oracle. No GPU, no MPI. +carbon_add_unit_test(boundary_data_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. diff --git a/tests/README.md b/tests/README.md index 78a3cb54..37866b3b 100644 --- a/tests/README.md +++ b/tests/README.md @@ -23,6 +23,7 @@ completeness. | `test_logging.cpp` | Logging smoke test: `carbon::init()` plus a single `CARBON_LOG_INFO` call to verify the spdlog wiring. | CPU only | | `test_memory_side.cpp` | `MemorySide` enum: count, integer values, `to_string` / `to_int`, stream insertion, exception on out-of-range conversion. | CPU only | | `test_dense_distributed_bc_host.cpp` | `DenseDistributed` per-face boundary conditions (Dirichlet / Neumann): `neighbour_bc` equals `neighbour` when no conditions are set, matches an independent oracle for every owned cell and offset on emulated slab / pencil / brick worlds (radius 1 and 2, mixed periodic axes), reproduces linear fields exactly, and keeps edge / corner reads invalid. | CPU only | +| `test_boundary_data_host.cpp` | Spatially varying `DenseDistributed` boundary data: constant data equals the per-face constants path, Dirichlet rectangle / disc patches, per-component kinds and diagonal reads match an independent oracle on emulated slab / pencil / brick worlds (radius 1 and 2, periodic axes), stored face ranges and coverage across ranks, the pinning helper and validation. | CPU only | | `test_stencil.cpp` | `Stencil` construction from point lists; verifies radius computation, point storage, and the empty-stencil case. | CPU only | | `test_transfer.cpp` | Host-only `BufferGroup` transfer: builds two single-entry host buffer groups and exercises `Transfer` on the CPU side without touching CUDA. | CPU only | | `test_gpu.cpp` | `device_count()`, `GpuGroup` default construction, multi-allocation buffer groups, `StreamGroup` / `EventGroup` sizing across all visible devices. | Multi-GPU | diff --git a/tests/test_boundary_data_host.cpp b/tests/test_boundary_data_host.cpp new file mode 100644 index 00000000..24cf0368 --- /dev/null +++ b/tests/test_boundary_data_host.cpp @@ -0,0 +1,635 @@ +// Host-side tests for spatially varying boundary data on carbon::DenseDistributed +// (HostBoundaryStore, BoundaryView::resolve / dirichlet_at, Partition::neighbour_bc with a view). +// +// No GPU and no MPI: every rank of a process grid is emulated on the host. Each rank gets the Span +// the grid would build, a HostBoundaryStore filled from a deterministic function of global position, +// and a host buffer filled the way a completed halo exchange leaves it (in-domain cells, including +// halo cells that alias a neighbour's owned cells, hold the analytic field; halo cells outside the +// domain hold a sentinel that must never be read). +// +// Parts: +// A Equivalence guard: constant data reproduces the per-face constants path +// (Partition::neighbour_bc without a view) for every offset, layout and mode. +// B Oracle: a Dirichlet rectangle and a Dirichlet disc on otherwise Neumann faces, faces with no +// condition, and a two-component field with a different kind per component, compared with an +// independent per-cell reference. Offsets include diagonals, so the condition must come from the +// face cell under the target, across rank boundaries and on unsplit axes. +// C Geometry: stored ranges per rank, empty ranks, coverage of every global face cell, and +// deterministic agreement of cells stored on several ranks. +// D Pinning helper and validation. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace dd = carbon::detail::dense_distributed; +using carbon::Axis; +using carbon::BcKind; +using carbon::BoundaryConditions; +using carbon::BoundaryModeDistributed; +using carbon::Face; +using carbon::FaceBc; +using carbon::ProcessGrid; +using carbon::Stencil; +using dd::Idx; +using dd::Partition; +using dd::Span; + +int g_checks = 0; + +#define CHECK(cond, ctx) \ + do { \ + ++g_checks; \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL %s:%d %s [%s]\n", __FILE__, __LINE__, #cond, \ + std::string(ctx).c_str()); \ + std::exit(1); \ + } \ + } while (0) + +constexpr double kSentinel = 1.0e30; + +[[nodiscard]] auto +field(int64_t x, + int64_t y, + int64_t z, + int comp) -> double { + const double fx = static_cast(x); + const double fy = static_cast(y); + const double fz = static_cast(z); + return 1.0 + 0.37 * fx + 0.11 * fy + 0.053 * fz + 0.013 * fx * fy + 0.007 * fy * fz - + 0.003 * fx * fz + 0.0011 * fx * fy * fz + 100.0 * comp; +} + +[[nodiscard]] auto +cross_stencil(int radius) -> Stencil { + std::vector pts; + for (int r = 1; r <= radius; ++r) { + pts.push_back({r, 0, 0}); + pts.push_back({-r, 0, 0}); + pts.push_back({0, r, 0}); + pts.push_back({0, -r, 0}); + pts.push_back({0, 0, r}); + pts.push_back({0, 0, -r}); + } + return Stencil(pts); +} + +[[nodiscard]] auto +mod_pos(int64_t v, + int64_t n) -> int64_t { + const int64_t r = v % n; + return r < 0 ? r + n : r; +} + +struct Layout { + std::string name; + ProcessGrid pg; +}; + +[[nodiscard]] auto +layouts() -> std::vector { + return { + {"single(1,1,1)", ProcessGrid::custom(1, 1, 1, 1)}, + {"slab(1,1,2)", ProcessGrid::custom(2, 1, 1, 2)}, + {"slab(1,1,3)", ProcessGrid::custom(3, 1, 1, 3)}, + {"pencil(1,2,2)", ProcessGrid::custom(4, 1, 2, 2)}, + {"pencil(2,1,2)", ProcessGrid::custom(4, 2, 1, 2)}, + {"brick(2,2,2)", ProcessGrid::custom(8, 2, 2, 2)}, + }; +} + +[[nodiscard]] auto +mode_name(BoundaryModeDistributed m) -> std::string { + std::string s; + s += carbon::is_periodic(m, Axis::X) ? "X" : ""; + s += carbon::is_periodic(m, Axis::Y) ? "Y" : ""; + s += carbon::is_periodic(m, Axis::Z) ? "Z" : ""; + return s.empty() ? "open" : "periodic:" + s; +} + +[[nodiscard]] auto +modes() -> std::vector { + using M = BoundaryModeDistributed; + return {M::Open, M::PeriodicZ, M::PeriodicX, M::PeriodicX | M::PeriodicY}; +} + +// One emulated rank. +struct RankView { + Span span; + std::vector buf; // components * linear_storage_elements + carbon::int64_3d owned{}; + carbon::int64_3d halo{}; + dd::HostBoundaryStore store; +}; + +template +[[nodiscard]] auto +build_rank(const carbon::int64_3d& global, + const ProcessGrid& pg, + carbon::int32_3d coords, + BoundaryModeDistributed mode, + const Stencil& stencil, + float spacing, + int comps, + const BoundaryConditions& span_bc, + Fn&& cond) -> RankView { + const carbon::int64_3d halo = dd::halo_extent(pg, mode, stencil); + const dd::RankChunk chunk = dd::rank_chunk(global, pg, coords, halo); + RankView rv; + rv.span = Span(chunk.haloed, global, chunk.xy_pitch, chunk.offset, chunk.halo, mode, + carbon::float32_3d{}, spacing, span_bc); + rv.owned = chunk.owned; + rv.halo = chunk.halo; + rv.store = dd::HostBoundaryStore(rv.span, stencil.radius3(), comps); + rv.store.fill(global, cond); + const size_t stride = static_cast(rv.span.linear_storage_elements()); + rv.buf.assign(stride * static_cast(comps), kSentinel); + const int64_t gdim[3] = {global.x, global.y, global.z}; + const Axis axes[3] = {Axis::X, Axis::Y, Axis::Z}; + for (int c = 0; c < comps; ++c) { + for (int64_t bz = 0; bz < chunk.haloed.z; ++bz) { + for (int64_t by = 0; by < chunk.haloed.y; ++by) { + for (int64_t bx = 0; bx < chunk.haloed.x; ++bx) { + const int64_t g[3] = {bx + chunk.offset.x, by + chunk.offset.y, bz + chunk.offset.z}; + int64_t w[3]; + bool fillable = true; + for (int a = 0; a < 3; ++a) { + const bool out = g[a] < 0 || g[a] >= gdim[a]; + if (!out) { + w[a] = g[a]; + } else if (carbon::is_periodic(mode, axes[a])) { + w[a] = mod_pos(g[a], gdim[a]); + } else { + fillable = false; + } + } + if (fillable) { + rv.buf[static_cast(rv.span.linear_offset(Idx(bx, by, bz), c))] = + field(w[0], w[1], w[2], c); + } + } + } + } + } + return rv; +} + +template +void +for_each_rank_cell_offset(const RankView& rv, + const Stencil& stencil, + Fn&& fn) { + const carbon::int32_3d r3 = stencil.radius3(); + for (int64_t iz = 0; iz < rv.owned.z; ++iz) { + for (int64_t iy = 0; iy < rv.owned.y; ++iy) { + for (int64_t ix = 0; ix < rv.owned.x; ++ix) { + const Idx idx(rv.halo.x + ix, rv.halo.y + iy, rv.halo.z + iz); + for (int dz = -r3.z; dz <= r3.z; ++dz) { + for (int dy = -r3.y; dy <= r3.y; ++dy) { + for (int dx = -r3.x; dx <= r3.x; ++dx) { + fn(idx, carbon::int8_3d{static_cast(dx), static_cast(dy), + static_cast(dz)}); + } + } + } + } + } + } +} + +// --------------------------------------------------------------------------------------------- +// Part A: constant data equals the per-face constants path. +// --------------------------------------------------------------------------------------------- +void +part_a_equivalence() { + const carbon::int64_3d global{9, 8, 7}; + using carbon::dirichlet; + using carbon::neumann; + const BoundaryConditions all = BoundaryConditions::none() + .with(Face::XLow, neumann(0.0)) + .with(Face::XHigh, neumann(0.75)) + .with(Face::YLow, dirichlet(-1.25)) + .with(Face::YHigh, neumann(0.0)) + .with(Face::ZLow, dirichlet(2.0)) + .with(Face::ZHigh, neumann(-0.5)); + const BoundaryConditions one = BoundaryConditions::none().with(Face::ZHigh, dirichlet(1.0)); + for (const BoundaryConditions& bc : {all, one}) { + for (int radius = 1; radius <= 2; ++radius) { + const Stencil stencil = cross_stencil(radius); + for (const BoundaryModeDistributed mode : modes()) { + // Conditions on a periodic axis are rejected by the grid; keep them off the spec here. + BoundaryConditions spec = bc; + const Axis axes[3] = {Axis::X, Axis::Y, Axis::Z}; + for (int f = 0; f < carbon::kFaceCount; ++f) { + if (carbon::is_periodic(mode, axes[f / 2])) { + spec = spec.with(static_cast(f), FaceBc{}); + } + } + for (const Layout& lay : layouts()) { + for (int rank = 0; rank < lay.pg.world_size(); ++rank) { + const std::string ctx = "A r=" + std::to_string(radius) + " " + mode_name(mode) + " " + + lay.name + " rank=" + std::to_string(rank); + const RankView rv = build_rank(global, lay.pg, lay.pg.coords_of(rank), mode, stencil, + 0.5F, 1, spec, [&](Face f, carbon::int64_3d, int) { + return spec.at(f); + }); + const Partition part(const_cast(rv.buf.data())); + const dd::BoundaryView view = rv.store.host_view(); + for_each_rank_cell_offset(rv, stencil, [&](const Idx& idx, carbon::int8_3d off) { + const auto a = part.neighbour_bc(rv.span, idx, off, 0); + const auto b = part.neighbour_bc(rv.span, view, idx, off, 0); + CHECK(a.valid == b.valid, ctx); + if (a.valid) { + CHECK(a.value == b.value, ctx); + } + }); + } + } + } + } + } +} + +// --------------------------------------------------------------------------------------------- +// Part B: varying data against an independent oracle. +// --------------------------------------------------------------------------------------------- + +// The spatially varying conditions under test, a deterministic function of global position. +// comps == 1: ZHigh = Dirichlet rectangle in Neumann; XLow = Dirichlet disc in Neumann; YHigh has no +// condition elsewhere than a Neumann strip; other faces None. +// comps == 2: ZLow carries Dirichlet for component 0 and Neumann for component 1. +[[nodiscard]] auto +cond_patches(Face f, + int64_t t0, + int64_t t1, + int comp) -> FaceBc { + using carbon::dirichlet; + using carbon::neumann; + switch (f) { + case Face::ZHigh: // tangential (x, y) + if (t0 >= 3 && t0 < 6 && t1 >= 2 && t1 < 5) { + return dirichlet(2.0 + 0.1 * static_cast(t0) - 0.05 * static_cast(t1)); + } + return neumann(0.5); + case Face::XLow: { // tangential (y, z) + const double dy = static_cast(t0) - 3.5; + const double dz = static_cast(t1) - 3.0; + if (dy * dy + dz * dz <= 2.6 * 2.6) { + return dirichlet(-1.0 + 0.2 * static_cast(t1)); + } + return neumann(0.0); + } + case Face::YHigh: // tangential (x, z) + if (t1 >= 2 && t1 < 4) { + return neumann(-0.75); + } + return {}; + case Face::ZLow: // tangential (x, y): per-component kind + return comp == 0 ? dirichlet(0.25 * static_cast(t0)) : neumann(1.5); + default: + return {}; + } +} + +[[nodiscard]] auto +cond_for(int comps, + Face f, + const carbon::int64_3d& g, + int comp) -> FaceBc { + const int a = static_cast(f) / 2; + const int64_t gg[3] = {g.x, g.y, g.z}; + const int64_t t0 = gg[dd::tangential_axis(a, 0)]; + const int64_t t1 = gg[dd::tangential_axis(a, 1)]; + if (comps == 1) { + return f == Face::ZLow ? FaceBc{} : cond_patches(f, t0, t1, comp); + } + return f == Face::ZLow ? cond_patches(f, t0, t1, comp) : FaceBc{}; +} + +struct Expected { + bool valid{false}; + double value{0.0}; +}; + +[[nodiscard]] auto +oracle(const carbon::int64_3d& global, + BoundaryModeDistributed mode, + int comps, + float spacing, + const int64_t cell_global[3], + carbon::int8_3d off, + int comp) -> Expected { + const int64_t gdim[3] = {global.x, global.y, global.z}; + const Axis axes[3] = {Axis::X, Axis::Y, Axis::Z}; + const int64_t o[3] = {off.x, off.y, off.z}; + int64_t t[3]; + int out_axes = 0; + int bc_axis = -1; + for (int a = 0; a < 3; ++a) { + t[a] = cell_global[a] + o[a]; + if (t[a] >= 0 && t[a] < gdim[a]) { + continue; + } + if (carbon::is_periodic(mode, axes[a])) { + t[a] = mod_pos(t[a], gdim[a]); + continue; + } + ++out_axes; + bc_axis = a; + } + if (out_axes == 0) { + return {true, field(t[0], t[1], t[2], comp)}; + } + if (out_axes > 1) { + return {}; + } + const bool is_low = t[bc_axis] < 0; + const int64_t k = is_low ? -t[bc_axis] : t[bc_axis] - (gdim[bc_axis] - 1); + int64_t m[3] = {t[0], t[1], t[2]}; + m[bc_axis] = is_low ? k : (gdim[bc_axis] - 1) - k; + if (m[bc_axis] < 0 || m[bc_axis] >= gdim[bc_axis]) { + return {}; + } + // The condition is the one at the face cell under the target: face axis at 0 / extent-1, the + // tangential coordinates of the target. + int64_t fc[3] = {t[0], t[1], t[2]}; + fc[bc_axis] = is_low ? 0 : gdim[bc_axis] - 1; + const Face f = static_cast(2 * bc_axis + (is_low ? 0 : 1)); + const FaceBc bc = cond_for(comps, f, carbon::int64_3d{fc[0], fc[1], fc[2]}, comp); + if (bc.kind == BcKind::None) { + return {}; + } + const double u_m = field(m[0], m[1], m[2], comp); + if (bc.kind == BcKind::Dirichlet) { + return {true, 2.0 * bc.value - u_m}; + } + return {true, u_m + 2.0 * static_cast(k) * static_cast(spacing) * bc.value}; +} + +void +run_oracle_case(int comps, + int radius, + BoundaryModeDistributed mode) { + const carbon::int64_3d global{9, 8, 7}; + const Stencil stencil = cross_stencil(radius); + const float spacing = 0.5F; + for (const Layout& lay : layouts()) { + for (int rank = 0; rank < lay.pg.world_size(); ++rank) { + const std::string ctx = "B comps=" + std::to_string(comps) + " r=" + std::to_string(radius) + + " " + mode_name(mode) + " " + lay.name + + " rank=" + std::to_string(rank); + const RankView rv = + build_rank(global, lay.pg, lay.pg.coords_of(rank), mode, stencil, spacing, comps, + BoundaryConditions::none(), [&](Face f, carbon::int64_3d g, int c) { + return cond_for(comps, f, g, c); + }); + const dd::BoundaryView view = rv.store.host_view(); + const carbon::int64_3d origin = rv.span.offset(); + const auto run = [&](const auto& part) { + for_each_rank_cell_offset(rv, stencil, [&](const Idx& idx, carbon::int8_3d off) { + const carbon::int64_3d c = idx.cell(); + const int64_t cg[3] = {c.x + origin.x, c.y + origin.y, c.z + origin.z}; + for (int comp = 0; comp < comps; ++comp) { + const Expected e = oracle(global, mode, comps, spacing, cg, off, comp); + const auto got = part.neighbour_bc(rv.span, view, idx, off, comp); + CHECK(got.valid == e.valid, ctx); + if (e.valid) { + CHECK(std::fabs(got.value - e.value) <= 1e-12 * (1.0 + std::fabs(e.value)), ctx); + CHECK(std::fabs(got.value) < 1.0e20, ctx + " (sentinel consumed)"); + } + } + }); + }; + if (comps == 1) { + run(Partition(const_cast(rv.buf.data()))); + } else { + run(Partition(const_cast(rv.buf.data()))); + } + } + } +} + +void +part_b_oracle() { + using M = BoundaryModeDistributed; + for (int radius = 1; radius <= 2; ++radius) { + for (const M mode : modes()) { + run_oracle_case(1, radius, mode); + run_oracle_case(2, radius, mode); + } + } +} + +// --------------------------------------------------------------------------------------------- +// Part C: geometry, coverage, deterministic agreement. +// --------------------------------------------------------------------------------------------- +void +part_c_geometry() { + using M = BoundaryModeDistributed; + struct Case { + carbon::int64_3d global; + M mode; + }; + const std::vector cases = {{{9, 8, 7}, M::Open}, + {{9, 8, 7}, M::PeriodicZ}, + {{6, 6, 2}, M::Open}, + {{5, 7, 3}, M::PeriodicX}}; + for (int radius = 1; radius <= 2; ++radius) { + const Stencil stencil = cross_stencil(radius); + const carbon::int32_3d r3 = stencil.radius3(); + for (const Case& cs : cases) { + if (std::min({cs.global.x, cs.global.y, cs.global.z}) <= radius) { + continue; // a condition on such an axis is rejected (checked in part D) + } + for (const Layout& lay : layouts()) { + const std::string base = "C r=" + std::to_string(radius) + " " + mode_name(cs.mode) + " " + + lay.name + " global=" + std::to_string(cs.global.x) + "x" + + std::to_string(cs.global.y) + "x" + std::to_string(cs.global.z); + const carbon::int64_3d halo = dd::halo_extent(lay.pg, cs.mode, stencil); + const int64_t gdim[3] = {cs.global.x, cs.global.y, cs.global.z}; + const int64_t rad[3] = {r3.x, r3.y, r3.z}; + const Axis axes[3] = {Axis::X, Axis::Y, Axis::Z}; + // covered[face] = set of (t0, t1) stored by at least one rank; value map checks agreement. + std::map, std::pair> seen; + std::map, bool> covered; + for (int rank = 0; rank < lay.pg.world_size(); ++rank) { + const carbon::int32_3d co = lay.pg.coords_of(rank); + const dd::RankChunk chunk = dd::rank_chunk(cs.global, lay.pg, co, halo); + // independent owned range from the split sizes + const int32_t cc[3] = {co.x, co.y, co.z}; + const int32_t dims[3] = {lay.pg.dims().x, lay.pg.dims().y, lay.pg.dims().z}; + int64_t lo[3], hi[3]; + for (int a = 0; a < 3; ++a) { + const auto counts = dd::split_extent(gdim[a], static_cast(dims[a])); + lo[a] = 0; + for (int i = 0; i < cc[a]; ++i) { + lo[a] += static_cast(counts[static_cast(i)]); + } + hi[a] = lo[a] + static_cast(counts[static_cast(cc[a])]); + } + const bool has_cells = hi[0] > lo[0] && hi[1] > lo[1] && hi[2] > lo[2]; + const Span span(chunk.haloed, cs.global, chunk.xy_pitch, chunk.offset, chunk.halo, + cs.mode); + dd::HostBoundaryStore store(span, r3, 1); + store.fill(cs.global, [&](Face f, carbon::int64_3d g, int c) { + return FaceBc{BcKind::Dirichlet, static_cast(g.x * 10000 + g.y * 100 + g.z) + + static_cast(static_cast(f)) * 0.001 + + c}; + }); + for (int f = 0; f < carbon::kFaceCount; ++f) { + const int a = f / 2; + const bool high = (f % 2) == 1; + const dd::FaceRange& r = store.range(static_cast(f)); + const bool touches = has_cells && !carbon::is_periodic(cs.mode, axes[a]) && + (high ? hi[a] == gdim[a] : lo[a] == 0); + if (!touches) { + CHECK(r.cells() == 0, + base + " rank=" + std::to_string(rank) + " untouched face stores 0"); + continue; + } + for (int w = 0; w < 2; ++w) { + const int t = dd::tangential_axis(a, w); + int64_t elo = std::max(0, lo[t] - rad[t]); + int64_t ehi = std::min(gdim[t], hi[t] + rad[t]); + if (carbon::is_periodic(cs.mode, axes[t])) { + elo = 0; + ehi = gdim[t]; + } + CHECK(r.lo[w] == elo && r.hi[w] == ehi, base + " stored range"); + } + const dd::BoundaryView view = store.host_view(); + for (int64_t j = r.lo[1]; j < r.hi[1]; ++j) { + for (int64_t i = r.lo[0]; i < r.hi[0]; ++i) { + covered[{f, i, j}] = true; + const FaceBc bc = view.faces[f].at(i, j, 0); + CHECK(bc.kind == BcKind::Dirichlet, base + " stored kind"); + const auto key = std::make_tuple(f, i, j, 0); + const auto it = seen.find(key); + if (it == seen.end()) { + seen[key] = {static_cast(bc.kind), bc.value}; + } else { + CHECK(it->second.second == bc.value, base + " ranks disagree on a shared cell"); + } + } + } + } + } + // every global face cell on a non-periodic axis is stored by at least one rank + for (int f = 0; f < carbon::kFaceCount; ++f) { + const int a = f / 2; + if (carbon::is_periodic(cs.mode, axes[a])) { + continue; + } + const int t0 = dd::tangential_axis(a, 0); + const int t1 = dd::tangential_axis(a, 1); + for (int64_t j = 0; j < gdim[t1]; ++j) { + for (int64_t i = 0; i < gdim[t0]; ++i) { + CHECK(covered.count({f, i, j}) == 1, base + " face cell not stored by any rank"); + } + } + } + } + } + } +} + +// --------------------------------------------------------------------------------------------- +// Part D: pinning helper and validation. +// --------------------------------------------------------------------------------------------- +void +part_d_pinning_and_validation() { + const carbon::int64_3d global{6, 6, 6}; + const Stencil stencil = cross_stencil(1); + const ProcessGrid pg = ProcessGrid::custom(1, 1, 1, 1); + const auto make = [&](auto&& cond) { + return build_rank(global, pg, {0, 0, 0}, BoundaryModeDistributed::Open, stencil, 1.0F, 1, + BoundaryConditions::none(), cond); + }; + // XLow Dirichlet 1 (an electrode patch only for y < 3), ZHigh Dirichlet 5, rest Neumann. + const RankView rv = make([](Face f, carbon::int64_3d g, int) -> FaceBc { + if (f == Face::XLow) { + return g.y < 3 ? carbon::dirichlet(1.0) : carbon::neumann(0.0); + } + if (f == Face::ZHigh) { + return carbon::dirichlet(5.0); + } + return carbon::neumann(0.0); + }); + const dd::BoundaryView view = rv.store.host_view(); + const auto at = [&](int64_t x, int64_t y, int64_t z, double& v) { + return view.dirichlet_at(rv.span, Idx(x + rv.halo.x, y + rv.halo.y, z + rv.halo.z), 0, v); + }; + double v = 0.0; + CHECK(at(0, 1, 2, v) && v == 1.0, "D XLow electrode cell is Dirichlet 1"); + CHECK(!at(0, 4, 2, v), "D XLow insulating cell is not Dirichlet"); + CHECK(at(3, 3, 5, v) && v == 5.0, "D ZHigh cell is Dirichlet 5"); + CHECK(at(0, 1, 5, v) && v == 1.0, "D edge cell takes the first Dirichlet face in order (XLow)"); + CHECK(at(0, 4, 5, v) && v == 5.0, + "D edge cell falls through to ZHigh when XLow is Neumann there"); + CHECK(!at(3, 3, 3, v), "D interior cell is not on any face"); + + const auto throws = [&](auto&& cond, const Stencil& st, const carbon::int64_3d& g) { + try { + (void)build_rank(g, pg, {0, 0, 0}, BoundaryModeDistributed::Open, st, 1.0F, 1, + BoundaryConditions::none(), cond); + } catch (const std::invalid_argument&) { + return true; + } + return false; + }; + CHECK(throws( + [](Face, carbon::int64_3d, int) { + return carbon::dirichlet(std::numeric_limits::quiet_NaN()); + }, + stencil, global), + "D non-finite value must throw"); + CHECK(throws( + [](Face f, carbon::int64_3d, int) { + return f == Face::ZLow ? carbon::neumann() : FaceBc{}; + }, + stencil, carbon::int64_3d{6, 6, 1}), + "D extent equal to the radius must throw"); + CHECK(!throws( + [](Face, carbon::int64_3d, int) { + return FaceBc{}; + }, + stencil, carbon::int64_3d{6, 6, 1}), + "D no conditions never throws"); +} + +} // namespace + +auto +main() -> int { + part_a_equivalence(); + std::printf("part A (constant data == per-face constants): ok\n"); + part_b_oracle(); + std::printf("part B (patches, per-component, diagonal reads vs oracle): ok\n"); + part_c_geometry(); + std::printf("part C (geometry, coverage, agreement): ok\n"); + part_d_pinning_and_validation(); + std::printf("part D (pinning helper, validation): ok\n"); + std::printf("test_boundary_data_host: %d checks passed\n", g_checks); + return 0; +} From c3c5ba2afc2c79fa0b3968ea53f7d6e4da00666b Mon Sep 17 00:00:00 2001 From: Ryan Pepper Date: Tue, 10 Nov 2026 13:33:03 +0000 Subject: [PATCH 07/10] Add the BoundaryData handle BoundaryData owns the per-GPU storage for spatially varying face conditions: fill() from a deterministic function of global position (or from the per-face constants), upload() through Transfer, view(gpu) for device kernels and host_view(gpu) for host use. It needs no access token and no loader change; the data must stay constant while a Skeleton using it runs. --- include/carbon/boundary_data_distributed.h | 216 +++++++++++++++++++++ include/carbon/carbon.h | 1 + 2 files changed, 217 insertions(+) create mode 100644 include/carbon/boundary_data_distributed.h diff --git a/include/carbon/boundary_data_distributed.h b/include/carbon/boundary_data_distributed.h new file mode 100644 index 00000000..af68c19f --- /dev/null +++ b/include/carbon/boundary_data_distributed.h @@ -0,0 +1,216 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace carbon { + +/** + * Spatially varying boundary conditions for a @ref DenseDistributed grid, held separately from the + * grid: the condition (kind and value, per component) of every cell of every exterior face. + * + * Unlike the per-face constants of @ref BoundaryConditions, the condition can change from cell to + * cell (a conducting electrode patch on an otherwise insulating face, an inlet on a wall), can + * differ per component (free-slip wall: Dirichlet normal velocity, Neumann tangential), and belongs + * to the data rather than the grid, so different fields on one grid can have different conditions. + * + * @par Use + * @code + * carbon::BoundaryData<1> bnd(grid, "phi_bc"); + * bnd.fill([](carbon::Face f, carbon::int64_3d g, int comp) -> carbon::FaceBc { + * if (f == carbon::Face::ZHigh && g.x < 8) return carbon::dirichlet(1.0); // electrode + * return carbon::neumann(0.0); // insulating + * }); + * bnd.upload(); + * // in a kernel loading lambda (no token, no loader change): + * const auto bv = bnd.view(loader.relative_gpu_id()); + * // in the device lambda: + * auto n = pin.neighbour_bc(span, bv, idx, carbon::int8_3d{0, 0, 1}, comp); + * @endcode + * + * @par What is stored + * Each GPU stores only the faces it touches, over its owned tangential range widened by one stencil + * radius (clipped to the domain), so a diagonal read across a face finds the cell under its target. + * Faces on a periodic axis are never stored. The stored cells are visited by @ref fill, which must + * be a deterministic function of global position: cells in the margin are filled independently on + * each neighbouring GPU and must agree. + * + * @par Lifetime and updates + * Constant while a Skeleton using it runs; the handle must outlive that Skeleton. It needs no + * access token: Read/Read pairs never conflict in the Skeleton. Do not call @ref fill or + * @ref upload while such a Skeleton is running. + * + * @tparam Components Number of components the conditions are given for. A field read through a view + * needs @c component_id < Components. + */ +template +class BoundaryData { + static_assert(Components >= 1, + "BoundaryData needs at least one component"); + +public: + /** + * Allocate storage for @p grid. All conditions start as @c BcKind::None; call @ref fill and + * @ref upload. + */ + BoundaryData(const DenseDistributed& grid, + std::string name) + : state_(std::make_shared()) { + State& s = *state_; + s.name = std::move(name); + s.sys = grid.system(); + s.global = grid.global_extent(); + const size_t n = grid.gpu_count(); + if (n == 0U) { + log::throw_with_log("BoundaryData '{}': grid has no GPUs", s.name); + } + const carbon::int32_3d radius3 = grid.stencil().radius3(); + s.stores.reserve(n); + for (size_t i = 0; i < n; ++i) { + s.stores.emplace_back(grid.spans()[i], radius3, Components); + } + recompute_layout_(); + s.dev_kind = s.sys.gpu_group().template buffer(s.kind_counts); + s.dev_value = s.sys.gpu_group().template buffer(s.value_counts); + } + + [[nodiscard]] auto + name() const noexcept -> const std::string& { + return state_->name; + } + + /** + * Set the condition of every stored face cell: @p fn(face, global_node, comp) returns a + * @ref FaceBc. @c global_node is the cell on the face (its own axis at 0 or extent - 1). + * + * @throws std::invalid_argument for a non-finite value, or a condition on an axis whose extent + * is not larger than the stencil radius. + */ + template + requires std::invocable void + fill(Fn&& fn) { + for (auto& store : state_->stores) { + store.fill(state_->global, fn); + } + } + + /** Same condition on every cell of each face, taken from the per-face constants @p bc. */ + void + fill(const BoundaryConditions& bc) { + fill([&bc](Face f, int64_3d, int) { + return bc.at(f); + }); + } + + /** Copy the host arrays to the devices and wait for the copy to finish. */ + void + upload() { + State& s = *state_; + const size_t n = s.stores.size(); + std::vector> hk; + std::vector> hv; + hk.reserve(n); + hv.reserve(n); + for (size_t i = 0; i < n; ++i) { + auto k = Cpu::buffer(s.kind_counts[i]); + auto v = Cpu::buffer(s.value_counts[i]); + for (int f = 0; f < kFaceCount; ++f) { + const auto& src_k = s.stores[i].kind_data(static_cast(f)); + const auto& src_v = s.stores[i].value_data(static_cast(f)); + if (!src_k.empty()) { + std::memcpy(k.data() + s.face_offset[i][f], src_k.data(), src_k.size() * sizeof(uint8_t)); + std::memcpy(v.data() + s.face_offset[i][f], src_v.data(), src_v.size() * sizeof(double)); + } + } + hk.push_back(std::move(k)); + hv.push_back(std::move(v)); + } + const auto host_k = detail::BufferGroup::from_vector(std::move(hk)); + const auto host_v = detail::BufferGroup::from_vector(std::move(hv)); + Stream stream = s.sys.stream(); + Transfer(s.sys, host_k, s.dev_kind)(stream); + Transfer(s.sys, host_v, s.dev_value)(stream); + stream.wait(); + } + + /** Device view for GPU @p gpu (index @c KernelLoader::relative_gpu_id()). */ + [[nodiscard]] auto + view(size_t gpu) const -> detail::dense_distributed::BoundaryView { + const State& s = *state_; + detail::dense_distributed::BoundaryView v; + for (int f = 0; f < kFaceCount; ++f) { + const auto& r = s.stores[gpu].range(static_cast(f)); + if (r.cells() == 0) { + continue; + } + v.faces[f] = detail::dense_distributed::HostBoundaryStore::make_face_view( + r, s.dev_kind[gpu].data() + s.face_offset[gpu][f], + s.dev_value[gpu].data() + s.face_offset[gpu][f], Components); + } + return v; + } + + /** Host view for GPU @p gpu, over the host arrays (host kernels and tests). */ + [[nodiscard]] auto + host_view(size_t gpu) const -> detail::dense_distributed::BoundaryView { + return state_->stores[gpu].host_view(); + } + +private: + struct State { + std::string name; + System sys; + int64_3d global{}; + std::vector stores; + std::vector> face_offset; + std::vector kind_counts; + std::vector value_counts; + Buffer dev_kind{}; + Buffer dev_value{}; + }; + + void + recompute_layout_() { + State& s = *state_; + const size_t n = s.stores.size(); + s.face_offset.assign(n, {}); + s.kind_counts.assign(n, 0U); + s.value_counts.assign(n, 0U); + for (size_t i = 0; i < n; ++i) { + size_t off = 0; + for (int f = 0; f < kFaceCount; ++f) { + s.face_offset[i][f] = off; + off += static_cast(s.stores[i].range(static_cast(f)).cells()) * + static_cast(Components); + } + s.kind_counts[i] = off; + s.value_counts[i] = off; + } + } + + std::shared_ptr state_; +}; + +} // namespace carbon diff --git a/include/carbon/carbon.h b/include/carbon/carbon.h index 2b9bf29f..b8bf84ba 100644 --- a/include/carbon/carbon.h +++ b/include/carbon/carbon.h @@ -23,6 +23,7 @@ device_count() noexcept -> int; } // namespace carbon #include +#include #include #include #include From e7c3d5e8c937a97f7457380b4a4cccc5b7e74cfe Mon Sep 17 00:00:00 2001 From: Ryan Pepper Date: Tue, 10 Nov 2026 13:33:03 +0000 Subject: [PATCH 08/10] Document spatially varying boundary data --- AGENTS.md | 1 + docs/CHANGELOG.md | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 38d5d943..020e1979 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,6 +18,7 @@ include/carbon/ Public API (umbrella: carbon/carbon.h) detail/ Internal: GPU/buffer/stream/event wrappers detail/dense/ Dense-grid primitives: idx, span, partition, field, kernel, launch_shape boundary_condition_distributed.h Per-face Dirichlet / Neumann conditions for DenseDistributed (opt-in, read via Partition::neighbour_bc) + boundary_data_distributed.h BoundaryData: per-cell, per-component face conditions held apart from the grid (read via Partition::neighbour_bc with a view) boundary_mode.h BoundaryMode enum (Open / PeriodicZ), both honoured end-to-end boundary_mode_distributed.h BoundaryModeDistributed per-axis periodic bitmask (DenseDistributed) data_view.h DataView enum (Standard / Internal / Boundary) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 9c558067..cbbbba74 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6209,3 +6209,29 @@ This unblocked the matrix on this host: the `sycl` and `hip-nvidia` images build 2, mixed periodic axes) checks the no-condition equivalence, an independent per-cell oracle, exact reproduction of linear fields on low and high faces, and the documented limits. `Dense`, `DenseDisg` and `Block` keep `BoundaryMode` and are not covered yet. +- **2026-11 — Spatially varying boundary data for `DenseDistributed` (`BoundaryData`).** The + per-face constants of the first boundary-condition change could not express a conducting + patch on an insulating face, an inlet on a wall, or different conditions for different + fields and components, because one kind and one value per face lived on the grid. New + `carbon/boundary_data_distributed.h` adds `BoundaryData`, a handle held apart + from the grid that stores the condition (`BcKind` and value) of every cell of every + exterior face, per component, filled from a deterministic function of global position + (`fill(fn(face, global_node, comp))`, or from the old constants) and uploaded like a field. + A kernel's loading lambda takes `bnd.view(loader.relative_gpu_id())` and the device lambda + calls the new `Partition::neighbour_bc(span, view, idx, offset, comp)`: the formulas are + unchanged (Dirichlet `2*g - u_m`, Neumann `u_m + 2*k*h*g`) but the condition is looked up + at the face cell under the *target* of the read, so a diagonal read across a patch edge + sees the right condition, including across rank boundaries and on unsplit axes. Each GPU + stores only the faces it touches, over its owned tangential range widened by the stencil + radius and clipped to the domain; faces on periodic axes are never stored. No loader, + access-token or Skeleton change is needed: the data is read-only to kernels and Read/Read + pairs never conflict, so it must simply stay constant while a Skeleton using it runs. + `BoundaryView::dirichlet_at` gives solvers the pinning query (first Dirichlet face in the + order XLow, XHigh, YLow, YHigh, ZLow, ZHigh on an edge or corner). Reads across two faces at + once stay invalid, and `fill` rejects non-finite values and conditions on an axis no larger + than the stencil radius. `Span`, `neighbour_bc` without a view and the grid constructors are + untouched. `boundary_data_host` (host-only, emulated slab / pencil / brick worlds) checks + equivalence with the constants path, rectangle and disc patches, per-component kinds and + diagonal reads against an independent oracle, the stored ranges and coverage across ranks, + agreement of margin cells, the pinning helper and validation; four mutations (Neumann sign, + tangential margin, source-versus-target lookup, pinning order) each make it fail. From 7bd3366b3304d92f9f4623a4ddbcb6c623fe342b Mon Sep 17 00:00:00 2001 From: Ryan Pepper Date: Tue, 10 Nov 2026 13:39:33 +0000 Subject: [PATCH 09/10] Add the BoundaryData device test Runs a six-point neighbour-sum kernel through a Skeleton, reading every neighbour with neighbour_bc and a BoundaryData view, over a grid with a Dirichlet rectangle, a Dirichlet disc, Neumann regions and unconditioned faces, and compares every owned cell with an independent host oracle. It requires boundary reads and invalid reads to both occur, so it cannot pass by taking only one path. --- tests/CMakeLists.txt | 3 + tests/README.md | 1 + tests/test_boundary_data.cu | 268 ++++++++++++++++++++++++++++++++++++ 3 files changed, 272 insertions(+) create mode 100644 tests/test_boundary_data.cu diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index b88de10f..ed0ac4dd 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -164,6 +164,9 @@ carbon_add_unit_test(dense_distributed_bc_host) # Spatially varying boundary data (BoundaryData views, HostBoundaryStore, Partition::neighbour_bc with # a view) on emulated slab / pencil / brick worlds against an independent oracle. No GPU, no MPI. carbon_add_unit_test(boundary_data_host) +# Device half: BoundaryData allocation, fill, upload and a neighbour_bc-with-view kernel in a Skeleton, +# against an independent host oracle (patched faces, unconditioned faces). +carbon_add_cuda_unit_test(boundary_data) # 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. diff --git a/tests/README.md b/tests/README.md index 37866b3b..7de41698 100644 --- a/tests/README.md +++ b/tests/README.md @@ -24,6 +24,7 @@ completeness. | `test_memory_side.cpp` | `MemorySide` enum: count, integer values, `to_string` / `to_int`, stream insertion, exception on out-of-range conversion. | CPU only | | `test_dense_distributed_bc_host.cpp` | `DenseDistributed` per-face boundary conditions (Dirichlet / Neumann): `neighbour_bc` equals `neighbour` when no conditions are set, matches an independent oracle for every owned cell and offset on emulated slab / pencil / brick worlds (radius 1 and 2, mixed periodic axes), reproduces linear fields exactly, and keeps edge / corner reads invalid. | CPU only | | `test_boundary_data_host.cpp` | Spatially varying `DenseDistributed` boundary data: constant data equals the per-face constants path, Dirichlet rectangle / disc patches, per-component kinds and diagonal reads match an independent oracle on emulated slab / pencil / brick worlds (radius 1 and 2, periodic axes), stored face ranges and coverage across ranks, the pinning helper and validation. | CPU only | +| `test_boundary_data.cu` | `BoundaryData` end to end: fill, upload, the per-GPU view taken in a kernel loading lambda and `neighbour_bc` with a view inside a `Skeleton`, over a grid with Dirichlet patches, Neumann regions and unconditioned faces, against an independent host oracle. | Multi-GPU | | `test_stencil.cpp` | `Stencil` construction from point lists; verifies radius computation, point storage, and the empty-stencil case. | CPU only | | `test_transfer.cpp` | Host-only `BufferGroup` transfer: builds two single-entry host buffer groups and exercises `Transfer` on the CPU side without touching CUDA. | CPU only | | `test_gpu.cpp` | `device_count()`, `GpuGroup` default construction, multi-allocation buffer groups, `StreamGroup` / `EventGroup` sizing across all visible devices. | Multi-GPU | diff --git a/tests/test_boundary_data.cu b/tests/test_boundary_data.cu new file mode 100644 index 00000000..3533a5bf --- /dev/null +++ b/tests/test_boundary_data.cu @@ -0,0 +1,268 @@ +// Device-side test for spatially varying boundary data on carbon::DenseDistributed (single process, +// every visible device; on the SYCL omp backend the host is the device). +// +// A six-point neighbour-sum kernel reads every neighbour through Partition::neighbour_bc with a +// BoundaryData view, inside a real Skeleton, so the whole path is exercised: BoundaryData +// allocation, fill, upload, the per-GPU view taken in the loading lambda, and the device lambda. The +// result over every owned cell is compared with an independent host oracle. +// +// The conditions vary across faces: a Dirichlet rectangle in an otherwise Neumann ZHigh face, a +// Dirichlet disc in an otherwise Neumann XLow face, a Neumann strip on YHigh, and nothing on the +// remaining faces (those reads must come back invalid). + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace { + +using carbon::BcKind; +using carbon::DenseDistributed; +using carbon::Face; +using carbon::FaceBc; +using carbon::int64_3d; + +constexpr double kInvalid = -999.0; +constexpr double kSentinel = 1.0e30; + +[[nodiscard]] auto +field(int64_t x, + int64_t y, + int64_t z) -> double { + const double fx = static_cast(x); + const double fy = static_cast(y); + const double fz = static_cast(z); + return 1.0 + 0.37 * fx + 0.11 * fy + 0.053 * fz + 0.013 * fx * fy + 0.007 * fy * fz - + 0.003 * fx * fz; +} + +[[nodiscard]] auto +condition(Face f, + const int64_3d& g) -> FaceBc { + switch (f) { + case Face::ZHigh: + if (g.x >= 3 && g.x < 7 && g.y >= 2 && g.y < 6) { + return carbon::dirichlet(2.0 + 0.1 * static_cast(g.x)); + } + return carbon::neumann(0.5); + case Face::XLow: { + const double dy = static_cast(g.y) - 5.0; + const double dz = static_cast(g.z) - 5.0; + if (dy * dy + dz * dz <= 3.2 * 3.2) { + return carbon::dirichlet(-1.0 + 0.2 * static_cast(g.z)); + } + return carbon::neumann(0.0); + } + case Face::YHigh: + return (g.z >= 3 && g.z < 6) ? carbon::neumann(-0.75) : FaceBc{}; + default: + return {}; + } +} + +// Independent reference for one neighbour read of owned cell g in direction d (one axis only). +[[nodiscard]] auto +expected_read(const int64_3d& ge, + const int64_t g[3], + const int d[3], + double h, + double& out) -> bool { + const int64_t ext[3] = {ge.x, ge.y, ge.z}; + int64_t t[3] = {g[0] + d[0], g[1] + d[1], g[2] + d[2]}; + for (int a = 0; a < 3; ++a) { + if (t[a] >= 0 && t[a] < ext[a]) { + continue; + } + const bool low = t[a] < 0; + const int64_t k = low ? -t[a] : t[a] - (ext[a] - 1); + int64_t m[3] = {t[0], t[1], t[2]}; + m[a] = low ? k : (ext[a] - 1) - k; + int64_t fc[3] = {t[0], t[1], t[2]}; + fc[a] = low ? 0 : ext[a] - 1; + const FaceBc bc = + condition(static_cast(2 * a + (low ? 0 : 1)), int64_3d{fc[0], fc[1], fc[2]}); + if (bc.kind == BcKind::None) { + return false; + } + const double u_m = field(m[0], m[1], m[2]); + out = bc.kind == BcKind::Dirichlet ? 2.0 * bc.value - u_m + : u_m + 2.0 * static_cast(k) * h * bc.value; + return true; + } + out = field(t[0], t[1], t[2]); + return true; +} + +} // namespace + +auto +main() -> int { + carbon::init(); + if (carbon::device_count() <= 0) { + CARBON_LOG_ERROR("test_boundary_data: no devices visible"); + return 1; + } + carbon::System sys(carbon::get_all_devices()); + const int64_3d global{12, 12, 12}; + const float spacing = 0.5F; + 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); + DenseDistributed grid(sys, global, stencil, carbon::BoundaryModeDistributed::Open, + carbon::float32_3d{}, spacing); + + carbon::BoundaryData<1> bnd(grid, "bc"); + bnd.fill([](Face f, int64_3d g, int) { + return condition(f, g); + }); + bnd.upload(); + + auto in = grid.newField(carbon::MemorySide::HostDevice, "in"); + auto out = grid.newField(carbon::MemorySide::HostDevice, "out"); + for (size_t gpu = 0; gpu < grid.gpu_count(); ++gpu) { + const auto& span = grid.spans()[gpu]; + 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(); + double* hi = in.cpu_buffers()[gpu].data(); + double* ho = out.cpu_buffers()[gpu].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 bool own = x >= halo.x && x < halo.x + owned.x && y >= halo.y && + y < halo.y + owned.y && z >= halo.z && z < halo.z + owned.z; + 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] = own ? field(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); + stream.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_boundary_data: upload failed: {}", e.what()); + return 1; + } + + using Span = DenseDistributed::Span; + using Idx = DenseDistributed::Idx; + carbon::Skeleton sk(sys, carbon::Skeleton::Options(carbon::OverlapMode::None)); + sk.add(carbon::Kernel::compute( + grid, + [in, out, &bnd](carbon::KernelLoader& loader) { + const auto pin = loader.read_stencil(in); + const auto pout = loader.write(out); + const auto bv = bnd.view(loader.relative_gpu_id()); + return [pin, pout, bv] CARBON_HOST_DEVICE(Span s, Idx idx) { + const int dirs[6][3] = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, + {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}; + double acc = 0.0; + for (const auto& d : dirs) { + const auto n = pin.neighbour_bc( + s, bv, idx, + carbon::int8_3d{static_cast(d[0]), static_cast(d[1]), + static_cast(d[2])}, + 0); + acc += n.valid ? n.value : kInvalid; + } + pout.write(s, idx, 0, acc); + }; + }, + "bc_neighbour_sum")); + try { + sk.compile(); + sk.run(); + sk.wait(); + carbon::Transfer(sys, out.gpu_buffers(), out.cpu_buffers())(stream); + stream.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_boundary_data: skeleton or download failed: {}", e.what()); + return 1; + } + + size_t cells = 0; + size_t mismatches = 0; + size_t boundary_reads = 0; + size_t invalid_reads = 0; + for (size_t gpu = 0; gpu < grid.gpu_count(); ++gpu) { + const auto& span = grid.spans()[gpu]; + 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 double* ho = out.cpu_buffers()[gpu].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 g3 = + span.global_location(span.make_idx(halo.x + x, halo.y + y, halo.z + z)); + const int64_t g[3] = {g3.x, g3.y, g3.z}; + 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 want = 0.0; + for (const auto& d : kDirs) { + double v = 0.0; + if (expected_read(global, g, d, static_cast(spacing), v)) { + want += v; + const int64_t t[3] = {g[0] + d[0], g[1] + d[1], g[2] + d[2]}; + boundary_reads += (t[0] < 0 || t[0] >= global.x || t[1] < 0 || t[1] >= global.y || + t[2] < 0 || t[2] >= global.z) + ? 1U + : 0U; + } else { + want += kInvalid; + ++invalid_reads; + } + } + const double got = ho[(halo.z + z) * pitch + (halo.y + y) * haloed.x + (halo.x + x)]; + ++cells; + if (std::fabs(got - want) > 1e-9 * (1.0 + std::fabs(want))) { + if (mismatches < 4U) { + CARBON_LOG_ERROR("test_boundary_data: cell ({},{},{}) got {} want {}", g[0], g[1], + g[2], got, want); + } + ++mismatches; + } + } + } + } + } + if (boundary_reads == 0U || invalid_reads == 0U) { + CARBON_LOG_ERROR( + "test_boundary_data: the case must exercise both boundary reads ({}) and unconditioned " + "faces ({})", + boundary_reads, invalid_reads); + return 1; + } + if (mismatches != 0U) { + CARBON_LOG_ERROR("test_boundary_data: {} of {} cells differ from the oracle", mismatches, + cells); + return 1; + } + CARBON_LOG_INFO( + "test_boundary_data: {} cells match the oracle ({} boundary reads, {} invalid reads)", cells, + boundary_reads, invalid_reads); + return 0; +} From 980bddba4d320d47bbfabc1c7406383cca4fd013 Mon Sep 17 00:00:00 2001 From: Ryan Pepper Date: Tue, 10 Nov 2026 14:26:34 +0000 Subject: [PATCH 10/10] Add the offset_current_terminals example Current enters a conducting box through a disc terminal on the top face and leaves through an offset one on the bottom face, insulating elsewhere, with a resistive sphere between. The flux differs from cell to cell on one face, so it is declared with BoundaryData and read through neighbour_bc with a view in a Jacobi sweep run by a Skeleton; a second BoundaryData gives the conductivity zero flux on every face. It solves the declared terminals and the same current spread evenly over each face, writes a two-panel PPM of the potential, and fails unless the iteration has converged and the current crossing the plane midway between the terminals matches the injected current to 1%. --- docs/CHANGELOG.md | 13 + examples/CMakeLists.txt | 5 + examples/offset_current_terminals.cu | 588 +++++++++++++++++++++++++++ 3 files changed, 606 insertions(+) create mode 100644 examples/offset_current_terminals.cu diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index cbbbba74..7fd92be8 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6235,3 +6235,16 @@ This unblocked the matrix on this host: the `sycl` and `hip-nvidia` images build diagonal reads against an independent oracle, the stored ranges and coverage across ranks, agreement of margin cells, the pinning helper and validation; four mutations (Neumann sign, tangential margin, source-versus-target lookup, pinning order) each make it fail. +- **2026-11 — `offset_current_terminals` example.** Steady current flow in a conducting box with a + resistive sphere: current enters through a disc-shaped terminal on the top face and leaves + through an offset one on the bottom face, insulating elsewhere. That is a non-zero flux that + differs from cell to cell on one face, which per-face constants cannot express, so it is declared + with `BoundaryData` and read through `Partition::neighbour_bc` with a view in a Jacobi sweep run + by a Skeleton. A second `BoundaryData` gives the conductivity field zero flux on every face, so + two fields on one grid carry different conditions. The program solves the declared terminals and + the same current spread evenly over each face (all one constant per face can say), writes a + two-panel PPM of the potential (`--raw DIR` also dumps phi and the current density), and exits + non-zero unless the iteration has converged and the current crossing the plane midway between + the terminals matches the injected current to 1% (the even case must carry none sideways). The + checks run on the host over small arrays, so the example does not depend on the reduction + kernels. Flipping the Neumann sign reverses the current and fails the check. diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 533910a0..0bc93fd4 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -105,6 +105,11 @@ _carbon_example_add(carbon_example_cg_poisson_unified cg_poisson_unified.cu) target_link_libraries(carbon_example_cg_poisson_unified PRIVATE carbon::carbon carbon::third_party::clipp) +# Spatially varying boundary data: current injected through one disc terminal and extracted through +# an offset one, insulating elsewhere. Needs carbon::BoundaryData (a different flux per face cell). +_carbon_example_add(carbon_example_offset_current_terminals offset_current_terminals.cu) +target_link_libraries(carbon_example_offset_current_terminals PRIVATE carbon::carbon) + _carbon_example_add(carbon_example_salt_pepper_filter salt_pepper_filter.cu) target_link_libraries(carbon_example_salt_pepper_filter PRIVATE carbon::carbon) # Bake the absolute path of examples/data into the binary so running with no args picks diff --git a/examples/offset_current_terminals.cu b/examples/offset_current_terminals.cu new file mode 100644 index 00000000..b7865747 --- /dev/null +++ b/examples/offset_current_terminals.cu @@ -0,0 +1,588 @@ +// Current flow between two offset terminals on opposite faces of a box. +// +// Steady current flow in a conducting box solves div(sigma grad(phi)) = 0. Current J0 enters +// through a disc-shaped terminal on the top face and leaves through an equal terminal on the bottom +// face, shifted sideways. Every other part of the box surface is insulating, and a resistive sphere +// sits between the terminals. +// +// Boundary conditions, in terms of the outward-normal derivative dphi/dn (sigma = 1 at the faces): +// top face, inside the inlet disc dphi/dn = +J0 (Neumann, non-zero) +// bottom face, inside the outlet disc dphi/dn = -J0 (Neumann, non-zero) +// everywhere else dphi/dn = 0 (insulating) +// +// This is the case per-face constants (carbon::BoundaryConditions) cannot express: the flux differs +// from cell to cell on one face. It is declared once with carbon::BoundaryData, and the stencil +// kernel reads every neighbour through Partition::neighbour_bc with that data, with no edge +// branches. The conductivity field uses a second BoundaryData (zero flux on every face), so two +// fields on one grid carry different conditions. +// +// The program solves two cases and compares them: +// terminals the declared terminals above; +// uniform the same total current spread evenly over each whole face, which is all a single +// constant per face can say. +// +// Checks (the program exits non-zero if either fails; both run on the host over small arrays): +// - the Jacobi iteration has converged (relative update below 1e-6); +// - all the injected current crosses the plane midway between the terminals, to within 1%. +// The uniform case carries no sideways current at all. +// +// Output: a two-panel PPM of the potential on the mid-plane slice (left: terminals, right: uniform, +// one shared diverging colour scale), and with --raw DIR the raw float64 arrays (phi, jx, jz of both +// cases, indexed [z][y][x]) for plotting. Single process only. +// +// Usage: +// ./carbon_example_offset_current_terminals [--size N] [--iters N] [--out image.ppm] [--raw DIR] +// +// Pure flux problem: the potential is defined up to a constant, so the images subtract the mean. + +#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::BoundaryData; +using carbon::DenseDistributed; +using carbon::Face; +using carbon::FaceBc; +using carbon::int64_3d; + +constexpr double kInletFlux = 1.0; +constexpr double kInclusionSigma = 0.05; + +// Geometry, scaled with the box side n so any --size keeps the same picture. +struct Geometry { + int64_t n{0}; + int64_t cx{0}; // box axis / sphere centre + int64_t xa{0}; // inlet terminal centre (top face), x + int64_t xb{0}; // outlet terminal centre (bottom face), x + double terminal_r{0.0}; + double sphere_r{0.0}; + + explicit Geometry(int64_t side) + : n(side), + cx(side / 2), + xa(side * 27 / 100), + xb(side - 1 - side * 27 / 100), + terminal_r(0.15 * static_cast(side)), + sphere_r(0.17 * static_cast(side)) {} + + [[nodiscard]] auto + in_terminal(int64_t x, + int64_t y, + int64_t centre_x) const -> bool { + const double dx = static_cast(x - centre_x); + const double dy = static_cast(y - cx); + return dx * dx + dy * dy <= terminal_r * terminal_r; + } + + [[nodiscard]] auto + sigma(int64_t x, + int64_t y, + int64_t z) const -> double { + const double dx = static_cast(x - cx); + const double dy = static_cast(y - cx); + const double dz = static_cast(z - cx); + return dx * dx + dy * dy + dz * dz <= sphere_r * sphere_r ? kInclusionSigma : 1.0; + } + + // Trapezoid weight of a node on a node-centred face / plane: edge nodes carry half a cell. + [[nodiscard]] auto + weight(int64_t a) const -> double { + return (a == 0 || a == n - 1) ? 0.5 : 1.0; + } + + // Current entering through the inlet terminal, weighted like the discrete face integral. + [[nodiscard]] auto + injected_current() const -> double { + double total = 0.0; + for (int64_t y = 0; y < n; ++y) { + for (int64_t x = 0; x < n; ++x) { + if (in_terminal(x, y, xa)) { + total += kInletFlux * weight(x) * weight(y); + } + } + } + return total; + } +}; + +// One Jacobi sweep of div(sigma grad(phi)) = 0 with harmonic-mean face conductivity. Every +// neighbour of phi and sigma is read through neighbour_bc with that field's own boundary data. +template +[[nodiscard]] auto +build_sweep(const Grid& grid, + typename Grid::template Field& phi_in, + typename Grid::template Field& phi_out, + typename Grid::template Field& sigma, + const BoundaryData<1>& phi_bc, + const BoundaryData<1>& sigma_bc, + std::string name) -> carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return carbon::Kernel::compute( + grid, + [&phi_in, &phi_out, &sigma, &phi_bc, &sigma_bc](carbon::KernelLoader& loader) { + const auto pin = loader.read_stencil(phi_in); + const auto sig = loader.read_stencil(sigma); + const auto pout = loader.write(phi_out); + const auto pv = phi_bc.view(loader.relative_gpu_id()); + const auto sv = sigma_bc.view(loader.relative_gpu_id()); + return [pin, sig, pout, pv, sv] CARBON_HOST_DEVICE(Span s, Idx idx) -> void { + const int dirs[6][3] = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, + {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}; + const double sc = sig.read(s, idx, 0); + double num = 0.0; + double den = 0.0; + for (const auto& d : dirs) { + const carbon::int8_3d o{static_cast(d[0]), static_cast(d[1]), + static_cast(d[2])}; + const auto p = pin.neighbour_bc(s, pv, idx, o, 0); + const auto m = sig.neighbour_bc(s, sv, idx, o, 0); + const double sf = 2.0 * sc * m.value / (sc + m.value); + num += sf * p.value; + den += sf; + } + pout.write(s, idx, 0, num / den); + }; + }, + std::move(name)); +} + +// Current density j = -sigma grad(phi): component 0 is j_x, component 1 is j_z. +template +[[nodiscard]] auto +build_current(const Grid& grid, + typename Grid::template Field& phi, + typename Grid::template Field& sigma, + typename Grid::template Field& current, + const BoundaryData<1>& phi_bc, + std::string name) -> carbon::Kernel { + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + return carbon::Kernel::compute( + grid, + [&phi, &sigma, ¤t, &phi_bc](carbon::KernelLoader& loader) { + const auto pin = loader.read_stencil(phi); + const auto sig = loader.read(sigma); + const auto jout = loader.write(current); + const auto pv = phi_bc.view(loader.relative_gpu_id()); + return [pin, sig, jout, pv] CARBON_HOST_DEVICE(Span s, Idx idx) -> void { + const double sc = sig.read(s, idx, 0); + const auto xp = pin.neighbour_bc(s, pv, idx, carbon::int8_3d{1, 0, 0}, 0); + const auto xm = pin.neighbour_bc(s, pv, idx, carbon::int8_3d{-1, 0, 0}, 0); + const auto zp = pin.neighbour_bc(s, pv, idx, carbon::int8_3d{0, 0, 1}, 0); + const auto zm = pin.neighbour_bc(s, pv, idx, carbon::int8_3d{0, 0, -1}, 0); + jout.write(s, idx, 0, -sc * 0.5 * (xp.value - xm.value)); + jout.write(s, idx, 1, -sc * 0.5 * (zp.value - zm.value)); + }; + }, + std::move(name)); +} + +struct CaseResult { + std::vector phi; // [z][y][x], mean removed + std::vector jx; + std::vector jz; + double plane_current{0.0}; + double relative_update{0.0}; + int sweeps{0}; +}; + +// Copy the owned cells of a per-GPU field into one global [z][y][x] array. +template +void +gather(const DenseDistributed& grid, + const DenseDistributed::Field& field, + int comp, + int64_t n, + std::vector& out) { + out.assign(static_cast(n * n * n), 0.0); + for (size_t gpu = 0; gpu < grid.gpu_count(); ++gpu) { + const auto& span = grid.spans()[gpu]; + const int64_3d halo = span.halo(); + const int64_3d owned = span.logic_extent(); + const int64_t pitch = span.xy_slab_elements(); + const int64_t stride = span.linear_storage_elements(); + const double* h = field.cpu_buffers()[gpu].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)); + const int64_t off = static_cast(comp) * stride + (halo.z + z) * pitch + + (halo.y + y) * span.haloed_extent().x + (halo.x + x); + out[static_cast((g.z * n + g.y) * n + g.x)] = h[off]; + } + } + } + } +} + +[[nodiscard]] auto +solve_case(carbon::System& sys, + const Geometry& geo, + bool terminals, + int sweeps_requested, + CaseResult& result) -> bool { + const int64_t n = geo.n; + const int64_3d global{n, n, n}; + 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); + DenseDistributed grid(sys, global, stencil); + + // The uniform case spreads the same total current over each whole face: the only thing one + // constant per face can say. + int64_t terminal_cells = 0; + for (int64_t y = 0; y < n; ++y) { + for (int64_t x = 0; x < n; ++x) { + terminal_cells += geo.in_terminal(x, y, geo.xa) ? 1 : 0; + } + } + const double uniform_flux = + kInletFlux * static_cast(terminal_cells) / static_cast(n * n); + + BoundaryData<1> phi_bc(grid, terminals ? "phi_terminals" : "phi_uniform"); + phi_bc.fill([&](Face f, int64_3d g, int) -> FaceBc { + if (f == Face::ZHigh) { + if (!terminals) { + return carbon::neumann(+uniform_flux); + } + return geo.in_terminal(g.x, g.y, geo.xa) ? carbon::neumann(+kInletFlux) + : carbon::neumann(0.0); + } + if (f == Face::ZLow) { + if (!terminals) { + return carbon::neumann(-uniform_flux); + } + return geo.in_terminal(g.x, g.y, geo.xb) ? carbon::neumann(-kInletFlux) + : carbon::neumann(0.0); + } + return carbon::neumann(0.0); + }); + phi_bc.upload(); + + // The conductivity carries different conditions from the potential on the same grid: zero flux + // on every face, which makes its out-of-box value the in-box value. + BoundaryData<1> sigma_bc(grid, "sigma_bc"); + sigma_bc.fill(carbon::BoundaryConditions::none() + .with(Face::XLow, carbon::neumann()) + .with(Face::XHigh, carbon::neumann()) + .with(Face::YLow, carbon::neumann()) + .with(Face::YHigh, carbon::neumann()) + .with(Face::ZLow, carbon::neumann()) + .with(Face::ZHigh, carbon::neumann())); + sigma_bc.upload(); + + auto phi_a = grid.newField(carbon::MemorySide::HostDevice, "phi_a"); + auto phi_b = grid.newField(carbon::MemorySide::HostDevice, "phi_b"); + auto sigma = grid.newField(carbon::MemorySide::HostDevice, "sigma"); + auto current = grid.newField(carbon::MemorySide::HostDevice, "current"); + + for (size_t gpu = 0; gpu < grid.gpu_count(); ++gpu) { + const auto& span = grid.spans()[gpu]; + 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(); + double* ha = phi_a.cpu_buffers()[gpu].data(); + double* hb = phi_b.cpu_buffers()[gpu].data(); + double* hs = sigma.cpu_buffers()[gpu].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 bool own = x >= halo.x && x < halo.x + owned.x && y >= halo.y && + y < halo.y + owned.y && z >= halo.z && z < halo.z + owned.z; + const int64_3d g = span.global_location(span.make_idx(x, y, z)); + const int64_t off = z * pitch + y * haloed.x + x; + ha[off] = hb[off] = 0.0; + hs[off] = own ? geo.sigma(g.x, g.y, g.z) : 1.0; + } + } + } + } + carbon::Stream stream = sys.stream(); + carbon::Transfer(sys, phi_a.cpu_buffers(), phi_a.gpu_buffers())(stream); + carbon::Transfer(sys, phi_b.cpu_buffers(), phi_b.gpu_buffers())(stream); + carbon::Transfer(sys, sigma.cpu_buffers(), sigma.gpu_buffers())(stream); + stream.wait(); + + const int cycles = (sweeps_requested + 1) / 2; + carbon::Skeleton pipe(sys); + pipe.add(build_sweep(grid, phi_a, phi_b, sigma, phi_bc, sigma_bc, "sweep_ab")); + pipe.add(build_sweep(grid, phi_b, phi_a, sigma, phi_bc, sigma_bc, "sweep_ba")); + pipe.compile(); + for (int c = 0; c < cycles; ++c) { + pipe.run(); + } + pipe.wait(); + result.sweeps = cycles * 2; + + // Convergence: size of the last update (phi_a against phi_b, one sweep apart) relative to the size + // of the solution. The checks run on the host: the arrays are small. + carbon::Skeleton cur(sys); + cur.add(build_current(grid, phi_a, sigma, current, phi_bc, "current_density")); + cur.run(); + cur.wait(); + + carbon::Transfer(sys, phi_a.gpu_buffers(), phi_a.cpu_buffers())(stream); + carbon::Transfer(sys, phi_b.gpu_buffers(), phi_b.cpu_buffers())(stream); + carbon::Transfer(sys, current.gpu_buffers(), current.cpu_buffers())(stream); + stream.wait(); + gather<1>(grid, phi_a, 0, n, result.phi); + std::vector phi_prev; + gather<1>(grid, phi_b, 0, n, phi_prev); + gather<2>(grid, current, 0, n, result.jx); + gather<2>(grid, current, 1, n, result.jz); + + double diff2 = 0.0; + double norm2 = 0.0; + for (size_t i = 0; i < result.phi.size(); ++i) { + const double d = result.phi[i] - phi_prev[i]; + diff2 += d * d; + norm2 += result.phi[i] * result.phi[i]; + } + result.relative_update = std::sqrt(diff2 / std::max(norm2, 1.0e-300)); + + // Current crossing the plane x == cx: sum of j_x, trapezoid-weighted in y and z. + for (int64_t z = 0; z < n; ++z) { + for (int64_t y = 0; y < n; ++y) { + result.plane_current += + geo.weight(y) * geo.weight(z) * result.jx[static_cast((z * n + y) * n + geo.cx)]; + } + } + + double mean = 0.0; + for (double v : result.phi) { + mean += v; + } + mean /= static_cast(result.phi.size()); + for (double& v : result.phi) { + v -= mean; + } + return true; +} + +// Diverging blue-white-red map, t in [-1, 1]. +void +diverging(double t, + unsigned char rgb[3]) { + const double c = std::clamp(t, -1.0, 1.0); + const double neutral[3] = {240.0, 239.0, 236.0}; + const double blue[3] = {24.0, 79.0, 149.0}; + const double red[3] = {179.0, 45.0, 45.0}; + const double* end = c < 0.0 ? blue : red; + const double a = std::fabs(c); + for (int i = 0; i < 3; ++i) { + rgb[i] = static_cast(std::lround(neutral[i] + (end[i] - neutral[i]) * a)); + } +} + +[[nodiscard]] auto +write_ppm(const std::string& path, + const CaseResult& left, + const CaseResult& right, + int64_t n) -> bool { + constexpr int64_t kScale = 8; + constexpr int64_t kGap = 12; + constexpr int64_t kBar = 16; + const int64_t panel = n * kScale; + const int64_t width = 2 * panel + kGap + kGap + kBar; + const int64_t height = panel; + double vmax = 0.0; + for (const auto* r : {&left, &right}) { + for (double v : r->phi) { + vmax = std::max(vmax, std::fabs(v)); + } + } + std::vector img(static_cast(width * height * 3), 252); + const int64_t y_mid = n / 2; + const auto put = [&](int64_t px, int64_t py, const unsigned char rgb[3]) { + const size_t i = static_cast((py * width + px) * 3); + img[i] = rgb[0]; + img[i + 1] = rgb[1]; + img[i + 2] = rgb[2]; + }; + const CaseResult* panels[2] = {&left, &right}; + for (int p = 0; p < 2; ++p) { + const int64_t x0 = p * (panel + kGap); + for (int64_t z = 0; z < n; ++z) { + for (int64_t x = 0; x < n; ++x) { + unsigned char rgb[3]; + diverging(panels[p]->phi[static_cast((z * n + y_mid) * n + x)] / vmax, rgb); + for (int64_t dy = 0; dy < kScale; ++dy) { + for (int64_t dx = 0; dx < kScale; ++dx) { + put(x0 + x * kScale + dx, (n - 1 - z) * kScale + dy, rgb); // z up + } + } + } + } + } + const int64_t bar_x0 = 2 * panel + 2 * kGap; + for (int64_t py = 0; py < height; ++py) { + unsigned char rgb[3]; + diverging(1.0 - 2.0 * static_cast(py) / static_cast(height - 1), rgb); + for (int64_t px = 0; px < kBar; ++px) { + put(bar_x0 + px, py, rgb); + } + } + std::ofstream f(path, std::ios::binary); + if (!f) { + return false; + } + f << "P6\n" << width << " " << height << "\n255\n"; + f.write(reinterpret_cast(img.data()), static_cast(img.size())); + return static_cast(f); +} + +void +write_raw(const std::string& dir, + const std::string& tag, + const CaseResult& r) { + const auto dump = [&](const char* name, const std::vector& v) { + std::ofstream f(dir + "/" + tag + "_" + name + ".bin", std::ios::binary); + f.write(reinterpret_cast(v.data()), + static_cast(v.size() * sizeof(double))); + }; + dump("phi", r.phi); + dump("jx", r.jx); + dump("jz", r.jz); +} + +[[nodiscard]] auto +arg_value(int argc, + char** argv, + std::string_view flag) -> std::string { + for (int i = 1; i + 1 < argc; ++i) { + if (std::string_view{argv[i]} == flag) { + return std::string{argv[i + 1]}; + } + } + return {}; +} + +} // namespace + +auto +main(int argc, + char** argv) -> int { + carbon::init(); + if (carbon::device_count() <= 0) { + CARBON_LOG_ERROR("offset_current_terminals: no devices visible"); + return EXIT_FAILURE; + } + int64_t size = 25; + int iters = 4000; + try { + if (const std::string v = arg_value(argc, argv, "--size"); !v.empty()) { + size = std::stoll(v); + } + if (const std::string v = arg_value(argc, argv, "--iters"); !v.empty()) { + iters = std::stoi(v); + } + } catch (const std::exception&) { + CARBON_LOG_ERROR("offset_current_terminals: --size and --iters take integers"); + return EXIT_FAILURE; + } + if (size < 15 || iters < 2) { + CARBON_LOG_ERROR("offset_current_terminals: need --size >= 15 and --iters >= 2"); + return EXIT_FAILURE; + } + std::string out_path = arg_value(argc, argv, "--out"); + if (out_path.empty()) { + out_path = "offset_current_terminals.ppm"; + } + const std::string raw_dir = arg_value(argc, argv, "--raw"); + + carbon::System sys(carbon::get_all_devices()); + if (sys.distributed() != nullptr) { + CARBON_LOG_ERROR( + "offset_current_terminals: single process only (the output gathers on rank 0)"); + return EXIT_FAILURE; + } + const Geometry geo(size); + const double injected = geo.injected_current(); + + CaseResult terminals; + CaseResult uniform; + try { + if (!solve_case(sys, geo, /*terminals=*/true, iters, terminals) || + !solve_case(sys, geo, /*terminals=*/false, iters, uniform)) { + return EXIT_FAILURE; + } + } catch (const std::exception& e) { + CARBON_LOG_ERROR("offset_current_terminals: {}", e.what()); + return EXIT_FAILURE; + } + + const double swing_t = *std::max_element(terminals.phi.begin(), terminals.phi.end()); + const double swing_u = *std::max_element(uniform.phi.begin(), uniform.phi.end()); + CARBON_LOG_INFO( + "offset_current_terminals: {}^3 box, {} sweeps. Injected current {:.3f}. Current crossing " + "the " + "mid-plane: terminals {:.3f}, uniform {:.3f}. Potential swing +-{:.3f} (terminals) against " + "+-{:.3f} (uniform). Relative update: {:.2e} / {:.2e}.", + size, terminals.sweeps, injected, terminals.plane_current, uniform.plane_current, swing_t, + swing_u, terminals.relative_update, uniform.relative_update); + + if (!write_ppm(out_path, terminals, uniform, size)) { + CARBON_LOG_ERROR("offset_current_terminals: could not write {}", out_path); + return EXIT_FAILURE; + } + if (!raw_dir.empty()) { + write_raw(raw_dir, "terminals", terminals); + write_raw(raw_dir, "uniform", uniform); + } + CARBON_LOG_INFO("offset_current_terminals: wrote {} (left: terminals, right: uniform)", out_path); + + bool ok = true; + if (terminals.relative_update > 1.0e-6 || uniform.relative_update > 1.0e-6) { + CARBON_LOG_ERROR("offset_current_terminals: not converged; raise --iters"); + ok = false; + } + if (std::fabs(terminals.plane_current - injected) > 0.01 * injected) { + CARBON_LOG_ERROR( + "offset_current_terminals: current crossing the mid-plane ({:.3f}) differs from the " + "injected " + "current ({:.3f}) by more than 1%", + terminals.plane_current, injected); + ok = false; + } + if (std::fabs(uniform.plane_current) > 0.01 * injected) { + CARBON_LOG_ERROR( + "offset_current_terminals: the uniform case should carry no sideways current ({:.3f})", + uniform.plane_current); + ok = false; + } + return ok ? EXIT_SUCCESS : EXIT_FAILURE; +}