diff --git a/.github/workflows/gpu-ci.yml b/.github/workflows/gpu-ci.yml index e5acc81f..f13e36c9 100644 --- a/.github/workflows/gpu-ci.yml +++ b/.github/workflows/gpu-ci.yml @@ -34,9 +34,9 @@ on: workflow_dispatch: inputs: configs: - description: 'Comma-separated configs to run (cuda,cuda-mpi). Defaults to both.' + description: 'Comma-separated configs to run (cuda,cuda-mpi,sycl,sycl-mpi). Defaults to all.' required: false - default: 'cuda,cuda-mpi' + default: 'cuda,cuda-mpi,sycl,sycl-mpi' jobs: gpu-matrix: @@ -47,7 +47,7 @@ jobs: github.event_name != 'pull_request' || contains(github.event.pull_request.labels.*.name, 'gpu-ci') runs-on: [self-hosted, linux, gpu, cuda] - timeout-minutes: 90 + timeout-minutes: 150 strategy: fail-fast: false @@ -58,13 +58,32 @@ jobs: # carbon_halo_disg_dist, dist_transfer, dense_dist, halo_dist, # halo_dist_periodic_z, native_io_dist, dist_reduce). Together # the two cells cover both audit-flagged silent-bug classes. - config: [cuda, cuda-mpi] + # `sycl` / `sycl-mpi` are the same two cells on the AdaptiveCpp + # backend (cuda:;omp targets) — SYCL has its own event / + # cross-device ordering code, so it needs its own GPU lane. + config: [cuda, cuda-mpi, sycl, sycl-mpi] steps: + - name: Select config + id: select + # workflow_dispatch runs only the configs named in `inputs.configs`. + env: + EVENT: ${{ github.event_name }} + CONFIGS: ${{ inputs.configs }} + CONFIG: ${{ matrix.config }} + run: | + if [ "${EVENT}" != "workflow_dispatch" ] || [[ ",${CONFIGS}," == *",${CONFIG},"* ]]; then + echo "run=1" >> "${GITHUB_OUTPUT}" + else + echo "gpu-ci: ${{ matrix.config }} not in inputs.configs, skipping" + fi + - name: Checkout + if: steps.select.outputs.run == '1' uses: actions/checkout@v4 - name: Preflight (docker + GPU) + if: steps.select.outputs.run == '1' run: | set -euo pipefail command -v docker >/dev/null || { echo "docker not on PATH"; exit 1; } @@ -83,7 +102,7 @@ jobs: else # >= 2 GPUs: assert the multi-device coverage actually runs. carbon_multi_gpu_gate # turns a mis-provisioned runner (driver hides a card, MIG partitioning, a stale - # CUDA_VISIBLE_DEVICES) into a red run instead of ~28 tests quietly self-skipping + # CUDA_VISIBLE_DEVICES) into a red run instead of ~30 tests quietly self-skipping # to a pass. Enumerate the affected set with `ctest -L needs_multi_device`. echo "CARBON_TEST_STRICT=1" >> "${GITHUB_ENV}" fi @@ -95,14 +114,21 @@ jobs: nvidia/cuda:12.6.3-base-ubuntu22.04 - name: Run docker matrix (${{ matrix.config }}) + if: steps.select.outputs.run == '1' env: # Forwarded to scripts/docker-build-all.sh; override per-runner via # repo / org Actions variables if a runner has a different SM arch. # sm_80 (A100) is the safest default — Ampere covers >= sm_80 # forward; older cards need the var override. SM_ARCH: ${{ vars.GPU_CI_SM_ARCH || 'sm_80' }} + # Space-separated KEY=VAL pairs forwarded into the container, e.g. + # `NCCL_P2P_DISABLE=1` on a runner whose PCIe peer DMA is unusable + # (NCCL's P2P transport hangs the distributed tests there). + DOCKER_ENV: ${{ vars.GPU_CI_DOCKER_ENV || '' }} run: | set -euo pipefail + env_args=() + for kv in ${DOCKER_ENV}; do env_args+=(--docker-env "${kv}"); done # `--only cuda` / `--only cuda-mpi` builds the image (cached on the # runner across runs) and runs ctest --output-on-failure inside the # container with --gpus all wired in. format-check rides the `cuda` @@ -113,15 +139,41 @@ jobs: scripts/docker-build-all.sh \ --only ${{ matrix.config }} \ --sm-arch "${SM_ARCH}" \ - --werror + --werror \ + "${env_args[@]}" + + - name: Repeat GPU tests (${{ matrix.config }}) + # Cross-device ordering bugs are intermittent: each fixed so far passed + # a single ctest run most of the time. Re-run every GPU test 20x in + # the build tree the previous step left behind (incremental: no + # rebuild). The MPI cells would repeat the same single-process tests, + # so the lane rides the non-MPI cells only. The orchestrator tees to + # docker-logs/run-.log, so the first run's log is kept aside. + if: steps.select.outputs.run == '1' && (matrix.config == 'cuda' || matrix.config == 'sycl') + env: + SM_ARCH: ${{ vars.GPU_CI_SM_ARCH || 'sm_80' }} + DOCKER_ENV: ${{ vars.GPU_CI_DOCKER_ENV || '' }} + run: | + set -euo pipefail + env_args=() + for kv in ${DOCKER_ENV}; do env_args+=(--docker-env "${kv}"); done + cp docker-logs/run-${{ matrix.config }}.log docker-logs/run-${{ matrix.config }}-main.log + scripts/docker-build-all.sh \ + --only ${{ matrix.config }} \ + --sm-arch "${SM_ARCH}" \ + --werror \ + --skip-build-images \ + --ctest-args "-L gpu -E format_check --repeat until-fail:20" \ + "${env_args[@]}" - name: Upload build + test logs - if: always() + if: always() && steps.select.outputs.run == '1' uses: actions/upload-artifact@v4 with: name: gpu-ci-${{ matrix.config }}-logs path: | docker-logs/run-${{ matrix.config }}.log + docker-logs/run-${{ matrix.config }}-main.log docker-logs/${{ matrix.config }}/build/Testing/Temporary/LastTest.log if-no-files-found: ignore retention-days: 14 diff --git a/AGENTS.md b/AGENTS.md index 89f0b325..060e305e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -79,15 +79,24 @@ same public API; what differs is which `detail/backend//` headers are pull and which toolchain compiles the per-cell device code. - **CUDA** is the historical and feature-complete backend. `nvcc` compiles `.cu` TUs; - per-cell launches go through `cudaLaunchKernel`. 90/90 default tests pass and all + per-cell launches go through `cudaLaunchKernel`. All 126 default tests pass (apart from + the `carbon_format_check` caveat in the snapshot below) and all example programs build and run. - **SYCL** is supported through [AdaptiveCpp](https://github.com/AdaptiveCpp/AdaptiveCpp) (a.k.a. `acpp`, formerly hipSYCL). Per-cell launches go through - `sycl::queue::parallel_for`; reductions through `sycl::reduction` over - `q.parallel_for` (single-stage, no per-block partials); cross-device peer copies via - a process-wide shared `sycl::context` (so `q.memcpy(dst_gpu_ptr, src_gpu_ptr, n)` does - the right thing whether `src`/`dst` sit on the same or different devices). 89/89 - default SYCL tests pass with cross-backend numerical parity. The 4-test delta vs + `sycl::queue::parallel_for`; `ReduceFinalize::DeviceReduce` through `sycl::reduction` + over `q.parallel_for` (single-stage, no per-block partials), `ReduceFinalize::BlockAtomic` + through a work-group `reduce_over_group` plus one `atomic_ref` add per group + (`detail/backend/sycl/block_atomic_reduce.h`), and `ReduceHostCopy::Deferred` is + supported. Cross-device peer copies go through a process-wide shared `sycl::context` + (so `q.memcpy(dst_gpu_ptr, src_gpu_ptr, n)` works whether `src`/`dst` sit on the same or + different devices); `System::async_copy` brackets a cross-device memcpy with explicit + custom-operation events, because AdaptiveCpp 25.02 does not order later submissions on + the in-order queue after it. Cross-backend gotcha: device code must not read a host + `static` (even `constexpr`) array — nvcc copes, AdaptiveCpp reads a zero-filled copy; + use literals or captured values. 108/108 default SYCL tests pass with cross-backend + numerical parity (every `gpu` test also 100× idle + 50× under GPU load, 2026-11). + The 4-test delta vs CUDA is exactly the `carbon_add_cuda_only_unit_test` gate — the explicit opt-out for tests that need raw CUDA-runtime APIs in their *body*: `block_cuda` (a smoke test pinning the `cudaMalloc` / `cudaMemset` / `cudaDeviceSynchronize` / @@ -114,11 +123,12 @@ and which toolchain compiles the per-cell device code. `-DCARBON_ENABLE_MPI=ON` on top of this does not configure on the dev box: the local MPI wrappers are built for g++ and `find_package(MPI)` fails its `MPI_CXX_WORKS` compile check under the pixi clang. SYCL+MPI is validated in the container matrix - (`scripts/docker-build-all.sh --only sycl-mpi`), not natively here. + (`scripts/docker-build-all.sh --only sycl-mpi --docker-env NCCL_P2P_DISABLE=1`, + 136 tests), not natively here. -Adding `-DCARBON_ENABLE_MPI=ON` registers **26** further distributed tests (ctest +Adding `-DCARBON_ENABLE_MPI=ON` registers **28** further distributed tests (ctest label `distributed`, one file per grid family × transport concern) on either -backend, for **116** total on CUDA. They cover intra-process multi-GPU + cross-rank +backend, for **140** total on CUDA and **136** on SYCL. They cover intra-process multi-GPU + cross-rank for every grid family, the `OverlapMode` matrix on every grid family (`skeleton_dist_overlap{,_disg,_block}`), multi-format I/O round-trip (`io_dist`), non-`Sum` reduction shapes on every grid family (`*_dist_reduce_ops`), and the @@ -198,7 +208,7 @@ cmake --build build --target format-check > > **Test labels.** `ctest -L cpu` selects the tests that do real work with zero visible > devices (the CPU CI lane); `-L gpu` needs at least one device; `-L needs_multi_device` -> lists the ~28 tests that self-skip below two GPUs; `-L warp` lists the 31 Python/Warp +> lists the ~30 tests that self-skip below two GPUs; `-L warp` lists the 31 Python/Warp > tests (`-DCARBON_ENABLE_PYTHON=ON`). Set `CARBON_TEST_STRICT=1` to make those self-skips > hard failures (`carbon_multi_gpu_gate`, `carbon_warp_gate`) instead of passes. > @@ -274,7 +284,11 @@ container (NVIDIA: `--gpus all` via the nvidia-container-toolkit; AMD: `docker-logs/run-.log` and the build trees are mirrored under `docker-logs//build/` for post-mortem inspection. Common knobs: `--only hip`, `--only sycl-rccl`, `--sm-arch sm_89`, `--gfx-arch gfx90a`, -`--no-cache`, `--skip-build-images`. +`--no-cache`, `--skip-build-images`, `--docker-env KEY=VAL` (repeatable; forwarded +into every container) and `--ctest-args "..."` (appended to the in-container ctest). +The NVIDIA `*-mpi` configs run with `--ipc=host`. On a host whose PCIe peer DMA is +unusable (carbon already leaves peer access off there) NCCL's P2P transport hangs the +distributed tests; pass `--docker-env NCCL_P2P_DISABLE=1`. ### CI workflows @@ -297,24 +311,29 @@ Two GitHub Actions workflows live under `.github/workflows/`: - **`gpu-ci.yml` — GPU validation lane (P1.γ).** Runs on a **self-hosted** runner labelled `[self-hosted, linux, gpu, cuda]` and is triggered by (a) the `gpu-ci` label on a PR or (b) `workflow_dispatch` (manual - re-run from the Actions tab) or (c) pushes to `main` / `master`. The - workflow shells out to `scripts/docker-build-all.sh --only cuda` and - `scripts/docker-build-all.sh --only cuda-mpi` so the runner host only + re-run from the Actions tab; its `configs` input picks a subset of the + matrix) or (c) pushes to `main` / `master`. The + workflow shells out to `scripts/docker-build-all.sh --only ` for + each of `cuda`, `cuda-mpi`, `sycl` and `sycl-mpi`, so the runner host only needs `docker` + `nvidia-container-toolkit` + an NVIDIA GPU — no - native clang / CUDA / MPI / NCCL / HDF5 install required. Build / - test logs land as workflow artifacts (`gpu-ci-cuda-logs`, - `gpu-ci-cuda-mpi-logs`) for 14 days. The matrix covers the two audit - classes the CPU lane cannot exercise: `cuda` runs the full default - test suite + `format-check`; `cuda-mpi` adds every - `distributed`-labelled test (`ctest -N -L distributed` for the current - list). The workflow + native clang / CUDA / MPI / NCCL / HDF5 / AdaptiveCpp install required. + Build / test logs land as workflow artifacts (`gpu-ci--logs`) for + 14 days. `cuda` runs the full default test suite + `format-check`; + `cuda-mpi` adds every `distributed`-labelled test (`ctest -N -L + distributed` for the current list); `sycl` / `sycl-mpi` are the same two + cells on the AdaptiveCpp backend. The `cuda` and `sycl` cells then re-run + every `gpu` test 20× (`--ctest-args "-L gpu -E format_check --repeat + until-fail:20"`, incremental, no rebuild): the cross-device ordering bugs + fixed so far each passed a single run most of the time. Runner-specific + container environment (e.g. `NCCL_P2P_DISABLE=1`) goes in the + `GPU_CI_DOCKER_ENV` Actions variable (space-separated `KEY=VAL`). The workflow passes `--werror` (gates the libcarbon host compile on the container g++) and its preflight prints the visible GPU count. On a runner with `>= 2` GPUs it exports `CARBON_TEST_STRICT=1` (forwarded into the container by `scripts/docker-build-all.sh`), so `carbon_multi_gpu_gate` fails if the devices turn out not to be visible to the test process — a hidden card, MIG partitioning, or a stale `CUDA_VISIBLE_DEVICES` - no longer downgrades ~28 `needs_multi_device` tests to silent + no longer downgrades ~30 `needs_multi_device` tests to silent no-op passes. Below 2 GPUs it emits a `::warning::` instead, since that configuration legitimately covers only the build plus the single-GPU suite. @@ -488,7 +507,31 @@ how a feature behaves at the edges, grep the changelog for the section name { None, Standard, Extended, TwoWayExtended }` opts in to the OCC rewrite — auto-halo insertion + Internal/Boundary split + halo-stream isolation. Single-stream fast path is preserved bit-for-bit. Catches - "halo missing before stencil" at compile time. Examples: + "halo missing before stencil" at compile time. **Region masks**: + `AccessToken::mask` (256-bit `RegionMask`, default all-ones) narrows a + Map access to user-defined label atoms via `KernelLoader::region(M)` or + `read/write/read_write(f, M)`; disjoint masks drop the edge, stencil / + halo / scalar tokens stay whole-field, masks are declaration-only (the + kernel filters itself), `Options::ignore_region_masks` / + `CARBON_IGNORE_REGION_MASKS=1` restore the whole-field schedule, and MPI + runs check masks are rank-invariant (`docs/skeleton/README.md`, + `examples/region_mask_cube.cu` minimal, `examples/region_mask_bc.cu`). **SubGrid**: + `SubGrid` / `SubGrid>` (`include/carbon/sub_grid.h`, `detail/sub_grid/`) + built by `Dense::new_sub_grid(labels, mask)` or `new_sub_grid(predicate, mask)` (same on + `Block`) keeps a per-GPU flat lane table of selected parent cells (parent-Internal first, + then parent-Boundary) and launches one thread per lane; `S::Span` / `S::Idx` derive from the parent's so parent + fields are read/written (and stencil-read through their halo) directly, SubGrid fields + are compact and halo-less (`read_stencil` on one is a compile error), kernels declare the + SubGrid mask automatically and OCC-split like Dense kernels, and loading another + SubGrid's field throws. Reductions (`Kernel::reduce` / `host_reduce` / + `reduce_universal`, `S.make_*reduce_kernel`) run one thread per lane through the usual + reduce pipeline via `ReduceLaunchTraits>` (`detail/sub_grid/reduce_traits.h`); + `compute_universal` over a SubGrid is still a static_assert. Per-parent enumeration and + host spans go through `ParentTraits` (`detail/sub_grid/parent_traits.h`); a Block + SubGrid's host kernels get spans from the Block's host tables (owned bricks only, so host + `neighbour` reads stay in the slab) (`docs/skeleton/README.md` "SubGrid", + `examples/sub_grid_cube.cu`, `examples/sub_grid_block_markers.cu`, + `tests/test_sub_grid*.cu`). Examples: `examples/jacobi_unified.cu` (Dense / DenseDisg / Block from one source file, runtime grid + transport + overlap selection); `examples/checkpoint_dense.cu` and `examples/checkpoint_sphere_image.cu` @@ -522,22 +565,27 @@ how a feature behaves at the edges, grep the changelog for the section name Counts drift with every feature, so treat these as a sanity check, not a contract — `ctest --test-dir -N` is the source of truth. Measured -2026-07-31 on a 2×RTX 6000 Ada box (`sm_89`), every configuration fully green: +2026-11-20 on a 2×RTX A4000 box (`sm_86`, peer access off); every configuration +green apart from `carbon_format_check`, which flags pre-existing violations in +files outside this work: | Configuration | Tests | | --- | --- | -| default (CUDA) | 93 | -| `-DCARBON_ENABLE_MPI=ON` (CUDA) | 116 † | -| `-DCARBON_BACKEND=Sycl` | 89 | -| `hip-nvidia` (HIP backend on NVIDIA) | 89 | +| default (CUDA) | 126 | +| `-DCARBON_ENABLE_MPI=ON` (CUDA) | 154 ‡ | +| `-DCARBON_BACKEND=Sycl` | 114 | +| `sycl-mpi` (SYCL + MPI) | 142 ‡ | +| `hip-nvidia` (HIP backend on NVIDIA) | 122 | -† not re-measured on 2026-07-31; carried over from the 2026-07-30 2×A100 run. +‡ 2026-11-18 count plus the SubGrid tests (14 on CUDA, 6 on SYCL); not re-run since. `hdf5_io` / `nanovdb_io` are registered unconditionally but compile-time -skip when their flags are off. The 26-test MPI delta is the `distributed` -ctest label and registers on both backends. The 4-test CUDA/SYCL delta is +skip when their flags are off. The 28-test MPI delta is the `distributed` +ctest label and registers on both backends. The 12-test CUDA/SYCL delta is the `carbon_add_cuda_only_unit_test` gate (`block_cuda` + the three -`mgrid_*` tests with hand-rolled `<<<>>>` kernels). +`mgrid_*` tests with hand-rolled `<<<>>>` kernels) plus the eight +`sub_grid_compile_fail_*` entries (CUDA and HIP; regexes match nvcc and clang wording). +HIP registers the compile-fail entries but not the CUDA-only gate, hence 4 fewer than CUDA. `carbon_format_check` is enforced on every backend. ### Packaging diff --git a/CMakeLists.txt b/CMakeLists.txt index 03017cd1..e924848a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -243,6 +243,7 @@ include(GNUInstallDirs) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") include(CarbonSpdlog) include(CarbonRapidjson) +include(CarbonSyclMirror) set(CARBON_VERSION_STRING "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}") @@ -292,6 +293,7 @@ add_library(carbon SHARED src/logging.cpp src/memory_side.cpp src/process_grid.cpp + src/region_mask.cpp src/report.cpp src/skeleton.cpp src/stencil.cpp @@ -424,6 +426,7 @@ elseif(CARBON_BACKEND STREQUAL "Sycl") src/logging.cpp src/memory_side.cpp src/process_grid.cpp + src/region_mask.cpp src/report.cpp src/skeleton.cpp src/stencil.cpp diff --git a/PROJECT_REVIEW.md b/PROJECT_REVIEW.md new file mode 100644 index 00000000..8d548d83 --- /dev/null +++ b/PROJECT_REVIEW.md @@ -0,0 +1,134 @@ +# Carbon — project review + +_Date: 2026-11-20. Branch: `carbon-bitmask` @ `f44d512`._ + +Opinionated review of the full Carbon tree after the SubGrid / region-mask / +Jacobi+AXPY work. This is a product and architecture view, not a line-by-line +audit. Earlier deep audits live in [`current_status.md`](current_status.md) +(2026-05 foundation) and [`carbon-review.md`](carbon-review.md) (2026-11 +distributed DenseDistributed backend). + +--- + +## Verdict + +Carbon is a serious multi-GPU grid runtime with a clear centre of gravity: +**Dense + Block + Kernel + Skeleton**, validated across CUDA, SYCL, and +HIP-on-NVIDIA. The recent SubGrid + region-mask work is the right kind of +feature — it extends the scheduler without forking it. The project feels +mature where that core is concerned, and uneven where parallel “grid products” +(DenseDisg, DenseDistributed, mGrid, Block I/O) still compete for attention. + +--- + +## What is strong + +**One public API, three backends.** The `cudalike` / SYCL split behind +`detail/backend/select.h` is disciplined. Roughly 126 CUDA / 114 SYCL / +122 hip-nvidia tests with shared examples is unusual for a rewrite of this age. + +**Skeleton as the product.** Auto-halo, OCC (`None` → `TwoWayExtended`), region +masks, launch-order / matrix DOT, and exact integer end-to-end tests show a +library that treats *scheduling* as a first-class concern, not an afterthought +on top of kernels. + +**Dense and Block as the solid data plane.** Z-slab Dense and brick-sparse Block +are coherent, well tested, and now share SubGrid through `ParentTraits` without +a second launcher stack. The Block host-span copy fix (`c3b78cd`) was the right +kind of fix: a real use-after-free, caught by a regression that would have +bitten SubGrid hard. + +**SubGrid design.** Flat Internal-first lanes, Span/Idx deriving from the +parent, no SubGrid field halo, ownership checks at kernel build — that is +Neon-sGrid shaped and OCC-compatible. The Jacobi+AXPY test (B ∥ C, Dense and +Block, 100 int64 iterations, every OCC mode) is the right pin: it proves values +*and* that masks actually parallelize. + +**Engineering culture.** Append-only `docs/CHANGELOG.md`, `AGENTS.md` as living +status, compile-fail tests, Docker matrix (`scripts/docker-build-all.sh`), +mutants that must fail — that is how you keep a header-heavy C++ GPU library +honest. + +--- + +## What is uneven + +**Too many “dense-like” stories.** `Dense`, `DenseDisg`, and `DenseDistributed` +are three stacks with different I/O, halo types, and maturity. For a new user +(or agent), that naming tax is real. DenseDisg has known flakiness under load; +DenseDistributed is thinly tested relative to its surface. + +**mGrid / multi-res** is present but still younger: some tests remain CUDA-only +(hand-rolled `<<<>>>`), and it is not yet first-class next to Dense/Block in the +SubGrid story. + +**MPI.** One-rank-per-GPU works; SubGrid reductions and several Skeleton paths +are not exercised under MPI. Distributed solvers that put BCs on a SubGrid are +the first place that will hurt. + +**HIP.** HIP-on-NVIDIA via cudalike is green; native AMD + HIP+NCCL are less of +a proven product surface than CUDA/SYCL. + +**Format debt.** `carbon_format_check` still fails on pre-existing files. Small, +but it muddies “green suite” messaging. + +--- + +## SubGrid + region masks (2026-11) + +Solvers now have a clean pattern: + +- **C** = bulk interior (masked parent kernel *or* a second SubGrid) +- **B** = incomplete-neighbour / BC / markers (SubGrid) +- Skeleton runs B and C without an edge; OCC gives **2 internal + 2 boundary** + launches per Jacobi step + +That matches how real codes are written. One scheduling compromise is worth +owning explicitly: **both boundary halves sit on the halo stream**. Correct, but +concurrency is left on the table when you have several region writers. Measure +that before changing the Skeleton. + +The dual encoding of C (`bc_parent` vs `bc_sub`) is powerful and a footgun. A +short “when to pack vs when to mask-and-skip” note in +[`docs/skeleton/README.md`](docs/skeleton/README.md) would buy more than another +parent type. + +Documented non-goals that should stay non-goals until a workload forces them: +brick-aware SubGrid lanes, nested SubGrid, DenseDisg-as-parent, multi-res Block +as SubGrid parent. + +--- + +## Where to invest next (priority order) + +1. **MPI SubGrid reduce + a small distributed Jacobi/BC path** — highest + correctness gap relative to the claims. +2. **Clarify the product surface** — pick a primary “dense” story for + docs/examples; demote DenseDisg / DenseDistributed to “specialized” so the + mental model stays Dense / Block / (mGrid). +3. **OCC boundary-stream contention** — benchmark Extended with ≥2 SubGrid + writers; only then decide whether boundary halves should fan out. +4. **Dynamic remasking** — rebuild cost and field lifetime for moving + interfaces; untested today. +5. **Block native I/O** (already deferred in the audits) if sparse apps need + checkpoint parity with Dense. + +Do *not* chase brick-aware SubGrid lanes, nested SubGrid, or DenseDisg-as-parent +until a real workload forces it. Flat lanes match the “few special voxels” use +case SubGrid was built for. + +--- + +## Bottom line + +As a rewrite of Neon’s grid + Skeleton layer, Carbon already looks like a +**production-minded research runtime**: strong core abstractions, real +multi-backend discipline, and tests that argue about schedules and bit-exactness, +not only that something ran. SubGrid over Dense/Block with region-mask parallel +B/C is a coherent milestone and raises the bar for what “done” means here. + +The risk is not that the core is weak — it is **product fragmentation** (too +many grid variants) and **distributed / HIP-native maturity** lagging the +single-node CUDA/SYCL story. Tighten the narrative around Dense + Block + +Skeleton, close the MPI SubGrid gap, and measure OCC under multiple SubGrids +before inventing more machinery. diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index 8d3616d3..29a35cce 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -32,17 +32,9 @@ function(_carbon_benchmark_add target source_cu) HIP_STANDARD 20 HIP_STANDARD_REQUIRED ON) elseif(CARBON_BACKEND STREQUAL "Sycl") - set(_src "${CMAKE_CURRENT_BINARY_DIR}/${target}.cpp") - configure_file("${CMAKE_CURRENT_SOURCE_DIR}/${source_cu}" "${_src}" COPYONLY) - add_executable(${target} "${_src}") - target_compile_features(${target} PRIVATE cxx_std_20) + carbon_add_sycl_mirrored_executable(${target} ${source_cu}) set_target_properties(${target} PROPERTIES BUILD_RPATH "${CARBON_RUNTIME_SEARCH_DIRS};${CMAKE_BINARY_DIR}") - add_sycl_to_target(TARGET ${target} SOURCES "${_src}") - if(CARBON_SYCL_TARGETS MATCHES "cuda") - target_compile_options(${target} PRIVATE --cuda-path=${CARBON_SYCL_CUDA_PATH}) - target_link_directories(${target} PRIVATE ${CARBON_SYCL_CUDA_PATH}/lib64) - endif() endif() endfunction() @@ -52,6 +44,7 @@ add_subdirectory(lbm_lid_driven_cavity_distributed) add_subdirectory(halo_scalability) add_subdirectory(reduce_throughput) add_subdirectory(skeleton_overlap) +add_subdirectory(skeleton_region_mask) add_subdirectory(block_sparse) add_subdirectory(jacobi_nvidia) add_subdirectory(cg) diff --git a/benchmarks/README.md b/benchmarks/README.md index 39702870..3802183a 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -410,6 +410,37 @@ compute-per-step dominates halo latency (heavier kernels, NVLink). Check Build target: `carbon_benchmark_skeleton_overlap`. +### `skeleton_region_mask` + +Jacobi ping-pong where every half step is one interior stencil plus `K` boundary kernels +on disjoint `RegionMask`s (strips of the x faces), so with masks honoured the `K + 1` +writers of the same field can run side by side. Variants per `K` (1, 4, 16, or `--k`): +`masks`, `ignored` (`Options::ignore_region_masks`, the whole-field schedule), +`masks_max2` / `masks_max4` (`Options::max_streams`), and `ignored_graph` (single stream +captured as a CUDA graph). One line per variant: + +``` +us_per_iter=66.7 host_us_per_iter=66.2 variant=masks k=1 streams=3 gpus=2 n=64 iters=300 repeats=3 +``` + +`host_us_per_iter` is the time spent inside `run()` (launches, events, fork/join). Once the +device is the bottleneck it also includes back-pressure from a full launch queue, so read it +as enqueue cost only on small grids. Every kernel launches over the whole grid and filters +itself (masks are declaration-only in v1), so at large `n` the boundary kernels are full +sweeps and concurrency has little idle hardware to use. Measured on 2× RTX A4000 (no P2P): + +- Halo-bound (2 GPUs, `n=64`): masks cut time per iteration by 16 % (`K=1`) and 12 % (`K=4`), + on par with single-stream CUDA graph capture. +- Device-bound (`n=128`–`256`): within −2 % … +7 % of `ignored`. +- Per extra stream: roughly 1.5–3 µs of host time per iteration (`n=16`, 1 GPU). With + `K=16` the uncapped 33-stream schedule loses (134 vs 82 µs/iter); `max_streams=2` + recovers parity, so cap streams in region-heavy pipelines. + +CLI: `--n`, `--k`, `--iters`, `--warmup`, `--repeats`, `--gpus`, `--report PATH` +(writes `PATH..k`). + +Build target: `carbon_benchmark_skeleton_region_mask`. + ### `block_sparse` Block Jacobi on a sphere-inscribed cube; reports MLUPS over **active** owned diff --git a/benchmarks/skeleton_region_mask/CMakeLists.txt b/benchmarks/skeleton_region_mask/CMakeLists.txt new file mode 100644 index 00000000..a3ff6f7a --- /dev/null +++ b/benchmarks/skeleton_region_mask/CMakeLists.txt @@ -0,0 +1,3 @@ +_carbon_benchmark_add(carbon_benchmark_skeleton_region_mask skeleton_region_mask.cu) +target_link_libraries(carbon_benchmark_skeleton_region_mask PRIVATE carbon::carbon + carbon_benchmark_common) diff --git a/benchmarks/skeleton_region_mask/skeleton_region_mask.cu b/benchmarks/skeleton_region_mask/skeleton_region_mask.cu new file mode 100644 index 00000000..a44ff2a1 --- /dev/null +++ b/benchmarks/skeleton_region_mask/skeleton_region_mask.cu @@ -0,0 +1,329 @@ +// Skeleton region-mask benchmark: interior stencil + K boundary-condition kernels. +// +// Each half step of a Jacobi ping-pong is one interior 6-point stencil plus K small +// boundary kernels, all writing the same field. Boundary kernel k owns the k-th y-strip of +// the two x faces, so the K + 1 RegionMasks are pairwise disjoint and, with masks honoured, +// the K + 1 kernels can run side by side. Every kernel launches over the whole grid and +// filters itself (masks are declaration-only), which is the v1 cost model. +// +// Variants, each for K in {1, 4, 16} (or --k): +// masks : masks honoured, uncapped streams +// ignored : Options::ignore_region_masks (the pre-region-mask schedule) +// masks_max2/4 : masks honoured, Options::max_streams = 2 / 4 +// ignored_graph : masks ignored, single stream captured as a CUDA graph +// +// Prints one line per (variant, K): +// us_per_iter=... host_us_per_iter=... variant=... k=... streams=... gpus=... n=... +// us_per_iter is wall time per full iteration (both half steps) including the final drain; +// host_us_per_iter is the time spent inside run() calls (enqueue cost: launches, events, +// fork/join), which grows with the stream count. + +#include "bench_report.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int64_t kDefaultN = 256; +constexpr int kDefaultIters = 200; +constexpr int kDefaultWarmup = 20; +constexpr int kDefaultRepeats = 3; + +struct Args { + int64_t n = kDefaultN; + int iters = kDefaultIters; + int warmup = kDefaultWarmup; + int n_gpus = -1; + int repeats = kDefaultRepeats; + int k = -1; + std::string report_path{}; +}; + +[[nodiscard]] auto +parse_args(int argc, + char** argv) -> Args { + Args a{}; + a.n = static_cast( + carbon::bench::parse_int_flag("--n", argc, argv, static_cast(kDefaultN))); + a.iters = carbon::bench::parse_int_flag("--iters", argc, argv, kDefaultIters); + a.warmup = carbon::bench::parse_int_flag("--warmup", argc, argv, kDefaultWarmup); + a.n_gpus = carbon::bench::parse_int_flag("--gpus", argc, argv, -1); + a.repeats = carbon::bench::parse_int_flag("--repeats", argc, argv, kDefaultRepeats); + a.k = carbon::bench::parse_int_flag("--k", argc, argv, -1); + a.report_path = carbon::bench::parse_string_flag("--report", argc, argv); + return a; +} + +using DenseGrid = carbon::Dense; +using Span = DenseGrid::Span; +using Idx = DenseGrid::Idx; +using FieldT = DenseGrid::Field; +using carbon::RegionMask; + +// Label 0 is the interior; label 1 + k is boundary strip k of the x faces. +struct Labeling { + int64_t n; + int k; + + [[nodiscard]] CARBON_HD auto + label(const carbon::int64_3d& g) const -> int { + if (g.x != 0 && g.x != n - 1) { + return 0; + } + return 1 + static_cast(g.y * k / n); + } +}; + +[[nodiscard]] auto +build_interior(DenseGrid& grid, + FieldT& fin, + FieldT& fout, + Labeling lab, + std::string name) -> carbon::Kernel { + return carbon::Kernel::compute( + grid, + [&fin, &fout, lab](carbon::KernelLoader& loader) { + loader.region(RegionMask::bit(0)); + const auto in = loader.read_stencil(fin); + const auto out = loader.write(fout); + return [in, out, lab] CARBON_HD(Span s, Idx idx) -> void { + if (lab.label(s.global_location(idx)) != 0) { + return; + } + const carbon::NeighbourValue xp = + in.neighbour(s, idx, carbon::int8_3d{1, 0, 0}, 0); + const carbon::NeighbourValue xm = + in.neighbour(s, idx, carbon::int8_3d{-1, 0, 0}, 0); + const carbon::NeighbourValue yp = + in.neighbour(s, idx, carbon::int8_3d{0, 1, 0}, 0); + const carbon::NeighbourValue ym = + in.neighbour(s, idx, carbon::int8_3d{0, -1, 0}, 0); + const carbon::NeighbourValue zp = + in.neighbour(s, idx, carbon::int8_3d{0, 0, 1}, 0); + const carbon::NeighbourValue zm = + in.neighbour(s, idx, carbon::int8_3d{0, 0, -1}, 0); + if (!(xp.valid && xm.valid && yp.valid && ym.valid && zp.valid && zm.valid)) { + out.write(s, idx, 0, 0.0F); + return; + } + const float sum = xp.value + xm.value + yp.value + ym.value + zp.value + zm.value; + out.write(s, idx, 0, sum * (1.0F / 6.0F)); + }; + }, + std::move(name)); +} + +[[nodiscard]] auto +build_boundary(DenseGrid& grid, + FieldT& fin, + FieldT& fout, + Labeling lab, + int strip, + std::string name) -> carbon::Kernel { + return carbon::Kernel::compute( + grid, + [&fin, &fout, lab, strip](carbon::KernelLoader& loader) { + loader.region(RegionMask::bit(static_cast(1 + strip))); + const auto in = loader.read(fin); + const auto out = loader.write(fout); + return [in, out, lab, strip] CARBON_HD(Span s, Idx idx) -> void { + if (lab.label(s.global_location(idx)) != 1 + strip) { + return; + } + out.write(s, idx, 0, 0.5F * in.read(s, idx, 0) + 0.01F * static_cast(strip)); + }; + }, + std::move(name)); +} + +[[nodiscard]] auto +build_zero(DenseGrid& grid, + FieldT& field, + std::string name) -> carbon::Kernel { + return carbon::Kernel::compute( + grid, + [&field](carbon::KernelLoader& loader) { + const auto out = loader.write(field); + return [out] CARBON_HD(Span s, Idx idx) -> void { + out.write(s, idx, 0, 0.0F); + }; + }, + std::move(name)); +} + +struct Variant { + const char* name; + carbon::Skeleton::Options options; +}; + +[[nodiscard]] auto +make_variants() -> std::vector { + carbon::Skeleton::Options ignored; + ignored.ignore_region_masks = true; + carbon::Skeleton::Options max2; + max2.max_streams = 2U; + carbon::Skeleton::Options max4; + max4.max_streams = 4U; + carbon::Skeleton::Options graph = ignored; + graph.use_cuda_graph = true; + return {{"masks", carbon::Skeleton::Options{}}, + {"ignored", ignored}, + {"masks_max2", max2}, + {"masks_max4", max4}, + {"ignored_graph", graph}}; +} + +struct Sample { + double wall_seconds; + double host_seconds; + size_t streams; +}; + +auto +bench_once(DenseGrid& grid, + carbon::System& sys, + const Variant& variant, + int k, + int64_t n, + int iters, + int warmup) -> Sample { + auto u = grid.newField(carbon::MemorySide::Device, "u"); + auto v = grid.newField(carbon::MemorySide::Device, "v"); + + carbon::Skeleton init(sys); + init.add(build_zero(grid, u, "zero_u")); + init.add(build_zero(grid, v, "zero_v")); + init.run(); + init.wait(); + + const Labeling lab{n, k}; + carbon::Skeleton pipe(sys, variant.options); + pipe.add(build_interior(grid, u, v, lab, "interior_uv")); + for (int s = 0; s < k; ++s) { + pipe.add(build_boundary(grid, u, v, lab, s, "bc_uv_" + std::to_string(s))); + } + pipe.add(build_interior(grid, v, u, lab, "interior_vu")); + for (int s = 0; s < k; ++s) { + pipe.add(build_boundary(grid, v, u, lab, s, "bc_vu_" + std::to_string(s))); + } + pipe.compile(); + + for (int w = 0; w < warmup; ++w) { + pipe.run(); + } + pipe.wait(); + + double host = 0.0; + const auto t0 = std::chrono::steady_clock::now(); + for (int it = 0; it < iters; ++it) { + const auto h0 = std::chrono::steady_clock::now(); + pipe.run(); + host += std::chrono::duration(std::chrono::steady_clock::now() - h0).count(); + } + pipe.wait(); + const auto t1 = std::chrono::steady_clock::now(); + return {std::chrono::duration(t1 - t0).count(), host, pipe.num_streams()}; +} + +[[nodiscard]] auto +make_config_json(const Args& args, + const char* variant, + int k) -> std::string { + std::ostringstream out; + out << "{\n"; + out << " \"n\": " << args.n << ",\n"; + out << " \"iters\": " << args.iters << ",\n"; + out << " \"warmup\": " << args.warmup << ",\n"; + out << " \"repeats\": " << args.repeats << ",\n"; + out << " \"k\": " << k << ",\n"; + out << " \"variant\": \"" << variant << "\"\n"; + out << " }"; + return out.str(); +} + +} // namespace + +int +main(int argc, + char** argv) { + carbon::init(); + const Args args = parse_args(argc, argv); + + std::vector devices = carbon::get_all_devices(); + if (devices.empty()) { + std::cerr << "skeleton_region_mask: no devices visible\n"; + return EXIT_FAILURE; + } + if (args.n_gpus > 0 && static_cast(args.n_gpus) < devices.size()) { + devices.erase(devices.begin() + args.n_gpus, devices.end()); + } + if (args.k > 254 || args.k == 0 || args.n < 8) { + std::cerr << "skeleton_region_mask: need 1 <= --k <= 254 and --n >= 8\n"; + return EXIT_FAILURE; + } + + carbon::System sys(devices); + const carbon::int64_3d global{args.n, args.n, args.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}}, + true); + + try { + DenseGrid grid(sys, global, stencil); + const std::vector ks = args.k > 0 ? std::vector{args.k} : std::vector{1, 4, 16}; + for (const int k : ks) { + for (const Variant& variant : make_variants()) { + std::vector wall; + double host = 0.0; + size_t streams = 0; + for (int r = 0; r < args.repeats; ++r) { + const Sample s = bench_once(grid, sys, variant, k, args.n, args.iters, args.warmup); + wall.push_back(s.wall_seconds); + host += s.host_seconds; + streams = s.streams; + } + const carbon::bench::TimingStats stats = carbon::bench::compute_timing_stats(wall); + const double us_per_iter = stats.median_seconds * 1.0e6 / args.iters; + const double host_us_per_iter = host * 1.0e6 / (args.iters * args.repeats); + std::cout << "us_per_iter=" << us_per_iter << " host_us_per_iter=" << host_us_per_iter + << " variant=" << variant.name << " k=" << k << " streams=" << streams + << " gpus=" << sys.gpu_group().size() << " n=" << args.n + << " iters=" << args.iters << " repeats=" << args.repeats << '\n'; + + if (!args.report_path.empty()) { + const std::string path = args.report_path + "." + variant.name + ".k" + std::to_string(k); + if (!carbon::bench::write_json_report(path, "skeleton_region_mask", + make_config_json(args, variant.name, k), sys, stats, + us_per_iter, "us_per_iter")) { + return EXIT_FAILURE; + } + } + } + } + } catch (const std::exception& e) { + std::cerr << "skeleton_region_mask: " << e.what() << '\n'; + return EXIT_FAILURE; + } + return EXIT_SUCCESS; +} diff --git a/cmake/CarbonSyclMirror.cmake b/cmake/CarbonSyclMirror.cmake new file mode 100644 index 00000000..dc0bb11b --- /dev/null +++ b/cmake/CarbonSyclMirror.cmake @@ -0,0 +1,28 @@ +# SYCL registration of a .cu source as an executable. +# +# acpp / clang sniff the .cu extension regardless of CMake's LANGUAGE CXX setting and turn +# on offload modes that need a libomptarget-nvptx-sm_XX.bc bitcode library we don't ship. +# The source is therefore copied to a .cpp twin in the build tree (configure_file COPYONLY +# re-runs whenever the .cu changes) and that twin is what acpp compiles. Nothing in a +# dual-backend .cu is CUDA-specific (no <<<>>>, no __global__); the extension only routes +# it through nvcc on the CUDA build. +# +# The twin lives in the binary dir, so quoted includes of headers that sit next to the +# original source ("test_domain.h", "wind_tunnel_common.h", ...) would not resolve; the +# source directory is added to the target's private include path to keep them working. +# +# Usage: carbon_add_sycl_mirrored_executable( ) +# is relative to CMAKE_CURRENT_SOURCE_DIR of the caller. +function(carbon_add_sycl_mirrored_executable target source_cu) + set(_src "${CMAKE_CURRENT_BINARY_DIR}/${target}.cpp") + configure_file("${CMAKE_CURRENT_SOURCE_DIR}/${source_cu}" "${_src}" COPYONLY) + get_filename_component(_src_dir "${CMAKE_CURRENT_SOURCE_DIR}/${source_cu}" DIRECTORY) + add_executable(${target} "${_src}") + target_include_directories(${target} PRIVATE "${_src_dir}") + target_compile_features(${target} PRIVATE cxx_std_20) + add_sycl_to_target(TARGET ${target} SOURCES "${_src}") + if(CARBON_SYCL_TARGETS MATCHES "cuda") + target_compile_options(${target} PRIVATE --cuda-path=${CARBON_SYCL_CUDA_PATH}) + target_link_directories(${target} PRIVATE ${CARBON_SYCL_CUDA_PATH}/lib64) + endif() +endfunction() diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index b6d1461e..079bce20 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6238,3 +6238,317 @@ This unblocked the matrix on this host: the `sycl` and `hip-nvidia` images build `System::stream()` per call (the old reference raced the inline D-to-H copy on SYCL OpenMP). Verified with `test_skeleton_reduce_split`, `test_reduce_sum`, and `test_reduce_ops` on SYCL OpenMP, and with `test_skeleton_reduce_split` on CUDA. +- **2026-11 — `CARBON_ENABLE_PYTHON=ON` builds again.** `append_dense_token` and + `append_block_token` in `libcarbonpy/src/cuda_driver.cpp` still built `AccessToken` + positionally as `{uid, mode, pattern, name, {}}` after `ResourceKind resource` became the + second member, so `mode` landed in the `resource` slot and `carbonpy` failed to compile + (`cannot convert AccessMode to ResourceKind`). The default build has Python off, which is + why nothing caught it. Both sites now pass `ResourceKind::Field` explicitly, matching + `append_mgrid_token`. +- **2026-11 — `RegionMask`: a 256-bit user-defined sub-domain label set.** Groundwork for + finer-than-field skeleton dependencies. The user maps each bit to a cell set of the domain; + Carbon never sees the geometry and only relies on the contract that bits are atoms + (pairwise disjoint cell sets), so masks that do not intersect name disjoint cells. All ones + means "the whole field"; default construction is the empty mask, like `std::bitset`. + Storage is a plain `uint64_t[4]` (not `std::array`) so the type stays usable from CUDA / HIP / + SYCL device code; `test(uint8_t)` / `from_label(uint8_t)` support the recommended per-cell + `uint8_t` label idiom (256 bits is exactly the `uint8_t` range). Index-taking factories + (`bit`, `range`, `{bits}`) are host-only and throw `std::out_of_range` instead of silently + wrapping. `to_string` renders `all` / `none` / `{0,3,5-9}` for diagnostics. +- **2026-11 — Sub-field (region-mask) dependencies in the Skeleton.** `AccessToken` gains a + trailing `RegionMask mask` (default all-ones, so every existing token, aggregate initialiser + and schedule is unchanged), and two accesses now conflict only when they share a field, + their modes conflict, *and* their masks intersect. Kernels declare their footprint with + `KernelLoader::region(M)` (applies to every Map access, readable in the launch phase) or a + per-call override `read(f, M)` / `write(f, M)` / `read_write(f, M)` / `operator()(f, M)`. + Masks are declaration-only — the kernel still filters its own cells — and bits are + user-defined pairwise-disjoint atoms. Stencil reads, halos and scalar readbacks stay + whole-field, so a stencil reader (and its auto-halo) still waits on every masked writer. + `Skeleton::Options::ignore_region_masks` / `CARBON_IGNORE_REGION_MASKS=1` restore the + whole-field schedule for A/B debugging; an empty mask warns once per kernel; a multi-stream + masked schedule with `use_cuda_graph` logs that it falls back to eager launches. Under MPI + the first `run()` after a compile of a halo/reduction pipeline compares a hash of the + pipeline shape (including masks) across ranks via the new `Distributed::all_ranks_equal` + and throws on mismatch instead of deadlocking in NCCL. Covered by + `tests/test_skeleton_region_mask.cu`. +- **2026-11 — Region masks in the Skeleton exporters.** `export_kernel_list_dot` adds a + `region {…}` note under each access chip whose mask is not all-ones (separate `R` / `W` + masks when they differ), `export_dot` node tooltips append each masked token's region, and + both option lines say `region_masks=ignored` when `Options::ignore_region_masks` or + `CARBON_IGNORE_REGION_MASKS` is in effect. Unmasked pipelines render byte-identically; + `export_launch_order` is unchanged. +- **2026-11 — Region-mask example and benchmark.** `examples/region_mask_bc.cu` splits the + `jacobi_unified` heat problem into an interior stencil kernel and a Dirichlet boundary + kernel on a per-cell label partition (`from_label(0)` / `~from_label(0)`), shows the + 3-stream masked schedule next to the 1-stream whole-field one, checks they are + bit-identical, and writes both DOT views with `--dot`. `benchmarks/skeleton_region_mask` + (interior stencil + `K` disjoint boundary kernels) measured on 2× RTX A4000: −16 % / + −12 % time per iteration for `K` = 1 / 4 when halo-bound (2 GPUs, `n=64`), within + noise when device-bound (`n` ≥ 128, because v1 masked kernels still sweep the whole grid), + and ~1.5–3 µs of host time per extra stream per iteration — uncapped `K=16` (33 streams) + is slower than the whole-field schedule, `max_streams=2` restores parity. Single-stream + CUDA graph capture matches or beats eager multi-stream at small sizes; that is the + trigger for the multi-stream capture follow-up, not a regression. +- **2026-11 — Region-mask documentation.** `docs/skeleton/README.md` gains a "Region masks" + section (contract, `DataView` vs `RegionMask`, API, exporter annotations, measured costs + and the `max_streams` / CUDA-graph guidance); the `AGENTS.md` Skeleton entry lists the + feature. Known gaps, deliberately deferred: no warning yet when `region(M)` ends up on + stencil-only kernels (no effect), stencil footprints are not dilatable, masked kernels + still launch over the whole grid, and Python/Warp tokens stay all-ones. +- **2026-11 — Region masks across MPI ranks.** `tests/test_skeleton_region_mask_dist.cu` + (2 ranks, label `distributed`): a masked interior + wall pipeline under `None` and + `Standard` is bit-identical to `ignore_region_masks` with equal launch orders on every + rank, a rank-local `export_kernel_list_dot` does not block, and a rank-dependent mask + makes the first `run()` throw on every rank instead of deadlocking. Validated in the + `cuda-mpi` container (28/28 distributed tests). On hosts whose PCIe peer DMA is unusable + (carbon already leaves it off there) NCCL's own P2P transport hangs; run the distributed + suite with `NCCL_P2P_DISABLE=1`. +- **2026-11 — `Halo` drains its intra-node copies before any GPU writes again.** Each peer + copy is enqueued on the *destination* GPU's stream but reads the *source* GPU's owned + cells, and the only cross-GPU ordering was the leading producer fence. The old comment + claimed the next halo's leading fence covered the copy-vs-overwrite WAR; that holds only + when a second halo sits between the copy and the source GPU's next write (two-field + ping-pong). A pipeline with one halo per iteration (a field rewritten in place, e.g. an + interior writer followed by a stencil of the same field) let gpu0 overwrite its top layers + while gpu1 was still copying them. `test_skeleton_region_mask` exposed it: masks shorten + the source GPU's critical path, and with a second process loading both GPUs it failed + 23–25/50 runs (always at gpu0's top owned layers), 0/100 idle. `Halo::operator()` now + records a second per-GPU event group (`drain_event_`, allocated only for + multi-local-GPU layouts, like `fence_event_`) after `intra_` and fan-in-waits on it. + Under the same load: 0/50 with the fix, 25/50 with it reverted. +- **2026-11 — SYCL build drift: every target compiles again.** Under `CARBON_BACKEND=Sycl` each + dual-backend `.cu` is copied to a `.cpp` twin in the build tree (acpp sniffs `.cu`), so quoted + includes of headers next to the source (`test_domain.h`, `wind_tunnel_common.h`) stopped + resolving once tests started using them: 12 tests and one example failed to compile, which + nothing caught because no CI lane builds SYCL with GPU targets. The four copies of the mirror + logic (unit tests, MPI tests, examples, benchmarks) are now one + `carbon_add_sycl_mirrored_executable` (`cmake/CarbonSyclMirror.cmake`) that also puts the + source directory on the target's include path. Two drifts that broke the CUDA build too: + `examples/wind_tunnel_common.h` used `LbmParameters` without its new `Real` argument, and + `render_wind_tunnel_live` (ImGui panels outside `CARBON_HAVE_VIEWER`) is now registered only + with `CARBON_BUILD_VIEWER=ON`. SYCL on 2× A4000: 106 tests build, 101 pass; the rest are the + multi-GPU reduce and reduce-option gaps tracked next. +- **2026-11 — SYCL: cross-device copies were not ordered before the next submission.** + Symptom: multi-GPU reductions occasionally (`skeleton_overlapped` 2/50, + `skeleton_reduce_split` 2/30) or deterministically (`mgrid_locator` in a fresh process) came + back with one GPU's share missing or replaced by a value from an *earlier* reduction. + `tests/test_reduce_partials_multi_gpu.cu` (new, both backends) reads every + `ReductionResult::gpu_partial(g)` back after the reduce drained: every per-GPU partial was + right and only the combined total was wrong, so stage 1 and `sycl::reduction` were innocent. + The stage-2 peer copy of a partial into the root GPU's staging slot is a `q.memcpy` between + two devices on the root's in-order queue; AdaptiveCpp 25.02 records it as a + device-to-device operation it may run on the source device's backend stream, and the + in-order queue then does not order the combine kernel submitted next on `q` after it, so the + combine read the staging slot before the bytes landed (stale data from a reused allocation). + A host wait on every queue *before* the copy did not help; a host wait on the copy's event, + or an explicit dependency on it, did (8/10 failing runs → 0/10). `System::async_copy` now + pins both edges of a cross-device copy with explicit events (a no-op custom operation the + copy depends on, and one that depends on the copy), with no host blocking. Every device copy + goes through `async_copy`, so halo peer copies get the same ordering. Measured after the + fix: 0/50 for `skeleton`, `skeleton_overlapped`, `skeleton_reduce_split`, + `skeleton_region_mask`, `reduce_partials_multi_gpu`, `reduce_sum_multi_gpu`, + `dense_disg_reduce`, `block_reduce`, `mgrid_skeleton`, `skeleton_reduce`; `mgrid_locator` + 20/20 across fresh containers. +- **2026-11 — SYCL: `ReduceHostCopy::Deferred` enabled.** It was rejected on SYCL at + construction, so `skeleton_scalar_pattern{,_multi_gpu}` threw. Nothing in the deferred path + is backend-specific (`ScalarReadbackKernelImpl` is an `async_copy` plus the slot-done event); + the missing piece was a trustworthy SYCL slot-done event. `ReductionResult`'s SYCL + record/wait now use the same `AdaptiveCpp_enqueue_custom_operation` idiom as `EventGroup` + (recording writes into the shared `sycl::event` instead of `const_cast`-replacing the + `Event`), and the commented-out experiments are gone. 0/50 for both scalar-pattern tests, + `skeleton_reduce` and `reduce_scalar_ring` (2 GPUs, 2-slot ring with lag 1 included). +- **2026-11 — SYCL: `ReduceFinalize::BlockAtomic` implemented.** It threw on SYCL + (`reduce_atomic` aborted). New `detail/backend/sycl/block_atomic_reduce.h`: an `nd_range` + launch (256-wide groups) where each work-group sums its cells with + `sycl::reduce_over_group(…, sycl::plus())` and adds the group sum into the per-GPU scalar + with one device-scope `atomic_ref` add, after a `memset` on the same in-order queue. Same + admissible set as CUDA (Sum; float/double/int32/int64; plain Dense and DenseDistributed; the + constructor still rejects DenseDisg and Block), wired through a `sycl_block_atomic` entry on + `ReduceLaunchTraits`. `reduce_atomic` (BlockAtomic vs DeviceReduce for int64/float/double on + 2 GPUs) 30/30. The carbon-owned rewrite of the `sycl::reduction` reducers that was planned + alongside this is dropped: `test_reduce_partials_multi_gpu` showed every per-GPU partial + `sycl::reduction` produced was exact, the lost share was the cross-device copy above. +- **2026-11 — Halo drain fence extended to `HaloDisg`, `HaloBlock` (and so mGrid) and + `HaloDistributed`.** They had the same shape as `Halo` before its trailing fence was added: + each intra-process copy runs on the destination GPU's stream and reads the source GPU's owned + cells, and only a leading fence ordered it. Each now records a per-GPU `drain_event_` after + its intra copies (`HaloDistributed`: after the axis-pass loop and after the non-pass + `dist_`), so a writer on the source GPU queued behind the halo can't overwrite cells a peer + copy is still reading. No reproducer on this host. Under `skeleton_overlap` load, the + DenseDisg/Block/mGrid halo tests pass 40/40 with and without the fence, and + `skeleton_block{,_extended}`/`block_overlapped_stencil` show 0 drift either way. Without + region masks, which are Dense-only, the source GPU always runs the stencil between the halo + and the next overwrite, which shrinks the window. The fix is the same fence argument as + `Halo`. +- **2026-11 — SYCL stress sweep; `skeleton_scalar_pattern` test race fixed.** Every `gpu`-labelled + test (93) was run in the SYCL container 100× on idle GPUs and 50× with + `carbon_benchmark_skeleton_overlap` holding both GPUs at ~98%. That is 13 950 runs, and the only + failure was `skeleton_scalar_pattern` under load: SYCL 29/50, CUDA 23/50, both + `lag-1 sum 192 expected ~128`. The cause was in the test. It re-uploaded `f` on its own + stream straight after an asynchronous `sk.run()`, so the upload raced the reduction reading + `f`. It now calls `sk.wait()` first, and is 0/100 under load on both backends. The + `needs_multi_device` label covers only 30 of the multi-GPU tests (`skeleton`, `mgrid_locator` + and `skeleton_region_mask` run on every device without it), so the sweep used `-L gpu`. +- **2026-11 — `sycl-mpi` validated; `docker-build-all.sh` gains `--docker-env` and + `--ctest-args`.** First `sycl-mpi` run this cycle: 134/136, failing `carbon_format_check` + (the pre-existing violations every config has) and `block_dist_stencil_parity`, which was + deterministic, 3232 mismatches per rank, with every six-direction probe returning the cell's + own value. The probe kernel indexed a function-local `static constexpr std::array` of + offsets from device code. nvcc copes, but AdaptiveCpp device code reads a zero-filled copy, so + all six offsets were `{0,0,0}`. The kernel now uses literal offsets, as the file's Jacobi + step already did. Result: 0/20, and `sycl-mpi` is 135/135 with `-E format_check`, with the + 28 distributed tests green 5× in a row. `cuda-mpi` is still 28/28. The script now forwards + `--docker-env KEY=VAL` (repeatable) into every container, so `NCCL_P2P_DISABLE=1` can be set + on hosts whose PCIe peer DMA is unusable. It runs the NVIDIA `*-mpi` configs with + `--ipc=host`, since NCCL/MPI shared-memory transports outgrow docker's 64 MiB `/dev/shm`. + `--ctest-args` appends to the in-container ctest, for repeat lanes. `usage` now prints the + whole header, where the old line range had cut the flag docs off. +- **2026-11 — `gpu-ci` gains `sycl` / `sycl-mpi` cells and a repeat lane.** The matrix is now + `[cuda, cuda-mpi, sycl, sycl-mpi]`. SYCL has its own event and cross-device ordering code, + and every SYCL bug fixed this cycle was invisible to the CUDA cells. The `cuda` and `sycl` + cells re-run every `gpu` test 20× (`--repeat until-fail:20`) in the build tree the first + step left behind. The cross-device races fixed this cycle each passed a single run most of + the time. Runner-specific container environment comes from the `GPU_CI_DOCKER_ENV` Actions + variable, e.g. `NCCL_P2P_DISABLE=1`. The `workflow_dispatch` `configs` input was declared + but never read; it now selects matrix cells. The job timeout goes from 90 to 150 minutes. + The `AGENTS.md` SYCL paragraph, docker knobs and test-count table were refreshed + (2×RTX A4000: CUDA 112, CUDA+MPI 140, SYCL 108, SYCL+MPI 136). +- **2026-11 — `examples/region_mask_cube.cu`, a minimal region-mask walk-through.** It uses a + cube with two regions: bit 0 is the interior and bit 1 is the boundary. Each kernel tests + for the boundary from its voxel coordinates, so there is no label field. One field `u` + goes through four kernels: `fill_boundary` (boundary), `fill_interior` and `scale_interior` + (interior), then `count_wrong`, an unmasked `int64_t` Sum reduce that doubles as the + self-check. The example prints the compiled dependency table, built from `min_edges()` and + `kernel_streams()`, with masks honoured and with masks ignored, and `--dot` writes both + schedules. Honoured gives 2 streams: the boundary fill sits beside the interior chain and + the check waits for both. Ignored gives a 4-kernel chain on 1 stream. The result is 0 wrong + voxels on CUDA (2 GPUs) and SYCL. `region_mask_bc.cu` stays the heat-solver walk-through. +- **2026-11 — Region-mask examples: launch matrix and `--overlap`.** With `--dot `, + both `region_mask_bc` and `region_mask_cube` now also write the launch matrix + (`export_launch_matrix_dot`, one column per stream) for the masked and the masks-ignored + schedule. Both also accept `--overlap none|standard`. In `region_mask_bc` Standard OCC + splits both interior stencils into Internal and Boundary halves around their halos, while + the boundary-condition kernels keep their own streams. `auto_halo_v` still waits for + `boundary_v`, and the results stay bit-identical. On 2×RTX A4000 the combination pays off + only between launch-bound and saturated sizes. In µs per iteration (none / masks / OCC / + both): 64³ gives ~90 / 73 / 71 / 85, 128³ gives 218 / 169 / 144 / 140, and 256³ gives + 1023 / 920 / 970 / 947. The cube pipeline has no stencil, so OCC leaves its schedule + unchanged, and the example says so. +- **2026-11 — `SubGrid`: compact iteration over a region.** `S = SubGrid(G, F, B)` + keeps, per GPU, a table of the owned parent cells selected by `F` and launches one thread + per entry ("lane"); `B` is the region its kernels declare. Built by + `Dense::new_sub_grid(labels, mask)` (a `uint8_t` label field, `F` = label bit in `mask`) + or `new_sub_grid(predicate, mask)`. Decisions: + - *Compact owner storage, like Neon's sGrid.* SubGrid fields hold one value per lane and + nothing else. They have no halo, so `read_stencil` on one is a `static_assert` (the + `HaloCapableField` concepts in `kernel.h`), and SubGrid partitions have no neighbour API. + Stencils read *parent* fields, through the parent's halo. + - *`S::Span` / `S::Idx` derive from the parent's.* The Idx adds its lane and the Span adds + the lane table, so `uG.read(s, i, 0)` on a parent field works with no conversion call + and keeps the parent's semantics. The risk of deriving is name hiding: a derived member + shadowing a parent one. The derived types add only `sub_lane()` / `sub()`, and + `static_assert`s reject a parent that already has them. SubGrid partitions take only the + SubGrid types; in debug builds they also check the owner, the lane range and the cell. + - *Lane order: parent-Internal cells first, then parent-Boundary.* `DataView::Internal` / + `Boundary` are then two contiguous lane ranges, so the Skeleton's OCC rewrites (keyed only + on kind and tokens) split SubGrid kernels like Dense ones. That includes Extended OCC + splitting a SubGrid kernel that produces a stencil-read parent field. + - *The mask comes from the SubGrid.* The loader's kernel-wide region is preset to `B`, so + two SubGrids with disjoint masks writing one parent field run unordered. The loader is + also bound to the SubGrid's uid, so loading another SubGrid's field (or a SubGrid field + from a parent kernel) throws when the kernel is built. + - *The lane table is built once, on the host, and the SubGrid is immutable.* The selection + runs as a Dense kernel into a flag field, is downloaded, and is compacted in iteration + order, which keeps it deterministic and backend-neutral. A device scan is a later + optimisation. There are no nested SubGrids, and no reductions or `compute_universal` + yet (`static_assert`). `Kernel::compute` / `host_compute` forward to + `S.make_kernel` / `make_host_kernel`. + - *Compile-time rules are tested as builds.* `sub_grid_compile_fail_{0..5}` are targets + outside `all` that ctest builds and that must fail with a given diagnostic (CUDA only). + Validated on 2×RTX A4000 with CUDA and SYCL (AdaptiveCpp), and on one GPU. A mixed Dense + + SubGrid pipeline is bit-identical to a hand-sequenced run under every `OverlapMode`. + `examples/sub_grid_cube.cu` fills the boundary of a 256³ cube in 28.7 µs, versus 58.8 µs + for the filtered Dense kernel (2.8× at 384³; launch-bound below 128³). +- **2026-11 — Reductions over a `SubGrid`, and SubGrid validated on HIP.** `Kernel::reduce`, + `host_reduce` and `reduce_universal` now accept a SubGrid, with + `S.make_reduce_kernel` / `make_host_reduce_kernel` / `make_universal_reduce_kernel` as + sugar. The per-cell lambda is `T(const S::Span&, const S::Idx&)`. Decisions: + - *Reuse the reduce pipeline, swap only the stage-1 launch.* `ReduceKernelImpl` and its + host / universal siblings already go through `ReduceLaunchTraits` / + `HostLaunchTraits`. Specialising those for `SubGrid` + (`detail/sub_grid/reduce_traits.h`) gives SubGrid reductions the multi-GPU combine, the + cross-rank stage, `ReduceFinalize::BlockAtomic`, `ReductionResult` and the Skeleton's + OCC Partial / Merge split without touching any of them. Stage 1 is one thread per lane + over the view's lane range in fixed 256-thread blocks + (`detail/backend/{cudalike,sycl}/sub_grid_reduce.h`); the host path is an OpenMP loop + over lanes with per-thread partials. + - *Loading goes through `BoundLoading`.* `load(S, fn, loader)` presets the region and the + SubGrid uid, but the reduce impls call the loading functor directly. `Kernel::reduce` + wraps it in a functor that calls `load` first, so ownership checks and mask declarations + are identical to `S.make_kernel`. + - *`ReduceOptions::stage1_threads[_y]` throw.* They shape Dense's 2D stage-1 tiles, which + a lane range does not have. Rejecting them is better than ignoring them silently. + - *`compute_universal` over a SubGrid stays a static_assert.* It needs the grid's launch + geometry (`gpu_grid` / `gpu_block`), which a SubGrid does not expose. The universal + *reduction* only needs the traits, so it works. + - *The SubGrid compile-fail tests also run on HIP.* Under HIP-on-NVIDIA the compiler is + nvcc, so the diagnostics match. Two regexes were widened to clang's wording + (`no member named`, `no matching member function`) for HIP on AMD, which this host + cannot build. + `tests/test_sub_grid_reduce.cu` covers Sum / Max / count over parent and SubGrid fields, + the Internal + Boundary = Standard split, BlockAtomic, host and universal launches, mask + tokens, the ownership and options throws, an empty SubGrid (identity), and a Skeleton + where a SubGrid reduction stencil-reads a parent field, checked against a host reference + under every `OverlapMode`. When OCC is on, it also checks that the Internal / Boundary + partials appear. Forcing the CUDA lane offset to 0 fails 4 checks. Measured on 2×RTX + A4000, excluding `carbon_format_check`: CUDA 121/121 (also on one GPU for the new test), + SYCL (AdaptiveCpp) 111/111, and `hip-nvidia` 117/117. HIP's SubGrid tests, + `examples/sub_grid_cube.cu` and all six compile-fail cases pass. HIP's last measured + count, from 2026-07, was 89. +- **2026-11 — `SubGrid` over a `Block` parent; copied Blocks no longer share host spans.** + `Block::new_sub_grid(labels, mask)` / `new_sub_grid(predicate, mask)` build a + `SubGrid>` with the same API as the Dense one. Decisions: + - *Flat lane table, not a brick-aware one.* Each lane is one `Block::Idx` (brick, intra + offset), so the existing lane launchers, reduce traits and Skeleton integration work + unchanged. A brick-aware layout (one GPU block per touched brick, a per-brick voxel + list) would help a selection that fills whole bricks, but SubGrids are meant for a few + voxels that need special treatment, and those mostly sit in different bricks. Multi- + resolution Blocks and `DenseDisg` stay out of scope; any other parent is a static_assert. + - *A `ParentTraits` seam.* `host_span`, `for_each_cell` (enumerate selected cells in + the parent's iteration order) and `flag_offset` are the only parent-specific pieces of + the Builder; Dense's code moved behind its specialisation unchanged. + - *Host spans come from the parent's host tables.* Building a SubGrid host span from a + device span works for Dense (the Span holds no pointers) but makes a Block host kernel + dereference device pointers. The Builder now takes host spans from + `ParentTraits::host_span` on the State's own copy of the parent. The Block's host tables + cover owned bricks only, so host `neighbour` reads must stay in the GPU's slab. + - *Copying a Block resets its memoised host spans.* `Block::host_spans()` memoises spans + that point into the Block's own host vectors, and the copy constructor copied the memo, + so a copy kept pointing into the source (a use-after-free once the source died). The + memo is now a `ResetOnCopy` member; `tests/test_block_host_parity.cu` checks copies and + a host reduce through a copy whose source was destroyed. + `tests/test_sub_grid_block.cu` (64³ ball, 655 markers, including voxels on brick faces, + next to inactive voxels and on the slab cut) covers construction, device and host kernels with neighbour + reads, reductions, the ownership throw, and a Skeleton under every `OverlapMode`, with + exact results. Building host spans from device spans segfaults it, and offsetting the + flag index or swapping x / z fails it. Two compile-fail cases were added (`read_stencil` on + a Block SubGrid field, a `DenseDisg` parent). `examples/sub_grid_block_markers.cu` updates + one voxel in 1000 of a 256³ ball in 5.8 µs per launch against 79.1 µs for a Block kernel + with a label filter (2×RTX A4000; SYCL 9.4 / 80.3, HIP on NVIDIA 4.9 / 79.0). Measured + excluding `carbon_format_check`: CUDA 124/124, SYCL (AdaptiveCpp) 112/112, `hip-nvidia` + 120/120; the new test also passes on one GPU. +- **2026-11 — End-to-end SubGrid test: Jacobi + AXPY with B and C in parallel.** + `tests/test_sub_grid_jacobi_axpy.cu` runs 100 iterations of an int64 Jacobi step followed + by `y = 3 u + y` on a Dense box and a Block ball. B is the voxels missing a face neighbour + (own rule); C is every other active voxel (sum of six / 6). A per-voxel source keeps the + field from flattening. Each grid runs: one kernel that branches on neighbour validity + (`no_s`); B as a SubGrid plus C as a masked parent kernel (`bc_parent`); and B and C as two + SubGrids with complementary masks (`bc_sub`). The BC forms run under every OverlapMode. + Every variant must match a host reference exactly in `u` and in `y`. Schedule checks: B and + C are not ordered and run on different streams; under OCC each Jacobi step has exactly two + `[compute/internal]` and two `[compute/boundary]` launches (the Skeleton currently places + both boundary halves on the halo stream); AXPYs stay a single `[compute/standard]` launch + except under TwoWayExtended, which also splits them. Lane counts: `B.count + C.count` + equals the owned voxels. Breaking the B rule, the C SubGrid rule, the C region declaration + or the B predicate each makes it fail. Measured excluding `carbon_format_check`: CUDA + 125/125 (also on one GPU), SYCL (AdaptiveCpp) 113/113, `hip-nvidia` 121/121. diff --git a/docs/skeleton/README.md b/docs/skeleton/README.md index 2952bca8..82083b98 100644 --- a/docs/skeleton/README.md +++ b/docs/skeleton/README.md @@ -109,3 +109,175 @@ number, stream, view) so rows cross-reference the launch matrix. `prefix_ab_matrix.dot` / `prefix_ba_matrix.dot` and the kernel lists `prefix_ab_kernels.dot` / `prefix_ba_kernels.dot`. See `tests/test_skeleton_launch_order.cu`. + +## Region masks (sub-field dependencies) + +By default an access covers its whole field, so two kernels that write the same field +are always ordered. A `RegionMask` (``, 256 bits) narrows a Map +access to a user-defined part of the domain; two accesses then conflict only when they +share a field, their modes conflict, **and** their masks intersect. Disjoint writers of +one field get no edge and may land on different streams. + +```cpp +const RegionMask kInterior = RegionMask::from_label(0); +const RegionMask kBoundary = ~kInterior; // full partition: "every other cell" + +auto bc = carbon::Kernel::compute(dense, [&](carbon::KernelLoader& L) { + L.region(kBoundary); // every Map access below is masked + const auto lab = L.read(labels, RegionMask::all()); // read before the filter: everywhere + const auto out = L.write(u); + return [lab, out] CARBON_HD(Span s, Idx idx) { + if (lab.read(s, idx, 0) == 0) { return; } // the kernel filters itself + out.write(s, idx, 0, /* Dirichlet value */ 0.0F); + }; +}, "bc"); +``` + +Contract (Carbon trusts the declaration; a false one is a silent data race): + +- **Bits are atoms.** You decide what each bit means; Carbon only assumes different bits + are disjoint cell sets. Make them a full partition (e.g. one `uint8_t` label per cell, + `from_label(label)`), so `~M` really is the rest of the domain. +- **Masks only declare.** They do not change the launch: the kernel still iterates its + whole `DataView` and must skip cells outside its mask. The effective iteration set is + the `DataView` band (Carbon-owned Internal / Boundary geometry) intersected with the + cells the body accepts (your labels) — the two concepts are independent. +- **A mask covers every cell the access touches**, including reads made before the + filter (declare those `RegionMask::all()`, as with `labels` above) and reads of other + cells through the same view (Map must really be cell-local). +- **Stencil reads, halos and scalar readbacks are always whole-field.** A stencil reader + — and the auto-halo in front of it — still waits on every masked writer of the field. +- **Same masks on every GPU and rank, fixed at kernel construction.** Under MPI the first + `run()` of a pipeline with halos or reductions compares a hash of the pipeline shape + (including masks) across ranks and throws `std::logic_error` on mismatch instead of + letting NCCL deadlock. +- **An empty mask conflicts with nothing** and warns once per kernel at compile time. + +API: `KernelLoader::region(M)` sets the default mask for every Map access of the kernel +(whichever order it is called in; `L.region()` reads it back, also in the launch phase), +and `read(f, M)` / `write(f, M)` / `read_write(f, M)` / `L(f, M)` pin one access. +`Skeleton::Options::ignore_region_masks` — or `CARBON_IGNORE_REGION_MASKS=1` at run time +— makes every access whole-field again, giving exactly the pre-region-mask schedule for A/B +debugging; `Skeleton::region_masks_honoured()` reports the effective setting. + +Inspection: `export_kernel_list_dot()` adds a `region {…}` note under each masked access +chip, `export_dot()` tooltips list each masked token's region, and both option lines show +`region_masks=ignored` when masks are off. Unmasked pipelines render exactly as before. + +Costs to keep in mind (numbers from `benchmarks/skeleton_region_mask`, see +`benchmarks/README.md`): + +- Every masked kernel still sweeps the whole grid, so concurrency pays off when the device + has idle time (halo-bound multi-GPU, small grids): −12 … −16 % per iteration there, + within noise once the device is saturated. +- Each extra stream costs roughly 1.5–3 µs of host time per iteration (events and + fork/join). Many tiny disjoint kernels can be slower than the whole-field schedule; cap + with `Options::max_streams` (2 was best for 16 boundary kernels). +- CUDA graph capture only covers single-stream schedules; with `use_cuda_graph` a masked + multi-stream schedule falls back to eager launches (logged at compile). + `max_streams = 1` keeps it capturable. + +`examples/region_mask_cube.cu` is the minimal starting point: on a cube, one kernel fills +the boundary voxels and two update the interior of the same field, and the printed schedule +shows the boundary kernel running beside the interior chain (one stream with masks ignored). +`examples/region_mask_bc.cu` is the end-to-end walk-through (interior stencil + Dirichlet +boundary kernel, 3 streams vs 1, bit-identical check, `--dot` for both DOT views); +`tests/test_skeleton_region_mask.cu` pins the semantics. + +## SubGrid (compact iteration over a region) + +A masked Dense kernel still sweeps the whole grid and skips cells itself. +`carbon::SubGrid` (``, included by ``) is the +compact counterpart: `S = SubGrid(G, F, B)` stores, per GPU, the owned parent cells selected +by `F` as a lane table and launches one thread per lane. `B` is the region its kernels +declare. The parent can also be the block-sparse grid: `carbon::SubGrid>`, +built with the same two `block.new_sub_grid(...)` factories (see "Block parent" below). + +```cpp +using S = carbon::SubGrid; +// From a uint8_t label field: the owned cells whose label bit is in the mask. +const S walls = dense.new_sub_grid(labels, RegionMask::from_label(1), "walls"); +// From any predicate (evaluated once by a Dense kernel); B defaults to all. +const S shell = dense.new_sub_grid([n](carbon::KernelLoader&) { + return [n] CARBON_HD(const Span& s, const Idx& i) { return on_face(s.global_location(i), n); }; +}, kBoundary, "shell"); + +auto q = walls.newField(carbon::MemorySide::Device, "q"); // one value per lane +auto bc = carbon::Kernel::compute(walls, [&](carbon::KernelLoader& L) { + const auto uG = L.read_stencil(u); // parent field: own cell and neighbours (u's halo) + const auto vG = L.write(v); // parent field: the lane's cell + const auto qS = L.read_write(q); // SubGrid field + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) { + vG.write(s, i, 0, uG.read(s, i, 0) + qS.read(s, i, 0)); + }; +}, "wall_bc"); +``` + +Rules: + +- **Types.** `S::Span` and `S::Idx` derive from the parent's (the Idx adds its lane, the Span + the lane table), so parent-field partitions accept them unchanged. SubGrid partitions take + only `S::Span` / `S::Idx` and have no neighbour access. +- **Region.** The loader's kernel-wide region is preset to `B`, so parent-field Map accesses + carry `B` and the Skeleton orders the kernel like a masked Dense kernel. The label + constructor makes `F` match `B` by construction; with the predicate constructor, `B` is + your declaration that every selected cell lies in `B` (same contract as above). +- **No halos on SubGrid fields.** `read_stencil` on one is a compile error. Stencil-reading + a *parent* field is fine and makes the kernel an OCC candidate: lanes are stored + parent-Internal first, then parent-Boundary, so `DataView::Internal` / `Boundary` are two + contiguous lane ranges and Standard / Extended OCC split SubGrid kernels like Dense ones. +- **Ownership.** A SubGrid field can only be loaded by kernels of its own SubGrid; anything + else throws `std::invalid_argument` when the kernel is built. +- **Immutable.** The lane table is built once on the host (deterministic order) and never + changes; build a new SubGrid for a new selection. No SubGrid of a SubGrid, and no + `compute_universal` over a SubGrid (static_assert). +- **Factories.** `Kernel::compute` / `Kernel::host_compute`, or `S.make_kernel(fn[, name][, + shared_mem])` / `S.make_host_kernel(fn[, name])`. Tested on CUDA, SYCL and HIP (on NVIDIA). +- **Reductions.** `Kernel::reduce` / `host_reduce` / `reduce_universal` accept a + SubGrid, as do `S.make_reduce_kernel(fn, dst[, op][, shared_mem][, options])`, + `S.make_host_reduce_kernel(fn, dst[, op])` and `S.make_universal_reduce_kernel`. + The per-cell lambda is `T(const S::Span&, const S::Idx&)` and may read parent and SubGrid + fields. One thread per lane in fixed 256-thread blocks feeds the usual pipeline (block + partials, multi-GPU combine, then the cross-rank stage, which no SubGrid test runs under + MPI yet), so `ReductionResult`, the `reduce::` ops and `ReduceFinalize::BlockAtomic` work + unchanged; `ReduceOptions::stage1_threads[_y]` throw. + An empty SubGrid yields the op's identity. A reduction that stencil-reads a parent field + is split by OCC into Internal / Boundary partials plus a merge, as on Dense. +- **Block parent.** `SubGrid>` has the same API. Its lane table is flat: one + `Block::Idx` (brick, intra-brick offset) per selected active voxel, parent-Internal bricks + first, in brick then z / y / x order. That suits a few scattered voxels, which mostly sit + in different bricks; a selection that fills whole bricks gains little over a Block kernel + with a filter. Device kernels read parent fields anywhere their halo allows. Host kernels + get spans built from the Block's host tables, which cover owned bricks only, so a host + `neighbour` read must stay in the GPU's slab (slabs split along z). Any other parent type + is a compile error. + +```cpp +carbon::ReductionResult wall_flux(sys); +auto k = walls.make_reduce_kernel([&](carbon::KernelLoader& L) { + const auto uG = L.read(u); // parent field + const auto qS = L.read(q); // SubGrid field + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) -> double { + return uG.read(s, i, 0) * qS.read(s, i, 0); + }; +}, wall_flux); // reduce::Sum by default +``` + +`examples/sub_grid_cube.cu` puts the cube boundary in a SubGrid, mixes SubGrid and Dense +kernels in one masked Skeleton, and times the boundary fill against the filtered Dense +kernel. On 2×RTX A4000 (µs per launch, Dense + filter / SubGrid): 64³ is launch-bound at +4.8 / 4.9, 128³ gives 9.6 / 3.6, 256³ gives 58.8 / 28.7 (SYCL 85.5 / 32.0), and 384³ +gives 189 / 67. A SubGrid pays one lane-table read per thread and its parent accesses are +gathers, so it wins when the selection is a small fraction of the grid. +`examples/sub_grid_block_markers.cu` does the same over a Block ball: about one active voxel +in 1000 is a marker that gets an x/y-neighbour average, compared against a Block kernel that +filters on a label. On 2×RTX A4000 (µs per launch, Block + filter / SubGrid): 128³ gives +10.5 / 6.1, 256³ gives 79.1 / 5.8 (one GPU 155.9 / 6.0, SYCL 80.3 / 9.4, HIP on NVIDIA +79.0 / 4.9), and 256³ with one marker in 100 gives 126.2 / 23.5. +`tests/test_sub_grid*.cu` (`test_sub_grid_reduce.cu` for reductions, `test_sub_grid_block.cu` +for the Block parent) and `tests/sub_grid_compile_fail.cu` pin the semantics. +`test_sub_grid_jacobi_axpy.cu` is the end-to-end case: 100 int64 Jacobi + AXPY iterations +on Dense and Block. B (voxels missing a neighbour) and C (the rest) write disjoint regions +and run in parallel — C as a masked parent kernel or as a second SubGrid — under every OCC +mode. With OCC on, each Jacobi step has exactly two internal and two boundary launches; +values match a host reference exactly. diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 1f930cd0..c3c8628d 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -28,16 +28,8 @@ function(_carbon_example_add target source_cu) HIP_STANDARD 20 HIP_STANDARD_REQUIRED ON) elseif(CARBON_BACKEND STREQUAL "Sycl") - set(_src "${CMAKE_CURRENT_BINARY_DIR}/${target}.cpp") - configure_file("${CMAKE_CURRENT_SOURCE_DIR}/${source_cu}" "${_src}" COPYONLY) - add_executable(${target} "${_src}") - target_compile_features(${target} PRIVATE cxx_std_20) + carbon_add_sycl_mirrored_executable(${target} ${source_cu}) set_target_properties(${target} PROPERTIES BUILD_RPATH "${CARBON_RUNTIME_SEARCH_DIRS};${CMAKE_BINARY_DIR}") - add_sycl_to_target(TARGET ${target} SOURCES "${_src}") - if(CARBON_SYCL_TARGETS MATCHES "cuda") - target_compile_options(${target} PRIVATE --cuda-path=${CARBON_SYCL_CUDA_PATH}) - target_link_directories(${target} PRIVATE ${CARBON_SYCL_CUDA_PATH}/lib64) - endif() endif() endfunction() @@ -105,6 +97,26 @@ _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) +# Region masks: an interior stencil and a boundary-condition kernel that write disjoint +# cells of the same field run side by side (Skeleton sub-field dependencies). +_carbon_example_add(carbon_example_region_mask_bc region_mask_bc.cu) +target_link_libraries(carbon_example_region_mask_bc PRIVATE carbon::carbon) + +# Region masks, minimal walk-through: on a cube, one kernel writes only the boundary voxels and +# two only the interior; the Skeleton orders them by region, not by field. +_carbon_example_add(carbon_example_region_mask_cube region_mask_cube.cu) +target_link_libraries(carbon_example_region_mask_cube PRIVATE carbon::carbon) + +# SubGrid: the cube boundary as its own grid (one thread per boundary voxel, compact fields), +# mixed with Dense kernels in one masked Skeleton, and timed against the filtered Dense kernel. +_carbon_example_add(carbon_example_sub_grid_cube sub_grid_cube.cu) +target_link_libraries(carbon_example_sub_grid_cube PRIVATE carbon::carbon) + +# SubGrid over a Block: a few scattered marker voxels of a block-sparse ball updated by one +# thread each, checked and timed against a Block kernel that filters every active voxel. +_carbon_example_add(carbon_example_sub_grid_block_markers sub_grid_block_markers.cu) +target_link_libraries(carbon_example_sub_grid_block_markers 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 @@ -143,11 +155,15 @@ _carbon_example_link_viewer(carbon_example_render_wind_tunnel) target_include_directories(carbon_example_render_wind_tunnel PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../benchmarks/lbm_lid_driven_cavity/src) -_carbon_example_add(carbon_example_render_wind_tunnel_live render_wind_tunnel_live.cu) -target_link_libraries(carbon_example_render_wind_tunnel_live PRIVATE carbon::carbon) -_carbon_example_link_viewer(carbon_example_render_wind_tunnel_live) -target_include_directories(carbon_example_render_wind_tunnel_live - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../benchmarks/lbm_lid_driven_cavity/src) +# The live variant's ImGui panels are not behind CARBON_HAVE_VIEWER, so it only builds +# with the viewer. +if(CARBON_BUILD_VIEWER) + _carbon_example_add(carbon_example_render_wind_tunnel_live render_wind_tunnel_live.cu) + target_link_libraries(carbon_example_render_wind_tunnel_live PRIVATE carbon::carbon) + _carbon_example_link_viewer(carbon_example_render_wind_tunnel_live) + target_include_directories(carbon_example_render_wind_tunnel_live + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../benchmarks/lbm_lid_driven_cavity/src) +endif() # Distributed 6-neighbour stencil + axpy with a CLI-selected slab | pencil | brick decomposition. # Self-verifying (global sums vs. a serial host reference). With the SYCL backend, an omp-only diff --git a/examples/region_mask_bc.cu b/examples/region_mask_bc.cu new file mode 100644 index 00000000..fa8ccc57 --- /dev/null +++ b/examples/region_mask_bc.cu @@ -0,0 +1,321 @@ +// Region masks: run a boundary-condition kernel beside the interior stencil. +// +// The heat problem of jacobi_unified (hot z- face, cold z+ face, zero x/y faces) split the +// way production solvers are written: one kernel updates the interior with a 6-point stencil, +// another applies the Dirichlet values on the boundary voxels. Both write the same field, so +// without more information the Skeleton must serialise them. A per-cell label field plus a +// RegionMask per kernel tells it the two kernels write disjoint cells: +// +// label 0 : interior -> kInterior = RegionMask::from_label(0) +// labels 1..3 : hot / cold / side -> kBoundary = ~kInterior (the labels are a full +// partition, so the complement is "every other cell") +// +// Each kernel declares its footprint with L.region(...) and filters itself on the label; the +// label field is read before the filter, i.e. everywhere, so that read is declared all-ones +// (harmless: nothing writes labels inside the pipeline). Stencil reads stay whole-field, so +// the next half step's stencil still waits on both kernels (through the auto-halo). +// +// The example runs the same pipeline twice — masks honoured and Options::ignore_region_masks +// — prints both schedules, checks the fields are bit-identical, and with --dot +// writes _schedule.dot / _kernels.dot / _matrix.dot (the launch +// matrix: one column per stream) plus _matrix_ignored.dot for the whole-field +// schedule (render with `dot -Tsvg`). +// +// `--overlap standard` compiles both schedules with OverlapMode::Standard: each interior +// stencil is split into an Internal half, which runs while its halo is in flight, and a +// Boundary half after it. The masks still let the boundary-condition kernels run on their own +// streams. +// +// carbon_example_region_mask_bc [--n 64] [--iters 200] [--overlap none|standard] +// [--dot region_mask_bc] + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using Span = carbon::Dense::Span; +using Idx = carbon::Dense::Idx; +using Field = carbon::Dense::Field; +using Labels = carbon::Dense::Field; +using carbon::RegionMask; + +constexpr int32_t kInteriorLabel = 0; +constexpr int32_t kHotLabel = 1; +constexpr int32_t kColdLabel = 2; +constexpr int32_t kSideLabel = 3; + +const RegionMask kInterior = RegionMask::from_label(kInteriorLabel); +const RegionMask kBoundary = ~kInterior; + +struct Args { + int64_t n = 64; + int iters = 200; + carbon::OverlapMode overlap = carbon::OverlapMode::None; + std::string dot_prefix{}; +}; + +[[nodiscard]] auto +parse_overlap(std::string_view s) -> carbon::OverlapMode { + if (s == "none") { + return carbon::OverlapMode::None; + } + if (s == "standard") { + return carbon::OverlapMode::Standard; + } + throw std::invalid_argument("--overlap must be none or standard, got " + std::string{s}); +} + +[[nodiscard]] auto +parse_args(int argc, + char** argv) -> Args { + Args a{}; + for (int i = 1; i + 1 < argc; i += 2) { + const std::string_view flag = argv[i]; + if (flag == "--n") { + a.n = std::atoll(argv[i + 1]); + } else if (flag == "--iters") { + a.iters = std::atoi(argv[i + 1]); + } else if (flag == "--overlap") { + a.overlap = parse_overlap(argv[i + 1]); + } else if (flag == "--dot") { + a.dot_prefix = argv[i + 1]; + } else { + throw std::invalid_argument("unknown flag " + std::string{flag}); + } + } + if (a.n < 4 || a.iters < 1) { + throw std::invalid_argument("need --n >= 4 and --iters >= 1"); + } + return a; +} + +[[nodiscard]] auto +build_labels(carbon::Dense& dense, + Labels& labels, + carbon::int64_3d global) -> carbon::Kernel { + return carbon::Kernel::compute( + dense, + [&labels, global](carbon::KernelLoader& loader) { + const auto out = loader.write(labels); + return [out, global] CARBON_HD(Span s, Idx idx) { + const carbon::int64_3d g = s.global_location(idx); + int32_t label = kInteriorLabel; + if (g.z == 0) { + label = kHotLabel; + } else if (g.z == global.z - 1) { + label = kColdLabel; + } else if (g.x == 0 || g.y == 0 || g.x == global.x - 1 || g.y == global.y - 1) { + label = kSideLabel; + } + out.write(s, idx, 0, label); + }; + }, + "init_labels"); +} + +[[nodiscard]] auto +build_zero(carbon::Dense& dense, + Field& f, + std::string name) -> carbon::Kernel { + return carbon::Kernel::compute( + dense, + [&f](carbon::KernelLoader& loader) { + const auto out = loader.write(f); + return [out] CARBON_HD(Span s, Idx idx) { + out.write(s, idx, 0, 0.0F); + }; + }, + std::move(name)); +} + +// Interior cells: 6-point average of @p fin. +[[nodiscard]] auto +build_interior(carbon::Dense& dense, + Labels& labels, + Field& fin, + Field& fout, + std::string name) -> carbon::Kernel { + return carbon::Kernel::compute( + dense, + [&labels, &fin, &fout](carbon::KernelLoader& loader) { + loader.region(kInterior); + const auto lab = loader.read(labels, RegionMask::all()); + const auto in = loader.read_stencil(fin); + const auto out = loader.write(fout); + return [lab, in, out] CARBON_HD(Span s, Idx idx) { + if (lab.read(s, idx, 0) != kInteriorLabel) { + return; + } + const float sum = in.neighbour(s, idx, carbon::int8_3d{1, 0, 0}, 0).value + + in.neighbour(s, idx, carbon::int8_3d{-1, 0, 0}, 0).value + + in.neighbour(s, idx, carbon::int8_3d{0, 1, 0}, 0).value + + in.neighbour(s, idx, carbon::int8_3d{0, -1, 0}, 0).value + + in.neighbour(s, idx, carbon::int8_3d{0, 0, 1}, 0).value + + in.neighbour(s, idx, carbon::int8_3d{0, 0, -1}, 0).value; + out.write(s, idx, 0, sum * (1.0F / 6.0F)); + }; + }, + std::move(name)); +} + +// Boundary cells: Dirichlet values by label. +[[nodiscard]] auto +build_boundary(carbon::Dense& dense, + Labels& labels, + Field& fout, + std::string name) -> carbon::Kernel { + return carbon::Kernel::compute( + dense, + [&labels, &fout](carbon::KernelLoader& loader) { + loader.region(kBoundary); + const auto lab = loader.read(labels, RegionMask::all()); + const auto out = loader.write(fout); + return [lab, out] CARBON_HD(Span s, Idx idx) { + const int32_t label = lab.read(s, idx, 0); + if (label == kInteriorLabel) { + return; + } + out.write(s, idx, 0, label == kHotLabel ? 1.0F : (label == kColdLabel ? -1.0F : 0.0F)); + }; + }, + std::move(name)); +} + +auto +add_pipeline(carbon::Skeleton& sk, + carbon::Dense& dense, + Labels& labels, + Field& u, + Field& v) -> void { + sk.add(build_interior(dense, labels, u, v, "interior_uv")); + sk.add(build_boundary(dense, labels, v, "boundary_v")); + sk.add(build_interior(dense, labels, v, u, "interior_vu")); + sk.add(build_boundary(dense, labels, u, "boundary_u")); +} + +[[nodiscard]] auto +time_runs(carbon::Skeleton& sk, + int iters) -> double { + const auto t0 = std::chrono::steady_clock::now(); + for (int it = 0; it < iters; ++it) { + sk.run(); + } + sk.wait(); + return std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); +} + +} // namespace + +int +main(int argc, + char** argv) { + try { + carbon::init(); + const Args args = parse_args(argc, argv); + + carbon::System sys(carbon::get_all_devices()); + const size_t n_gpus = sys.gpu_group().size(); + const carbon::int64_3d global{args.n, args.n, args.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); + carbon::Dense dense(sys, global, stencil); + + auto labels = dense.newField(carbon::MemorySide::Device, "labels"); + auto u = dense.newField(carbon::MemorySide::HostDevice, "u"); + auto v = dense.newField(carbon::MemorySide::HostDevice, "v"); + auto u_ref = dense.newField(carbon::MemorySide::HostDevice, "u_ref"); + auto v_ref = dense.newField(carbon::MemorySide::HostDevice, "v_ref"); + + carbon::Skeleton init(sys); + init.add(build_labels(dense, labels, global)); + init.add(build_zero(dense, u, "zero_u")); + init.add(build_zero(dense, v, "zero_v")); + init.add(build_zero(dense, u_ref, "zero_u_ref")); + init.add(build_zero(dense, v_ref, "zero_v_ref")); + init.run(); + init.wait(); + + const carbon::Skeleton::Options honour_masks(args.overlap); + carbon::Skeleton masked(sys, honour_masks); + add_pipeline(masked, dense, labels, u, v); + carbon::Skeleton::Options whole_field(args.overlap); + whole_field.ignore_region_masks = true; + carbon::Skeleton reference(sys, whole_field); + add_pipeline(reference, dense, labels, u_ref, v_ref); + masked.compile(); + reference.compile(); + + std::cout << "region_mask_bc: n=" << args.n << " iters=" << args.iters << " gpus=" << n_gpus + << " overlap=" + << (args.overlap == carbon::OverlapMode::Standard ? "standard" : "none") + << "\n interior mask = " << carbon::to_string(kInterior) + << ", boundary mask = " << carbon::to_string(kBoundary) << "\n\n"; + std::cout << "masks honoured: " << masked.num_streams() << " stream(s)\n" + << masked.export_launch_order() << '\n'; + std::cout << "masks ignored: " << reference.num_streams() << " stream(s)\n" + << reference.export_launch_order() << '\n'; + + if (!args.dot_prefix.empty()) { + const bool ok = + masked.export_dot_file(args.dot_prefix + "_schedule.dot", "region_mask_bc") && + masked.export_kernel_list_dot_file(args.dot_prefix + "_kernels.dot", "region_mask_bc") && + masked.export_launch_matrix_dot_file(args.dot_prefix + "_matrix.dot", "region_mask_bc") && + reference.export_launch_matrix_dot_file(args.dot_prefix + "_matrix_ignored.dot", + "region_mask_bc_ignored"); + std::cout << (ok ? "wrote " : "FAILED to write ") << args.dot_prefix + << "_{schedule,kernels,matrix,matrix_ignored}.dot\n\n"; + } + + const double ms_masked = time_runs(masked, args.iters); + const double ms_reference = time_runs(reference, args.iters); + std::cout << "masks honoured: " << ms_masked * 1000.0 / args.iters << " us/iter\n" + << "masks ignored: " << ms_reference * 1000.0 / args.iters << " us/iter\n"; + + carbon::Stream s = sys.stream(); + carbon::Transfer(sys, u.gpu_buffers(), u.cpu_buffers())(s); + carbon::Transfer(sys, u_ref.gpu_buffers(), u_ref.cpu_buffers())(s); + s.wait(); + size_t mismatches = 0; + for (size_t g = 0; g < n_gpus; ++g) { + const auto& span = dense.spans()[g]; + const int64_t begin = span.halo_z() * span.xy_slab_elements(); + const int64_t end = begin + span.logic_extent().z * span.xy_slab_elements(); + const float* a = u.cpu_buffers()[g].data(); + const float* b = u_ref.cpu_buffers()[g].data(); + for (int64_t i = begin; i < end; ++i) { + mismatches += a[i] != b[i] ? 1U : 0U; + } + } + if (mismatches != 0U) { + std::cerr << "region_mask_bc: " << mismatches + << " cell(s) differ between the masked and whole-field schedules\n"; + return EXIT_FAILURE; + } + std::cout << "masked and whole-field results are bit-identical\n"; + } catch (const std::exception& e) { + std::cerr << "region_mask_bc: " << e.what() << '\n'; + return EXIT_FAILURE; + } + return EXIT_SUCCESS; +} diff --git a/examples/region_mask_cube.cu b/examples/region_mask_cube.cu new file mode 100644 index 00000000..48abd4f2 --- /dev/null +++ b/examples/region_mask_cube.cu @@ -0,0 +1,354 @@ +// Region masks, the smallest complete example: boundary voxels vs. the rest of a cube. +// +// WHAT IT SHOWS +// +// A Skeleton orders two kernels whenever they touch the same field and at least one of them +// writes it. That is safe, but too strict when the kernels touch *different cells* of the +// field. A RegionMask lets each kernel say which part of the domain it touches, and the +// Skeleton then only orders kernels whose parts overlap. +// +// THE DOMAIN +// +// An n x n x n cube, split into two regions that together cover every voxel exactly once: +// +// region bit 0, "interior" : voxels with no coordinate on a face of the cube +// region bit 1, "boundary" : voxels with at least one coordinate equal to 0 or n - 1 +// +// The bit numbers are ours to choose; Carbon never learns the geometry. It only assumes that +// different bits name disjoint sets of voxels. +// +// THE PIPELINE (one field u, four kernels) +// +// 1. fill_boundary writes u on the boundary u = 1 region: boundary +// 2. fill_interior writes u on the interior u = 2 region: interior +// 3. scale_interior updates u on the interior u = 10 * u region: interior +// 4. count_wrong reads u everywhere sums wrong voxels region: whole cube +// +// Expected dependencies: +// +// fill_boundary ──────────────────────┐ +// ├──> count_wrong +// fill_interior ──> scale_interior ───┘ +// +// - 1 and 2 both write u, but on disjoint regions: no edge, they may run concurrently. +// - 3 updates the interior that 2 wrote: same region, so 3 waits for 2 (and only for 2). +// - 4 reads the whole cube, so it overlaps both regions and waits for 1 and 3. +// +// Without masks every kernel would wait for the previous one: 1 -> 2 -> 3 -> 4. +// +// HOW A KERNEL USES A MASK (two rules, both needed) +// +// a) Declare: `loader.region(M)` in the loading lambda tells the Skeleton "every access of +// this kernel stays inside region M". It only feeds the dependency analysis. +// b) Keep the promise: the launch still covers the whole grid, so the per-voxel body must +// skip voxels outside M itself (here with `on_boundary`). A kernel that writes outside its +// declared region is a silent data race: Carbon trusts the declaration. +// +// The example compiles the pipeline twice, once with masks honoured and once with +// Skeleton::Options::ignore_region_masks (the whole-field schedule), prints both dependency +// tables, runs both, and checks that every voxel holds the expected value. With +// `--dot ` it also writes, for each schedule (`masked` / `ignored`), the dependency +// graph _.dot and the launch matrix __matrix.dot (one +// column per stream, one row per launch / event record / event wait); render them with +// `dot -Tsvg`. +// +// `--overlap standard` compiles both schedules with OverlapMode::Standard (OCC). OCC splits +// stencil kernels around their halo; this pipeline has no stencil, so the schedules stay the +// same and the flag only shows that masks and OCC compose. +// +// carbon_example_region_mask_cube [--n 32] [--overlap none|standard] [--dot region_mask_cube] +// +// See docs/skeleton/README.md, "Region masks", for the full contract, and region_mask_bc.cu +// for the same idea inside a heat solver. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using Span = carbon::Dense::Span; +using Idx = carbon::Dense::Idx; +using Field = carbon::Dense::Field; +using carbon::RegionMask; + +// ---- The two regions ------------------------------------------------------------------------- + +constexpr unsigned kInteriorBit = 0; +constexpr unsigned kBoundaryBit = 1; + +const RegionMask kInterior = RegionMask::bit(kInteriorBit); +const RegionMask kBoundary = RegionMask::bit(kBoundaryBit); + +// The geometric test behind kBoundary. Every kernel that declares a region filters itself with +// it, so declaration and behaviour cannot drift apart. +[[nodiscard]] CARBON_HD constexpr auto +on_boundary(carbon::int64_3d g, + int64_t n) noexcept -> bool { + return g.x == 0 || g.y == 0 || g.z == 0 || g.x == n - 1 || g.y == n - 1 || g.z == n - 1; +} + +// ---- The values the pipeline writes ----------------------------------------------------------- + +constexpr float kBoundaryValue = 1.0F; +constexpr float kInteriorValue = 2.0F; +constexpr float kInteriorScale = 10.0F; + +// ---- The four kernels ------------------------------------------------------------------------- + +// 1. u = 1 on the boundary. +[[nodiscard]] auto +build_fill_boundary(carbon::Dense& dense, + Field& u, + int64_t n) -> carbon::Kernel { + return carbon::Kernel::compute( + dense, + [&u, n](carbon::KernelLoader& loader) { + loader.region(kBoundary); // (a) declare: this kernel only touches boundary voxels + const auto out = loader.write(u); + return [out, n] CARBON_HD(Span s, Idx idx) { + if (!on_boundary(s.global_location(idx), n)) { + return; // (b) keep the promise: leave interior voxels alone + } + out.write(s, idx, 0, kBoundaryValue); + }; + }, + "fill_boundary"); +} + +// 2. u = 2 on the interior. +[[nodiscard]] auto +build_fill_interior(carbon::Dense& dense, + Field& u, + int64_t n) -> carbon::Kernel { + return carbon::Kernel::compute( + dense, + [&u, n](carbon::KernelLoader& loader) { + loader.region(kInterior); + const auto out = loader.write(u); + return [out, n] CARBON_HD(Span s, Idx idx) { + if (on_boundary(s.global_location(idx), n)) { + return; + } + out.write(s, idx, 0, kInteriorValue); + }; + }, + "fill_interior"); +} + +// 3. u = 10 * u on the interior. Reads and writes the same voxel only (a cell-local update), +// which is what lets a single region describe the whole access. +[[nodiscard]] auto +build_scale_interior(carbon::Dense& dense, + Field& u, + int64_t n) -> carbon::Kernel { + return carbon::Kernel::compute( + dense, + [&u, n](carbon::KernelLoader& loader) { + loader.region(kInterior); + const auto io = loader.read_write(u); + return [io, n] CARBON_HD(Span s, Idx idx) { + if (on_boundary(s.global_location(idx), n)) { + return; + } + io.write(s, idx, 0, io.read(s, idx, 0) * kInteriorScale); + }; + }, + "scale_interior"); +} + +// 4. Count the voxels that do not hold their expected value. No region is declared, so the read +// covers the whole cube and this kernel waits for every writer of u. +[[nodiscard]] auto +build_count_wrong(carbon::Dense& dense, + Field& u, + int64_t n, + carbon::ReductionResult& wrong) -> carbon::Kernel { + return carbon::Kernel::reduce( + dense, + [&u, n](carbon::KernelLoader& loader) { + const auto in = loader.read(u); + return [in, n] CARBON_HD(Span s, Idx idx) -> int64_t { + const float expected = on_boundary(s.global_location(idx), n) + ? kBoundaryValue + : kInteriorValue * kInteriorScale; + return in.read(s, idx, 0) == expected ? 0 : 1; + }; + }, + wrong, carbon::reduce::Sum{}, "count_wrong"); +} + +// ---- Helpers ---------------------------------------------------------------------------------- + +struct Args { + int64_t n = 32; + carbon::OverlapMode overlap = carbon::OverlapMode::None; + std::string dot_prefix{}; +}; + +[[nodiscard]] auto +parse_overlap(std::string_view s) -> carbon::OverlapMode { + if (s == "none") { + return carbon::OverlapMode::None; + } + if (s == "standard") { + return carbon::OverlapMode::Standard; + } + throw std::invalid_argument("--overlap must be none or standard, got " + std::string{s}); +} + +[[nodiscard]] auto +parse_args(int argc, + char** argv) -> Args { + Args a{}; + for (int i = 1; i + 1 < argc; i += 2) { + const std::string_view flag = argv[i]; + if (flag == "--n") { + a.n = std::atoll(argv[i + 1]); + } else if (flag == "--overlap") { + a.overlap = parse_overlap(argv[i + 1]); + } else if (flag == "--dot") { + a.dot_prefix = argv[i + 1]; + } else { + throw std::invalid_argument("unknown flag " + std::string{flag}); + } + } + if (a.n < 3) { + throw std::invalid_argument("need --n >= 3 (so the cube has an interior)"); + } + return a; +} + +auto +add_pipeline(carbon::Skeleton& sk, + carbon::Dense& dense, + Field& u, + int64_t n, + carbon::ReductionResult& wrong) -> void { + sk.add(build_fill_boundary(dense, u, n)); + sk.add(build_fill_interior(dense, u, n)); + sk.add(build_scale_interior(dense, u, n)); + sk.add(build_count_wrong(dense, u, n, wrong)); +} + +// One line per kernel: the stream it was given and the kernels it waits for. `min_edges()` is +// the dependency graph after removing edges implied by longer paths. +auto +print_schedule(carbon::Skeleton& sk, + std::string_view title) -> void { + sk.compile(); + const auto& kernels = sk.effective_kernels(); + const auto& successors = sk.min_edges(); + const auto& streams = sk.kernel_streams(); + + std::vector waits_for(kernels.size()); + for (size_t i = 0; i < kernels.size(); ++i) { + for (const size_t j : successors[i]) { + waits_for[j] += (waits_for[j].empty() ? "" : ", ") + std::string{kernels[i].name()}; + } + } + + std::cout << title << " (" << sk.num_streams() << " stream(s))\n"; + for (size_t i = 0; i < kernels.size(); ++i) { + std::cout << " " << std::left << std::setw(16) << kernels[i].name() << " stream " << streams[i] + << " waits for: " << (waits_for[i].empty() ? "-" : waits_for[i]) << '\n'; + } + std::cout << '\n'; +} + +// Runs the pipeline once and returns how many voxels ended up with the wrong value. +[[nodiscard]] auto +run_and_count_wrong(carbon::System& sys, + carbon::Skeleton& sk, + carbon::ReductionResult& wrong) -> int64_t { + sk.run(); + sk.wait(); + carbon::Stream stream = sys.stream(); + wrong.sync(stream); + stream.wait(); + return wrong.host_value(); +} + +} // namespace + +int +main(int argc, + char** argv) { + try { + carbon::init(); + const Args args = parse_args(argc, argv); + const int64_t n = args.n; + + carbon::System sys(carbon::get_all_devices()); + carbon::Dense dense(sys, carbon::int64_3d{n, n, n}, carbon::Stencil{}); + + const int64_t interior_voxels = (n - 2) * (n - 2) * (n - 2); + std::cout << "region_mask_cube: " << n << "^3 cube on " << sys.gpu_group().size() + << " GPU(s): " << n * n * n - interior_voxels << " boundary + " << interior_voxels + << " interior voxels\n" + << " interior region = " << carbon::to_string(kInterior) + << ", boundary region = " << carbon::to_string(kBoundary) << "\n\n"; + + // Same pipeline twice, each on its own field so the two runs cannot interfere. + Field u_masked = dense.newField(carbon::MemorySide::Device, "u_masked"); + Field u_whole = dense.newField(carbon::MemorySide::Device, "u_whole"); + carbon::ReductionResult wrong_masked(sys); + carbon::ReductionResult wrong_whole(sys); + + const carbon::Skeleton::Options honour_masks(args.overlap); + carbon::Skeleton masked(sys, honour_masks); + add_pipeline(masked, dense, u_masked, n, wrong_masked); + + carbon::Skeleton::Options ignore_masks(args.overlap); + ignore_masks.ignore_region_masks = true; + carbon::Skeleton whole(sys, ignore_masks); + add_pipeline(whole, dense, u_whole, n, wrong_whole); + + print_schedule(masked, "masks honoured"); + print_schedule(whole, "masks ignored, every access covers the whole cube"); + + if (!args.dot_prefix.empty()) { + const bool ok = + masked.export_dot_file(args.dot_prefix + "_masked.dot", "region_mask_cube_masked") && + masked.export_launch_matrix_dot_file(args.dot_prefix + "_masked_matrix.dot", + "region_mask_cube_masked") && + whole.export_dot_file(args.dot_prefix + "_ignored.dot", "region_mask_cube_ignored") && + whole.export_launch_matrix_dot_file(args.dot_prefix + "_ignored_matrix.dot", + "region_mask_cube_ignored"); + std::cout << (ok ? "wrote " : "FAILED to write ") << args.dot_prefix + << "_{masked,ignored}{,_matrix}.dot\n\n"; + } + + const int64_t bad_masked = run_and_count_wrong(sys, masked, wrong_masked); + const int64_t bad_whole = run_and_count_wrong(sys, whole, wrong_whole); + std::cout << "wrong voxels: masks honoured = " << bad_masked + << ", masks ignored = " << bad_whole << '\n'; + if (bad_masked != 0 || bad_whole != 0) { + std::cerr << "region_mask_cube: FAILED\n"; + return EXIT_FAILURE; + } + std::cout << "region_mask_cube: OK (boundary = " << kBoundaryValue + << ", interior = " << kInteriorValue * kInteriorScale << " everywhere)\n"; + } catch (const std::exception& e) { + std::cerr << "region_mask_cube: " << e.what() << '\n'; + return EXIT_FAILURE; + } + return EXIT_SUCCESS; +} diff --git a/examples/sub_grid_block_markers.cu b/examples/sub_grid_block_markers.cu new file mode 100644 index 00000000..01bf17ca --- /dev/null +++ b/examples/sub_grid_block_markers.cu @@ -0,0 +1,285 @@ +// SubGrid over a block-sparse grid: a few scattered voxels that need special treatment. +// +// WHAT IT SHOWS +// +// A Block (block-sparse) grid G holds a ball. A small set of "marker" voxels, about one in +// --every active voxels and scattered so that most of them sit in different bricks, needs +// an extra update: here, the average of its x/y neighbours in a parent field. +// +// Without a SubGrid the update is a Block kernel over every active voxel that reads a label +// and returns unless the voxel is a marker: one thread per active voxel, almost all idle. +// S = SubGrid(G, F, B) stores, per GPU, the list of marker voxels and launches one thread +// per marker. Its kernel reads and writes parent fields at the marker (and its neighbours) +// with the SubGrid's Span and Idx, which convert to the Block's. +// +// The example builds S from the label field, checks that both kernels write the same +// values, and times them for --iters launches each. +// +// The x/y neighbours of a voxel stay in its GPU's slab (slabs split along z), so these +// standalone launches need no halo. Under a Skeleton, a stencil read in any direction gets +// its HaloBlock automatically, for SubGrid kernels as for Block kernels. +// +// carbon_example_sub_grid_block_markers [--n 128] [--every 1000] [--iters 200] +// +// See docs/skeleton/README.md, "SubGrid", and sub_grid_cube.cu for the Dense version. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using B = carbon::Block<>; +using S = carbon::SubGrid; +using carbon::RegionMask; + +constexpr std::uint8_t kMarker = 1; + +[[nodiscard]] auto +in_ball(carbon::int64_3d g, + int64_t n) -> bool { + const double c = static_cast(n - 1) * 0.5; + const double r = static_cast(n) * 0.45; + const double dx = static_cast(g.x) - c; + const double dy = static_cast(g.y) - c; + const double dz = static_cast(g.z) - c; + return dx * dx + dy * dy + dz * dz <= r * r; +} + +/** Deterministic scatter: about one voxel in @p every . */ +[[nodiscard]] CARBON_HD constexpr auto +is_marker(carbon::int64_3d g, + int64_t every) -> bool { + const auto h = (static_cast(g.x) * 73856093ULL) ^ + (static_cast(g.y) * 19349663ULL) ^ + (static_cast(g.z) * 83492791ULL); + return h % static_cast(every) == 0ULL; +} + +/** Average of the active x/y neighbours of @p i in @p u (0 when there are none). */ +template +[[nodiscard]] CARBON_HD auto +xy_average(const P& u, + const SpanT& s, + const IdxT& i) -> float { + const auto xp = u.neighbour(s, i, carbon::int8_3d{1, 0, 0}, 0); + const auto xm = u.neighbour(s, i, carbon::int8_3d{-1, 0, 0}, 0); + const auto yp = u.neighbour(s, i, carbon::int8_3d{0, 1, 0}, 0); + const auto ym = u.neighbour(s, i, carbon::int8_3d{0, -1, 0}, 0); + const int n = (xp.valid ? 1 : 0) + (xm.valid ? 1 : 0) + (yp.valid ? 1 : 0) + (ym.valid ? 1 : 0); + const float sum = (xp.valid ? xp.value : 0.0F) + (xm.valid ? xm.value : 0.0F) + + (yp.valid ? yp.value : 0.0F) + (ym.valid ? ym.value : 0.0F); + return n > 0 ? sum / static_cast(n) : 0.0F; +} + +// The update without a SubGrid: every active voxel, filtered by its label. +[[nodiscard]] auto +build_filtered(const B& block, + const B::Field& labels, + const B::Field& u, + B::Field& out) -> carbon::Kernel { + return carbon::Kernel::compute( + block, + [labels, u, out](carbon::KernelLoader& loader) { + const auto lab = loader.read(labels); + const auto in = loader.read_stencil(u); + const auto dst = loader.write(out); + return [lab, in, dst] CARBON_HD(const B::Span& s, const B::Idx& i) { + if (lab.read(s, i, 0) != kMarker) { + return; + } + dst.write(s, i, 0, xy_average(in, s, i)); + }; + }, + "markers_filtered"); +} + +// The same update as a SubGrid kernel: one thread per marker, no filter. +[[nodiscard]] auto +build_sub_grid(const S& markers, + const B::Field& u, + B::Field& out) -> carbon::Kernel { + return carbon::Kernel::compute( + markers, + [u, out](carbon::KernelLoader& loader) { + const auto in = loader.read_stencil(u); + const auto dst = loader.write(out); + return [in, dst] CARBON_HD(const S::Span& s, const S::Idx& i) { + dst.write(s, i, 0, xy_average(in, s, i)); + }; + }, + "markers_sub_grid"); +} + +struct Args { + int64_t n = 128; + int64_t every = 1000; + int iters = 200; +}; + +[[nodiscard]] auto +parse_args(int argc, + char** argv) -> Args { + Args a{}; + for (int i = 1; i + 1 < argc; i += 2) { + const std::string_view flag = argv[i]; + if (flag == "--n") { + a.n = std::atoll(argv[i + 1]); + } else if (flag == "--every") { + a.every = std::atoll(argv[i + 1]); + } else if (flag == "--iters") { + a.iters = std::atoi(argv[i + 1]); + } else { + throw std::invalid_argument("unknown flag " + std::string{flag}); + } + } + if (a.n < 8 || a.every < 1 || a.iters < 1) { + throw std::invalid_argument("need --n >= 8, --every >= 1 and --iters >= 1"); + } + return a; +} + +// Mean microseconds per launch of @p k over @p iters launches, after one warm-up launch. +[[nodiscard]] auto +time_launches(carbon::Stream& stream, + const carbon::Kernel& k, + int iters) -> double { + k.launch(stream); + stream.wait(); + const auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < iters; ++i) { + k.launch(stream); + } + stream.wait(); + const std::chrono::duration dt = std::chrono::steady_clock::now() - t0; + return dt.count() / iters; +} + +/** Zeroes every storage slot (owned and ghost) of a Block field on the device. */ +auto +zero(carbon::System& sys, + const B& block, + B::Field& f, + carbon::Stream& stream) -> void { + for (size_t g = 0; g < block.gpu_count(); ++g) { + const size_t n = static_cast(block.storage_block_count(g)) * B::VoxelCount; + if (n != 0U) { + sys.async_memset(f.gpu_buffers()[g], 0, n * sizeof(float), stream); + } + } +} + +} // namespace + +int +main(int argc, + char** argv) { + try { + carbon::init(); + const Args args = parse_args(argc, argv); + const int64_t n = args.n; + const int64_t every = args.every; + + carbon::System sys(carbon::get_all_devices()); + const B block( + sys, carbon::int64_3d{n, n, n}, + [n](const carbon::int64_3d& g) { + return in_ball(g, n); + }, + "ball"); + carbon::Stream stream = sys.stream(); + + // Labels on the device, then S = SubGrid(G, F, B) with F = "label bit in B". + auto labels = block.newField(carbon::MemorySide::Device, "labels"); + carbon::Kernel::compute( + block, + [labels, every](carbon::KernelLoader& loader) { + const auto out = loader.write(labels); + return [out, every] CARBON_HD(const B::Span& s, const B::Idx& i) { + out.write(s, i, 0, is_marker(s.global_location(i), every) ? kMarker : std::uint8_t{0}); + }; + }, + "label") + .launch(stream); + stream.wait(); + const S markers = block.new_sub_grid(labels, RegionMask{kMarker}, "markers"); + + std::cout << "sub_grid_block_markers: " << n << "^3 ball on " << sys.gpu_group().size() + << " GPU(s), " << block.block_count() << " bricks, " << block.active_voxel_count() + << " active voxels; SubGrid '" << markers.name() << "' has " << markers.total_count() + << " markers\n"; + for (size_t g = 0; g < markers.gpu_count(); ++g) { + std::cout << " GPU " << g << ": " << markers.count(g) << " lanes (" + << markers.internal_count(g) << " in internal bricks + " + << markers.boundary_count(g) << " in bricks next to another GPU's slab)\n"; + } + + auto u = block.newField(carbon::MemorySide::Device, "u"); + carbon::Kernel::compute( + block, + [u](carbon::KernelLoader& loader) { + const auto out = loader.write(u); + return [out] CARBON_HD(const B::Span& s, const B::Idx& i) { + const carbon::int64_3d g = s.global_location(i); + out.write(s, i, 0, static_cast((g.x * 7 + g.y * 3 + g.z) % 101 + 1)); + }; + }, + "init_u") + .launch(stream); + auto out_filtered = block.newField(carbon::MemorySide::Device, "out_filtered"); + auto out_sub = block.newField(carbon::MemorySide::Device, "out_sub"); + zero(sys, block, out_filtered, stream); + zero(sys, block, out_sub, stream); + + const carbon::Kernel filtered = build_filtered(block, labels, u, out_filtered); + const carbon::Kernel sub = build_sub_grid(markers, u, out_sub); + filtered.launch(stream); + sub.launch(stream); + const auto host_filtered = block.download_to_host(out_filtered, stream); + const auto host_sub = block.download_to_host(out_sub, stream); + stream.wait(); + int64_t mismatches = 0; + int64_t written = 0; + for (size_t g = 0; g < block.gpu_count(); ++g) { + const size_t owned = static_cast(block.block_count(g)) * B::VoxelCount; + for (size_t k = 0; k < owned; ++k) { + mismatches += host_filtered[g].data()[k] == host_sub[g].data()[k] ? 0 : 1; + written += host_sub[g].data()[k] != 0.0F ? 1 : 0; + } + } + std::cout << "voxels written by the SubGrid kernel: " << written + << ", voxels where the two kernels differ: " << mismatches << "\n\n"; + + const double t_filtered = time_launches(stream, filtered, args.iters); + const double t_sub = time_launches(stream, sub, args.iters); + std::cout << std::fixed << std::setprecision(1) << "marker update, " << args.iters + << " launches: Block + label filter " << t_filtered << " us, SubGrid " << t_sub + << " us per launch\n"; + + if (mismatches != 0 || written != markers.total_count()) { + std::cerr << "sub_grid_block_markers: FAILED\n"; + return EXIT_FAILURE; + } + std::cout << "sub_grid_block_markers: OK\n"; + } catch (const std::exception& e) { + std::cerr << "sub_grid_block_markers: " << e.what() << '\n'; + return EXIT_FAILURE; + } + return EXIT_SUCCESS; +} diff --git a/examples/sub_grid_cube.cu b/examples/sub_grid_cube.cu new file mode 100644 index 00000000..4b6039f9 --- /dev/null +++ b/examples/sub_grid_cube.cu @@ -0,0 +1,344 @@ +// SubGrid, the smallest complete example: the boundary voxels of a cube as their own grid. +// +// WHAT IT SHOWS +// +// region_mask_cube.cu writes the boundary of a cube with a Dense kernel that declares the +// boundary region and then has to skip every interior voxel itself: the launch still covers +// the whole cube. A SubGrid S = SubGrid(G, F, B) instead stores, per GPU, the list of parent +// voxels selected by F and launches one thread per selected voxel. Here G is the cube, F is +// "on a face of the cube" and B is the boundary region bit. +// +// WHAT A SUBGRID KERNEL CAN DO +// +// - read / write parent fields at its voxel: `u.read(s, i, 0)` with the SubGrid's Span and +// Idx, which convert to the parent's; +// - read / write its own compact fields (one value per selected voxel, nothing elsewhere); +// - stencil-read a parent field through the parent's halo (not used here). SubGrid fields +// have no halo, so they cannot be stencil-read. +// +// Its parent-field accesses are declared with region B automatically, and the kernel only +// ever visits B voxels, so the "keep the promise" filter of region_mask_cube is gone. +// +// THE PIPELINE (parent field u, compact SubGrid field half) +// +// 1. fill_boundary SubGrid u = 1 region: boundary (from the SubGrid) +// 2. fill_interior Dense u = 2 region: interior (filters itself) +// 3. scale_interior Dense u = 10 * u region: interior (filters itself) +// 4. sample_boundary SubGrid half = 0.5 * u region: boundary +// 5. count_wrong Dense sums wrong voxels of u, whole cube +// +// Expected dependencies (masks honoured): 1 and 2 write disjoint regions of u, so they run +// side by side; 3 waits for 2; 4 waits for 1 only; 5 waits for 1 and 3. +// +// It then times the boundary fill both ways, a Dense kernel over the whole cube that skips +// interior voxels versus the SubGrid kernel, for --iters launches each. +// +// The per-GPU lane counts are split into lanes away from and next to a GPU-slab boundary, +// the two DataViews OCC launches separately. This grid declares no stencil, so it has no +// halo band and every lane is "internal". +// +// carbon_example_sub_grid_cube [--n 128] [--iters 200] [--dot sub_grid_cube] +// +// See docs/skeleton/README.md, "SubGrid", and region_mask_cube.cu. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using Span = carbon::Dense::Span; +using Idx = carbon::Dense::Idx; +using Field = carbon::Dense::Field; +using S = carbon::SubGrid; +using carbon::RegionMask; + +const RegionMask kInterior = RegionMask::bit(0); +const RegionMask kBoundary = RegionMask::bit(1); + +[[nodiscard]] CARBON_HD constexpr auto +on_boundary(carbon::int64_3d g, + int64_t n) noexcept -> bool { + return g.x == 0 || g.y == 0 || g.z == 0 || g.x == n - 1 || g.y == n - 1 || g.z == n - 1; +} + +constexpr float kBoundaryValue = 1.0F; +constexpr float kInteriorValue = 2.0F; +constexpr float kInteriorScale = 10.0F; +constexpr float kSampleScale = 0.5F; + +// ---- SubGrid kernels: no geometric filter, the SubGrid only launches boundary voxels ------- + +[[nodiscard]] auto +build_fill_boundary(const S& boundary, + Field& u) -> carbon::Kernel { + return carbon::Kernel::compute( + boundary, + [&u](carbon::KernelLoader& loader) { + const auto out = loader.write(u); // parent field, declared with region kBoundary + return [out] CARBON_HD(const S::Span& s, const S::Idx& i) { + out.write(s, i, 0, kBoundaryValue); + }; + }, + "fill_boundary"); +} + +[[nodiscard]] auto +build_sample_boundary(const S& boundary, + Field& u, + S::Field& half) -> carbon::Kernel { + return carbon::Kernel::compute( + boundary, + [&u, &half](carbon::KernelLoader& loader) { + const auto in = loader.read(u); + const auto out = loader.write(half); // compact SubGrid field + return [in, out] CARBON_HD(const S::Span& s, const S::Idx& i) { + out.write(s, i, 0, kSampleScale * in.read(s, i, 0)); + }; + }, + "sample_boundary"); +} + +// ---- Dense kernels ------------------------------------------------------------------------ + +[[nodiscard]] auto +build_fill_interior(carbon::Dense& dense, + Field& u, + int64_t n) -> carbon::Kernel { + return carbon::Kernel::compute( + dense, + [&u, n](carbon::KernelLoader& loader) { + loader.region(kInterior); + const auto out = loader.write(u); + return [out, n] CARBON_HD(Span s, Idx idx) { + if (on_boundary(s.global_location(idx), n)) { + return; + } + out.write(s, idx, 0, kInteriorValue); + }; + }, + "fill_interior"); +} + +[[nodiscard]] auto +build_scale_interior(carbon::Dense& dense, + Field& u, + int64_t n) -> carbon::Kernel { + return carbon::Kernel::compute( + dense, + [&u, n](carbon::KernelLoader& loader) { + loader.region(kInterior); + const auto io = loader.read_write(u); + return [io, n] CARBON_HD(Span s, Idx idx) { + if (on_boundary(s.global_location(idx), n)) { + return; + } + io.write(s, idx, 0, io.read(s, idx, 0) * kInteriorScale); + }; + }, + "scale_interior"); +} + +[[nodiscard]] auto +build_count_wrong(carbon::Dense& dense, + Field& u, + int64_t n, + carbon::ReductionResult& wrong) -> carbon::Kernel { + return carbon::Kernel::reduce( + dense, + [&u, n](carbon::KernelLoader& loader) { + const auto in = loader.read(u); + return [in, n] CARBON_HD(Span s, Idx idx) -> int64_t { + const float expected = on_boundary(s.global_location(idx), n) + ? kBoundaryValue + : kInteriorValue * kInteriorScale; + return in.read(s, idx, 0) == expected ? 0 : 1; + }; + }, + wrong, carbon::reduce::Sum{}, "count_wrong"); +} + +// The region_mask_cube way to fill the boundary: launch over the whole cube, skip the rest. +[[nodiscard]] auto +build_fill_boundary_dense(carbon::Dense& dense, + Field& u, + int64_t n) -> carbon::Kernel { + return carbon::Kernel::compute( + dense, + [&u, n](carbon::KernelLoader& loader) { + loader.region(kBoundary); + const auto out = loader.write(u); + return [out, n] CARBON_HD(Span s, Idx idx) { + if (!on_boundary(s.global_location(idx), n)) { + return; + } + out.write(s, idx, 0, kBoundaryValue); + }; + }, + "fill_boundary_dense"); +} + +// ---- Helpers ------------------------------------------------------------------------------ + +struct Args { + int64_t n = 128; + int iters = 200; + std::string dot_prefix{}; +}; + +[[nodiscard]] auto +parse_args(int argc, + char** argv) -> Args { + Args a{}; + for (int i = 1; i + 1 < argc; i += 2) { + const std::string_view flag = argv[i]; + if (flag == "--n") { + a.n = std::atoll(argv[i + 1]); + } else if (flag == "--iters") { + a.iters = std::atoi(argv[i + 1]); + } else if (flag == "--dot") { + a.dot_prefix = argv[i + 1]; + } else { + throw std::invalid_argument("unknown flag " + std::string{flag}); + } + } + if (a.n < 3) { + throw std::invalid_argument("need --n >= 3 (so the cube has an interior)"); + } + if (a.iters < 1) { + throw std::invalid_argument("need --iters >= 1"); + } + return a; +} + +auto +print_schedule(carbon::Skeleton& sk) -> void { + sk.compile(); + const auto& kernels = sk.effective_kernels(); + const auto& successors = sk.min_edges(); + const auto& streams = sk.kernel_streams(); + std::vector waits_for(kernels.size()); + for (size_t i = 0; i < kernels.size(); ++i) { + for (const size_t j : successors[i]) { + waits_for[j] += (waits_for[j].empty() ? "" : ", ") + std::string{kernels[i].name()}; + } + } + std::cout << "schedule, masks honoured (" << sk.num_streams() << " stream(s))\n"; + for (size_t i = 0; i < kernels.size(); ++i) { + std::cout << " " << std::left << std::setw(16) << kernels[i].name() << " stream " << streams[i] + << " waits for: " << (waits_for[i].empty() ? "-" : waits_for[i]) << '\n'; + } + std::cout << '\n'; +} + +// Mean microseconds per launch of @p k over @p iters launches, after one warm-up launch. +[[nodiscard]] auto +time_launches(carbon::Stream& stream, + const carbon::Kernel& k, + int iters) -> double { + k.launch(stream); + stream.wait(); + const auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < iters; ++i) { + k.launch(stream); + } + stream.wait(); + const std::chrono::duration dt = std::chrono::steady_clock::now() - t0; + return dt.count() / iters; +} + +} // namespace + +int +main(int argc, + char** argv) { + try { + carbon::init(); + const Args args = parse_args(argc, argv); + const int64_t n = args.n; + + carbon::System sys(carbon::get_all_devices()); + carbon::Dense dense(sys, carbon::int64_3d{n, n, n}, carbon::Stencil{}); + + // S = SubGrid(G, F, B): F selects the face voxels, B is the region its kernels declare. + const S boundary = dense.new_sub_grid( + [n](carbon::KernelLoader&) { + return [n] CARBON_HD(const Span& s, const Idx& idx) { + return on_boundary(s.global_location(idx), n); + }; + }, + kBoundary, "boundary"); + + std::cout << "sub_grid_cube: " << n << "^3 cube on " << sys.gpu_group().size() + << " GPU(s); SubGrid '" << boundary.name() << "' has " << boundary.total_count() + << " of " << n * n * n << " voxels\n"; + for (size_t g = 0; g < boundary.gpu_count(); ++g) { + std::cout << " GPU " << g << ": " << boundary.count(g) << " lanes (" + << boundary.internal_count(g) << " internal + " << boundary.boundary_count(g) + << " next to a GPU-slab boundary)\n"; + } + std::cout << '\n'; + + Field u = dense.newField(carbon::MemorySide::Device, "u"); + auto half = boundary.newField(carbon::MemorySide::HostDevice, "half"); + carbon::ReductionResult wrong(sys); + + carbon::Skeleton sk(sys); + sk.add(build_fill_boundary(boundary, u)); + sk.add(build_fill_interior(dense, u, n)); + sk.add(build_scale_interior(dense, u, n)); + sk.add(build_sample_boundary(boundary, u, half)); + sk.add(build_count_wrong(dense, u, n, wrong)); + print_schedule(sk); + + if (!args.dot_prefix.empty()) { + const bool ok = + sk.export_dot_file(args.dot_prefix + ".dot", "sub_grid_cube") && + sk.export_launch_matrix_dot_file(args.dot_prefix + "_matrix.dot", "sub_grid_cube"); + std::cout << (ok ? "wrote " : "FAILED to write ") << args.dot_prefix << "{,_matrix}.dot\n\n"; + } + + sk.run(); + sk.wait(); + carbon::Stream stream = sys.stream(); + wrong.sync(stream); + carbon::Transfer(sys, half.gpu_buffers(), half.cpu_buffers())(stream); + stream.wait(); + int64_t wrong_half = 0; + for (size_t g = 0; g < boundary.gpu_count(); ++g) { + for (int64_t lane = 0; lane < boundary.count(g); ++lane) { + wrong_half += half.cpu_buffers()[g].data()[lane] == kSampleScale * kBoundaryValue ? 0 : 1; + } + } + std::cout << "wrong voxels of u: " << wrong.host_value() + << ", wrong lanes of the SubGrid field: " << wrong_half << "\n\n"; + + const carbon::Kernel dense_fill = build_fill_boundary_dense(dense, u, n); + const carbon::Kernel sub_fill = build_fill_boundary(boundary, u); + const double t_dense = time_launches(stream, dense_fill, args.iters); + const double t_sub = time_launches(stream, sub_fill, args.iters); + std::cout << std::fixed << std::setprecision(1) << "boundary fill, " << args.iters + << " launches: Dense + filter " << t_dense << " us, SubGrid " << t_sub + << " us per launch\n"; + + if (wrong.host_value() != 0 || wrong_half != 0) { + std::cerr << "sub_grid_cube: FAILED\n"; + return EXIT_FAILURE; + } + std::cout << "sub_grid_cube: OK\n"; + } catch (const std::exception& e) { + std::cerr << "sub_grid_cube: " << e.what() << '\n'; + return EXIT_FAILURE; + } + return EXIT_SUCCESS; +} diff --git a/examples/wind_tunnel_common.h b/examples/wind_tunnel_common.h index efaee82d..910d2920 100644 --- a/examples/wind_tunnel_common.h +++ b/examples/wind_tunnel_common.h @@ -754,7 +754,8 @@ class LiveSim { auto rebuild_kernels() -> void { re_ = clamp_re(config_.ulb, config_.diameter(), config_.re); - params_ = LbmParameters{config_.ulb, compute_omega(config_.ulb, config_.diameter(), re_)}; + params_ = + LbmParameters{config_.ulb, compute_omega(config_.ulb, config_.diameter(), re_)}; wall_k_ = make_compute_wall_mask_kernel(dense_, cells_, cells_scratch_); macro_a_ = make_macroscopic_kernel(dense_, pop_a_, cells_, density_, @@ -934,7 +935,7 @@ class LiveSim { } [[nodiscard]] auto - params() const noexcept -> LbmParameters { + params() const noexcept -> LbmParameters { return params_; } @@ -985,7 +986,7 @@ class LiveSim { carbon::System& sys_; LiveSimConfig config_; float re_; - LbmParameters params_; + LbmParameters params_; carbon::Stream stream_; carbon::Dense dense_; carbon::Dense::Field pop_a_; diff --git a/include/carbon/access_token.h b/include/carbon/access_token.h index f1751966..e0e17ace 100644 --- a/include/carbon/access_token.h +++ b/include/carbon/access_token.h @@ -23,8 +23,17 @@ * stays cache-friendly for the conflict scan; future variants (e.g. a stencil-aware * @c StencilToken with a radius / direction byte) can subclass or sit alongside * without invalidating this layout. + * + * @par Sub-field footprints + * @ref AccessToken::mask narrows an access to a user-defined @ref RegionMask of the field. + * Two accesses to the same field conflict only if their modes conflict @b and their masks + * intersect, which is how a kernel on region A and a kernel on region B of the same field + * can run concurrently. The default is @ref RegionMask::all , so tokens recorded without a + * mask keep their whole-field meaning. */ +#include + #include #include #include @@ -169,6 +178,17 @@ struct AccessToken { * @c Skeleton::compile_auto_insert_scalar_readbacks_ . */ std::shared_ptr scalar_readback_factory{}; + /** + * @brief Cells of the field this access may touch, as a user-defined @ref RegionMask . + * + * Set by the masked @c KernelLoader entry points (@c loader.region(M) for the kernel-wide + * default, @c loader.read(f, M) / @c write(f, M) / ... per access) on @c Map tokens only. + * Stencil reads, halos and reduction scalars stay @ref RegionMask::all : carbon cannot + * dilate a user region, a halo reads and writes cells of every region, and a scalar is not + * a field. Last member on purpose, so positional initialisers of the fields above keep + * compiling. + */ + RegionMask mask{RegionMask::all()}; }; /** @@ -190,4 +210,16 @@ conflicts(AccessMode earlier, return true; } +/** + * Token-level conflict predicate: same resource id, conflicting modes, and intersecting + * @ref AccessToken::mask footprints. Disjoint masks on the same field name disjoint cells + * (see the @ref RegionMask contract), so neither ordering can observe the other. + */ +[[nodiscard]] inline auto +conflicts(const AccessToken& earlier, + const AccessToken& later) noexcept -> bool { + return earlier.field_uid == later.field_uid && conflicts(earlier.mode, later.mode) && + earlier.mask.intersects(later.mask); +} + } // namespace carbon diff --git a/include/carbon/block.h b/include/carbon/block.h index 37d6f3e8..98349f95 100644 --- a/include/carbon/block.h +++ b/include/carbon/block.h @@ -26,10 +26,12 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -39,6 +41,41 @@ namespace carbon { +struct KernelLoader; + +template +class SubGrid; + +namespace detail::block { + +/** + * A memoised value derived from (and pointing into) other members of its owner. Copies start + * empty, so a copied owner rebuilds the value from its own members instead of keeping + * pointers into the source object; moves keep it (moved-from vectors keep their buffers). + */ +template +struct ResetOnCopy { + T value{}; + + ResetOnCopy() = default; + ResetOnCopy(const ResetOnCopy& /*other*/) noexcept {} + ResetOnCopy(ResetOnCopy&&) noexcept = default; + ~ResetOnCopy() = default; + + auto + operator=(const ResetOnCopy& other) noexcept -> ResetOnCopy& { + if (this != &other) { + value = T{}; + } + return *this; + } + + auto + operator=(ResetOnCopy&&) noexcept -> ResetOnCopy& = default; +}; + +} // namespace detail::block + /** * Block-sparse multi-GPU grid (port of Neon's @c bGrid). Both build-out phases * have landed: multi-GPU brick partitioning (phase A) and ghost bricks + @@ -279,10 +316,11 @@ class Block { */ [[nodiscard]] auto host_spans() const -> const std::vector& { - if (!host_spans_.empty() || host_bitmasks_per_gpu_.empty()) { - return host_spans_; + auto& memo = host_spans_cache_.value; + if (!memo.empty() || host_bitmasks_per_gpu_.empty()) { + return memo; } - host_spans_.reserve(host_bitmasks_per_gpu_.size()); + memo.reserve(host_bitmasks_per_gpu_.size()); for (size_t g = 0; g < host_bitmasks_per_gpu_.size(); ++g) { const auto& bm = host_bitmasks_per_gpu_[g]; const auto& conn = host_connectivity_per_gpu_[g]; @@ -291,9 +329,9 @@ class Block { (g < n_internal_per_gpu_.size()) ? n_internal_per_gpu_[g] : n_blocks; const int32_3d* origins = host_origins_per_gpu_[g].empty() ? nullptr : host_origins_per_gpu_[g].data(); - host_spans_.emplace_back(bm.data(), n_blocks, n_internal, conn.data(), origins); + memo.emplace_back(bm.data(), n_blocks, n_internal, conn.data(), origins); } - return host_spans_; + return memo; } /** @@ -816,6 +854,37 @@ class Block { Components>& field, const ::carbon::Stream& stream) const -> std::vector>; + /** + * @brief Builds a @ref SubGrid of the active voxels whose @c std::uint8_t label bit is set + * in @p mask . + * + * Same contract as @c Dense::new_sub_grid(labels, mask) : the selection is derived from + * @p mask , @p labels must be up to date on the device and is read once, now (the SubGrid + * is immutable). Launches a selection kernel and blocks until the lane tables are built, + * so call it from a device translation unit (same rule as @ref make_kernel ). Definition + * lives in @c carbon/sub_grid.h . + */ + template + [[nodiscard]] auto + new_sub_grid(const Field& labels, + const ::carbon::RegionMask& mask, + std::string name = {}) const -> SubGrid; + + /** + * @brief Builds a @ref SubGrid of the active voxels selected by a loading callable. + * + * @p select has the shape of a @ref make_kernel loading lambda whose per-voxel callable + * returns @c bool : @c (KernelLoader&) -> CARBON_HD (Span, Idx) -> bool . @p mask is the + * footprint S kernels declare on parent fields; it must cover every selected voxel. + * Same blocking, device-TU and immutability rules as the label overload. + */ + template L> + [[nodiscard]] auto + new_sub_grid(L&& select, + const ::carbon::RegionMask& mask = ::carbon::RegionMask::all(), + std::string name = {}) const -> SubGrid; + private: /** * Inter-phase scratch state used to break the @c Block ctor into a sequence @@ -980,8 +1049,9 @@ class Block { std::vector spans_{}; // Memoised per-GPU @c Span values whose @c bitmask() / @c connectivity() pointers // point at the host mirror tables. Built on demand by @c host_spans() so the OpenMP - // launch path can dereference topology metadata from a host TU. - mutable std::vector host_spans_{}; + // launch path can dereference topology metadata from a host TU. A copy of the Block starts + // with an empty memo: the spans point into this object's own host vectors. + mutable detail::block::ResetOnCopy> host_spans_cache_{}; std::vector bz_begin_per_gpu_{}; std::vector bz_end_per_gpu_{}; std::vector n_internal_per_gpu_{}; diff --git a/include/carbon/carbon.h b/include/carbon/carbon.h index 55636c2f..edd06ca3 100644 --- a/include/carbon/carbon.h +++ b/include/carbon/carbon.h @@ -41,9 +41,11 @@ device_count() noexcept -> int; #include #include #include +#include #include #include #include +#include #include #include diff --git a/include/carbon/dense.h b/include/carbon/dense.h index 58ee8df4..392318a3 100644 --- a/include/carbon/dense.h +++ b/include/carbon/dense.h @@ -11,19 +11,26 @@ #include #include #include +#include #include #include #include +#include #include #include #include +#include #include #include namespace carbon { class Kernel; +struct KernelLoader; + +template +class SubGrid; template class ReductionResult; @@ -510,6 +517,41 @@ class CARBON_API Dense { std::string name = {}) const -> Field; + /** + * @brief Builds a @ref SubGrid of the cells whose @c std::uint8_t label bit is set in + * @p mask . + * + * Recommended constructor: the selection is derived from @p mask , so the footprint S + * kernels declare on parent fields covers exactly the selected cells. @p labels must be + * up to date on the device; it is read once, now (the SubGrid is immutable). + * + * Launches a selection kernel and blocks until the lane tables are built, so call it from + * a device translation unit (same rule as @ref make_kernel ). Definition lives in + * @c carbon/sub_grid.h . + */ + template + [[nodiscard]] auto + new_sub_grid(const Field& labels, + const RegionMask& mask, + std::string name = {}) const -> SubGrid; + + /** + * @brief Builds a @ref SubGrid of the cells selected by a loading callable. + * + * @p select has the shape of a @ref make_kernel loading lambda but its per-cell callable + * returns @c bool : @c (KernelLoader&) -> CARBON_HD (Span, Idx) -> bool . @p mask is the + * footprint S kernels declare on parent fields; it must cover every selected cell, which + * carbon cannot check (the default, @ref RegionMask::all , is always correct). + * + * Same blocking, device-TU and immutability rules as the label overload. + */ + template L> + [[nodiscard]] auto + new_sub_grid(L&& select, + const RegionMask& mask = RegionMask::all(), + std::string name = {}) const -> SubGrid; + private: int64_3d global_{}; System system_; diff --git a/include/carbon/detail/backend/cudalike/sub_grid_launch.h b/include/carbon/detail/backend/cudalike/sub_grid_launch.h new file mode 100644 index 00000000..f506dc12 --- /dev/null +++ b/include/carbon/detail/backend/cudalike/sub_grid_launch.h @@ -0,0 +1,74 @@ +#pragma once + +/** + * CUDA / HIP launch for @c carbon::SubGrid compute kernels: a 1D grid over the lanes of one + * @ref DataView . Include only from device translation units; @c SubGrid 's kernel impl is + * the only caller. + */ + +#include +#include +#include + +#include +#include + +#if CARBON_CUDALIKE_DEVICE_TU +#include +#endif + +namespace carbon::detail::sub_grid { + +/** Threads per block for SubGrid launches (lanes are independent, so any warp multiple works). */ +inline constexpr unsigned kLaneBlockThreads = 256U; + +#if CARBON_CUDALIKE_DEVICE_TU + +/** + * One thread per lane of @c [lane_begin, lane_begin + lane_count) . Builds the SubGrid @c Idx + * from the lane table, so the parent cell and the lane always agree. + */ +template +__global__ void +sub_grid_kernel(SpanT span, + int64_t lane_begin, + int64_t lane_count, + F fn) { + const int64_t k = static_cast(blockIdx.x) * static_cast(blockDim.x) + + static_cast(threadIdx.x); + if (k >= lane_count) { + return; + } + const int64_t lane = lane_begin + k; + fn(span, IdxT(span.sub().parent_idx(lane), lane)); +} + +/** + * Launch @p fn over the lanes of @p view on @p gpu . An empty lane range is a no-op (CUDA + * rejects a zero-sized grid). + */ +template +[[nodiscard]] inline auto +launch_lanes(const ::carbon::detail::Gpu& gpu, + const SpanT& span, + ::carbon::DataView view, + size_t shared_mem, + gpu_stream_t stream, + F fn) -> gpu_error_t { + const int64_t count = span.sub().lane_count(view); + if (count <= 0) { + return gpu_success; + } + const int64_t begin = span.sub().lane_offset(view); + const auto blocks = static_cast((count + kLaneBlockThreads - 1) / kLaneBlockThreads); + return gpu.template typed_launch<&sub_grid_kernel>( + dim3(blocks), dim3(kLaneBlockThreads), shared_mem, stream, span, begin, count, fn); +} + +#endif + +} // namespace carbon::detail::sub_grid diff --git a/include/carbon/detail/backend/cudalike/sub_grid_reduce.h b/include/carbon/detail/backend/cudalike/sub_grid_reduce.h new file mode 100644 index 00000000..db3579b5 --- /dev/null +++ b/include/carbon/detail/backend/cudalike/sub_grid_reduce.h @@ -0,0 +1,126 @@ +#pragma once + +/** + * CUDA / HIP stage 1 of a reduction over a @c carbon::SubGrid : one thread per lane of a + * @ref DataView , each block collapsed with @c gpucub::BlockReduce into a partial (or, for + * @c ReduceFinalize::BlockAtomic , added atomically into the per-GPU scalar). Stages 2 / 3 + * are the grid-agnostic ones in @c reduce_kernel_impl.h ; @c ReduceLaunchTraits + * is the only caller. + */ + +#include +#include + +#include +#include + +#if CARBON_CUDALIKE_DEVICE_TU +#include +#include +#endif + +namespace carbon::detail::sub_grid { + +/** Threads per block of the stage-1 reduce launch. */ +inline constexpr int kReduceBlockThreads = 256; + +#if CARBON_CUDALIKE_DEVICE_TU + +template +__device__ inline auto +lane_value(const SpanT& span, + int64_t lane_begin, + int64_t lane_count, + F& fn, + T init) -> T { + const int64_t k = + static_cast(blockIdx.x) * kReduceBlockThreads + static_cast(threadIdx.x); + if (k >= lane_count) { + return init; + } + const int64_t lane = lane_begin + k; + return fn(span, IdxT(span.sub().parent_idx(lane), lane)); +} + +/** Fused map + block-reduce over @c [lane_begin, lane_begin + lane_count) ; one partial per block. */ +template +__global__ void +sub_grid_reduce_kernel(SpanT span, + int64_t lane_begin, + int64_t lane_count, + F fn, + Op op, + T init, + T* partials) { + using BlockReduceT = gpucub::BlockReduce; + __shared__ typename BlockReduceT::TempStorage temp_storage; + const T v = lane_value(span, lane_begin, lane_count, fn, init); + const T block_val = BlockReduceT(temp_storage).Reduce(v, op); + if (threadIdx.x == 0U) { + partials[blockIdx.x] = block_val; + } +} + +/** Same, but each block sum is added into @p global_out ( @c reduce::Sum only). */ +template +__global__ void +sub_grid_reduce_block_atomic_kernel(SpanT span, + int64_t lane_begin, + int64_t lane_count, + F fn, + Op op, + T init, + T* global_out) { + using BlockReduceT = gpucub::BlockReduce; + __shared__ typename BlockReduceT::TempStorage temp_storage; + const T v = lane_value(span, lane_begin, lane_count, fn, init); + const T block_val = BlockReduceT(temp_storage).Reduce(v, op); + if (threadIdx.x == 0U) { + reduce_atomic_accumulate(global_out, block_val); + } +} + +template +[[nodiscard]] inline auto +launch_lane_reduce(const ::carbon::detail::Gpu& gpu, + int64_t blocks, + size_t shared_mem, + gpu_stream_t stream, + const SpanT& span, + ::carbon::DataView view, + F& fn, + Op& op, + T init, + T* out) -> gpu_error_t { + const int64_t begin = span.sub().lane_offset(view); + const int64_t count = span.sub().lane_count(view); + const dim3 grid(static_cast(blocks)); + const dim3 block(static_cast(kReduceBlockThreads)); + if constexpr (BlockAtomic) { + return gpu.template typed_launch<&sub_grid_reduce_block_atomic_kernel>( + grid, block, shared_mem, stream, span, begin, count, fn, op, init, out); + } else { + return gpu.template typed_launch<&sub_grid_reduce_kernel>( + grid, block, shared_mem, stream, span, begin, count, fn, op, init, out); + } +} + +#endif + +} // namespace carbon::detail::sub_grid diff --git a/include/carbon/detail/backend/sycl/block_atomic_reduce.h b/include/carbon/detail/backend/sycl/block_atomic_reduce.h new file mode 100644 index 00000000..60f18227 --- /dev/null +++ b/include/carbon/detail/backend/sycl/block_atomic_reduce.h @@ -0,0 +1,82 @@ +#pragma once + +/** + * SYCL twin of the CUDA backend's @c ReduceFinalize::BlockAtomic stage 1 for row-major + * dense spans (@c dense::Span and @c dense_distributed::Span ): each work-group sums its + * cells with @c sycl::reduce_over_group and adds the group sum into the per-GPU scalar with + * one device-scope atomic. No partials buffer and no second pass. Only @c reduce::Sum is + * allowed for BlockAtomic, so the group algorithm uses @c sycl::plus (custom operators are + * not portable group-algorithm operators). Floating-point sums are not bitwise-deterministic + * across launches (atomic order), as on CUDA. + */ + +#include +#include +#include + +#include + +#include +#include +#include + +namespace carbon::detail::sycl_reduce { + +/** Work-group size of the block-atomic launch (same default as the CUDA path). */ +constexpr size_t kBlockAtomicGroupSize = 256; + +/** + * @brief Zero @p out on @p queue , then add @c fn(span, idx) over every owned cell of + * @p view into it. + * + * @param out Device pointer to one @c T on @p queue 's device. + * @param total_cells @c span.iter_extent(view).volume() . + */ +template +inline auto +launch_dense_block_atomic_sum(sycl::queue& queue, + SpanT span, + ::carbon::DataView view, + F fn, + T* out, + int64_t total_cells) -> void { + try { + queue.memset(out, 0, sizeof(T)); + if (total_cells <= 0) { + return; + } + const ::carbon::int64_3d ext = span.iter_extent(view); + const size_t total = static_cast(total_cells); + const size_t global = + (total + kBlockAtomicGroupSize - 1U) / kBlockAtomicGroupSize * kBlockAtomicGroupSize; + queue.parallel_for(sycl::nd_range<1>(global, kBlockAtomicGroupSize), [=](sycl::nd_item<1> it) { + const size_t flat_u = it.get_global_id(0); + T v{}; + if (flat_u < total) { + const int64_t flat = static_cast(flat_u); + const int64_t ix = flat % ext.x; + const int64_t rest = flat / ext.x; + const int64_t iy = rest % ext.y; + const int64_t iz = rest / ext.y; + const auto vi = span.set_and_validate(view, ix, iy, iz); + if (vi.valid) { + v = fn(span, vi.idx); + } + } + const T group_sum = sycl::reduce_over_group(it.get_group(), v, sycl::plus()); + if (it.get_local_id(0) == 0U) { + sycl::atomic_ref + acc(*out); + acc.fetch_add(group_sum); + } + }); + } catch (const sycl::exception& ex) { + ::carbon::log::throw_with_log( + "launch_dense_block_atomic_sum: SYCL submission failed: {}", ex.what()); + } +} + +} // namespace carbon::detail::sycl_reduce diff --git a/include/carbon/detail/backend/sycl/sub_grid_launch.h b/include/carbon/detail/backend/sycl/sub_grid_launch.h new file mode 100644 index 00000000..ef6f1888 --- /dev/null +++ b/include/carbon/detail/backend/sycl/sub_grid_launch.h @@ -0,0 +1,65 @@ +#pragma once + +/** + * SYCL launch for @c carbon::SubGrid compute kernels: a 1D @c nd_range over the lanes of one + * @ref DataView . Twin of @c detail/backend/cudalike/sub_grid_launch.h . + */ + +#include +#include + +#include + +#include +#include +#include + +namespace carbon::detail::sub_grid { + +/** Work-items per work-group for SubGrid launches. */ +inline constexpr size_t kLaneBlockThreads = 256U; + +/** + * Submit @p fn over the lanes of @p view on @p queue . An empty lane range is a no-op. + * @throws std::runtime_error on dynamic shared memory (unsupported under SYCL, as for Dense) + * or a failed submission. + */ +template +inline auto +launch_lanes(sycl::queue& queue, + const SpanT& span, + ::carbon::DataView view, + size_t shared_mem, + F fn) -> void { + if (shared_mem != 0U) { + ::carbon::log::throw_with_log( + "SubGrid kernel: dynamic shared memory ({} bytes) is not supported under the SYCL " + "backend.", + shared_mem); + } + const int64_t count = span.sub().lane_count(view); + if (count <= 0) { + return; + } + const int64_t begin = span.sub().lane_offset(view); + const size_t groups = (static_cast(count) + kLaneBlockThreads - 1U) / kLaneBlockThreads; + const SpanT s = span; + try { + queue.parallel_for(sycl::nd_range<1>{groups * kLaneBlockThreads, kLaneBlockThreads}, + [=](sycl::nd_item<1> it) { + const auto k = static_cast(it.get_global_id(0)); + if (k >= count) { + return; + } + const int64_t lane = begin + k; + fn(s, IdxT(s.sub().parent_idx(lane), lane)); + }); + } catch (const sycl::exception& ex) { + ::carbon::log::throw_with_log( + "SubGrid kernel: SYCL parallel_for submission failed: {}", ex.what()); + } +} + +} // namespace carbon::detail::sub_grid diff --git a/include/carbon/detail/backend/sycl/sub_grid_reduce.h b/include/carbon/detail/backend/sycl/sub_grid_reduce.h new file mode 100644 index 00000000..79aa1bf9 --- /dev/null +++ b/include/carbon/detail/backend/sycl/sub_grid_reduce.h @@ -0,0 +1,100 @@ +#pragma once + +/** + * SYCL reduction over the lanes of a @c carbon::SubGrid @ref DataView : a single-pass + * @c sycl::reduction (twin of @c launch_dense_reduce ) and the @c ReduceFinalize::BlockAtomic + * variant (twin of @c launch_dense_block_atomic_sum ). @c ReduceLaunchTraits is the + * only caller. + */ + +#include +#include + +#include + +#include +#include +#include + +namespace carbon::detail::sub_grid { + +template +inline auto +launch_lane_reduce(sycl::queue& queue, + SpanT span, + ::carbon::DataView view, + F fn, + Op op, + T init, + T* out) -> void { + const int64_t begin = span.sub().lane_offset(view); + const int64_t count = span.sub().lane_count(view); + try { + if (count <= 0) { + queue.fill(out, init, 1U); + return; + } + queue.submit([&](sycl::handler& cgh) { + auto reducer = + sycl::reduction(out, init, op, sycl::property::reduction::initialize_to_identity{}); + cgh.parallel_for(sycl::range<1>(static_cast(count)), reducer, + [=](sycl::id<1> k, auto& red) { + const int64_t lane = begin + static_cast(k[0]); + red.combine(fn(span, IdxT(span.sub().parent_idx(lane), lane))); + }); + }); + } catch (const sycl::exception& ex) { + ::carbon::log::throw_with_log("SubGrid reduce: SYCL submission failed: {}", + ex.what()); + } +} + +/** Work-group size of the block-atomic launch (same as the CUDA stage 1). */ +inline constexpr size_t kBlockAtomicGroupSize = 256; + +template +inline auto +launch_lane_block_atomic_sum(sycl::queue& queue, + SpanT span, + ::carbon::DataView view, + F fn, + T* out) -> void { + const int64_t begin = span.sub().lane_offset(view); + const int64_t count = span.sub().lane_count(view); + try { + queue.memset(out, 0, sizeof(T)); + if (count <= 0) { + return; + } + const size_t total = static_cast(count); + const size_t global = + (total + kBlockAtomicGroupSize - 1U) / kBlockAtomicGroupSize * kBlockAtomicGroupSize; + queue.parallel_for(sycl::nd_range<1>(global, kBlockAtomicGroupSize), [=](sycl::nd_item<1> it) { + const size_t k = it.get_global_id(0); + T v{}; + if (k < total) { + const int64_t lane = begin + static_cast(k); + v = fn(span, IdxT(span.sub().parent_idx(lane), lane)); + } + const T group_sum = sycl::reduce_over_group(it.get_group(), v, sycl::plus()); + if (it.get_local_id(0) == 0U) { + sycl::atomic_ref + acc(*out); + acc.fetch_add(group_sum); + } + }); + } catch (const sycl::exception& ex) { + ::carbon::log::throw_with_log( + "SubGrid block-atomic reduce: SYCL submission failed: {}", ex.what()); + } +} + +} // namespace carbon::detail::sub_grid diff --git a/include/carbon/detail/launch_traits.h b/include/carbon/detail/launch_traits.h index a5dca73a..a87bce29 100644 --- a/include/carbon/detail/launch_traits.h +++ b/include/carbon/detail/launch_traits.h @@ -50,10 +50,11 @@ #if CARBON_BACKEND_IS_CUDALIKE #include #if CARBON_CUDALIKE_DEVICE_TU -#include #include +#include #endif #elif CARBON_BACKEND_IS_SYCL +#include #include #endif @@ -563,8 +564,9 @@ struct ReduceLaunchTraits { bx, by, gpu, blocks, shared_mem, stream, span, view, fn, op, identity, partials, iter_cells); } - const int bt = dense_stage1_threads > 0 ? dense_stage1_threads - : ::carbon::detail::dense_distributed::kReduceBlockThreads; + const int bt = dense_stage1_threads > 0 + ? dense_stage1_threads + : ::carbon::detail::dense_distributed::kReduceBlockThreads; return ::carbon::detail::dense_distributed::launch_dense_grid_reduce_kernel( bt, gpu, blocks, shared_mem, stream, span, view, fn, op, identity, partials, iter_cells); } else { @@ -609,13 +611,13 @@ struct ReduceLaunchTraits { if (dense_stage1_threads_y > 0) { const int bx = dense_stage1_threads > 0 ? dense_stage1_threads : 32; const int by = dense_stage1_threads_y; - return ::carbon::detail::dense_distributed:: - launch_dense_grid_reduce_block_atomic_kernel_2d( - bx, by, gpu, blocks, shared_mem, stream, span, view, fn, op, identity, global_out, - iter_cells); + return ::carbon::detail::dense_distributed::launch_dense_grid_reduce_block_atomic_kernel_2d< + F, T, Op>(bx, by, gpu, blocks, shared_mem, stream, span, view, fn, op, identity, + global_out, iter_cells); } - const int bt = dense_stage1_threads > 0 ? dense_stage1_threads - : ::carbon::detail::dense_distributed::kReduceBlockThreads; + const int bt = dense_stage1_threads > 0 + ? dense_stage1_threads + : ::carbon::detail::dense_distributed::kReduceBlockThreads; return ::carbon::detail::dense_distributed::launch_dense_grid_reduce_block_atomic_kernel( bt, gpu, blocks, shared_mem, stream, span, view, fn, op, identity, global_out, @@ -661,6 +663,25 @@ struct ReduceLaunchTraits { iter_cells); } } + + /** @c ReduceFinalize::BlockAtomic stage 1 (Sum only; the reduce ctor rejects DenseDisg). */ + template + static auto + sycl_block_atomic(sycl::queue& q, + const typename Grid::Span& span, + ::carbon::DataView view, + F& fn, + T* out, + int64_t iter_cells) -> void { + if constexpr (requires { typename Grid::DisgPolicy; }) { + ::carbon::log::throw_with_log( + "Kernel::reduce: ReduceFinalize::BlockAtomic is not supported on DenseDisg grids"); + } else { + ::carbon::detail::sycl_reduce::launch_dense_block_atomic_sum(q, span, view, fn, out, + iter_cells); + } + } #endif }; @@ -772,6 +793,19 @@ struct ReduceLaunchTraits<::carbon::Block> { ::carbon::detail::block::launch_block_reduce(q, span, view, fn, op, identity, out); } + + template + static auto + sycl_block_atomic(sycl::queue&, + const typename Grid::Span&, + ::carbon::DataView, + F&, + T*, + int64_t) -> void { + ::carbon::log::throw_with_log( + "Kernel::reduce: ReduceFinalize::BlockAtomic is not supported on Block grids"); + } #endif }; diff --git a/include/carbon/detail/reduce_kernel_impl.h b/include/carbon/detail/reduce_kernel_impl.h index e86dd64f..54a53b33 100644 --- a/include/carbon/detail/reduce_kernel_impl.h +++ b/include/carbon/detail/reduce_kernel_impl.h @@ -164,16 +164,6 @@ class ReduceKernelImpl final : public KernelImpl { "Kernel::reduce: ReduceFinalize::BlockAtomic requires T to be float, double, " "int32_t, or int64_t"); } -#if CARBON_BACKEND_IS_SYCL - log::throw_with_log( - "Kernel::reduce: ReduceFinalize::BlockAtomic is supported only on the CUDA/HIP backend"); -#endif - } - if (reduce_options_.host_copy == reduce::ReduceHostCopy::Deferred) { -#if CARBON_BACKEND_IS_SYCL - log::throw_with_log( - "Kernel::reduce: ReduceHostCopy::Deferred is supported only on the CUDA/HIP backend"); -#endif } if (reduce_options_.stage1_threads != 0U || reduce_options_.stage1_threads_y != 0U) { if constexpr (requires { typename Grid::DisgPolicy; }) { @@ -220,8 +210,7 @@ class ReduceKernelImpl final : public KernelImpl { total_cells_per_gpu_[g_idx] = Traits::iter_cell_count(grid_, g_idx, DataView::Standard); block_count_per_gpu_[g_idx] = Traits::stage1_unit_count( grid_, g_idx, DataView::Standard, dense_stage1_threads_, dense_stage1_threads_y_); - for (const DataView view : - {DataView::Standard, DataView::Internal, DataView::Boundary}) { + for (const DataView view : {DataView::Standard, DataView::Internal, DataView::Boundary}) { stage1_scratch_blocks_per_gpu_[g_idx] = std::max(stage1_scratch_blocks_per_gpu_[g_idx], Traits::stage1_unit_count(grid_, g_idx, view, dense_stage1_threads_, @@ -535,6 +524,7 @@ class ReduceKernelImpl final : public KernelImpl { } } #elif CARBON_BACKEND_IS_SYCL + const bool block_atomic = reduce_options_.finalize == reduce::ReduceFinalize::BlockAtomic; for (size_t g_idx = 0; g_idx < gpu_count; ++g_idx) { const auto span = grid_.spans()[g_idx]; const int64_t iter_cells = Traits::iter_cell_count(grid_, g_idx, view); @@ -547,6 +537,16 @@ class ReduceKernelImpl final : public KernelImpl { KernelLoaderPhase::Launch}; auto device_fn = loading_fn_(ctx); using F = decltype(device_fn); + if (block_atomic) { + // The ctor admits BlockAtomic only for Sum over float/double/int32/int64. + if constexpr (std::is_same_v> && + (std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v)) { + Traits::template sycl_block_atomic(q, span, view, device_fn, stage2_out, + iter_cells); + } + continue; + } Traits::template sycl_singlepass(q, span, view, device_fn, op_, op_.identity(), stage2_out, iter_cells); } @@ -618,8 +618,8 @@ class ReduceKernelImpl final : public KernelImpl { #elif CARBON_BACKEND_IS_SYCL if (stream.size() != grid_.gpu_count()) { log::throw_with_log( - "Kernel::reduce::launch_merge: stream-group size ({}) != gpu_count ({})", - stream.size(), grid_.gpu_count()); + "Kernel::reduce::launch_merge: stream-group size ({}) != gpu_count ({})", stream.size(), + grid_.gpu_count()); } ReductionResult& dst = *dst_; (void)dst.begin_launch_slot(DataView::Standard, stream); @@ -644,13 +644,11 @@ class ReduceKernelImpl final : public KernelImpl { "Kernel::reduce::launch_merge: SYCL submission failed: {}", ex.what()); } - reduce_stages::run_stage3_cross_rank(grid_.system(), stream, dst, - DataView::Standard); + reduce_stages::run_stage3_cross_rank(grid_.system(), stream, dst, DataView::Standard); if (reduce_options_.host_copy == reduce::ReduceHostCopy::Inline) { const size_t slot = dst.active_slot(); grid_.system().async_copy(dst.device_allocation(DataView::Standard, slot), - dst.host_allocation(DataView::Standard, slot), sizeof(T), - stream); + dst.host_allocation(DataView::Standard, slot), sizeof(T), stream); dst.record_readback_done(DataView::Standard, slot, stream); dst.mark_fresh(DataView::Standard); } diff --git a/include/carbon/detail/sub_grid/field.h b/include/carbon/detail/sub_grid/field.h new file mode 100644 index 00000000..0313811d --- /dev/null +++ b/include/carbon/detail/sub_grid/field.h @@ -0,0 +1,167 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace carbon::detail::sub_grid { + +/** + * Per-GPU storage of a @ref carbon::SubGrid field: one packed SoA buffer per GPU holding + * @c Components planes of @c count(gpu) elements, plus one @c Partition per GPU. + * + * No halo and no halo kernel: SubGrid fields only support same-cell access (see + * @ref Partition ). Built only through @c SubGrid::newField . + * + * The SubGrid is stored by value (a shallow handle), so a field keeps its lane tables alive. + * Copies share the underlying buffers, like @c Dense::Field . + * + * @tparam Grid The owning @c carbon::SubGrid . + * @tparam T Element type per component. + * @tparam Components Components per cell. + */ +template +class Field { + static_assert(Components >= 1, + "carbon::SubGrid::Field requires Components >= 1."); + +public: + using value_type = T; + static constexpr int components = Components; + using Partition = typename Grid::template Partition; + + /** Empty placeholder (no grid, no buffers, no partitions). */ + Field() = default; + + [[nodiscard]] auto + sub_grid() const noexcept -> const Grid& { + return grid_; + } + + /** Identity of the SubGrid this field is laid out for; @c KernelLoader checks it. */ + [[nodiscard]] auto + sub_grid_uid() const noexcept -> std::uint64_t { + return grid_.uid(); + } + + /** Diagnostic name (Skeleton DOT labels, logs); identity is the buffer uid. */ + [[nodiscard]] auto + name() const noexcept -> const std::string& { + return name_; + } + + auto + set_name(std::string name) -> Field& { + name_ = std::move(name); + return *this; + } + + [[nodiscard]] auto + side() const noexcept -> ::carbon::MemorySide { + return side_; + } + + [[nodiscard]] auto + gpu_buffers() noexcept -> ::carbon::Buffer& { + return gpu_buffers_; + } + + [[nodiscard]] auto + gpu_buffers() const noexcept -> const ::carbon::Buffer& { + return gpu_buffers_; + } + + /** Host mirror buffers; empty for @c MemorySide::Device fields. */ + [[nodiscard]] auto + cpu_buffers() noexcept -> ::carbon::Buffer& { + return cpu_buffers_; + } + + [[nodiscard]] auto + cpu_buffers() const noexcept -> const ::carbon::Buffer& { + return cpu_buffers_; + } + + /** Per-GPU partitions bound to the device buffers (host buffers for Host-only fields). */ + [[nodiscard]] auto + partitions() const noexcept -> const std::vector& { + return partitions_; + } + + /** Per-GPU partitions bound to the host mirror; empty for @c MemorySide::Device fields. */ + [[nodiscard]] auto + host_partitions() const noexcept -> const std::vector& { + return host_partitions_; + } + + /** + * Fill every lane on the host mirror with @p fn applied to the lane's parent cell in global + * coordinates and the component — the SubGrid twin of @c Dense::Field::fill_owned_host . + * Push to the device afterwards with a @c Transfer , as for Dense fields. + * + * @tparam Fn Callable as @c fn(carbon::int64_3d global, int component) returning @c T . + * @throws std::invalid_argument when the field has no host mirror. + */ + template + void + fill_owned_host(Fn&& fn) { + static_assert(std::is_invocable_r_v, + "SubGrid::Field::fill_owned_host expects a callable invocable as " + "fn(carbon::int64_3d global, int component) returning T."); + const size_t n_gpus = grid_.gpu_count(); + if (cpu_buffers_.size() != n_gpus) { + log::throw_with_log( + "SubGrid::Field::fill_owned_host: field '{}' has no host mirror " + "(cpu_buffers().size()={}, " + "gpu_count={}). Construct it with MemorySide::Host or MemorySide::HostDevice.", + name_, cpu_buffers_.size(), n_gpus); + } + for (size_t g = 0; g < n_gpus; ++g) { + const int64_t n = grid_.count(g); + T* h = cpu_buffers_[g].data(); + for (int c = 0; c < Components; ++c) { + for (int64_t lane = 0; lane < n; ++lane) { + h[static_cast(c) * n + lane] = + static_cast(fn(grid_.global_location(g, lane), c)); + } + } + } + } + +private: + friend Grid; + + Field(Grid grid, + ::carbon::Buffer gpu_buffers, + ::carbon::Buffer cpu_buffers, + std::vector partitions, + std::vector host_partitions, + ::carbon::MemorySide side, + std::string name) + : grid_(std::move(grid)), + gpu_buffers_(std::move(gpu_buffers)), + cpu_buffers_(std::move(cpu_buffers)), + partitions_(std::move(partitions)), + host_partitions_(std::move(host_partitions)), + side_(side), + name_(std::move(name)) {} + + Grid grid_{}; + ::carbon::Buffer gpu_buffers_{}; + ::carbon::Buffer cpu_buffers_{}; + std::vector partitions_{}; + std::vector host_partitions_{}; + ::carbon::MemorySide side_{::carbon::MemorySide::Device}; + std::string name_{}; +}; + +} // namespace carbon::detail::sub_grid diff --git a/include/carbon/detail/sub_grid/fwd.h b/include/carbon/detail/sub_grid/fwd.h new file mode 100644 index 00000000..940256aa --- /dev/null +++ b/include/carbon/detail/sub_grid/fwd.h @@ -0,0 +1,22 @@ +#pragma once + +/** Forward declaration of @c carbon::SubGrid and its type trait, for headers that dispatch on it. */ + +namespace carbon { + +template +class SubGrid; + +namespace detail::sub_grid { + +template +inline constexpr bool is_sub_grid_v = false; + +template +inline constexpr bool is_sub_grid_v<::carbon::SubGrid> = true; + +template +struct BoundLoading; + +} // namespace detail::sub_grid +} // namespace carbon diff --git a/include/carbon/detail/sub_grid/idx.h b/include/carbon/detail/sub_grid/idx.h new file mode 100644 index 00000000..6a34b9c8 --- /dev/null +++ b/include/carbon/detail/sub_grid/idx.h @@ -0,0 +1,49 @@ +#pragma once + +#include + +#include + +namespace carbon::detail::sub_grid { + +/** + * Cell index of a @ref carbon::SubGrid launch. + * + * Derives from the parent grid's @c Idx and carries one extra value, the cell's @b lane: its + * slot in the packed SubGrid storage. Because the base subobject is the parent cell, an S + * kernel passes an @c Idx straight to a parent-field partition (it binds to + * @c const ParentIdx& ), while SubGrid partitions address their packed storage through + * @ref sub_lane . The conversion only goes one way: a plain @c ParentIdx does not convert to + * an @c Idx , so a parent-grid kernel cannot address a SubGrid field. + * + * Only the launcher builds an @c Idx (from the lane table); user code receives it. + * + * @par Name rule + * A member of a derived class hides every base member with the same name, so this class adds + * exactly one name, @ref sub_lane , and checks that the parent index does not already use it. + */ +template +class Idx : public ParentIdx { + static_assert( + !requires(const ParentIdx& p) { p.sub_lane(); }, + "carbon::SubGrid: the parent grid's Idx already has a sub_lane() member; " + "SubGrid's Idx would hide it."); + + int64_t lane_{}; + +public: + constexpr Idx() noexcept = default; + + CARBON_HD constexpr Idx(const ParentIdx& parent, + int64_t lane) noexcept + : ParentIdx(parent), + lane_(lane) {} + + /** Slot of this cell in the packed SubGrid storage (same index space as the lane table). */ + [[nodiscard]] CARBON_HD constexpr auto + sub_lane() const noexcept -> int64_t { + return lane_; + } +}; + +} // namespace carbon::detail::sub_grid diff --git a/include/carbon/detail/sub_grid/kernel_impl.h b/include/carbon/detail/sub_grid/kernel_impl.h new file mode 100644 index 00000000..49219d1a --- /dev/null +++ b/include/carbon/detail/sub_grid/kernel_impl.h @@ -0,0 +1,277 @@ +#pragma once + +/** + * Compute kernels over a @c carbon::SubGrid : the @c KernelImpl leaves behind + * @c SubGrid::make_kernel (device, @ref KernelKind::Compute ) and @c SubGrid::make_host_kernel + * (OpenMP, @ref KernelKind::ComputeHost ). + * + * Same loading-lambda contract as Dense kernels, with three SubGrid rules applied to every + * loader before the user's lambda runs: + * - the kernel-wide region is the SubGrid's mask, so parent-field accesses carry it as their + * footprint (the user may still narrow it with @c loader.region ); + * - the loader is bound to the SubGrid, so loading a field of another SubGrid throws at + * construction; + * - launches are 1D over the lanes of the requested @ref DataView . + * + * Being @c Compute , a device SubGrid kernel that stencil-reads a parent field after a halo is + * OCC-split by the @ref Skeleton like any parent kernel; the internal-first lane order makes + * each half one contiguous lane range. + */ + +#include +#include +#include +#include +#include +#include + +#if CARBON_BACKEND_IS_CUDALIKE +#include +#elif CARBON_BACKEND_IS_SYCL +#include +#endif + +#include +#include +#include +#include +#include +#include +#include + +#if CARBON_BACKEND_IS_CUDALIKE && CARBON_CUDALIKE_DEVICE_TU +#include +#endif + +namespace carbon { + +struct KernelLoader; + +namespace detail::sub_grid { + +template +inline constexpr bool sub_grid_launch_requires_device_tu_ = false; + +/** Applies the SubGrid loader rules, then runs the user's loading lambda. */ +template +auto +load(const Grid& grid, + LoadingFn& loading_fn, + ::carbon::KernelLoader& loader) { + loader.region(grid.mask()); + loader.bind_sub_grid(grid.uid()); + return loading_fn(loader); +} + +/** + * A loading lambda with the SubGrid loader rules applied, for the grid-agnostic reduction + * impls, which call their loading callable directly. + */ +template +struct BoundLoading { + Grid grid; + LoadingFn fn; + + auto + operator()(::carbon::KernelLoader& loader) { + return load(grid, fn, loader); + } + + /** The stage-1 block shape is fixed for SubGrid reductions. */ + static auto + check_reduce_options(const reduce::ReduceOptions& options) -> void { + if (options.stage1_threads != 0U || options.stage1_threads_y != 0U) { + log::throw_with_log( + "Kernel::reduce (SubGrid): ReduceOptions::stage1_threads / stage1_threads_y are not " + "supported; SubGrid reductions use a fixed 1D block over lanes"); + } + } +}; + +/** Device compute kernel over a SubGrid (@ref KernelKind::Compute ). */ +template +class DeviceKernelImpl final : public ::carbon::detail::KernelImpl { +public: + template + DeviceKernelImpl(const Grid& grid, + L&& loading, + size_t shared_mem, + std::string name) + : KernelImpl(std::move(name)), + grid_(grid), + loading_fn_(std::forward(loading)), + shared_mem_(shared_mem) { + static_assert(std::is_invocable_v, + "SubGrid::make_kernel: the loading callable must be invocable as " + "`loader(KernelLoader&) -> F`, where F is the per-cell " + "`CARBON_HD (SubGrid::Span, SubGrid::Idx)` callable."); + discover_tokens_(); + } + + [[nodiscard]] auto + kind() const noexcept -> KernelKind override { + return KernelKind::Compute; + } + + [[nodiscard]] auto + tokens() const noexcept -> const std::vector& override { + return tokens_; + } + + [[nodiscard]] auto + runs_on_device() const noexcept -> bool override { + return true; + } + + auto + launch(const ::carbon::Stream& stream, + DataView view) -> void override { + launch_on_device(stream, view); + } + + auto + launch_on_device(const ::carbon::Stream& stream, + DataView view) -> void override { + const size_t n = grid_.gpu_count(); + if (n > 0U && stream.size() != n) { + log::throw_with_log( + "SubGrid kernel '{}': stream group size {} must equal gpu_count() {}", name(), + stream.size(), n); + } +#if CARBON_BACKEND_IS_CUDALIKE && CARBON_CUDALIKE_DEVICE_TU + using Idx = typename Grid::Idx; + std::vector errs(n, gpu_success); +#pragma omp parallel for num_threads(static_cast(n)) if (n > 1) + for (size_t i = 0; i < n; ++i) { + KernelLoader ctx{i, KernelTarget::Device, KernelLoaderPhase::Launch}; + auto device_fn = load(grid_, loading_fn_, ctx); + errs[i] = launch_lanes(grid_.system().gpu_group().devices()[i], grid_.spans()[i], view, + shared_mem_, stream[i].get(), device_fn); + } + for (size_t i = 0; i < n; ++i) { + if (errs[i] != gpu_success) { + log::throw_with_log( + "SubGrid kernel '{}': launch failed on relative_gpu_id={}: {} (gpu error {})", name(), + i, gpu_error_string(errs[i]), static_cast(errs[i])); + } + } +#elif CARBON_BACKEND_IS_SYCL + using Idx = typename Grid::Idx; + for (size_t i = 0; i < n; ++i) { + KernelLoader ctx{i, KernelTarget::Device, KernelLoaderPhase::Launch}; + auto device_fn = load(grid_, loading_fn_, ctx); + launch_lanes(stream[i].queue(), grid_.spans()[i], view, shared_mem_, device_fn); + } +#else + static_assert(sub_grid_launch_requires_device_tu_, + "SubGrid::make_kernel launches require a device translation unit (a .cu file " + "compiled with nvcc / hipcc). Only the call site needs to be device code."); + (void)view; +#endif + } + +private: + auto + discover_tokens_() -> void { + if (grid_.gpu_count() == 0U) { + return; + } + KernelLoader ctx{0U, KernelTarget::Device}; + [[maybe_unused]] auto fn = load(grid_, loading_fn_, ctx); + tokens_ = ctx.tokens(); + } + + Grid grid_{}; + LoadingFn loading_fn_; + size_t shared_mem_{}; + std::vector tokens_{}; +}; + +/** + * Host (OpenMP) compute kernel over a SubGrid (@ref KernelKind::ComputeHost ). Waits on the + * stream, then runs the lanes of the requested view on each GPU's host lane table. + * Every field it loads needs a host mirror. + */ +template +class HostKernelImpl final : public ::carbon::detail::KernelImpl { +public: + template + HostKernelImpl(const Grid& grid, + L&& loading, + std::string name) + : KernelImpl(std::move(name)), + grid_(grid), + loading_fn_(std::forward(loading)) { + static_assert(std::is_invocable_v, + "SubGrid::make_host_kernel: the loading callable must be invocable as " + "`loader(KernelLoader&) -> F`, where F is the per-cell " + "`(SubGrid::Span, SubGrid::Idx)` callable."); + discover_tokens_(); + } + + [[nodiscard]] auto + kind() const noexcept -> KernelKind override { + return KernelKind::ComputeHost; + } + + [[nodiscard]] auto + tokens() const noexcept -> const std::vector& override { + return tokens_; + } + + [[nodiscard]] auto + runs_on_host() const noexcept -> bool override { + return true; + } + + auto + launch(const ::carbon::Stream& stream, + DataView view) -> void override { + launch_on_host(stream, view); + } + + auto + launch_on_host(const ::carbon::Stream& stream, + DataView view) -> void override { + try { + stream.wait(); + } catch (const std::exception& ex) { + log::throw_with_log( + "SubGrid host kernel '{}': stream.wait() before the host loop failed: {}", name(), + ex.what()); + } + using Idx = typename Grid::Idx; + const size_t n = grid_.gpu_count(); + for (size_t g = 0; g < n; ++g) { + KernelLoader ctx{g, KernelTarget::Host, KernelLoaderPhase::Launch}; + auto host_fn = load(grid_, loading_fn_, ctx); + const auto& span = grid_.host_spans()[g]; + const int64_t begin = span.sub().lane_offset(view); + const int64_t count = span.sub().lane_count(view); +#pragma omp parallel for + for (int64_t k = 0; k < count; ++k) { + const int64_t lane = begin + k; + host_fn(span, Idx(span.sub().parent_idx(lane), lane)); + } + } + } + +private: + auto + discover_tokens_() -> void { + if (grid_.gpu_count() == 0U) { + return; + } + KernelLoader ctx{0U, KernelTarget::Device}; + [[maybe_unused]] auto fn = load(grid_, loading_fn_, ctx); + tokens_ = ctx.tokens(); + } + + Grid grid_{}; + LoadingFn loading_fn_; + std::vector tokens_{}; +}; + +} // namespace detail::sub_grid +} // namespace carbon diff --git a/include/carbon/detail/sub_grid/parent_traits.h b/include/carbon/detail/sub_grid/parent_traits.h new file mode 100644 index 00000000..8be831ff --- /dev/null +++ b/include/carbon/detail/sub_grid/parent_traits.h @@ -0,0 +1,128 @@ +#pragma once + +/** + * Per-parent-family hooks used to build a @c carbon::SubGrid : how to enumerate the parent's + * cells of a @ref DataView on the host, where a cell's selection flag lives in the downloaded + * flag buffer, and which parent span a host kernel may dereference. + * + * Supported parents: @ref carbon::Dense and @ref carbon::Block . The primary template is left + * undefined so any other parent fails at @c SubGrid instantiation. + */ + +#include +#include +#include +#include + +#include +#include + +namespace carbon::detail::sub_grid { + +template +struct ParentTraits; + +template +inline constexpr bool has_parent_traits_v = requires { + sizeof(ParentTraits); +}; + +template <> +struct ParentTraits<::carbon::Dense> { + using Span = ::carbon::Dense::Span; + using Idx = ::carbon::Dense::Idx; + + /** Dense spans are pure geometry (no pointers), so the device span serves the host too. */ + [[nodiscard]] static auto + host_span(const ::carbon::Dense& grid, + size_t gpu) -> Span { + return grid.spans()[gpu]; + } + + /** Calls @p fn for every cell of @p view in the parent's iteration order. */ + template + static auto + for_each_cell(const Span& span, + ::carbon::DataView view, + F&& fn) -> void { + const int64_3d ext = span.iter_extent(view); + for (int64_t z = 0; z < ext.z; ++z) { + for (int64_t y = 0; y < ext.y; ++y) { + for (int64_t x = 0; x < ext.x; ++x) { + const auto r = span.set_and_validate(view, x, y, z); + if (r.valid) { + fn(r.idx); + } + } + } + } + } + + /** Offset of @p idx 's flag in a host copy of a one-component parent field. */ + [[nodiscard]] static auto + flag_offset(const Span& span, + const Idx& idx) -> int64_t { + return span.linear_offset(idx); + } +}; + +template +struct ParentTraits<::carbon::Block> { + using Grid = ::carbon::Block; + using Span = typename Grid::Span; + using Idx = typename Grid::Idx; + + /** + * A span over @p grid 's own host topology tables (bitmasks, connectivity, origins). + * + * Built here instead of taken from @c Block::host_spans() , whose memoised spans are copied + * along with the @c Block and are not thread-safe. The host tables cover owned bricks only, + * so a host-side @c neighbour that crosses the slab cut (into a ghost slot) is out of range, + * exactly as for @c Block 's own host kernels. + */ + [[nodiscard]] static auto + host_span(const Grid& grid, + size_t gpu) -> Span { + const uint32_t n_blocks = grid.block_count(gpu); + if (n_blocks == 0U) { + return Span{}; + } + return Span(grid.host_bitmasks(gpu).data(), n_blocks, grid.n_internal_blocks(gpu), + grid.host_connectivity(gpu).data(), grid.host_origins(gpu).data()); + } + + /** + * Calls @p fn for every active voxel of @p view : bricks in storage order (Internal bricks, + * then Boundary bricks), voxels z-y-x within a brick, which is also their storage order. + * @p span must be a host span (the bitmask is dereferenced). + */ + template + static auto + for_each_cell(const Span& span, + ::carbon::DataView view, + F&& fn) -> void { + const uint32_t n = span.iter_block_count(view); + for (uint32_t it = 0; it < n; ++it) { + const uint32_t b = span.view_block_idx(view, it); + for (int iz = 0; iz < Span::MemZ; ++iz) { + for (int iy = 0; iy < Span::MemY; ++iy) { + for (int ix = 0; ix < Span::MemX; ++ix) { + const auto r = span.set_and_validate(b, ix, iy, iz); + if (r.valid) { + fn(r.idx); + } + } + } + } + } + } + + /** Offset of @p idx 's flag in the owned-brick buffer returned by @c Block::download_to_host . */ + [[nodiscard]] static auto + flag_offset(const Span& span, + const Idx& idx) -> int64_t { + return span.linear_offset(idx, 1, 0); + } +}; + +} // namespace carbon::detail::sub_grid diff --git a/include/carbon/detail/sub_grid/partition.h b/include/carbon/detail/sub_grid/partition.h new file mode 100644 index 00000000..324d7635 --- /dev/null +++ b/include/carbon/detail/sub_grid/partition.h @@ -0,0 +1,108 @@ +#pragma once + +#include +#include +#include + +#include +#include + +namespace carbon::detail::sub_grid { + +/** + * Per-GPU view of a @ref carbon::SubGrid field: a raw pointer to packed SoA storage of + * @c Components planes, each @c span.sub().count() elements long, indexed by lane. + * + * Same-cell access only. There is deliberately no @c neighbour , @c read_pull or cursor: + * SubGrid fields have no halo, and neighbouring lanes are not neighbouring cells. Stencils + * belong on parent fields (an S kernel may stencil-read those through the parent's halo). + * For the same reason this class must not derive from the parent grid's @c Partition . + * + * Takes the SubGrid @c Span and @c Idx — not the parent's — so a parent-grid kernel, which + * has no lane, cannot address a SubGrid field. Does not own the storage. + */ +template +class Partition { + static_assert(Components >= 1, + "carbon::SubGrid::Partition requires Components >= 1."); + +public: + using Span = sub_grid::Span; + using Idx = sub_grid::Idx; + + /** Compile-time component count (same as @p Components ). */ + static constexpr int static_value = Components; + + constexpr Partition() noexcept = default; + + /** + * @param ptr Packed storage for this GPU: @c Components * count elements. + * @param owner Identity of the SubGrid the storage is laid out for. + */ + constexpr Partition(T* ptr, + std::uint64_t owner) noexcept + : ptr_(ptr), + owner_(owner) {} + + [[nodiscard]] CARBON_HD constexpr auto + ptr() const noexcept -> T* { + return ptr_; + } + + /** Identity of the SubGrid this storage is laid out for. */ + [[nodiscard]] CARBON_HD constexpr auto + owner() const noexcept -> std::uint64_t { + return owner_; + } + + /** Value of component @p component_id at the cell of @p idx . No bounds checking. */ + [[nodiscard]] CARBON_HD constexpr auto + read(const Span& span, + const Idx& idx, + int component_id) const noexcept -> const T& { + return ptr_[offset_(span, idx, component_id)]; + } + + /** Stores @p value as component @p component_id of the cell of @p idx . */ + CARBON_HD constexpr auto + write(const Span& span, + const Idx& idx, + int component_id, + T value) const noexcept -> void { + ptr_[offset_(span, idx, component_id)] = value; + } + +private: + [[nodiscard]] CARBON_HD constexpr auto + offset_(const Span& span, + const Idx& idx, + int component_id) const noexcept -> int64_t { + const int64_t lane = idx.sub_lane(); +#ifndef NDEBUG + assert(span.sub().owner() == owner_ && "SubGrid field used with a different SubGrid"); + assert(lane >= 0 && lane < span.sub().count()); + assert(component_id >= 0 && component_id < Components); + if constexpr (requires { idx.cell(); }) { + assert(span.sub().parent_idx(lane).cell() == idx.cell() && + "SubGrid Idx lane does not match its parent cell"); + } else if constexpr (requires { + idx.block_idx(); + idx.intra(); + }) { + assert(span.sub().parent_idx(lane).block_idx() == idx.block_idx() && + span.sub().parent_idx(lane).intra() == idx.intra() && + "SubGrid Idx lane does not match its parent cell"); + } +#endif + if constexpr (Components == 1) { + (void)component_id; + return lane; + } + return static_cast(component_id) * span.sub().count() + lane; + } + + T* ptr_{}; + std::uint64_t owner_{}; +}; + +} // namespace carbon::detail::sub_grid diff --git a/include/carbon/detail/sub_grid/reduce_traits.h b/include/carbon/detail/sub_grid/reduce_traits.h new file mode 100644 index 00000000..7f68c199 --- /dev/null +++ b/include/carbon/detail/sub_grid/reduce_traits.h @@ -0,0 +1,209 @@ +#pragma once + +/** + * @c ReduceLaunchTraits / @c HostLaunchTraits for @c carbon::SubGrid , so the grid-agnostic + * reduction impls ( @c ReduceKernelImpl , @c ReduceHostKernelImpl , + * @c UniversalReduceKernelImpl ) run SubGrid reductions unchanged: multi-GPU combine, + * cross-rank stage, @c ReduceFinalize::BlockAtomic , deferred host copy, and the OCC + * Partial / Merge split. Stage 1 iterates the lanes of the requested @ref DataView ; + * internal-first lane order makes Internal and Boundary two contiguous ranges. + */ + +#include +#include +#include +#include + +#if CARBON_BACKEND_IS_CUDALIKE +#include +#elif CARBON_BACKEND_IS_SYCL +#include +#endif + +#include + +#include +#include +#include +#include + +namespace carbon::detail { + +template +struct ReduceLaunchTraits<::carbon::SubGrid> { + using Grid = ::carbon::SubGrid; + + static constexpr auto + stage1_block_threads() noexcept -> int { + return 256; + } + + static auto + stage1_unit_count(const Grid& grid, + size_t g_idx, + ::carbon::DataView view, + int /*dense_stage1_threads*/ = 0, + int /*dense_stage1_threads_y*/ = 0) -> int64_t { + const int64_t lanes = iter_cell_count(grid, g_idx, view); + return (lanes + stage1_block_threads() - 1) / stage1_block_threads(); + } + + static auto + is_empty_domain(const Grid& grid, + size_t g_idx, + ::carbon::DataView view) -> bool { + return iter_cell_count(grid, g_idx, view) == 0; + } + + static auto + iter_cell_count(const Grid& grid, + size_t g_idx, + ::carbon::DataView view) -> int64_t { + return grid.spans()[g_idx].sub().lane_count(view); + } + +#if CARBON_BACKEND_IS_CUDALIKE && CARBON_CUDALIKE_DEVICE_TU + template + static auto + assert_reduce_fn() noexcept -> void { + static_assert(std::is_invocable_r_v, + "Kernel::reduce (SubGrid): the device callable returned by the loading " + "function must be invocable as fn(SubGrid::Span, SubGrid::Idx) -> T."); + } + + template + static auto + cuda_stage1(const ::carbon::detail::Gpu& gpu, + int64_t blocks, + size_t shared_mem, + gpu_stream_t stream, + const typename Grid::Span& span, + ::carbon::DataView view, + F& fn, + Op& op, + T identity, + T* partials, + int64_t /*iter_cells*/, + int /*dense_stage1_threads*/ = 0, + int /*dense_stage1_threads_y*/ = 0) -> gpu_error_t { + return sub_grid::launch_lane_reduce( + gpu, blocks, shared_mem, stream, span, view, fn, op, identity, partials); + } + + template + static auto + cuda_stage1_block_atomic(const ::carbon::detail::Gpu& gpu, + int64_t blocks, + size_t shared_mem, + gpu_stream_t stream, + const typename Grid::Span& span, + ::carbon::DataView view, + F& fn, + Op& op, + T identity, + T* global_out, + int64_t /*iter_cells*/, + int /*dense_stage1_threads*/ = 0, + int /*dense_stage1_threads_y*/ = 0) -> gpu_error_t { + return sub_grid::launch_lane_reduce( + gpu, blocks, shared_mem, stream, span, view, fn, op, identity, global_out); + } +#endif + +#if CARBON_BACKEND_IS_SYCL + template + static auto + sycl_singlepass(sycl::queue& q, + const typename Grid::Span& span, + ::carbon::DataView view, + F& fn, + Op& op, + T identity, + T* out, + int64_t /*iter_cells*/) -> void { + sub_grid::launch_lane_reduce(q, span, view, fn, op, identity, out); + } + + template + static auto + sycl_block_atomic(sycl::queue& q, + const typename Grid::Span& span, + ::carbon::DataView view, + F& fn, + T* out, + int64_t /*iter_cells*/) -> void { + sub_grid::launch_lane_block_atomic_sum(q, span, view, fn, out); + } +#endif +}; + +template +struct HostLaunchTraits<::carbon::SubGrid> { + using Grid = ::carbon::SubGrid; + + /** Host lane tables: the device spans' tables are not reachable from host threads. */ + static auto + spans_for_host(const Grid& grid) -> const auto& { + return grid.host_spans(); + } + + template + static auto + iterate_slab(const Span& span, + ::carbon::DataView view, + HostFn& host_fn) -> void { + using Idx = typename Grid::Idx; + const int64_t begin = span.sub().lane_offset(view); + const int64_t count = span.sub().lane_count(view); +#pragma omp parallel for default(shared) + for (int64_t k = 0; k < count; ++k) { + const int64_t lane = begin + k; + host_fn(span, Idx(span.sub().parent_idx(lane), lane)); + } + } + + template + static auto + iterate_slab_reduce(const Span& span, + ::carbon::DataView view, + HostFn& host_fn, + Op& op) -> T { + using Idx = typename Grid::Idx; + const int64_t begin = span.sub().lane_offset(view); + const int64_t count = span.sub().lane_count(view); + if (count <= 0) { + return op.identity(); + } + std::vector partials(static_cast(::omp_get_max_threads()), op.identity()); +#pragma omp parallel default(shared) + { + T local = op.identity(); +#pragma omp for nowait + for (int64_t k = 0; k < count; ++k) { + const int64_t lane = begin + k; + local = op(local, host_fn(span, Idx(span.sub().parent_idx(lane), lane))); + } + partials[static_cast(::omp_get_thread_num())] = local; + } + T acc = op.identity(); + for (const T& p : partials) { + acc = op(acc, p); + } + return acc; + } +}; + +} // namespace carbon::detail diff --git a/include/carbon/detail/sub_grid/span.h b/include/carbon/detail/sub_grid/span.h new file mode 100644 index 00000000..c92e6f1e --- /dev/null +++ b/include/carbon/detail/sub_grid/span.h @@ -0,0 +1,147 @@ +#pragma once + +#include +#include + +#include + +namespace carbon::detail::sub_grid { + +/** + * Per-GPU lane table of a @ref carbon::SubGrid : which parent cells the SubGrid selected, in + * packed order, plus the counts that split them by @ref DataView . + * + * Lanes are ordered internal cells first, then boundary cells: + * + * @code + * lanes: [ 0 .. internal_count() ) [ internal_count() .. count() ) + * parent Internal cells parent Boundary cells + * @endcode + * + * so every view is one contiguous lane range (@ref lane_offset , @ref lane_count ) and + * @c Internal + @c Boundary covers @c Standard exactly once — the same guarantee the parent + * grid gives through @c iter_extent . Within each range lanes follow the parent's own + * iteration order for that view. + * + * A plain view: @c table points to device memory on a device span and to host memory on a + * host span; the owning @ref carbon::SubGrid keeps both alive. + */ +template +class Lanes { +public: + constexpr Lanes() noexcept = default; + + constexpr Lanes(const ParentIdx* table, + int64_t count, + int64_t internal_count, + std::uint64_t owner) noexcept + : table_(table), + count_(count), + internal_count_(internal_count), + owner_(owner) {} + + /** Number of selected cells on this GPU (the S field length per component). */ + [[nodiscard]] CARBON_HD constexpr auto + count() const noexcept -> int64_t { + return count_; + } + + /** Selected cells that lie in the parent's Internal region. */ + [[nodiscard]] CARBON_HD constexpr auto + internal_count() const noexcept -> int64_t { + return internal_count_; + } + + /** Selected cells that lie in the parent's Boundary region. */ + [[nodiscard]] CARBON_HD constexpr auto + boundary_count() const noexcept -> int64_t { + return count_ - internal_count_; + } + + /** First lane of @p view . */ + [[nodiscard]] CARBON_HD constexpr auto + lane_offset(::carbon::DataView view) const noexcept -> int64_t { + return view == ::carbon::DataView::Boundary ? internal_count_ : 0; + } + + /** Number of lanes in @p view . */ + [[nodiscard]] CARBON_HD constexpr auto + lane_count(::carbon::DataView view) const noexcept -> int64_t { + switch (view) { + case ::carbon::DataView::Internal: + return internal_count_; + case ::carbon::DataView::Boundary: + return count_ - internal_count_; + case ::carbon::DataView::Standard: + break; + } + return count_; + } + + /** Parent cell of @p lane . No bounds checking. */ + [[nodiscard]] CARBON_HD constexpr auto + parent_idx(int64_t lane) const noexcept -> const ParentIdx& { + return table_[lane]; + } + + /** Raw lane table (@ref count entries). */ + [[nodiscard]] CARBON_HD constexpr auto + table() const noexcept -> const ParentIdx* { + return table_; + } + + /** Identity of the owning SubGrid; SubGrid partitions check it in debug builds. */ + [[nodiscard]] CARBON_HD constexpr auto + owner() const noexcept -> std::uint64_t { + return owner_; + } + +private: + const ParentIdx* table_{}; + int64_t count_{}; + int64_t internal_count_{}; + std::uint64_t owner_{}; +}; + +/** + * Per-GPU span of a @ref carbon::SubGrid . + * + * Derives from the parent grid's @c Span and its base subobject @b is the parent span of the + * same GPU, so an S kernel passes it straight to parent-field partitions + * (@c uG.read(s, i, 0) ) and inherited queries such as @c global_location , @c origin and + * @c spacing describe the parent cell. SubGrid-specific data lives behind @ref sub . + * + * The inherited 3D iteration members (@c iter_extent , @c set_and_validate , ...) still + * describe the parent slab; a SubGrid launch is 1D over the lanes of @ref sub . + * + * @par Name rule + * A member of a derived class hides every base member with the same name, which would give one + * object two answers to the same query depending on the static type at the call site. This + * class therefore adds exactly one name, @ref sub , and checks that the parent span does not + * already use it. + */ +template +class Span : public ParentSpan { + static_assert( + !requires(const ParentSpan& p) { p.sub(); }, + "carbon::SubGrid: the parent grid's Span already has a sub() member; " + "SubGrid's Span would hide it."); + + Lanes sub_{}; + +public: + constexpr Span() noexcept = default; + + constexpr Span(const ParentSpan& parent, + const Lanes& lanes) noexcept + : ParentSpan(parent), + sub_(lanes) {} + + /** SubGrid lane table and counts for this GPU. */ + [[nodiscard]] CARBON_HD constexpr auto + sub() const noexcept -> const Lanes& { + return sub_; + } +}; + +} // namespace carbon::detail::sub_grid diff --git a/include/carbon/detail/universal_reduce_kernel_impl.h b/include/carbon/detail/universal_reduce_kernel_impl.h index 628913c5..f5f26bdc 100644 --- a/include/carbon/detail/universal_reduce_kernel_impl.h +++ b/include/carbon/detail/universal_reduce_kernel_impl.h @@ -82,12 +82,6 @@ class UniversalReduceKernelImpl final : public KernelImpl { dst_(&dst), shared_mem_(shared_mem), reduce_options_(options) { - if (reduce_options_.host_copy == reduce::ReduceHostCopy::Deferred) { -#if CARBON_BACKEND_IS_SYCL - log::throw_with_log( - "Kernel::reduce: ReduceHostCopy::Deferred is supported only on the CUDA/HIP backend"); -#endif - } if (grid_.gpu_count() == 0U) { log::throw_with_log( "Kernel::reduce: grid has no GPUs (gpu_count == 0)"); diff --git a/include/carbon/distributed.h b/include/carbon/distributed.h index 7719073b..efc97065 100644 --- a/include/carbon/distributed.h +++ b/include/carbon/distributed.h @@ -3,6 +3,7 @@ #include #include +#include #include namespace carbon { @@ -120,6 +121,15 @@ class CARBON_API Distributed { size_t bytes, int root) const; + /** + * Collective on @c MPI_COMM_WORLD : @c true on every rank iff every rank passed the same + * @p value . Two @c MPI_Allreduce calls (min and max), so every rank gets the same answer + * and can act on a mismatch together instead of some ranks proceeding into a collective + * the others never join. Throws @c std::runtime_error on any MPI error. + */ + [[nodiscard]] auto + all_ranks_equal(std::uint64_t value) const -> bool; + private: // Bridge to the underlying MPI_Comm lives in @c src/distributed_internal.h, which is only // included from translation units that may already see @c ; this keeps MPI types out diff --git a/include/carbon/halo.h b/include/carbon/halo.h index 30e97201..6301e035 100644 --- a/include/carbon/halo.h +++ b/include/carbon/halo.h @@ -216,17 +216,26 @@ class Halo { // the source GPU's stream — but @c cudaMemcpyPeerAsync enqueued on the // DESTINATION GPU's stream carries no implicit ordering against that source-side // compute. Record every per-GPU stream's current tail and fan-in-wait so each - // copy is sequenced behind every GPU's prior writes; the same fence on the next - // halo call transitively covers the copy-vs-next-overwrite WAR. Without this the + // copy is sequenced behind every GPU's prior writes. Without this the // halo silently reads transient source bytes under cross-GPU timing pressure (a // genuine but contention-masked numerical drift, not just harness contention). - // @c fence_event_ is empty for single-GPU / no-halo layouts, where the whole - // block is skipped. + // + // The trailing drain fence is the matching WAR guard: each copy reads the SOURCE + // GPU's owned cells from the destination GPU's stream, so the source GPU's next + // write to those cells must wait for the copy. A later halo's leading fence only + // covers that when another halo sits between the copy and the overwrite (a + // two-field ping-pong); a pipeline with one halo per iteration rewrites the field + // first. @c fence_event_ / @c drain_event_ are empty for single-GPU / no-halo + // layouts, where both blocks are skipped. if (!fence_event_.empty()) { fence_event_.record(stream); stream.wait_for_all(fence_event_); } intra_(stream); + if (!drain_event_.empty()) { + drain_event_.record(stream); + stream.wait_for_all(drain_event_); + } #ifdef CARBON_HAVE_MPI_NCCL dist_(stream); #endif @@ -334,6 +343,8 @@ class Halo { // because the fence records into it from the const @ref operator() — the group is a // shallow shared handle, so recording mutates the underlying events in place. mutable Event fence_event_{}; + // Same allocation rule as @c fence_event_ ; backs the post-copy drain fence. + mutable Event drain_event_{}; std::vector host_intra_{}; Stencil stencil_{}; StencilSemantic semantic_{StencilSemantic::Standard}; @@ -581,6 +592,7 @@ Halo 0U) { System sys = dense.system(); fence_event_ = sys.event(); + drain_event_ = sys.event(); } } diff --git a/include/carbon/halo_block.h b/include/carbon/halo_block.h index e4d3632c..561a3b84 100644 --- a/include/carbon/halo_block.h +++ b/include/carbon/halo_block.h @@ -151,6 +151,7 @@ class HaloBlock { // compute; allocate the per-GPU event group from a shallow System copy. System sys = block.system(); fence_event_ = sys.event(); + drain_event_ = sys.event(); } } @@ -211,12 +212,17 @@ class HaloBlock { // and @c StreamGroup::wait_for_all. The intra brick copies read source-GPU owned // bricks written by prior compute on the source GPU's stream, but a peer copy on // the destination GPU's stream has no implicit ordering against it. fence_event_ - // is empty for single-GPU layouts (pair_count_ == 0 already skips this branch). + // is empty for single-GPU layouts (pair_count_ == 0 already skips this branch). The + // drain fence after the copies is the matching WAR guard (see carbon::Halo::operator()). if (!fence_event_.empty()) { fence_event_.record(stream); stream.wait_for_all(fence_event_); } transfer_(stream); + if (!drain_event_.empty()) { + drain_event_.record(stream); + stream.wait_for_all(drain_event_); + } } #ifdef CARBON_HAVE_MPI_NCCL if (dist_entry_count_ != 0U) { @@ -377,6 +383,7 @@ class HaloBlock { // Per-GPU event group backing the cross-GPU producer fence in @ref operator() (see the // matching member on @c carbon::Halo). Allocated only when pair_count_ > 0. mutable Event fence_event_{}; + mutable Event drain_event_{}; }; } // namespace carbon diff --git a/include/carbon/halo_disg.h b/include/carbon/halo_disg.h index 7593619d..2bd08537 100644 --- a/include/carbon/halo_disg.h +++ b/include/carbon/halo_disg.h @@ -192,12 +192,17 @@ class HaloDisg { // and @c StreamGroup::wait_for_all. The intra peer copies read each pair's // source-GPU owned cells written by prior compute on the source GPU's stream, but a // peer copy on the destination GPU's stream has no implicit ordering against it. - // Empty fence_event_ (single-GPU / no-halo) skips the block. + // Empty fence_event_ (single-GPU / no-halo) skips the block. The drain fence after the + // copies is the matching WAR guard (see carbon::Halo::operator()). if (!fence_event_.empty()) { fence_event_.record(stream); stream.wait_for_all(fence_event_); } intra_(stream); + if (!drain_event_.empty()) { + drain_event_.record(stream); + stream.wait_for_all(drain_event_); + } #ifdef CARBON_HAVE_MPI_NCCL dist_(stream); #endif @@ -260,6 +265,7 @@ class HaloDisg { // Per-GPU event group backing the cross-GPU producer fence in @ref operator() (see the // matching member on @c carbon::Halo). Allocated only for multi-local-GPU layouts. mutable Event fence_event_{}; + mutable Event drain_event_{}; }; namespace detail::halo_disg { @@ -528,6 +534,7 @@ HaloDisg 0U) { System sys = dense.system(); fence_event_ = sys.event(); + drain_event_ = sys.event(); } } diff --git a/include/carbon/halo_distributed.h b/include/carbon/halo_distributed.h index ae4605a8..988abf79 100644 --- a/include/carbon/halo_distributed.h +++ b/include/carbon/halo_distributed.h @@ -242,12 +242,12 @@ class HaloDistributed { // the source GPU's stream — but @c cudaMemcpyPeerAsync enqueued on the // DESTINATION GPU's stream carries no implicit ordering against that source-side // compute. Record every per-GPU stream's current tail and fan-in-wait so each - // copy is sequenced behind every GPU's prior writes; the same fence on the next - // halo call transitively covers the copy-vs-next-overwrite WAR. Without this the + // copy is sequenced behind every GPU's prior writes. Without this the // halo silently reads transient source bytes under cross-GPU timing pressure (a // genuine but contention-masked numerical drift, not just harness contention). - // @c fence_event_ is empty for single-GPU / no-halo layouts, where the whole - // block is skipped. + // The drain fence after the last copies is the matching WAR guard (see + // carbon::Halo::operator()). @c fence_event_ / @c drain_event_ are empty for + // single-GPU / no-halo layouts, where both blocks are skipped. if (!fence_event_.empty()) { fence_event_.record(stream); stream.wait_for_all(fence_event_); @@ -294,6 +294,10 @@ class HaloDistributed { #endif } } + if (!drain_event_.empty()) { + drain_event_.record(stream); + stream.wait_for_all(drain_event_); + } return; } @@ -301,6 +305,10 @@ class HaloDistributed { #ifdef CARBON_HAVE_MPI_NCCL dist_(stream); #endif + if (!drain_event_.empty()) { + drain_event_.record(stream); + stream.wait_for_all(drain_event_); + } } /** @@ -487,6 +495,8 @@ class HaloDistributed { // because the fence records into it from the const @ref operator() — the group is a // shallow shared handle, so recording mutates the underlying events in place. mutable Event fence_event_{}; + // Same allocation rule as @c fence_event_ ; backs the post-copy drain fence. + mutable Event drain_event_{}; std::vector host_intra_{}; std::vector axis_passes_{}; #if CARBON_BACKEND_IS_CUDALIKE @@ -798,6 +808,7 @@ HaloDistributed 0U) { System sys = dense.system(); fence_event_ = sys.event(); + drain_event_ = sys.event(); } } @@ -1096,6 +1107,7 @@ HaloDistributed #include #include +#include #include #include #include @@ -271,6 +272,91 @@ struct KernelLoader { return lookup_partition_(field); } + /** + * @brief Declare the kernel-wide @ref RegionMask : the sub-domain of cells this kernel + * touches, in the user's own bit-to-region mapping. + * + * Applies to every @c Map access of the loading lambda that does not pass an explicit + * mask, whether recorded before or after this call (the last @c region call wins). + * Stencil reads keep @ref RegionMask::all . Two kernels whose accesses to a shared field + * have disjoint masks carry no dependency through that field, so the @ref Skeleton may run + * them concurrently. + * + * The mask is a declaration, not a launch restriction: the per-cell body must only touch + * cells of @c R(mask) and filter itself (e.g. on a per-cell @c uint8_t label read with an + * explicit @c RegionMask::all ). It must not depend on @ref relative_gpu_id or the MPI + * rank: tokens are discovered once, and every rank must build the same schedule. + * + * Stored in every phase, so @c region() returns it inside launch-phase bodies too. + */ + auto + region(const RegionMask& mask) const -> void { + region_ = mask; + if (phase_ == KernelLoaderPhase::Launch) { + return; + } + for (size_t i = 0; i < tokens_.size(); ++i) { + if (!explicit_mask_[i]) { + tokens_[i].mask = mask; + } + } + } + + /** + * @brief Bind this loader to the @c carbon::SubGrid identified by @p uid . Called by + * SubGrid kernels before the user's loading lambda runs; not meant for user code. + * + * While bound, loading a SubGrid field laid out for a different SubGrid throws + * @c std::invalid_argument at kernel construction (its lanes would not match). An unbound + * loader (every parent-grid kernel) rejects SubGrid fields altogether. + */ + auto + bind_sub_grid(std::uint64_t uid) noexcept -> void { + sub_grid_uid_ = uid; + } + + /** Kernel-wide @ref RegionMask declared via @ref region ; @ref RegionMask::all by default. */ + [[nodiscard]] auto + region() const noexcept -> const RegionMask& { + return region_; + } + + /** @ref operator() restricted to the cells of @p mask (explicit per-access footprint). */ + template + [[nodiscard]] auto + operator()(const Field& field, + const RegionMask& mask) const { + record_token_(field, AccessMode::ReadWrite, AccessPattern::Map, {}, &mask); + return lookup_partition_(field); + } + + /** @ref read restricted to the cells of @p mask (explicit per-access footprint). */ + template + [[nodiscard]] auto + read(const Field& field, + const RegionMask& mask) const { + record_token_(field, AccessMode::Read, AccessPattern::Map, {}, &mask); + return lookup_partition_(field); + } + + /** @ref write restricted to the cells of @p mask (explicit per-access footprint). */ + template + [[nodiscard]] auto + write(const Field& field, + const RegionMask& mask) const { + record_token_(field, AccessMode::Write, AccessPattern::Map, {}, &mask); + return lookup_partition_(field); + } + + /** @ref read_write restricted to the cells of @p mask (explicit per-access footprint). */ + template + [[nodiscard]] auto + read_write(const Field& field, + const RegionMask& mask) const { + record_token_(field, AccessMode::ReadWrite, AccessPattern::Map, {}, &mask); + return lookup_partition_(field); + } + /** * @brief Stencil read — records @c AccessMode::Read with * @c AccessPattern::Stencil and snapshots a @ref HaloFactoryBase for @@ -350,6 +436,15 @@ struct KernelLoader { template [[nodiscard]] auto lookup_partition_(const Field& field) const { + if constexpr (requires { field.sub_grid_uid(); }) { + if (phase_ != KernelLoaderPhase::Launch && field.sub_grid_uid() != sub_grid_uid_) { + log::throw_with_log( + "KernelLoader: SubGrid field '{}' is laid out for a different SubGrid than the " + "kernel loading it{}. A SubGrid field can only be loaded by kernels of its own " + "SubGrid (S.make_kernel / S.make_host_kernel).", + field.name(), sub_grid_uid_ == 0U ? " (a parent-grid kernel)" : ""); + } + } if (target_ == KernelTarget::Host) { const auto& parts = field.host_partitions(); if (parts.empty()) { @@ -368,7 +463,8 @@ struct KernelLoader { record_token_(const Field& field, AccessMode mode, AccessPattern pattern = AccessPattern::Map, - std::shared_ptr halo_factory = {}) const -> void { + std::shared_ptr halo_factory = {}, + const RegionMask* explicit_mask = nullptr) const -> void { // Launch phase: tokens are discovery-only metadata, so skip the push_back // (and the field.name() std::string copy it entails) entirely on the hot // path. Any halo_factory handed in has already been suppressed by the @@ -389,6 +485,15 @@ struct KernelLoader { // a later set_name does not retroactively rewrite already-recorded tokens). tokens_.push_back(AccessToken{field.gpu_buffers().get_uid(), ResourceKind::Field, mode, pattern, field.name(), std::move(halo_factory)}); + // Stencil reads stay all ones (carbon cannot dilate a user region); only Map tokens + // without an explicit mask follow the kernel-wide region, including a later region(). + const bool pinned = explicit_mask != nullptr || pattern != AccessPattern::Map; + if (explicit_mask != nullptr) { + tokens_.back().mask = *explicit_mask; + } else if (!pinned) { + tokens_.back().mask = region_; + } + explicit_mask_.push_back(pinned); } size_t relative_gpu_id_{}; @@ -399,6 +504,11 @@ struct KernelLoader { // perspective. The vector is local to each KernelLoader instance, so there is no // shared-state concern. mutable std::vector tokens_{}; + // Parallel to tokens_: true when the token's mask must not follow region(). + mutable std::vector explicit_mask_{}; + mutable RegionMask region_{RegionMask::all()}; + // SubGrid this loader serves (SubGrid::uid); 0 for parent-grid kernels. + std::uint64_t sub_grid_uid_{}; }; /** @@ -870,9 +980,13 @@ Kernel::compute(const Grid& grid, // @c DeviceKernelImpl ; the trait absorbs the helper choice and the // parameter-shape variation (Dense / DenseDisg unpack @c gpu_grid[i] / // @c gpu_block[i] ; Block derives the dims internally from @c SBlock ). - using Impl = detail::DeviceKernelImpl>; - return Kernel( - std::make_shared(grid, std::forward(loading), shared_mem, std::move(name))); + if constexpr (detail::sub_grid::is_sub_grid_v) { + return grid.make_kernel(std::forward(loading), std::move(name), shared_mem); + } else { + using Impl = detail::DeviceKernelImpl>; + return Kernel(std::make_shared(grid, std::forward(loading), shared_mem, + std::move(name))); + } } template , T, std::decay_t>; - return Kernel(std::make_shared(grid, std::forward(loading), dst, std::move(op), - shared_mem, std::move(name), options)); + if constexpr (detail::sub_grid::is_sub_grid_v) { + using Bound = detail::sub_grid::BoundLoading>; + Bound::check_reduce_options(options); + using Impl = detail::ReduceKernelImpl>; + return Kernel(std::make_shared(grid, Bound{grid, std::forward(loading)}, dst, + std::move(op), shared_mem, std::move(name), options)); + } else { + using Impl = detail::ReduceKernelImpl, T, std::decay_t>; + return Kernel(std::make_shared(grid, std::forward(loading), dst, std::move(op), + shared_mem, std::move(name), options)); + } } template @@ -970,8 +1092,12 @@ Kernel::host_compute(const Grid& grid, // @c detail/launch_traits.h ). Block / Dense / DenseDisg all bind to // @c DenseHostKernelImpl (the name is historical; the impl is now grid- // family agnostic). - using Impl = detail::DenseHostKernelImpl>; - return Kernel(std::make_shared(grid, std::forward(loading), std::move(name))); + if constexpr (detail::sub_grid::is_sub_grid_v) { + return grid.make_host_kernel(std::forward(loading), std::move(name)); + } else { + using Impl = detail::DenseHostKernelImpl>; + return Kernel(std::make_shared(grid, std::forward(loading), std::move(name))); + } } template and @c detail::HostLaunchTraits // (see @c detail/launch_traits.h ). + static_assert(!detail::sub_grid::is_sub_grid_v, + "Kernel::compute_universal: not supported for a SubGrid; use " + "Kernel::compute and Kernel::host_compute."); using Impl = detail::UniversalKernelImpl>; return Kernel( std::make_shared(grid, std::forward(loading), shared_mem, std::move(name))); @@ -1006,10 +1135,18 @@ Kernel::reduce_universal(const Grid& grid, // variation lives inside @c detail::ReduceLaunchTraits (device // stage-1) and @c detail::HostLaunchTraits::iterate_slab_reduce // (host fold). See @c detail/launch_traits.h . - using Impl = - detail::UniversalReduceKernelImpl, T, std::decay_t>; - return Kernel(std::make_shared(grid, std::forward(loading), dst, std::move(op), - shared_mem, std::move(name), options)); + if constexpr (detail::sub_grid::is_sub_grid_v) { + using Bound = detail::sub_grid::BoundLoading>; + Bound::check_reduce_options(options); + using Impl = detail::UniversalReduceKernelImpl>; + return Kernel(std::make_shared(grid, Bound{grid, std::forward(loading)}, dst, + std::move(op), shared_mem, std::move(name), options)); + } else { + using Impl = + detail::UniversalReduceKernelImpl, T, std::decay_t>; + return Kernel(std::make_shared(grid, std::forward(loading), dst, std::move(op), + shared_mem, std::move(name), options)); + } } template ::iterate_slab_reduce // (see @c detail/launch_traits.h ). - using Impl = detail::ReduceHostKernelImpl, T, std::decay_t>; - return Kernel(std::make_shared(grid, std::forward(loading), dst, std::move(op), - std::move(name))); + if constexpr (detail::sub_grid::is_sub_grid_v) { + using Bound = detail::sub_grid::BoundLoading>; + using Impl = detail::ReduceHostKernelImpl>; + return Kernel(std::make_shared(grid, Bound{grid, std::forward(loading)}, dst, + std::move(op), std::move(name))); + } else { + using Impl = detail::ReduceHostKernelImpl, T, std::decay_t>; + return Kernel(std::make_shared(grid, std::forward(loading), dst, std::move(op), + std::move(name))); + } } // Per-grid-family convenience members (Dense / Block / DenseDisg). Split into @@ -1117,9 +1261,27 @@ class TypedLatticeHaloFactory final : public HaloFactoryBase { } // namespace detail +namespace detail { + +template +concept HaloCapableField = requires(const Field& f) { + f.make_halo_kernel(std::string{}); +}; + +template +concept LatticeHaloCapableField = requires(const Field& f, Stencil s, StencilSemantic sem) { + f.make_halo_kernel(std::string{}, s, sem); +}; + +} // namespace detail + template auto KernelLoader::read_stencil(const Field& field) const { + static_assert(detail::HaloCapableField, + "KernelLoader::read_stencil: this field type has no halo (e.g. a SubGrid field), " + "so it cannot be stencil-read. Use read / write for same-cell access, or write " + "the values into a parent-grid field and stencil-read that one."); // Launch phase: no token, no halo factory — the make_shared + Field copy below // is exactly the per-launch overhead this split exists to eliminate. Return the // partition straight away (the only launch-relevant output of this call). @@ -1140,6 +1302,10 @@ auto KernelLoader::read_stencil(const Field& field, Stencil stencil, StencilSemantic semantic) const { + static_assert(detail::LatticeHaloCapableField, + "KernelLoader::read_stencil: this field type has no halo (e.g. a SubGrid field), " + "so it cannot be stencil-read. Use read / write for same-cell access, or write " + "the values into a parent-grid field and stencil-read that one."); if (phase_ != KernelLoaderPhase::Launch) { auto factory = std::make_shared>( field, std::move(stencil), semantic); diff --git a/include/carbon/reduce.h b/include/carbon/reduce.h index 5ab74562..b7a5bc16 100644 --- a/include/carbon/reduce.h +++ b/include/carbon/reduce.h @@ -36,8 +36,9 @@ * @c gpu_partial(view, g) . The loading lambda may also perform stencil reads and field * writes in the same launch (fused map/stencil + reduce). Backed by CUB/hipcub * (CUDA/HIP) or @c sycl::reduction (SYCL). With @ref ReduceFinalize::BlockAtomic , each - * CUDA/HIP block @c atomicAdd s into the per-GPU scalar and stage-1.5 @c DeviceReduce is - * skipped (floating-point sums may differ run-to-run vs the default path). + * CUDA/HIP block (SYCL work-group) atomically adds into the per-GPU scalar and stage-1.5 + * @c DeviceReduce is skipped (floating-point sums may differ run-to-run vs the default + * path). * 2. @b Stage-2 (intra-process combine). Per-GPU partials are peer-copied into the * rank-local root GPU's per-view stage-2 staging buffer and combined via the user's * @c Op into @c device_data(view) . Skipped when @c gpu_count == 1 (the per-GPU @@ -193,11 +194,11 @@ enum class ReduceFinalize : unsigned char { /** Block partials array + @c cub::DeviceReduce::Reduce (default). */ DeviceReduce = 0, /** - * Each CUDA/HIP block @c atomicAdd s its block sum into the per-GPU output scalar - * (NVIDIA @c jacobi_kernel style). Skips @c DeviceReduce on the partials buffer. - * Only supported with @ref Sum and @c T in @c {float, double, int32_t, int64_t} on - * plain @c Dense CUDA/HIP grids. Floating-point sums are not bitwise-deterministic across - * launches (atomic add order varies). + * Each CUDA/HIP block (SYCL work-group) atomically adds its block sum into the per-GPU + * output scalar (NVIDIA @c jacobi_kernel style). Skips @c DeviceReduce on the partials + * buffer. Only supported with @ref Sum and @c T in @c {float, double, int32_t, int64_t} on + * plain @c Dense / @c DenseDistributed grids. Floating-point sums are not + * bitwise-deterministic across launches (atomic add order varies). */ BlockAtomic = 1, }; @@ -736,25 +737,10 @@ class ReductionResult { detail::gpu_error_string(err)); } #elif CARBON_BACKEND_IS_SYCL - - sycl::queue& q = stream[root].queue(); - - q.submit([&](sycl::handler& h) { - h.depends_on(evt.event()); - h.single_task([]() {}); - }); - - - // #ifdef _ACPP_ - // sycl::queue& q = stream[root].queue(); - // q.AdaptiveCpp_enqueue_custom_operation([](sycl::interop_handle& h) {},evt.event()); - // #else - // sycl::queue& q = stream[root].queue(); - // q.submit([&](sycl::handler& h) { - // h.depends_on(evt.event()); - // }); - // #endif - + (void)stream[root].queue().AdaptiveCpp_enqueue_custom_operation( + [](sycl::interop_handle&) { + }, + std::vector{evt.event()}); #else (void)view; (void)slot; @@ -780,17 +766,9 @@ class ReductionResult { detail::gpu_error_string(err)); } #elif CARBON_BACKEND_IS_SYCL - sycl::queue& q = stream[root].queue(); - - sycl::event e = q.single_task([](){}); - - // #ifdef __ACPP__ - // auto e = q.AdaptiveCpp_enqueue_custom_operation([](sycl::interop_handle& h) {}); - // #else - // auto e = q.submit([](sycl::handler& h) {}); - // #endif - - *const_cast(&evt) = detail::Event(std::make_shared(e)); + evt.event() = + stream[root].queue().AdaptiveCpp_enqueue_custom_operation([](sycl::interop_handle&) { + }); #else (void)view; (void)slot; diff --git a/include/carbon/region_mask.h b/include/carbon/region_mask.h new file mode 100644 index 00000000..490b03e2 --- /dev/null +++ b/include/carbon/region_mask.h @@ -0,0 +1,284 @@ +#pragma once + +/** + * @file region_mask.h + * @brief @c carbon::RegionMask — a 256-bit, user-defined sub-domain label set that refines + * @ref AccessToken dependencies below whole-field granularity. + * + * The user owns the meaning of every bit: bit @c b names a cell set @c R(b) of the domain + * (a set of boundary-condition voxels, the lower half of the domain, ...). Carbon never + * learns the geometry; it only relies on the contract below to decide that two accesses to + * the same field cannot touch the same cells, so the @ref Skeleton may run them concurrently. + * + * @par Contract + * - **Bits are atoms.** The sets @c R(b) must be pairwise disjoint, and @c R(M) is the union + * of @c R(b) over the bits set in @c M . Under that rule, masks that do not intersect name + * disjoint cell sets. + * - **All ones is the whole field**, including any cell no bit covers. It is the default + * footprint of every access, so a pipeline that never names a mask behaves exactly as + * before. + * - Recommended: make the bits a full partition (every cell in exactly one bit, e.g. bit 0 + * for "everything else"), so @c ~M really means "the rest of the domain". 256 bits is the + * range of a @c uint8_t , so a per-cell @c uint8_t label field filtered with + * @ref test(std::uint8_t) gives that partition for free. + * - Masks are a declaration, not a launch restriction: a kernel declared on @c M must only + * touch cells in @c R(M) , and must filter itself. + * + * Default construction yields the empty mask (like @c std::bitset ); use @ref all for the + * whole field. + */ + +#include +#include + +#include +#include +#include +#include +#include + +namespace carbon { + +class RegionMask { +public: + static constexpr unsigned kBits = 256U; + static constexpr unsigned kWords = kBits / 64U; + + /** Empty mask (no bit set). */ + constexpr RegionMask() noexcept = default; + + /** + * @brief Mask with exactly the listed bits set, e.g. @c RegionMask{0, 3, 7} . + * @throws std::out_of_range if any bit is @c >= kBits . + */ + constexpr RegionMask(std::initializer_list bits) { + for (const unsigned b : bits) { + set(b); + } + } + + [[nodiscard]] CARBON_HD static constexpr auto + all() noexcept -> RegionMask { + RegionMask m; + for (unsigned i = 0; i < kWords; ++i) { + m.w_[i] = ~std::uint64_t{0}; + } + return m; + } + + [[nodiscard]] CARBON_HD static constexpr auto + none() noexcept -> RegionMask { + return RegionMask{}; + } + + /** + * @brief Single-bit mask. + * @throws std::out_of_range if @p b is @c >= kBits . + */ + [[nodiscard]] static constexpr auto + bit(unsigned b) -> RegionMask { + RegionMask m; + m.set(b); + return m; + } + + /** + * @brief Bits in the half-open range @c [lo, hi) . An empty range yields the empty mask. + * @throws std::out_of_range if @p lo > @p hi or @p hi > kBits . + */ + [[nodiscard]] static constexpr auto + range(unsigned lo, + unsigned hi) -> RegionMask { + if (lo > hi || hi > kBits) { + throw std::out_of_range("RegionMask::range: requires lo <= hi <= 256"); + } + RegionMask m; + for (unsigned b = lo; b < hi; ++b) { + m.w_[b / 64U] |= std::uint64_t{1} << (b % 64U); + } + return m; + } + + /** Single-bit mask for a per-cell @c uint8_t label; always in range. */ + [[nodiscard]] CARBON_HD static constexpr auto + from_label(std::uint8_t label) noexcept -> RegionMask { + RegionMask m; + m.w_[label / 64U] = std::uint64_t{1} << (label % 64U); + return m; + } + + /** + * @brief Set bit @p b . + * @throws std::out_of_range if @p b is @c >= kBits . + */ + constexpr auto + set(unsigned b) -> RegionMask& { + check_bit_(b); + w_[b / 64U] |= std::uint64_t{1} << (b % 64U); + return *this; + } + + /** + * @brief Clear bit @p b . + * @throws std::out_of_range if @p b is @c >= kBits . + */ + constexpr auto + reset(unsigned b) -> RegionMask& { + check_bit_(b); + w_[b / 64U] &= ~(std::uint64_t{1} << (b % 64U)); + return *this; + } + + /** Whether bit @p b is set; @c false for any @p b @c >= kBits . */ + [[nodiscard]] CARBON_HD constexpr auto + test(unsigned b) const noexcept -> bool { + return b < kBits && ((w_[b / 64U] >> (b % 64U)) & std::uint64_t{1}) != 0U; + } + + /** Whether the bit named by a per-cell @c uint8_t label is set. */ + [[nodiscard]] CARBON_HD constexpr auto + test(std::uint8_t label) const noexcept -> bool { + return ((w_[label / 64U] >> (label % 64U)) & std::uint64_t{1}) != 0U; + } + + /** Whether the two masks share at least one bit — i.e. may name overlapping cells. */ + [[nodiscard]] CARBON_HD constexpr auto + intersects(const RegionMask& other) const noexcept -> bool { + for (unsigned i = 0; i < kWords; ++i) { + if ((w_[i] & other.w_[i]) != 0U) { + return true; + } + } + return false; + } + + [[nodiscard]] CARBON_HD constexpr auto + empty() const noexcept -> bool { + for (unsigned i = 0; i < kWords; ++i) { + if (w_[i] != 0U) { + return false; + } + } + return true; + } + + [[nodiscard]] CARBON_HD constexpr auto + is_all() const noexcept -> bool { + for (unsigned i = 0; i < kWords; ++i) { + if (w_[i] != ~std::uint64_t{0}) { + return false; + } + } + return true; + } + + /** Number of bits set. */ + [[nodiscard]] CARBON_HD constexpr auto + count() const noexcept -> unsigned { + unsigned n = 0; + for (unsigned i = 0; i < kWords; ++i) { + for (std::uint64_t v = w_[i]; v != 0U; v &= v - 1U) { + ++n; + } + } + return n; + } + + /** Raw 64-bit word @p i (bit @c b lives in word @c b/64 at position @c b%64 ). */ + [[nodiscard]] CARBON_HD constexpr auto + word(unsigned i) const noexcept -> std::uint64_t { + return i < kWords ? w_[i] : 0U; + } + + CARBON_HD constexpr auto + operator&=(const RegionMask& o) noexcept -> RegionMask& { + for (unsigned i = 0; i < kWords; ++i) { + w_[i] &= o.w_[i]; + } + return *this; + } + + CARBON_HD constexpr auto + operator|=(const RegionMask& o) noexcept -> RegionMask& { + for (unsigned i = 0; i < kWords; ++i) { + w_[i] |= o.w_[i]; + } + return *this; + } + + CARBON_HD constexpr auto + operator^=(const RegionMask& o) noexcept -> RegionMask& { + for (unsigned i = 0; i < kWords; ++i) { + w_[i] ^= o.w_[i]; + } + return *this; + } + + [[nodiscard]] CARBON_HD constexpr auto + operator~() const noexcept -> RegionMask { + RegionMask m; + for (unsigned i = 0; i < kWords; ++i) { + m.w_[i] = ~w_[i]; + } + return m; + } + + [[nodiscard]] CARBON_HD friend constexpr auto + operator&(RegionMask a, + const RegionMask& b) noexcept -> RegionMask { + return a &= b; + } + + [[nodiscard]] CARBON_HD friend constexpr auto + operator|(RegionMask a, + const RegionMask& b) noexcept -> RegionMask { + return a |= b; + } + + [[nodiscard]] CARBON_HD friend constexpr auto + operator^(RegionMask a, + const RegionMask& b) noexcept -> RegionMask { + return a ^= b; + } + + [[nodiscard]] CARBON_HD friend constexpr auto + operator==(const RegionMask& a, + const RegionMask& b) noexcept -> bool { + for (unsigned i = 0; i < kWords; ++i) { + if (a.w_[i] != b.w_[i]) { + return false; + } + } + return true; + } + + [[nodiscard]] CARBON_HD friend constexpr auto + operator!=(const RegionMask& a, + const RegionMask& b) noexcept -> bool { + return !(a == b); + } + +private: + static constexpr auto + check_bit_(unsigned b) -> void { + if (b >= kBits) { + throw std::out_of_range("RegionMask: bit index must be < 256"); + } + } + + // Plain array rather than std::array: the type is captured by value into device lambdas + // and must stay usable from CUDA / HIP / SYCL device code without relaxed-constexpr. + std::uint64_t w_[kWords]{}; +}; + +static_assert(std::is_trivially_copyable_v); +static_assert(sizeof(RegionMask) == 32U); + +/** + * @brief Human-readable form used by diagnostics and the DOT exporters: @c "all" , + * @c "none" , or a compressed bit list such as @c "{0,3,5-9}" . + */ +[[nodiscard]] CARBON_API auto +to_string(const RegionMask& mask) -> std::string; + +} // namespace carbon diff --git a/include/carbon/skeleton.h b/include/carbon/skeleton.h index df561f8e..2fb484c8 100644 --- a/include/carbon/skeleton.h +++ b/include/carbon/skeleton.h @@ -18,6 +18,12 @@ * conflicting pair contributes an edge in the @ref edges adjacency list. * Read-Read pairs on the same field do not conflict, so two kernels reading * the same field can be parallelised. + * - **Region masks.** Each token also carries a user-defined @ref RegionMask + * (default all ones). Accesses whose masks do not intersect touch disjoint cells, so a + * kernel on region A and a kernel on region B of the same field carry no edge and can + * land on different streams. Stencil reads, halos and reduction scalars stay all ones. + * @ref Options::ignore_region_masks (or @c CARBON_IGNORE_REGION_MASKS=1 ) restores + * whole-field dependencies for A/B checks. * - **Transitive reduction.** After the conflict scan, @ref compile derives * @ref min_edges — the unique minimum DAG covering the same partial order * as @ref edges . An edge @c i→j is kept only when no longer path @@ -233,6 +239,14 @@ class CARBON_API Skeleton { bool use_cuda_graph; /** When @c High, streams carrying @c KernelKind::Halo steps use greatest driver priority. */ StreamPriority halo_stream_priority{StreamPriority::Normal}; + /** + * Treat every @ref AccessToken::mask as @ref RegionMask::all , i.e. fall back to + * whole-field dependencies. Recovers the schedule the pipeline would get without region + * masks, so results can be A/B compared to catch a mask that does not match what a + * kernel really touches. Also forced on by the environment variable + * @c CARBON_IGNORE_REGION_MASKS=1 . + */ + bool ignore_region_masks{false}; constexpr Options() noexcept : overlap_mode(OverlapMode::None), @@ -347,7 +361,8 @@ class CARBON_API Skeleton { * 1. **Conflict scan.** O(N²) pair-conflict scan over @ref effective_kernels * (typical N is 5–20 so cheap); emits directed edge @c i→j whenever * the kernel pair @c (i, j) shares a @c field_uid with conflicting - * modes. Read-Read is the only no-conflict pair. + * modes and intersecting @ref AccessToken::mask footprints. Read-Read is the + * only no-conflict mode pair; disjoint masks never conflict. * 2. **Stream assignment.** Greedy walk in topological order: kernel * @c k goes on a stream whose tail is a direct predecessor of @c k * (FIFO ordering covers the dep, no event needed); else on the @@ -458,6 +473,7 @@ class CARBON_API Skeleton { graph_.reset(); graph_disabled_ = false; captured_view_ = DataView::Standard; + rank_consistency_checked_ = false; compiled_ = false; } @@ -577,6 +593,16 @@ class CARBON_API Skeleton { return options_; } + /** + * @brief Whether the last @ref compile honoured @ref AccessToken::mask footprints + * (@c false when @ref Options::ignore_region_masks or + * @c CARBON_IGNORE_REGION_MASKS=1 forced whole-field dependencies). + */ + [[nodiscard]] auto + region_masks_honoured() const noexcept -> bool { + return region_masks_honoured_; + } + /** * @brief Effective kernel list — user kernels plus auto-inserted halos. * @@ -849,16 +875,31 @@ class CARBON_API Skeleton { event_annotation_(size_t event_idx) const -> std::string; /** - * @brief Test whether any token in @p a conflicts with any token in @p b on - * the same @c field_uid . Linear scan over both vectors — fine for - * the small per-kernel token counts (1–4) typical of carbon kernels. + * @brief Test whether two tokens conflict: same @c field_uid , conflicting modes and — + * unless @p honour_masks is @c false — intersecting @ref AccessToken::mask . + */ + [[nodiscard]] static auto + token_conflicts_(const AccessToken& a, + const AccessToken& b, + bool honour_masks) noexcept -> bool { + if (honour_masks) { + return conflicts(a, b); + } + return a.field_uid == b.field_uid && conflicts(a.mode, b.mode); + } + + /** + * @brief Test whether any token in @p a conflicts with any token in @p b (see + * @ref token_conflicts_ ). Linear scan over both vectors — fine for the small + * per-kernel token counts (1–4) typical of carbon kernels. */ [[nodiscard]] static auto pair_conflicts_(const std::vector& a, - const std::vector& b) noexcept -> bool { + const std::vector& b, + bool honour_masks) noexcept -> bool { for (const AccessToken& ta : a) { for (const AccessToken& tb : b) { - if (ta.field_uid == tb.field_uid && conflicts(ta.mode, tb.mode)) { + if (token_conflicts_(ta, tb, honour_masks)) { return true; } } @@ -908,6 +949,33 @@ class CARBON_API Skeleton { auto compile_validate_no_stencil_writes_() -> void; + /** + * @brief Region-mask checks run before the conflict scan: resolve + * @ref region_masks_honoured_ from @ref Options::ignore_region_masks and + * @c CARBON_IGNORE_REGION_MASKS , and warn once per kernel whose token carries an + * empty @ref RegionMask (sound — it conflicts with nothing — but usually a bug). + */ + auto + compile_validate_region_masks_() -> void; + + /** + * @brief Under MPI, require every rank to have added the same pipeline shape. + * + * Hashes the effective kernel list (kinds, token modes / patterns / resources / masks, + * fields by first-appearance index — raw uids are process-local addresses) plus the + * schedule-shaping options, and compares it across ranks with one collective. A mismatch + * (e.g. a rank-dependent @ref RegionMask ) would give ranks different schedules and + * therefore a different NCCL issue order, which deadlocks; this turns that into a + * @c std::logic_error thrown on every rank. + * + * Runs from @ref run (once per compile), not from @ref compile : @c compile also runs + * lazily from the exporters, which user code may call on one rank only. Skipped without a + * @c Distributed handle and for pipelines with no Halo / Reduction kernel, which are the + * only ones already collective — a rank-local skeleton never blocks. + */ + auto + check_rank_consistency_() const -> void; + /** * @brief Phase 0 of @ref compile : build @ref effective_kernels_ + * @ref effective_to_user_ from the user-added @ref kernels_ , @@ -1101,6 +1169,10 @@ class CARBON_API Skeleton { // the pipeline. std::unordered_map field_label_overrides_{}; bool compiled_{false}; + // Resolved by compile_validate_region_masks_ on every compile(). + bool region_masks_honoured_{true}; + // Cleared by compile(); set by the first run() after check_rank_consistency_. + bool rank_consistency_checked_{false}; // CUDA/HIP graph capture state (Options::use_cuda_graph). graph_ holds the // instantiated executable graph once captured; captured_view_ records the diff --git a/include/carbon/sub_grid.h b/include/carbon/sub_grid.h new file mode 100644 index 00000000..f55d8ec4 --- /dev/null +++ b/include/carbon/sub_grid.h @@ -0,0 +1,582 @@ +#pragma once + +/** + * @file sub_grid.h + * @brief @c carbon::SubGrid — a packed subset of a parent grid's cells with its own compact + * fields, built from a parent grid plus a cell selection plus a @ref RegionMask . + * + * A SubGrid @c S over a parent grid @c G stores only the selected cells. Each GPU holds a lane + * table mapping lane @c 0..count-1 to a parent cell; S fields are packed arrays indexed by + * lane, and S kernels launch one thread per lane instead of one per parent cell. + * + * - @b Types. @c S::Span derives from @c G::Span and @c S::Idx from @c G::Idx , so inside an + * S kernel @c uG.read(s, i, 0) reads a parent field at the lane's parent cell with no + * conversion code, while @c uS.read(s, i, 0) reads the packed S field at the lane. + * - @b DataView . Lanes are ordered parent-Internal cells first, then parent-Boundary cells, + * so every view is one contiguous lane range and S kernels can be OCC-split like parent + * kernels (see @ref detail::sub_grid::Lanes ). + * - @b Region mask. The @ref RegionMask passed at construction is the footprint S kernels + * declare on parent fields. It must cover every selected cell (the label constructor + * guarantees this by deriving the selection from the mask). + * - @b No halo. S fields support same-cell access only; stencils belong on parent fields. + * + * A SubGrid is immutable: the selection is evaluated once, at construction. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace carbon { + +namespace detail::sub_grid { + +struct Builder; + +} // namespace detail::sub_grid + +/** + * Packed subset of a parent grid @p G ( @ref Dense or @ref Block ). Build one with + * @c Dense::new_sub_grid or @c Block::new_sub_grid ; see the file comment for the model. + * + * Shallow handle: copies share the lane tables, which stay alive as long as any copy or any + * field built from it does. + */ +template +class SubGrid { + static_assert(!detail::sub_grid::is_sub_grid_v, + "carbon::SubGrid: a SubGrid of a SubGrid is not supported."); + static_assert(detail::sub_grid::is_sub_grid_v || detail::sub_grid::has_parent_traits_v, + "carbon::SubGrid: the parent grid must be carbon::Dense or carbon::Block."); + +public: + using Parent = G; + using Span = detail::sub_grid::Span; + using Idx = detail::sub_grid::Idx; + using Lanes = detail::sub_grid::Lanes; + + template + using Partition = detail::sub_grid::Partition; + + template + using Field = detail::sub_grid::Field; + + /** Empty placeholder: no parent, no GPUs, no lanes. */ + SubGrid() = default; + + [[nodiscard]] auto + parent() const -> const G& { + return st_().parent; + } + + [[nodiscard]] auto + name() const -> const std::string& { + return st_().name; + } + + /** Footprint S kernels declare on parent fields. */ + [[nodiscard]] auto + mask() const -> const RegionMask& { + return st_().mask; + } + + [[nodiscard]] auto + gpu_count() const noexcept -> size_t { + return state_ ? state_->count.size() : 0U; + } + + /** The parent's @ref System (devices, streams, events). */ + [[nodiscard]] auto + system() const -> const System& { + return st_().parent.system(); + } + + /** Identity of this SubGrid (shared by its copies); S partitions carry it as their owner. */ + [[nodiscard]] auto + uid() const noexcept -> std::uint64_t { + return static_cast(reinterpret_cast(state_.get())); + } + + /** One span per GPU whose lane table lives in device memory (device kernels). */ + [[nodiscard]] auto + spans() const -> const std::vector& { + return st_().spans; + } + + /** One span per GPU whose lane table lives in host memory (host kernels, inspection). */ + [[nodiscard]] auto + host_spans() const -> const std::vector& { + return st_().host_spans; + } + + /** Selected cells on GPU @p gpu . @throws std::out_of_range for a bad @p gpu . */ + [[nodiscard]] auto + count(size_t gpu) const -> int64_t { + return st_().count.at(gpu); + } + + /** Selected cells on GPU @p gpu that lie in the parent's Internal region. */ + [[nodiscard]] auto + internal_count(size_t gpu) const -> int64_t { + return st_().internal_count.at(gpu); + } + + /** Selected cells on GPU @p gpu that lie in the parent's Boundary region. */ + [[nodiscard]] auto + boundary_count(size_t gpu) const -> int64_t { + return count(gpu) - internal_count(gpu); + } + + /** Selected cells summed over the local GPUs. */ + [[nodiscard]] auto + total_count() const noexcept -> int64_t { + int64_t total = 0; + if (state_) { + for (const int64_t n : state_->count) { + total += n; + } + } + return total; + } + + /** Parent cell of @p lane on GPU @p gpu (host lane table). @throws std::out_of_range . */ + [[nodiscard]] auto + parent_idx(size_t gpu, + int64_t lane) const -> const typename G::Idx& { + const int64_t n = count(gpu); + if (lane < 0 || lane >= n) { + log::throw_with_log( + "SubGrid::parent_idx: lane {} out of range [0, {}) on gpu {}", lane, n, gpu); + } + return st_().host_spans[gpu].sub().parent_idx(lane); + } + + /** Global coordinates of the parent cell of @p lane on GPU @p gpu . */ + [[nodiscard]] auto + global_location(size_t gpu, + int64_t lane) const -> int64_3d { + return st_().host_spans[gpu].global_location(parent_idx(gpu, lane)); + } + + /** + * @brief Allocates a packed field: per GPU, @c Components planes of @c count(gpu) elements. + * + * @p side has the same meaning as for @c Dense::newField , except that a @c HostDevice + * mirror is allocated eagerly. Partitions bind the device side when present. + * + * @throws std::runtime_error when the SubGrid has no GPUs. + */ + template + [[nodiscard]] auto + newField(MemorySide side = MemorySide::Device, + std::string name = {}) const -> Field { + using P = Partition; + const State& st = st_(); + const size_t n = st.count.size(); + if (n == 0U) { + log::throw_with_log( + "SubGrid::newField: gpu_count is zero; cannot allocate field buffers"); + } + const System& sys = st.parent.system(); + const auto counts = sys.make_vector([&](size_t i) { + return static_cast(st.count[i]) * static_cast(Components); + }); + Buffer gpu_buffers{}; + if (has_device(side)) { + gpu_buffers = sys.gpu_group().template buffer(counts); + } + Buffer cpu_buffers{}; + if (has_host(side)) { + auto host_allocs = sys.make_vector([&](size_t i) { + return Cpu::buffer(counts[i]); + }); + cpu_buffers = detail::BufferGroup::from_vector(std::move(host_allocs)); + } + const std::uint64_t owner = uid(); + auto parts = sys.make_vector([&](size_t i) { + T* const ptr = has_device(side) ? gpu_buffers[i].data() : cpu_buffers[i].data(); + return P(ptr, owner); + }); + std::vector

host_parts; + if (has_host(side)) { + host_parts = sys.make_vector([&](size_t i) { + return P(cpu_buffers[i].data(), owner); + }); + } + return Field(*this, std::move(gpu_buffers), std::move(cpu_buffers), + std::move(parts), std::move(host_parts), side, std::move(name)); + } + + /** + * @brief Builds a device compute @ref Kernel that runs one thread per lane. + * + * Same loading-lambda shape as @c Dense::make_kernel ; the per-cell callable takes + * @c (SubGrid::Span, SubGrid::Idx) . Inside it: + * - @c uS.read(s, i, c) / @c uS.write(s, i, c, v) access a field of this SubGrid; + * - @c uG.read(s, i, c) / @c uG.write(...) access a parent field at the lane's parent + * cell (the SubGrid span and index convert to the parent's); + * - a parent field loaded with @c read_stencil may be read at neighbours of that cell + * through the parent's halo. SubGrid fields cannot be stencil-read (compile error). + * + * The kernel-wide region is preset to @ref mask , and loading a field of another SubGrid + * throws here, at construction. @c Kernel::launch(stream, view) runs the lanes of @p view ; + * the @ref Skeleton OCC-splits the kernel like a parent-grid one when it stencil-reads a parent + * field after a halo. Call from a device translation unit. + */ + template + [[nodiscard]] auto + make_kernel(L&& loading_fn, + size_t shared_mem = 0U) const -> Kernel { + return make_kernel(std::forward(loading_fn), std::string{}, shared_mem); + } + + /** @ref make_kernel with a diagnostic @p name (logs, Skeleton DOT labels). */ + template + [[nodiscard]] auto + make_kernel(L&& loading_fn, + std::string name, + size_t shared_mem = 0U) const -> Kernel { + using Impl = detail::sub_grid::DeviceKernelImpl>; + return Kernel::from_impl( + std::make_shared(*this, std::forward(loading_fn), shared_mem, std::move(name))); + } + + /** + * @brief Host (OpenMP) twin of @ref make_kernel over the host lane tables. Every field + * the loader touches needs a host mirror. + * + * With a @ref Block parent the span's topology (bitmask, connectivity, origins) is the + * parent's host copy, which covers owned bricks only: a parent @c neighbour read must not + * cross into another GPU's slab (same rule as @c Block::make_host_kernel ). + */ + template + [[nodiscard]] auto + make_host_kernel(L&& loading_fn, + std::string name = {}) const -> Kernel { + using Impl = detail::sub_grid::HostKernelImpl>; + return Kernel::from_impl( + std::make_shared(*this, std::forward(loading_fn), std::move(name))); + } + + /** + * @brief Device reduction over the lanes: the per-cell callable returns the lane's + * contribution, @c CARBON_HD (SubGrid::Span, SubGrid::Idx) -> T . + * + * Same pipeline and options as @c Dense::make_reduce_kernel (multi-GPU combine, + * cross-rank stage, @c ReduceFinalize::BlockAtomic , deferred host copy) except + * @c ReduceOptions::stage1_threads , which throws. The loader rules of @ref make_kernel + * apply, and a reduction that stencil-reads a parent field after its halo is OCC-split + * into Internal / Boundary partials plus a merge. Use @c Kernel::reduce for a name. + */ + template > + [[nodiscard]] auto + make_reduce_kernel(L&& loading_fn, + ReductionResult& dst, + Op op = {}, + size_t shared_mem = 0U, + reduce::ReduceOptions options = {}) const -> Kernel { + return Kernel::reduce(*this, std::forward(loading_fn), dst, std::move(op), {}, shared_mem, + options); + } + + /** Host (OpenMP) twin of @ref make_reduce_kernel ; fields need host mirrors. */ + template > + [[nodiscard]] auto + make_host_reduce_kernel(L&& loading_fn, + ReductionResult& dst, + Op op = {}) const -> Kernel { + return Kernel::host_reduce(*this, std::forward(loading_fn), dst, std::move(op), {}); + } + + /** Reduction launchable on the device ( @c launch ) or the host ( @c launch_on_host ). */ + template > + [[nodiscard]] auto + make_universal_reduce_kernel(L&& loading_fn, + ReductionResult& dst, + Op op = {}, + size_t shared_mem = 0U) const -> Kernel { + return Kernel::reduce_universal(*this, std::forward(loading_fn), dst, std::move(op), {}, + shared_mem); + } + +private: + friend struct detail::sub_grid::Builder; + + struct State { + G parent{}; + RegionMask mask{RegionMask::all()}; + std::string name{}; + Buffer device_tables{}; + Buffer host_tables{}; + std::vector count{}; + std::vector internal_count{}; + std::vector spans{}; + std::vector host_spans{}; + }; + + explicit SubGrid(std::shared_ptr state) + : state_(std::move(state)) {} + + [[nodiscard]] auto + st_() const -> const State& { + if (!state_) { + log::throw_with_log("SubGrid: empty (default-constructed) SubGrid"); + } + return *state_; + } + + std::shared_ptr state_{}; +}; + +namespace detail::sub_grid { + +/** + * Builds a @ref SubGrid from per-GPU host selection flags laid out like a one-component + * parent field (non-zero = selected; see @c ParentTraits::flag_offset ). + * + * Lane order is the parent's own iteration order, Internal view first and Boundary view + * second (@c ParentTraits::for_each_cell ), so the Internal / Boundary split is the parent's + * by construction and the table is deterministic. Only valid parent cells are visited, and + * their flag is read after that check: flags of other cells may be uninitialised. + */ +struct Builder { + template + [[nodiscard]] static auto + from_host_flags(const G& parent, + const std::vector& flags, + const RegionMask& mask, + std::string name) -> SubGrid { + using S = SubGrid; + using PIdx = typename G::Idx; + using State = typename S::State; + using Traits = ParentTraits; + + const size_t n = parent.spans().size(); + if (flags.size() != n) { + log::throw_with_log("SubGrid: {} flag buffers for {} GPUs", + flags.size(), n); + } + + auto state = std::make_shared(); + state->parent = parent; + state->mask = mask; + state->name = std::move(name); + + // Host spans must reference the State's own copy of the parent: they outlive `parent`. + std::vector parent_host_spans; + parent_host_spans.reserve(n); + for (size_t g = 0; g < n; ++g) { + parent_host_spans.push_back(Traits::host_span(state->parent, g)); + } + + std::vector> selected(n); + for (size_t g = 0; g < n; ++g) { + const auto& span = parent_host_spans[g]; + const std::uint8_t* f = flags[g]; + auto& out = selected[g]; + for (const DataView view : {DataView::Internal, DataView::Boundary}) { + Traits::for_each_cell(span, view, [&](const PIdx& idx) { + if (f[Traits::flag_offset(span, idx)] != 0U) { + out.push_back(idx); + } + }); + if (view == DataView::Internal) { + state->internal_count.push_back(static_cast(out.size())); + } + } + state->count.push_back(static_cast(out.size())); + } + + System sys = parent.system(); + auto host_allocs = sys.make_vector([&](size_t g) { + auto a = Cpu::buffer(selected[g].size()); + for (size_t k = 0; k < selected[g].size(); ++k) { + a.data()[k] = selected[g][k]; + } + return a; + }); + state->host_tables = BufferGroup::from_vector(std::move(host_allocs)); + const auto counts = sys.make_vector([&](size_t g) { + return selected[g].size(); + }); + state->device_tables = sys.gpu_group().template buffer(counts); + Stream stream = sys.stream(); + Transfer upload(sys, state->host_tables, state->device_tables); + upload(stream); + stream.wait(); + + const auto owner = static_cast(reinterpret_cast(state.get())); + for (size_t g = 0; g < n; ++g) { + const int64_t cnt = state->count[g]; + const int64_t internal = state->internal_count[g]; + state->spans.emplace_back(state->parent.spans()[g], + Lanes(state->device_tables[g].data(), cnt, internal, owner)); + state->host_spans.emplace_back( + parent_host_spans[g], Lanes(state->host_tables[g].data(), cnt, internal, owner)); + } + + S result(std::shared_ptr(std::move(state))); + if (n > 0U && result.total_count() == 0) { + CARBON_LOG_WARN("SubGrid '{}': the selection is empty on every GPU", result.name()); + } + return result; + } +}; + +/** Per-cell body of the selection pass: writes 1 where @p predicate holds, else 0. */ +template +struct SelectFn { + Predicate predicate; + Out out; + + template + CARBON_HD auto + operator()(const SpanT& span, + const IdxT& idx) const -> void { + out.write(span, idx, 0, predicate(span, idx) ? std::uint8_t{1} : std::uint8_t{0}); + } +}; + +/** Selection predicate of the label constructor: the cell's label bit is in @c mask . */ +template +struct LabelPredicate { + LabelPartition labels; + RegionMask mask; + + template + [[nodiscard]] CARBON_HD auto + operator()(const SpanT& span, + const IdxT& idx) const -> bool { + return mask.test(labels.read(span, idx, 0)); + } +}; + +} // namespace detail::sub_grid + +template L> +auto +Dense::new_sub_grid(L&& select, + const RegionMask& mask, + std::string name) const -> SubGrid { + auto flags = newField(MemorySide::HostDevice, "sub_grid_select"); + const Kernel select_kernel = + make_kernel([select = std::forward(select), flags](KernelLoader& loader) { + auto predicate = select(loader); + auto out = loader.write(flags); + return detail::sub_grid::SelectFn{predicate, out}; + }); + System sys = system_; + Stream stream = sys.stream(); + select_kernel.launch(stream); + Transfer download(sys, flags.gpu_buffers(), flags.cpu_buffers()); + download(stream); + stream.wait(); + + std::vector host_flags; + host_flags.reserve(gpu_count()); + for (size_t g = 0; g < gpu_count(); ++g) { + host_flags.push_back(flags.cpu_buffers()[g].data()); + } + return detail::sub_grid::Builder::from_host_flags(*this, host_flags, mask, std::move(name)); +} + +template +auto +Dense::new_sub_grid(const Field& labels, + const RegionMask& mask, + std::string name) const -> SubGrid { + static_assert(std::is_same_v, + "Dense::new_sub_grid(labels, mask): labels must be a Dense::Field " + "(one RegionMask bit per label value)."); + return new_sub_grid( + [labels, mask](KernelLoader& loader) { + auto label_partition = loader.read(labels); + return detail::sub_grid::LabelPredicate{label_partition, mask}; + }, + mask, std::move(name)); +} + +template +template L> +auto +Block::new_sub_grid(L&& select, + const RegionMask& mask, + std::string name) const -> SubGrid { + // The Block launcher visits active voxels only, so flags of inactive voxels stay + // uninitialised; the Builder reads a flag only after checking the voxel is active. + auto flags = newField(MemorySide::Device, "sub_grid_select"); + const Kernel select_kernel = + make_kernel([select = std::forward(select), flags](KernelLoader& loader) { + auto predicate = select(loader); + auto out = loader.write(flags); + return detail::sub_grid::SelectFn{predicate, out}; + }); + System sys = system_; + Stream stream = sys.stream(); + select_kernel.launch(stream); + const auto owned_flags = download_to_host(flags, stream); + stream.wait(); + + std::vector host_flags; + host_flags.reserve(owned_flags.size()); + for (const auto& alloc : owned_flags) { + host_flags.push_back(alloc.data()); + } + return detail::sub_grid::Builder::from_host_flags(*this, host_flags, mask, std::move(name)); +} + +template +template +auto +Block::new_sub_grid(const Field& labels, + const RegionMask& mask, + std::string name) const -> SubGrid { + static_assert(std::is_same_v, + "Block::new_sub_grid(labels, mask): labels must be a Block::Field " + "(one RegionMask bit per label value)."); + return new_sub_grid( + [labels, mask](KernelLoader& loader) { + auto label_partition = loader.read(labels); + return detail::sub_grid::LabelPredicate{label_partition, mask}; + }, + mask, std::move(name)); +} + +} // namespace carbon diff --git a/libcarbonpy/src/cuda_driver.cpp b/libcarbonpy/src/cuda_driver.cpp index 56ddb765..6c88f835 100644 --- a/libcarbonpy/src/cuda_driver.cpp +++ b/libcarbonpy/src/cuda_driver.cpp @@ -957,7 +957,12 @@ append_dense_token(DenseContainer* container, return -1; } auto push = [&](auto* field) -> int { - carbon::AccessToken token{field->gpu_buffers().get_uid(), mode, pattern, field->name(), {}}; + carbon::AccessToken token{field->gpu_buffers().get_uid(), + carbon::ResourceKind::Field, + mode, + pattern, + field->name(), + {}}; if (pattern == carbon::AccessPattern::Stencil && (mode == carbon::AccessMode::Read || mode == carbon::AccessMode::ReadWrite)) { using FieldT = std::decay_t; @@ -988,7 +993,12 @@ append_block_token(BlockContainer* container, return -1; } auto push = [&](auto* field) -> int { - carbon::AccessToken token{field->gpu_buffers().get_uid(), mode, pattern, field->name(), {}}; + carbon::AccessToken token{field->gpu_buffers().get_uid(), + carbon::ResourceKind::Field, + mode, + pattern, + field->name(), + {}}; if (pattern == carbon::AccessPattern::Stencil && (mode == carbon::AccessMode::Read || mode == carbon::AccessMode::ReadWrite)) { using FieldT = std::decay_t; diff --git a/scripts/docker-build-all.sh b/scripts/docker-build-all.sh index 8a3f56b9..18741b08 100755 --- a/scripts/docker-build-all.sh +++ b/scripts/docker-build-all.sh @@ -25,11 +25,22 @@ # Usage: # scripts/docker-build-all.sh [--only NAME[,NAME...]] [--no-cache] # [--sm-arch SM] [--gfx-arch GFX] [--werror] -# [--skip-build-images] +# [--skip-build-images] [--docker-env KEY=VAL]... +# [--ctest-args "ARGS"] # # --werror Gate the libcarbon host compile warning-clean (-DCARBON_WERROR=ON) # on the `cuda` config. Used by the gpu-ci workflow; off by default # for local runs so a stray host-gcc warning never blocks the matrix. +# --docker-env KEY=VAL +# Forward KEY=VAL into every config's container (repeatable). E.g. +# `--docker-env NCCL_P2P_DISABLE=1` on hosts whose PCIe peer DMA is +# unusable, where NCCL's P2P transport hangs the distributed tests. +# The NVIDIA `*-mpi` configs always run with --ipc=host (NCCL/MPI +# shared-memory transports outgrow docker's 64 MiB /dev/shm). +# --ctest-args "ARGS" +# Extra arguments appended to the in-container `ctest +# --output-on-failure`, e.g. a repeat lane: +# `--ctest-args "-L gpu -E format_check --repeat until-fail:20"`. # # Examples: # # Build everything; run tests for whatever GPU is present. @@ -73,13 +84,17 @@ ONLY_FILTER="" # container toolchain. Off by default so a local matrix run is never blocked by a # stray warning from a newer/older host gcc; CI opts in via --werror. WERROR=0 +# `-e KEY=VAL` pairs from --docker-env, forwarded to every `docker run`. +DOCKER_ENV_ARGS=() +# Appended verbatim to the in-container ctest command (--ctest-args). +CTEST_ARGS="" # ---------------------------------------------------------------------------- # CLI # ---------------------------------------------------------------------------- usage() { - sed -n '2,30p' "$0" + sed -n '2,/^set -uo pipefail/p' "$0" | sed '$d' } while [ $# -gt 0 ]; do @@ -90,6 +105,8 @@ while [ $# -gt 0 ]; do --gfx-arch) GFX_ARCH="$2"; shift 2 ;; --werror) WERROR=1; shift ;; --skip-build-images) SKIP_BUILD_IMAGES=1; shift ;; + --docker-env) DOCKER_ENV_ARGS+=(-e "$2"); shift 2 ;; + --ctest-args) CTEST_ARGS="$2"; shift 2 ;; -h|--help) usage; exit 0 ;; *) echo "unknown arg: $1" >&2; usage; exit 2 ;; esac @@ -248,6 +265,9 @@ run_config() { nvidia) if [ "${NVIDIA_DOCKER_OK}" = "1" ]; then docker_gpu_args+=(--gpus all) + case "${name}" in + *-mpi) docker_gpu_args+=(--ipc=host) ;; + esac can_run_tests=1 fi ;; @@ -293,7 +313,7 @@ INNER_EOF ) container_script+=$'\n'"${format_check_cmd}" container_script+=$'\n'"if [ \"${can_run_tests}\" = \"1\" ]; then" - container_script+=$'\n'" ctest --output-on-failure" + container_script+=$'\n'" ctest --output-on-failure ${CTEST_ARGS}" container_script+=$'\n'"else" container_script+=$'\n'" echo '(no matching GPU on host — skipping ctest)'" container_script+=$'\n'"fi" @@ -305,6 +325,7 @@ INNER_EOF -e CARBON_CONFIG="${name}" \ -e CMAKE_FLAGS="${cmake_flags}" \ -e CARBON_TEST_STRICT="${CARBON_TEST_STRICT:-}" \ + "${DOCKER_ENV_ARGS[@]}" \ "${image}" \ /bin/bash -lc "${container_script}" 2>&1 | tee "${LOG_DIR}/run-${name}.log" diff --git a/src/distributed.cpp b/src/distributed.cpp index 0f8e5c28..6673d123 100644 --- a/src/distributed.cpp +++ b/src/distributed.cpp @@ -149,6 +149,15 @@ Distributed::broadcast(void* data, check_mpi("MPI_Bcast", MPI_Bcast(data, count, MPI_BYTE, root, MPI_COMM_WORLD)); } +auto +Distributed::all_ranks_equal(std::uint64_t value) const -> bool { + std::uint64_t lo = 0; + std::uint64_t hi = 0; + check_mpi("MPI_Allreduce", MPI_Allreduce(&value, &lo, 1, MPI_UINT64_T, MPI_MIN, MPI_COMM_WORLD)); + check_mpi("MPI_Allreduce", MPI_Allreduce(&value, &hi, 1, MPI_UINT64_T, MPI_MAX, MPI_COMM_WORLD)); + return lo == hi; +} + auto Distributed::pin_local_device() const -> int { using namespace carbon::detail::gpu_compat; diff --git a/src/region_mask.cpp b/src/region_mask.cpp new file mode 100644 index 00000000..2a7e9e86 --- /dev/null +++ b/src/region_mask.cpp @@ -0,0 +1,42 @@ +#include + +#include + +namespace carbon { + +auto +to_string(const RegionMask& mask) -> std::string { + if (mask.is_all()) { + return "all"; + } + if (mask.empty()) { + return "none"; + } + std::string out = "{"; + bool first = true; + unsigned b = 0; + while (b < RegionMask::kBits) { + if (!mask.test(b)) { + ++b; + continue; + } + unsigned end = b; + while (end + 1U < RegionMask::kBits && mask.test(end + 1U)) { + ++end; + } + if (!first) { + out += ','; + } + first = false; + out += std::to_string(b); + if (end > b) { + out += '-'; + out += std::to_string(end); + } + b = end + 1U; + } + out += '}'; + return out; +} + +} // namespace carbon diff --git a/src/skeleton.cpp b/src/skeleton.cpp index 85caf584..47540ed6 100644 --- a/src/skeleton.cpp +++ b/src/skeleton.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -31,6 +32,7 @@ #include #include +#include #include #include #include @@ -196,8 +198,12 @@ overlap_mode_label(carbon::OverlapMode mode) -> std::string_view { // Compact Options line for DOT titles (launch matrix / kernel list). [[nodiscard]] auto -skeleton_options_summary(const carbon::Skeleton::Options& opts) -> std::string { +skeleton_options_summary(const carbon::Skeleton::Options& opts, + bool region_masks_honoured) -> std::string { std::string out = "overlap=" + std::string{overlap_mode_label(opts.overlap_mode)}; + if (!region_masks_honoured) { + out += " · region_masks=ignored"; + } if (opts.halo_stream_priority == carbon::StreamPriority::High) { out += " · halo_priority=high"; } @@ -213,6 +219,26 @@ skeleton_options_summary(const carbon::Skeleton::Options& opts) -> std::string { return out; } +[[nodiscard]] auto +ignore_region_masks_from_env() -> bool { + const char* raw = std::getenv("CARBON_IGNORE_REGION_MASKS"); + if (raw == nullptr) { + return false; + } + std::string value(raw); + for (char& c : value) { + c = static_cast(std::tolower(static_cast(c))); + } + if (value == "1" || value == "on" || value == "yes" || value == "true") { + return true; + } + if (!value.empty() && value != "0" && value != "off" && value != "no" && value != "false") { + CARBON_LOG_WARN("Skeleton: unrecognised CARBON_IGNORE_REGION_MASKS value \"{}\"; ignoring it", + raw); + } + return false; +} + } // namespace namespace carbon::detail { @@ -315,12 +341,14 @@ Skeleton::compile() -> void { // Phase pre-0: contract validation (Stencil-pattern WRITEs are illegal). compile_validate_no_stencil_writes_(); + compile_validate_region_masks_(); // Phase 0: auto-halo insertion. Builds effective_kernels_ + // effective_to_user_ from kernels_ , inserting an auto-halo ahead of // every Stencil-read of a dirty field. compile_auto_insert_halos_(); compile_auto_insert_scalar_readbacks_(); + rank_consistency_checked_ = false; copy_stream_idx_ = kNoStream_; has_detached_stream_ = false; @@ -373,6 +401,23 @@ Skeleton::compile() -> void { compile_prune_syncs_(); + if (options_.use_cuda_graph && region_masks_honoured_ && streams_.size() > 1U) { + const bool masked = + std::any_of(effective_kernels_.begin(), effective_kernels_.end(), [](const Kernel& k) { + const auto& toks = k.impl()->tokens(); + return std::any_of(toks.begin(), toks.end(), [](const AccessToken& t) { + return !t.mask.is_all(); + }); + }); + if (masked) { + CARBON_LOG_INFO( + "Skeleton::compile: the schedule uses {} streams (region masks expose concurrency), so " + "use_cuda_graph falls back to eager launches; set Options::max_streams = 1 to keep a " + "capturable single-stream schedule.", + streams_.size()); + } + } + compiled_ = true; // A recompile rebuilds the schedule (and its streams / events / captured @@ -414,6 +459,84 @@ Skeleton::compile_validate_no_stencil_writes_() -> void { } } +auto +Skeleton::compile_validate_region_masks_() -> void { + region_masks_honoured_ = !options_.ignore_region_masks && !ignore_region_masks_from_env(); + + for (size_t k_idx = 0; k_idx < kernels_.size(); ++k_idx) { + const Kernel& k = kernels_[k_idx]; + for (const AccessToken& t : k.impl()->tokens()) { + if (t.mask.empty()) { + CARBON_LOG_WARN( + "Skeleton::compile: kernel '{}' (index={}) declares an empty RegionMask on field " + "'{}' (uid={}); the access conflicts with nothing. Intended only for a kernel that " + "touches no cell of that field.", + std::string{k.name()}, k_idx, + t.field_name.empty() ? std::string{""} : t.field_name, t.field_uid); + break; + } + } + } +} + +auto +Skeleton::check_rank_consistency_() const -> void { +#ifdef CARBON_HAVE_MPI_NCCL + const Distributed* dist = sys_.distributed(); + if (dist == nullptr || dist->world_size() <= 1) { + return; + } + // Only pipelines that are collective anyway (halo exchanges, cross-rank reductions) take + // part, so a rank-local skeleton never blocks in a collective its peers do not join. + const bool collective = + std::any_of(effective_kernels_.begin(), effective_kernels_.end(), [](const Kernel& k) { + const KernelKind kind = k.kind(); + return kind == KernelKind::Halo || kind == KernelKind::Reduction || + kind == KernelKind::ReductionHost || kind == KernelKind::UniversalReduction; + }); + if (!collective) { + return; + } + // FNV-1a over the pipeline shape. Field uids are process-local addresses, so each field is + // replaced by the index of its first appearance, which still captures which accesses alias. + std::uint64_t h = 1469598103934665603ULL; + auto mix = [&h](std::uint64_t v) { + for (int byte = 0; byte < 8; ++byte) { + h ^= (v >> (8 * byte)) & 0xFFU; + h *= 1099511628211ULL; + } + }; + mix(static_cast(options_.overlap_mode)); + mix(options_.max_streams); + mix(region_masks_honoured_ ? 1U : 0U); + mix(effective_kernels_.size()); + std::unordered_map canonical_uid; + for (const Kernel& k : effective_kernels_) { + mix(static_cast(k.kind())); + const auto& toks = k.impl()->tokens(); + mix(toks.size()); + for (const AccessToken& t : toks) { + const auto [it, inserted] = canonical_uid.try_emplace(t.field_uid, canonical_uid.size()); + mix(it->second); + mix(static_cast(t.resource)); + mix(static_cast(t.mode)); + mix(static_cast(t.pattern)); + for (unsigned w = 0; w < RegionMask::kWords; ++w) { + mix(t.mask.word(w)); + } + } + } + if (!dist->all_ranks_equal(h)) { + log::throw_with_log( + "Skeleton::run: ranks added different pipelines (kernel kinds, access modes, or " + "RegionMasks differ; this rank's hash is {:#x}). Every rank must build the same " + "schedule or NCCL collectives are issued in different orders and deadlock. Region " + "masks must not depend on the rank.", + h); + } +#endif +} + auto Skeleton::compile_auto_insert_halos_() -> void { effective_kernels_.clear(); @@ -570,7 +693,7 @@ Skeleton::compile_build_conflict_dag_() -> void { const auto& tok_i = effective_kernels_[i].impl()->tokens(); for (size_t j = i + 1; j < n; ++j) { const auto& tok_j = effective_kernels_[j].impl()->tokens(); - if (pair_conflicts_(tok_i, tok_j)) { + if (pair_conflicts_(tok_i, tok_j, region_masks_honoured_)) { edges_[i].push_back(j); } } @@ -1101,6 +1224,10 @@ Skeleton::compile_step_graph_occ_(const std::vector>& direct auto Skeleton::run(DataView view) -> void { compile(); + if (!rank_consistency_checked_) { + check_rank_consistency_(); + rank_consistency_checked_ = true; + } // CUDA/HIP graph fast path: capture the schedule once, replay it thereafter. // Only engaged for single-stream / single-GPU schedules on a capture-capable @@ -1805,7 +1932,8 @@ Skeleton::export_launch_matrix_dot(std::string graph_name) -> std::string { << "\"> launch matrix · " << num_streams << " stream" << (num_streams == 1U ? "" : "s") << " · " << ops.size() << " ops in run() order" << "" - << font(10, kMuted, skeleton_options_summary(options_)) << ""; + << font(10, kMuted, skeleton_options_summary(options_, region_masks_honoured_)) + << ""; swatch(kHaloPal, "rounded", "halo"); swatch(kInternalPal, "rounded", "internal"); swatch(kBoundaryPal, "rounded", "boundary"); @@ -2011,6 +2139,8 @@ Skeleton::export_kernel_list_dot(std::string graph_name) -> std::string { bool read{false}; bool write{false}; bool stencil{false}; + RegionMask read_mask{}; + RegionMask write_mask{}; }; std::vector resources; std::unordered_map resource_col; @@ -2022,8 +2152,14 @@ Skeleton::export_kernel_list_dot(std::string graph_name) -> std::string { resources.push_back({t.field_uid, t.resource}); } Access& a = access[i][it->second]; - a.read = a.read || t.mode != AccessMode::Write; - a.write = a.write || t.mode != AccessMode::Read; + if (t.mode != AccessMode::Write) { + a.read = true; + a.read_mask |= t.mask; + } + if (t.mode != AccessMode::Read) { + a.write = true; + a.write_mask |= t.mask; + } a.stencil = a.stencil || t.pattern == AccessPattern::Stencil; } } @@ -2113,6 +2249,22 @@ Skeleton::export_kernel_list_dot(std::string graph_name) -> std::string { body += " " + font(7, a.write ? "#f8c471" : kStencilColor, "stencil"); return html_box({p.fill, kStencilColor}, "rounded", 70, 18, body); }; + // Empty when the access covers the whole field (or masks are ignored), so unmasked + // pipelines render exactly as before. + auto region_note = [&](const Access& a) -> std::string { + const bool read_all = !a.read || a.read_mask.is_all(); + const bool write_all = !a.write || a.write_mask.is_all(); + if (!region_masks_honoured_ || (read_all && write_all)) { + return {}; + } + if (!a.write || (a.read && a.read_mask == a.write_mask)) { + return "region " + to_string(a.read_mask); + } + if (!a.read) { + return "region " + to_string(a.write_mask); + } + return "R " + to_string(a.read_mask) + " · W " + to_string(a.write_mask); + }; auto kernel_id = [](size_t i) { return "K" + std::to_string(i + 1U); }; @@ -2143,7 +2295,8 @@ Skeleton::export_kernel_list_dot(std::string graph_name) -> std::string { " · add order") << "" << "" - << font(10, kMuted, skeleton_options_summary(options_)) << ""; + << font(10, kMuted, skeleton_options_summary(options_, region_masks_honoured_)) + << ""; os << legend_swatch(kStandardPal, "rounded", "compute"); os << legend_swatch(kReductionPal, "rounded", "reduction"); os << legend_swatch(kHaloPal, "rounded", "halo"); @@ -2192,6 +2345,11 @@ Skeleton::export_kernel_list_dot(std::string graph_name) -> std::string { std::string inner; if (it != access[i].end()) { inner = access_chip(it->second); + const std::string note = region_note(it->second); + if (!note.empty()) { + inner = "
" + inner + + "
" + font(7, kMuted, note) + "
"; + } } os << cell(bg, kResourceW, inner); } @@ -2393,6 +2551,9 @@ Skeleton::export_dot(std::string graph_name) -> std::string { os << ", "; } os << escape(field_label(tokens[i])) << ":" << fmt_mode(tokens[i].mode); + if (region_masks_honoured_ && !tokens[i].mask.is_all()) { + os << " region " << escape(to_string(tokens[i].mask)); + } } os << "\""; } @@ -2417,7 +2578,7 @@ Skeleton::export_dot(std::string graph_name) -> std::string { const Kernel& succ_k = effective_kernels_[schedule_[succ_step].kernel_idx]; for (const AccessToken& ta : pred_k.impl()->tokens()) { for (const AccessToken& tb : succ_k.impl()->tokens()) { - if (ta.field_uid == tb.field_uid && conflicts(ta.mode, tb.mode)) { + if (token_conflicts_(ta, tb, region_masks_honoured_)) { return std::string{field_label(ta)}; } } diff --git a/src/system.cpp b/src/system.cpp index ec460d32..20d73e24 100644 --- a/src/system.cpp +++ b/src/system.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #ifdef CARBON_HAVE_MPI_NCCL #include @@ -133,6 +134,24 @@ System::async_copy(const detail::Allocation& src, #elif CARBON_BACKEND_IS_SYCL sycl::queue& q = stream[static_cast(rel)].queue(); try { + if (sl == detail::AllocationLocation::Cuda && dl == detail::AllocationLocation::Cuda && + src.gpu_id() != dst.gpu_id()) { + // AdaptiveCpp (25.02) records a USM memcpy between two devices as a device-to-device + // operation it may run on the source device's backend stream, and the in-order queue + // then stops ordering the next submission on q after it: the consumer can read the + // destination before the bytes land. Pin both edges with explicit events. + const sycl::event before = q.AdaptiveCpp_enqueue_custom_operation([](sycl::interop_handle&) { + }); + const sycl::event copied = q.submit([&](sycl::handler& cgh) { + cgh.depends_on(before); + cgh.memcpy(d, s, size_bytes); + }); + (void)q.AdaptiveCpp_enqueue_custom_operation( + [](sycl::interop_handle&) { + }, + std::vector{copied}); + return; + } auto ev = q.memcpy(d, s, size_bytes); if (sl == detail::AllocationLocation::Cpu && dl == detail::AllocationLocation::Cuda) { // AdaptiveCpp 25.02 may not pin the host source for H2D memcpy in a shared diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ffe81c6e..312fc510 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -78,24 +78,10 @@ function(carbon_add_cuda_unit_test name) HIP_STANDARD 20 HIP_STANDARD_REQUIRED ON) elseif(CARBON_BACKEND STREQUAL "Sycl") - # acpp / clang sniff the .cu extension regardless of CMake's LANGUAGE CXX setting and - # turn on offload modes that need a libomptarget-nvptx-sm_80.bc bitcode library we - # don't ship. The simplest workaround is to copy the source to a .cpp twin in the - # build tree before compilation; configure_file with COPYONLY does that and re-runs - # whenever the .cu changes (so an edit doesn't need a fresh configure). Nothing in - # the test source itself is .cu-specific (no <<<>>>, no __global__) — the .cu - # extension is only there to make CMake route through nvcc on the CUDA build. - set(_src "${CMAKE_CURRENT_BINARY_DIR}/${target}.cpp") - configure_file("${CMAKE_CURRENT_SOURCE_DIR}/${target}.cu" "${_src}" COPYONLY) - add_executable(${target} "${_src}") + # .cu -> .cpp twin; see cmake/CarbonSyclMirror.cmake. + carbon_add_sycl_mirrored_executable(${target} ${target}.cu) target_link_libraries(${target} PRIVATE carbon::carbon) - target_compile_features(${target} PRIVATE cxx_std_20) set_target_properties(${target} PROPERTIES BUILD_RPATH "${CMAKE_BINARY_DIR}") - add_sycl_to_target(TARGET ${target} SOURCES "${_src}") - if(CARBON_SYCL_TARGETS MATCHES "cuda") - target_compile_options(${target} PRIVATE --cuda-path=${CARBON_SYCL_CUDA_PATH}) - target_link_directories(${target} PRIVATE ${CARBON_SYCL_CUDA_PATH}/lib64) - endif() endif() add_test(NAME carbon_${name} COMMAND ${target}) # Compute tests in this list grab every visible CUDA device through @@ -150,6 +136,7 @@ carbon_add_unit_test(memory_side) # code (std::thread, no device), so it stays on the cpu lane. carbon_add_unit_test(atomic_host) carbon_add_unit_test(stencil) +carbon_add_unit_test(region_mask) carbon_add_unit_test(system_default_stream) carbon_add_unit_test(transfer) carbon_add_unit_test(halo_coalesce) @@ -202,6 +189,7 @@ carbon_add_cuda_unit_test(mgrid_locator) carbon_add_cuda_unit_test(render_sample) carbon_add_cuda_unit_test(reduce_ops) carbon_add_cuda_unit_test(reduce_sum_multi_gpu) +carbon_add_cuda_unit_test(reduce_partials_multi_gpu) carbon_add_cuda_unit_test(reduce_sum_host_multi_gpu) carbon_add_cuda_unit_test(kernel_polymorphic) carbon_add_cuda_unit_test(field_fill_host) @@ -296,6 +284,59 @@ carbon_add_cuda_unit_test(halo_host) carbon_add_cuda_unit_test(halo_disg_host) carbon_add_cuda_unit_test(overlapped_stencil) carbon_add_cuda_unit_test(skeleton) +carbon_add_cuda_unit_test(skeleton_region_mask) +carbon_add_cuda_unit_test(sub_grid) +carbon_add_cuda_unit_test(sub_grid_kernel) +carbon_add_cuda_unit_test(sub_grid_skeleton) +carbon_add_cuda_unit_test(sub_grid_reduce) +carbon_add_cuda_unit_test(sub_grid_block) +carbon_add_cuda_unit_test(sub_grid_jacobi_axpy) + +# SubGrid compile-time rules: each case is a target outside `all` that ctest builds and that +# must fail with the given diagnostic (case 0 is the control and must build). CUDA and HIP: +# the regexes match nvcc and clang wording; acpp's SYCL mirror is not wired up. Serialised +# because each entry re-enters the build tree. +if(CARBON_BACKEND STREQUAL "Cuda" OR CARBON_BACKEND STREQUAL "Hip") + if(CARBON_BACKEND STREQUAL "Hip") + set_source_files_properties(sub_grid_compile_fail.cu PROPERTIES LANGUAGE HIP) + endif() + set(_carbon_sub_grid_cf_cases + "0|" + "1|has no halo" + "2|no member.*neighbour" + "3|no instance of overloaded function|no matching (member )?function|no suitable" + "4|a SubGrid of a SubGrid is not supported" + "5|compute_universal: not supported for a SubGrid" + "6|has no halo" + "7|the parent grid must be carbon::Dense or carbon::Block") + foreach(_case IN LISTS _carbon_sub_grid_cf_cases) + string(FIND "${_case}" "|" _bar) + string(SUBSTRING "${_case}" 0 ${_bar} _id) + math(EXPR _rest "${_bar} + 1") + string(SUBSTRING "${_case}" ${_rest} -1 _regex) + set(_target "sub_grid_compile_fail_${_id}") + add_executable(${_target} EXCLUDE_FROM_ALL sub_grid_compile_fail.cu) + target_link_libraries(${_target} PRIVATE carbon::carbon) + target_compile_definitions(${_target} PRIVATE CARBON_CF_CASE=${_id}) + if(CARBON_BACKEND STREQUAL "Hip") + if(CARBON_HIP_NVCC) + target_compile_options(${_target} PRIVATE $<$:${CARBON_NVCC_DEVICE_FLAGS}>) + endif() + set_target_properties(${_target} PROPERTIES HIP_STANDARD 20 HIP_STANDARD_REQUIRED ON) + else() + target_compile_options(${_target} PRIVATE $<$:${CARBON_NVCC_DEVICE_FLAGS}>) + set_target_properties(${_target} PROPERTIES CUDA_STANDARD 20 CUDA_STANDARD_REQUIRED ON) + endif() + add_test(NAME carbon_${_target} + COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target ${_target} --config $) + set_tests_properties(carbon_${_target} PROPERTIES + RESOURCE_LOCK carbon_compile_fail + LABELS "cpu") + if(NOT _regex STREQUAL "") + set_tests_properties(carbon_${_target} PROPERTIES PASS_REGULAR_EXPRESSION "${_regex}") + endif() + endforeach() +endif() carbon_add_cuda_unit_test(skeleton_initial_halo) carbon_add_cuda_unit_test(skeleton_cuda_graph) carbon_add_cuda_unit_test(skeleton_cuda_graph_multi) @@ -355,6 +396,7 @@ set(_carbon_multi_gpu_tests halo_block halo_block_host reduce_sum_multi_gpu + reduce_partials_multi_gpu reduce_sum_host_multi_gpu jacobi_integer dense_disg_multi_gpu @@ -415,18 +457,10 @@ if(CARBON_ENABLE_MPI AND MPI_FOUND) HIP_STANDARD 20 HIP_STANDARD_REQUIRED ON) elseif(CARBON_BACKEND STREQUAL "Sycl") - set(_src "${CMAKE_CURRENT_BINARY_DIR}/${target}.cpp") - configure_file("${CMAKE_CURRENT_SOURCE_DIR}/${target}.cu" "${_src}" COPYONLY) - add_executable(${target} "${_src}") + carbon_add_sycl_mirrored_executable(${target} ${target}.cu) target_link_libraries(${target} PRIVATE carbon::carbon) - target_compile_features(${target} PRIVATE cxx_std_20) set_target_properties(${target} PROPERTIES BUILD_RPATH "${CARBON_RUNTIME_SEARCH_DIRS};${CMAKE_BINARY_DIR}") - add_sycl_to_target(TARGET ${target} SOURCES "${_src}") - if(CARBON_SYCL_TARGETS MATCHES "cuda") - target_compile_options(${target} PRIVATE --cuda-path=${CARBON_SYCL_CUDA_PATH}) - target_link_directories(${target} PRIVATE ${CARBON_SYCL_CUDA_PATH}/lib64) - endif() endif() if(TARGET ${target}) carbon_test_enable_assertions(${target}) @@ -493,6 +527,9 @@ if(CARBON_ENABLE_MPI AND MPI_FOUND) # rewrite path. Anchors cross-rank parity for {Standard, Extended, # TwoWayExtended} vs OverlapMode::None on a halo + Jacobi pipeline. carbon_add_mpi_cuda_test(skeleton_dist_overlap 2) + # Region masks across ranks: masked numerics + launch-order parity, rank-local export, + # and a rank-dependent mask turning into std::logic_error instead of an NCCL deadlock. + carbon_add_mpi_cuda_test(skeleton_region_mask_dist 2) # Closes the DenseDisg half of P1.δ (audit fourth pass): same OCC-MPI # parity matrix as skeleton_dist_overlap, but driven through # DenseDisg::Field::make_halo_kernel + DenseDisg::make_kernel so apply_occ_ diff --git a/tests/sub_grid_compile_fail.cu b/tests/sub_grid_compile_fail.cu new file mode 100644 index 00000000..ce40c947 --- /dev/null +++ b/tests/sub_grid_compile_fail.cu @@ -0,0 +1,91 @@ +// SubGrid compile-time rules. Each CARBON_CF_CASE is built by its own ctest entry (see +// tests/CMakeLists.txt); case 0 must compile, every other case must fail with the +// diagnostic the test registration matches. +// +// 1 read_stencil on a SubGrid field (S has no halo) +// 2 neighbour access through a SubGrid partition +// 3 writing a SubGrid partition with the parent's Span / Idx +// 4 a SubGrid of a SubGrid +// 5 Kernel::compute_universal over a SubGrid +// 6 read_stencil on a field of a SubGrid over a Block +// 7 a SubGrid over an unsupported parent grid + +#include + +#ifndef CARBON_CF_CASE +#error "define CARBON_CF_CASE" +#endif + +using S = carbon::SubGrid; + +[[maybe_unused]] auto +build(const S& sub, + S::Field& f) -> carbon::Kernel { + return sub.make_kernel([f](carbon::KernelLoader& L) { +#if CARBON_CF_CASE == 1 + auto p = L.read_stencil(f); +#else + auto p = L.read_write(f); +#endif + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) { +#if CARBON_CF_CASE == 2 + (void)p.neighbour(s, i, carbon::int8_3d{0, 0, 1}, 0); +#elif CARBON_CF_CASE == 3 + const carbon::Dense::Span& ps = s; + const carbon::Dense::Idx& pi = i; + p.write(ps, pi, 0, 1.0F); +#else + (void)p.read(s, i, 0); +#endif + }; + }); +} + +using SB = carbon::SubGrid>; + +#if CARBON_CF_CASE == 0 || CARBON_CF_CASE == 6 +[[maybe_unused]] auto +build_block(const SB& sub, + SB::Field& f) -> carbon::Kernel { + return sub.make_kernel([f](carbon::KernelLoader& L) { +#if CARBON_CF_CASE == 6 + auto p = L.read_stencil(f); +#else + auto p = L.read_write(f); +#endif + return [=] CARBON_HD(const SB::Span& s, const SB::Idx& i) { + p.write(s, i, 0, p.read(s, i, 0) + 1.0F); + }; + }); +} +#endif + +#if CARBON_CF_CASE == 7 +[[maybe_unused]] auto unsupported_size = sizeof(carbon::SubGrid); +#endif + +#if CARBON_CF_CASE == 4 +[[maybe_unused]] carbon::SubGrid* nested = nullptr; +[[maybe_unused]] auto nested_size = sizeof(carbon::SubGrid); +#endif + +#if CARBON_CF_CASE == 5 +[[maybe_unused]] auto +build_universal(const S& sub, + S::Field& f) -> carbon::Kernel { + return carbon::Kernel::compute_universal(sub, [f](carbon::KernelLoader& L) { + auto p = L.write(f); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) { + p.write(s, i, 0, 1.0F); + }; + }); +} +#endif + +int +main() { + return 0; +} diff --git a/tests/test_block_dist_stencil_parity.cu b/tests/test_block_dist_stencil_parity.cu index 403f79b5..da17bd8b 100644 --- a/tests/test_block_dist_stencil_parity.cu +++ b/tests/test_block_dist_stencil_parity.cu @@ -177,14 +177,16 @@ run_six_direction_probe(BlockGrid& block, const auto out_fd3 = loader.write(fd3); const auto out_fd4 = loader.write(fd4); const auto out_fd5 = loader.write(fd5); + // Literal offsets, not kDirs: AdaptiveCpp device code reading a host `static constexpr` + // array sees a zero-filled copy, so every probe collapsed to the cell itself. return [in, out_fv0, out_fv1, out_fv2, out_fv3, out_fv4, out_fv5, out_fd0, out_fd1, out_fd2, out_fd3, out_fd4, out_fd5] CARBON_HD(Span s, Idx idx) -> void { - const auto n0 = in.neighbour(s, idx, kDirs[0], 0); - const auto n1 = in.neighbour(s, idx, kDirs[1], 0); - const auto n2 = in.neighbour(s, idx, kDirs[2], 0); - const auto n3 = in.neighbour(s, idx, kDirs[3], 0); - const auto n4 = in.neighbour(s, idx, kDirs[4], 0); - const auto n5 = in.neighbour(s, idx, kDirs[5], 0); + const auto n0 = in.neighbour(s, idx, carbon::int8_3d{1, 0, 0}, 0); + const auto n1 = in.neighbour(s, idx, carbon::int8_3d{-1, 0, 0}, 0); + const auto n2 = in.neighbour(s, idx, carbon::int8_3d{0, 1, 0}, 0); + const auto n3 = in.neighbour(s, idx, carbon::int8_3d{0, -1, 0}, 0); + const auto n4 = in.neighbour(s, idx, carbon::int8_3d{0, 0, 1}, 0); + const auto n5 = in.neighbour(s, idx, carbon::int8_3d{0, 0, -1}, 0); out_fv0.write(s, idx, 0, n0.valid ? n0.value : -1.0F); out_fv1.write(s, idx, 0, n1.valid ? n1.value : -1.0F); out_fv2.write(s, idx, 0, n2.valid ? n2.value : -1.0F); diff --git a/tests/test_block_host_parity.cu b/tests/test_block_host_parity.cu index 4b23fa08..e930e006 100644 --- a/tests/test_block_host_parity.cu +++ b/tests/test_block_host_parity.cu @@ -43,6 +43,7 @@ #include #include #include +#include #include #include @@ -274,6 +275,40 @@ run_test() -> int { return 1; } + // ----- Copies build their host spans from their own host tables ----- + // A copy taken after host_spans() was memoised must not point into the source's vectors. + const auto own_tables = [](const BlockGrid& g) -> bool { + const auto& spans = g.host_spans(); + return spans.size() == 1U && spans[0].bitmask() == g.host_bitmasks(0).data() && + spans[0].connectivity() == g.host_connectivity(0).data() && + spans[0].origins() == g.host_origins(0).data(); + }; + (void)block.host_spans(); + const BlockGrid copied(block); + BlockGrid assigned; + assigned = block; + if (!own_tables(block) || !own_tables(copied) || !own_tables(assigned)) { + std::fprintf(stderr, + "test_block_host_parity: a copied Block's host spans point into " + "another Block's host tables\n"); + return 1; + } + // Host reduction through a copy whose source is gone (identical topology, same field). + std::unique_ptr source = + std::make_unique(system, domain_extent, predicate, "copy_source"); + (void)source->host_spans(); + const BlockGrid survivor(*source); + source.reset(); + carbon::ReductionResult dst_survivor(system); + survivor.template make_host_reduce_kernel(sum_loading, dst_survivor).launch(stream); + stream.wait(); + if (dst_survivor.host_value() != expected_sum) { + std::fprintf( + stderr, "test_block_host_parity: host reduce over a copied Block: %lld, want %lld\n", + static_cast(dst_survivor.host_value()), static_cast(expected_sum)); + return 1; + } + std::printf("test_block_host_parity: OK (active=%ld, inactive=%ld, blocks=%u, sum=%lld)\n", static_cast(active_checked), static_cast(inactive_checked), block.block_count(), static_cast(got_host_sum)); diff --git a/tests/test_reduce_partials_multi_gpu.cu b/tests/test_reduce_partials_multi_gpu.cu new file mode 100644 index 00000000..60630ad2 --- /dev/null +++ b/tests/test_reduce_partials_multi_gpu.cu @@ -0,0 +1,115 @@ +// Per-GPU partials of a multi-GPU reduction, checked one by one. +// +// test_reduce_sum_multi_gpu only checks the combined value, and an end-to-end check can't +// tell "GPU g's stage 1 never wrote its partial" from "the combine read it too early". This +// test reads every ReductionResult::gpu_partial(g) back after the reduce has fully drained +// and compares it with GPU g's owned-cell count, over many rounds that alternate two grids +// of different sizes and two kernels. That is the pattern under which the SYCL backend lost +// one GPU's partial (test_mgrid_locator counting 8192 of 16384 cells, the combine reading a +// stale value from a previous reduction). +// +// Skipped (returns 0) with fewer than 2 visible devices. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace { + +constexpr int kRounds = 40; + +struct Outcome { + int bad_rounds = 0; + int first_bad_round = -1; +}; + +/** One round: reduce `scale` per owned cell, then check every per-GPU partial and the total. */ +auto +run_round(carbon::System& sys, + const carbon::Dense& dense, + const carbon::Stream& stream, + int64_t scale, + int round, + const char* label) -> bool { + carbon::ReductionResult result(sys); + auto reducer = dense.make_reduce_kernel( + [scale](carbon::KernelLoader&) { + return [scale] CARBON_HOST_DEVICE(carbon::Dense::Span, carbon::Dense::Idx) -> int64_t { + return scale; + }; + }, + result, carbon::reduce::Sum{}); + reducer.launch(stream, carbon::DataView::Standard); + result.sync(stream); + stream.wait(); + + const size_t n = sys.gpu_group().size(); + bool ok = true; + int64_t want_total = 0; + for (size_t g = 0; g < n; ++g) { + auto host = carbon::Cpu::pinned_buffer(1U); + sys.async_copy(result.gpu_partial(carbon::DataView::Standard, g), host, sizeof(int64_t), + stream); + stream.wait(); + const int64_t want = dense.spans()[g].iter_extent(carbon::DataView::Standard).volume() * scale; + want_total += want; + if (host.data()[0] != want) { + CARBON_LOG_ERROR("test_reduce_partials_multi_gpu[{} round {}]: gpu {} partial {} != {}", + label, round, g, host.data()[0], want); + ok = false; + } + } + const int64_t got_total = result.host_value(carbon::DataView::Standard); + if (got_total != want_total) { + CARBON_LOG_ERROR("test_reduce_partials_multi_gpu[{} round {}]: total {} != {}", label, round, + got_total, want_total); + ok = false; + } + return ok; +} + +} // namespace + +int +main() { + carbon::init(); + if (carbon::device_count() < 2) { + CARBON_LOG_INFO("test_reduce_partials_multi_gpu: <2 visible devices, skipping"); + return EXIT_SUCCESS; + } + carbon::System sys(carbon::get_all_devices()); + const carbon::Stream stream = sys.stream(); + + // Two grids of different sizes, like two mGrid levels. + const carbon::Dense big(sys, carbon::int64_3d{32, 32, 64}); + const carbon::Dense small(sys, carbon::int64_3d{16, 16, 32}); + + Outcome out; + for (int r = 0; r < kRounds; ++r) { + const bool use_big = (r % 2) == 0; + const bool ok = + run_round(sys, use_big ? big : small, stream, 1 + (r % 3), r, use_big ? "big" : "small"); + if (!ok) { + ++out.bad_rounds; + if (out.first_bad_round < 0) { + out.first_bad_round = r; + } + } + } + if (out.bad_rounds != 0) { + CARBON_LOG_ERROR("test_reduce_partials_multi_gpu: {} of {} rounds wrong (first: {})", + out.bad_rounds, kRounds, out.first_bad_round); + return EXIT_FAILURE; + } + CARBON_LOG_INFO("test_reduce_partials_multi_gpu: OK ({} rounds, {} GPUs)", kRounds, + sys.gpu_group().size()); + return EXIT_SUCCESS; +} diff --git a/tests/test_region_mask.cpp b/tests/test_region_mask.cpp new file mode 100644 index 00000000..6959fa60 --- /dev/null +++ b/tests/test_region_mask.cpp @@ -0,0 +1,137 @@ +#include +#include + +#include +#include +#include +#include + +namespace { + +template +auto +throws_out_of_range(F&& f) -> bool { + try { + f(); + } catch (const std::out_of_range&) { + return true; + } + return false; +} + +} // namespace + +int +main() { + using carbon::RegionMask; + + // Compile-time usability: the masks a kernel declares are typically constants. + static_assert(RegionMask{}.empty()); + static_assert(RegionMask::all().is_all()); + static_assert(RegionMask::all().count() == 256U); + static_assert(RegionMask{0, 3, 7}.count() == 3U); + static_assert(!RegionMask::bit(1).intersects(RegionMask::bit(2))); + static_assert(RegionMask::range(0, 128) == ~RegionMask::range(128, 256)); + static_assert(RegionMask::from_label(200) == RegionMask::bit(200)); + + { + const RegionMask empty; + assert(empty.empty()); + assert(!empty.is_all()); + assert(empty == RegionMask::none()); + assert(empty.count() == 0U); + assert(!empty.intersects(RegionMask::all())); + assert(!empty.intersects(empty)); + } + + { + const RegionMask all = RegionMask::all(); + for (unsigned b = 0; b < RegionMask::kBits; ++b) { + assert(all.test(b)); + assert(all.intersects(RegionMask::bit(b))); + } + assert(all.intersects(all)); + assert(!all.test(256U)); + assert((~all).empty()); + } + + // Word boundaries: bits 63/64 live in different words, 255 is the last bit. + for (const unsigned b : {0U, 1U, 63U, 64U, 127U, 128U, 191U, 192U, 255U}) { + const RegionMask m = RegionMask::bit(b); + assert(m.count() == 1U); + assert(m.test(b)); + assert(m.word(b / 64U) == (std::uint64_t{1} << (b % 64U))); + assert(m == RegionMask::from_label(static_cast(b))); + assert(m.test(static_cast(b))); + for (const unsigned other : {0U, 63U, 64U, 255U}) { + assert(m.intersects(RegionMask::bit(other)) == (b == other)); + } + } + + { + assert(RegionMask::range(5, 5).empty()); + assert(RegionMask::range(0, 256).is_all()); + const RegionMask r = RegionMask::range(60, 70); + assert(r.count() == 10U); + assert(!r.test(59U) && r.test(60U) && r.test(63U) && r.test(64U) && r.test(69U)); + assert(!r.test(70U)); + assert(r.intersects(RegionMask::bit(64))); + assert(!r.intersects(RegionMask::range(70, 256))); + } + + // The full-partition idiom: a region and its complement split every bit. + { + const RegionMask bc = RegionMask{0, 17, 200}; + const RegionMask rest = ~bc; + assert(!bc.intersects(rest)); + assert((bc | rest).is_all()); + assert((bc & rest).empty()); + assert((bc ^ RegionMask::all()) == rest); + assert(rest.count() == 253U); + } + + { + RegionMask m; + m.set(4).set(130); + assert(m.test(4U) && m.test(130U) && m.count() == 2U); + m.reset(4); + assert(!m.test(4U) && m == RegionMask::bit(130)); + RegionMask n = RegionMask::bit(1); + n |= RegionMask::bit(2); + n &= RegionMask{2, 3}; + assert(n == RegionMask::bit(2)); + n ^= RegionMask::bit(2); + assert(n.empty()); + assert(n != RegionMask::bit(2)); + } + + assert(throws_out_of_range([] { + (void)RegionMask::bit(256); + })); + assert(throws_out_of_range([] { + (void)RegionMask{1, 300}; + })); + assert(throws_out_of_range([] { + (void)RegionMask::range(10, 9); + })); + assert(throws_out_of_range([] { + (void)RegionMask::range(0, 257); + })); + assert(throws_out_of_range([] { + RegionMask m; + m.set(256); + })); + assert(throws_out_of_range([] { + RegionMask m; + m.reset(1000); + })); + + assert(carbon::to_string(RegionMask::all()) == "all"); + assert(carbon::to_string(RegionMask{}) == "none"); + assert(carbon::to_string(RegionMask{3}) == "{3}"); + assert(carbon::to_string(RegionMask{0, 3, 5, 6, 7, 8, 9}) == "{0,3,5-9}"); + assert(carbon::to_string(RegionMask::range(62, 66) | RegionMask::bit(255)) == "{62-65,255}"); + assert(carbon::to_string(~RegionMask::bit(0)) == "{1-255}"); + + return 0; +} diff --git a/tests/test_skeleton_region_mask.cu b/tests/test_skeleton_region_mask.cu new file mode 100644 index 00000000..9cf1c077 --- /dev/null +++ b/tests/test_skeleton_region_mask.cu @@ -0,0 +1,849 @@ +// carbon::Skeleton region-mask dependencies (AccessToken::mask / KernelLoader::region). +// +// The domain is labelled by a full partition of three atoms: +// +// kWall : the two x side walls (x == 0 || x == nx - 1) — boundary-condition cells +// kLower : interior cells with global z < nz / 2 +// kUpper : interior cells with global z >= nz / 2 +// +// Kernels declare their footprint with L.region(mask) and filter themselves in the body. +// The subtests lock: +// +// A. Structure: disjoint masked writers lose their edge and land on two streams; +// overlapping masks, all-ones vs masked, and masked write vs overlapping read keep it; +// R/R never conflicts. +// B. Stencil reads stay whole-field: a stencil reader (and its auto-halo) waits on every +// masked writer of the field; a masked Map reader still waits on the halo. +// C. Loader API: explicit per-call masks win over region() in either order, stencil +// tokens stay all-ones, region() is readable in the launch phase. +// D. Empty masks conflict with nothing; the max_streams cap still holds. +// E. Options::ignore_region_masks and CARBON_IGNORE_REGION_MASKS reproduce the unmasked +// schedule exactly (same edges, same launch order); schedules are deterministic. +// F. Numerics on every visible GPU: masked pipelines under every OverlapMode (including +// two masked stencils sharing one halo and a masked reduction racing a disjoint +// writer) match the same pipeline run sequentially with masks ignored. +// +// Every non-default schedule is compared bit-for-bit against that sequential reference, so +// a mask that wrongly drops a true dependency shows up as a numeric mismatch. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using Field = carbon::Dense::Field; +using carbon::RegionMask; + +constexpr std::uint8_t kWall = 0; +constexpr std::uint8_t kLower = 1; +constexpr std::uint8_t kUpper = 2; + +const RegionMask kWallMask = RegionMask::from_label(kWall); +const RegionMask kLowerMask = RegionMask::from_label(kLower); +const RegionMask kUpperMask = RegionMask::from_label(kUpper); +const RegionMask kInteriorMask = kLowerMask | kUpperMask; + +struct Geo { + int64_t nx; + int64_t nz; + + [[nodiscard]] CARBON_HD auto + label(const carbon::int64_3d& g) const -> std::uint8_t { + if (g.x == 0 || g.x == nx - 1) { + return kWall; + } + return g.z < nz / 2 ? kLower : kUpper; + } +}; + +auto +fail(const std::string& msg) -> bool { + CARBON_LOG_ERROR("test_skeleton_region_mask: {}", msg); + return false; +} + +// out = in * a + b on the cells whose label is in @p mask; every other cell is untouched. +[[nodiscard]] auto +build_affine(carbon::Dense& dense, + Field& in, + Field& out, + RegionMask mask, + float a, + float b, + Geo geo, + std::string name) -> carbon::Kernel { + return carbon::Kernel::compute( + dense, + [&in, &out, mask, a, b, geo](carbon::KernelLoader& loader) { + loader.region(mask); + const auto src = loader.read(in); + const auto dst = loader.write(out); + return [src, dst, mask, a, b, geo] CARBON_HOST_DEVICE(carbon::Dense::Span s, + carbon::Dense::Idx idx) { + if (!mask.test(geo.label(s.global_location(idx)))) { + return; + } + dst.write(s, idx, 0, src.read(s, idx, 0) * a + b); + }; + }, + std::move(name), + /*shared_mem=*/0U); +} + +// 6-point average of @p in (whole-field stencil read) written to @p out on @p mask cells. +[[nodiscard]] auto +build_stencil(carbon::Dense& dense, + Field& in, + Field& out, + RegionMask mask, + Geo geo, + std::string name) -> carbon::Kernel { + return carbon::Kernel::compute( + dense, + [&in, &out, mask, geo](carbon::KernelLoader& loader) { + loader.region(mask); + const auto src = loader.read_stencil(in); + const auto dst = loader.write(out); + return [src, dst, mask, geo] CARBON_HOST_DEVICE(carbon::Dense::Span s, + carbon::Dense::Idx idx) { + if (!mask.test(geo.label(s.global_location(idx)))) { + return; + } + const carbon::NeighbourValue xp = src.neighbour(s, idx, {1, 0, 0}, 0); + const carbon::NeighbourValue xm = src.neighbour(s, idx, {-1, 0, 0}, 0); + const carbon::NeighbourValue yp = src.neighbour(s, idx, {0, 1, 0}, 0); + const carbon::NeighbourValue ym = src.neighbour(s, idx, {0, -1, 0}, 0); + const carbon::NeighbourValue zp = src.neighbour(s, idx, {0, 0, 1}, 0); + const carbon::NeighbourValue zm = src.neighbour(s, idx, {0, 0, -1}, 0); + float sum = 0.0F; + float n = 0.0F; + for (const carbon::NeighbourValue& nb : {xp, xm, yp, ym, zp, zm}) { + if (nb.valid) { + sum += nb.value; + n += 1.0F; + } + } + dst.write(s, idx, 0, n > 0.0F ? sum / n : src.read(s, idx, 0)); + }; + }, + std::move(name), + /*shared_mem=*/0U); +} + +// Sum of @p in over the cells whose label is in @p mask. +[[nodiscard]] auto +build_masked_sum(carbon::Dense& dense, + Field& in, + RegionMask mask, + Geo geo, + carbon::ReductionResult& result) -> carbon::Kernel { + return dense.make_reduce_kernel( + [&in, mask, geo](carbon::KernelLoader& loader) { + loader.region(mask); + const auto src = loader.read(in); + return [src, mask, geo] CARBON_HOST_DEVICE(carbon::Dense::Span s, + carbon::Dense::Idx idx) -> float { + return mask.test(geo.label(s.global_location(idx))) ? src.read(s, idx, 0) : 0.0F; + }; + }, + result, carbon::reduce::Sum{}); +} + +struct Fields { + Field u; + Field v; + Field src; + Field dst; + Field out; +}; + +[[nodiscard]] auto +make_fields(carbon::Dense& dense) -> Fields { + return Fields{dense.newField(carbon::MemorySide::HostDevice, "u"), + dense.newField(carbon::MemorySide::HostDevice, "v"), + dense.newField(carbon::MemorySide::HostDevice, "src"), + dense.newField(carbon::MemorySide::HostDevice, "dst"), + dense.newField(carbon::MemorySide::HostDevice, "out")}; +} + +template +auto +for_each_field(Fields& f, + Fn fn) -> void { + fn(f.u, 0); + fn(f.v, 1); + fn(f.src, 2); + fn(f.dst, 3); + fn(f.out, 4); +} + +// Fills the whole storage (owned + halo) of every field with a distinct deterministic value. +auto +init_fields(const carbon::Dense& dense, + Fields& f) -> void { + for_each_field(f, [&dense](Field& field, int seed) { + for (size_t g = 0; g < dense.gpu_count(); ++g) { + const auto& span = dense.spans()[g]; + const auto haloed = span.haloed_extent(); + const int64_t pitch = span.xy_slab_elements(); + const int64_t z_origin = span.z_offset(); + float* h = field.cpu_buffers()[g].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) { + h[z * pitch + y * haloed.x + x] = + static_cast(seed * 1000 + x + y * 11 + (z_origin + z) * 113); + } + } + } + } + }); +} + +[[nodiscard]] auto +transfer_fields(const carbon::System& sys, + Fields& f, + const carbon::Stream& s, + bool to_device) -> bool { + try { + for_each_field(f, [&sys, &s, to_device](Field& field, int) { + if (to_device) { + carbon::Transfer(sys, field.cpu_buffers(), field.gpu_buffers())(s); + } else { + carbon::Transfer(sys, field.gpu_buffers(), field.cpu_buffers())(s); + } + }); + s.wait(); + } catch (const std::exception& e) { + return fail(std::string("transfer failed: ") + e.what()); + } + return true; +} + +[[nodiscard]] auto +compare_owned(const carbon::Dense& dense, + const Field& a, + const Field& b, + const std::string& tag) -> bool { + for (size_t g = 0; g < dense.gpu_count(); ++g) { + const auto& span = dense.spans()[g]; + const auto haloed = span.haloed_extent(); + const int64_t pitch = span.xy_slab_elements(); + const int64_t halo_z = span.halo_z(); + const int64_t lim_z = span.logic_extent().z; + const float* ha = a.cpu_buffers()[g].data(); + const float* hb = b.cpu_buffers()[g].data(); + for (int64_t z = halo_z; z < halo_z + lim_z; ++z) { + for (int64_t y = 0; y < haloed.y; ++y) { + for (int64_t x = 0; x < haloed.x; ++x) { + const int64_t off = z * pitch + y * haloed.x + x; + if (ha[off] != hb[off]) { + return fail(tag + ": mismatch on field '" + a.name() + "' at gpu=" + std::to_string(g) + + " (x=" + std::to_string(x) + ", y=" + std::to_string(y) + + ", z=" + std::to_string(z) + "): test=" + std::to_string(ha[off]) + + " ref=" + std::to_string(hb[off])); + } + } + } + } + } + return true; +} + +using Builder = std::function(carbon::Dense&, Fields&)>; + +[[nodiscard]] auto +make_skeleton(carbon::System& sys, + carbon::Dense& dense, + Fields& f, + const Builder& build, + carbon::Skeleton::Options opts) -> carbon::Skeleton { + carbon::Skeleton sk(sys, opts); + for (carbon::Kernel& k : build(dense, f)) { + sk.add(std::move(k)); + } + return sk; +} + +// Runs @p build under @p opts for @p iters iterations and compares every field against the +// same pipeline run on one stream with masks ignored (the pre-region-mask schedule). +[[nodiscard]] auto +run_and_compare(carbon::System& sys, + carbon::Dense& dense, + const Builder& build, + carbon::Skeleton::Options opts, + int iters, + const std::string& tag) -> bool { + Fields test = make_fields(dense); + Fields ref = make_fields(dense); + init_fields(dense, test); + init_fields(dense, ref); + carbon::Stream s = sys.stream(); + if (!transfer_fields(sys, test, s, true) || !transfer_fields(sys, ref, s, true)) { + return false; + } + + carbon::Skeleton::Options ref_opts; + ref_opts.max_streams = 1U; + ref_opts.ignore_region_masks = true; + try { + carbon::Skeleton sk_test = make_skeleton(sys, dense, test, build, opts); + carbon::Skeleton sk_ref = make_skeleton(sys, dense, ref, build, ref_opts); + for (int it = 0; it < iters; ++it) { + sk_test.run(); + } + sk_test.wait(); + for (int it = 0; it < iters; ++it) { + sk_ref.run(); + } + sk_ref.wait(); + if (opts.overlap_mode == carbon::OverlapMode::None && !opts.ignore_region_masks && + opts.max_streams != 1U && sk_test.num_streams() < 2U) { + return fail(tag + ": expected the masked schedule to use more than one stream"); + } + } catch (const std::exception& e) { + return fail(tag + ": run threw: " + e.what()); + } + + if (!transfer_fields(sys, test, s, false) || !transfer_fields(sys, ref, s, false)) { + return false; + } + return compare_owned(dense, test.u, ref.u, tag) && compare_owned(dense, test.v, ref.v, tag) && + compare_owned(dense, test.src, ref.src, tag) && + compare_owned(dense, test.dst, ref.dst, tag) && + compare_owned(dense, test.out, ref.out, tag); +} + +[[nodiscard]] auto +compiled(carbon::System& sys, + carbon::Dense& dense, + Fields& f, + const Builder& build, + carbon::Skeleton::Options opts = {}) -> carbon::Skeleton { + carbon::Skeleton sk = make_skeleton(sys, dense, f, build, opts); + sk.compile(); + return sk; +} + +using Edges = std::vector>; + +// ---------- A. structure ---------- + +[[nodiscard]] auto +subtest_structure(carbon::System& sys, + carbon::Dense& dense, + Geo geo) -> bool { + Fields f = make_fields(dense); + + auto two_writers = [geo](RegionMask m0, RegionMask m1) { + return [geo, m0, m1](carbon::Dense& d, Fields& fl) { + std::vector ks; + ks.push_back(build_affine(d, fl.src, fl.dst, m0, 2.0F, 1.0F, geo, "w0")); + ks.push_back(build_affine(d, fl.src, fl.dst, m1, 3.0F, 2.0F, geo, "w1")); + return ks; + }; + }; + + { + carbon::Skeleton sk = compiled(sys, dense, f, two_writers(kLowerMask, kUpperMask)); + if (sk.edges() != Edges{{}, {}}) { + return fail("disjoint writers: expected no edge"); + } + if (sk.kernel_streams() != std::vector{0U, 1U} || sk.num_streams() != 2U) { + return fail("disjoint writers: expected streams {0, 1}"); + } + } + { + carbon::Skeleton sk = compiled(sys, dense, f, two_writers(kInteriorMask, kUpperMask)); + if (sk.edges() != Edges{{1U}, {}}) { + return fail("overlapping writers: expected edge 0 -> 1"); + } + } + { + carbon::Skeleton sk = compiled(sys, dense, f, two_writers(RegionMask::all(), kUpperMask)); + if (sk.edges() != Edges{{1U}, {}} || sk.num_streams() != 1U) { + return fail("all-ones vs masked writer: expected edge 0 -> 1 on one stream"); + } + } + { + // W dst on kLower, then R dst on kUpper / kLower. + for (const bool overlap : {false, true}) { + const RegionMask reader = overlap ? kLowerMask : kUpperMask; + carbon::Skeleton sk = compiled(sys, dense, f, [geo, reader](carbon::Dense& d, Fields& fl) { + std::vector ks; + ks.push_back(build_affine(d, fl.src, fl.dst, kLowerMask, 2.0F, 0.0F, geo, "w")); + ks.push_back(build_affine(d, fl.dst, fl.out, reader, 1.0F, 1.0F, geo, "r")); + return ks; + }); + if (sk.edges() != (overlap ? Edges{{1U}, {}} : Edges{{}, {}})) { + return fail(std::string("masked write vs ") + (overlap ? "overlapping" : "disjoint") + + " read: wrong edges"); + } + } + } + { + // R/R on the same mask never conflicts; the writes go to different fields. + carbon::Skeleton sk = compiled(sys, dense, f, [geo](carbon::Dense& d, Fields& fl) { + std::vector ks; + ks.push_back(build_affine(d, fl.src, fl.dst, kLowerMask, 2.0F, 0.0F, geo, "r0")); + ks.push_back(build_affine(d, fl.src, fl.out, kLowerMask, 3.0F, 0.0F, geo, "r1")); + return ks; + }); + if (sk.edges() != Edges{{}, {}}) { + return fail("R/R on the same mask: expected no edge"); + } + } + return true; +} + +// ---------- B. stencil reads stay whole-field ---------- + +auto +writers_then_stencil(Geo geo) -> Builder { + return [geo](carbon::Dense& d, Fields& fl) { + std::vector ks; + ks.push_back(build_affine(d, fl.src, fl.dst, kLowerMask, 2.0F, 1.0F, geo, "w_lower")); + ks.push_back(build_affine(d, fl.src, fl.dst, kUpperMask, 3.0F, 2.0F, geo, "w_upper")); + ks.push_back(build_affine(d, fl.src, fl.dst, kWallMask, 4.0F, 3.0F, geo, "w_wall")); + ks.push_back(build_stencil(d, fl.dst, fl.out, RegionMask::all(), geo, "smooth")); + return ks; + }; +} + +// dst = f(src) everywhere; interior out = stencil(dst); wall out = map(dst). +auto +stencil_plus_bc(Geo geo) -> Builder { + return [geo](carbon::Dense& d, Fields& fl) { + std::vector ks; + ks.push_back(build_affine(d, fl.src, fl.dst, RegionMask::all(), 0.5F, 1.0F, geo, "fill")); + ks.push_back(build_stencil(d, fl.dst, fl.out, kInteriorMask, geo, "interior")); + ks.push_back(build_affine(d, fl.dst, fl.out, kWallMask, -1.0F, 0.0F, geo, "bc")); + return ks; + }; +} + +[[nodiscard]] auto +subtest_stencil(carbon::System& sys, + carbon::Dense& dense, + Geo geo) -> bool { + Fields f = make_fields(dense); + { + // Effective order: w_lower, w_upper, w_wall, auto_halo_dst, smooth. + carbon::Skeleton sk = compiled(sys, dense, f, writers_then_stencil(geo)); + const auto& eff = sk.effective_kernels(); + if (eff.size() != 5U || eff[3].kind() != carbon::KernelKind::Halo) { + return fail("writers + stencil: expected one auto-halo before the stencil reader"); + } + if (sk.min_edges() != Edges{{3U}, {3U}, {3U}, {4U}, {}}) { + return fail("writers + stencil: the halo must wait on every masked writer"); + } + if (sk.edges()[0] != std::vector{3U, 4U}) { + return fail("writers + stencil: the stencil read must conflict with each masked writer"); + } + } + { + // Effective order: fill, auto_halo_dst, interior, bc. + carbon::Skeleton sk = compiled(sys, dense, f, stencil_plus_bc(geo)); + const auto& eff = sk.effective_kernels(); + if (eff.size() != 4U || eff[1].kind() != carbon::KernelKind::Halo) { + return fail("stencil + bc: unexpected effective kernel list"); + } + if (sk.min_edges() != Edges{{1U}, {2U, 3U}, {}, {}}) { + return fail("stencil + bc: bc must wait on the halo and run beside the interior"); + } + if (sk.kernel_streams()[2] == sk.kernel_streams()[3]) { + return fail("stencil + bc: interior and bc should be on different streams"); + } + } + return true; +} + +// ---------- C. loader API ---------- + +[[nodiscard]] auto +subtest_loader(carbon::System& sys, + carbon::Dense& dense) -> bool { + Fields f = make_fields(dense); + + auto token_masks = [](const carbon::Kernel& k) { + std::vector masks; + for (const carbon::AccessToken& t : k.impl()->tokens()) { + masks.push_back(t.mask); + } + return masks; + }; + + // Explicit mask before region(), stencil read after it. + auto k_before = carbon::Kernel::compute( + dense, + [&f](carbon::KernelLoader& loader) { + const auto a = loader.read(f.u, RegionMask::all()); + loader.region(kLowerMask); + const auto b = loader.write(f.v); + const auto c = loader.read_stencil(f.src); + return [a, b, c] CARBON_HOST_DEVICE(carbon::Dense::Span s, carbon::Dense::Idx idx) { + b.write(s, idx, 0, a.read(s, idx, 0) + c.read(s, idx, 0)); + }; + }, + "before", 0U); + if (token_masks(k_before) != + std::vector{RegionMask::all(), kLowerMask, RegionMask::all()}) { + return fail("explicit mask before region(): wrong token masks"); + } + + // region() first, explicit mask afterwards; a later region() re-stamps implicit tokens only. + auto k_after = carbon::Kernel::compute( + dense, + [&f](carbon::KernelLoader& loader) { + loader.region(kLowerMask); + const auto a = loader.read(f.u, kUpperMask); + const auto b = loader.read_write(f.v); + loader.region(kInteriorMask); + return [a, b] CARBON_HOST_DEVICE(carbon::Dense::Span s, carbon::Dense::Idx idx) { + b.write(s, idx, 0, a.read(s, idx, 0) + b.read(s, idx, 0)); + }; + }, + "after", 0U); + if (token_masks(k_after) != std::vector{kUpperMask, kInteriorMask}) { + return fail("explicit mask after region(): wrong token masks"); + } + + // The launch-phase loader exposes the declared region to the loading lambda. + RegionMask seen = RegionMask::none(); + auto k_seen = carbon::Kernel::compute( + dense, + [&f, &seen](carbon::KernelLoader& loader) { + loader.region(kUpperMask); + seen = loader.region(); + const auto a = loader.write(f.out); + return [a] CARBON_HOST_DEVICE(carbon::Dense::Span s, carbon::Dense::Idx idx) { + a.write(s, idx, 0, 0.0F); + }; + }, + "seen", 0U); + seen = RegionMask::none(); + try { + carbon::Stream s = sys.stream(); + k_seen.launch(s, carbon::DataView::Standard); + s.wait(); + } catch (const std::exception& e) { + return fail(std::string("launch-phase region() kernel threw: ") + e.what()); + } + if (seen != kUpperMask) { + return fail("region() not visible in the launch phase: got " + carbon::to_string(seen)); + } + return true; +} + +// ---------- D. empty masks and the stream cap ---------- + +[[nodiscard]] auto +subtest_empty_and_cap(carbon::System& sys, + carbon::Dense& dense, + Geo geo) -> bool { + Fields f = make_fields(dense); + { + carbon::Skeleton sk = compiled(sys, dense, f, [geo](carbon::Dense& d, Fields& fl) { + std::vector ks; + ks.push_back(build_affine(d, fl.src, fl.dst, RegionMask::none(), 1.0F, 0.0F, geo, "e")); + ks.push_back(build_affine(d, fl.src, fl.dst, RegionMask::all(), 2.0F, 0.0F, geo, "a")); + return ks; + }); + if (sk.edges() != Edges{{}, {}}) { + return fail("empty mask: expected it to conflict with nothing"); + } + } + + // Four writers on atoms no cell carries: pairwise disjoint, so four parallel chains. + auto four = [geo](carbon::Dense& d, Fields& fl) { + std::vector ks; + for (unsigned b = 10; b < 14; ++b) { + ks.push_back(build_affine(d, fl.src, fl.dst, RegionMask::bit(b), 1.0F, 0.0F, geo, + "w" + std::to_string(b))); + } + return ks; + }; + { + carbon::Skeleton sk = compiled(sys, dense, f, four); + if (sk.num_streams() != 4U) { + return fail("four disjoint writers: expected 4 streams"); + } + } + { + carbon::Skeleton::Options opts; + opts.max_streams = 2U; + carbon::Skeleton sk = compiled(sys, dense, f, four, opts); + if (sk.num_streams() > 2U) { + return fail("max_streams = 2 not honoured with masked kernels"); + } + } + return true; +} + +// ---------- E. kill switch and determinism ---------- + +[[nodiscard]] auto +subtest_ignore_and_determinism(carbon::System& sys, + carbon::Dense& dense, + Geo geo) -> bool { + Fields f = make_fields(dense); + const Builder masked = stencil_plus_bc(geo); + const Builder unmasked = [geo](carbon::Dense& d, Fields& fl) { + std::vector ks; + ks.push_back(build_affine(d, fl.src, fl.dst, RegionMask::all(), 0.5F, 1.0F, geo, "fill")); + ks.push_back(build_stencil(d, fl.dst, fl.out, RegionMask::all(), geo, "interior")); + ks.push_back(build_affine(d, fl.dst, fl.out, RegionMask::all(), -1.0F, 0.0F, geo, "bc")); + return ks; + }; + + carbon::Skeleton sk_unmasked = compiled(sys, dense, f, unmasked); + const std::string order_unmasked = sk_unmasked.export_launch_order(); + + carbon::Skeleton::Options ignore; + ignore.ignore_region_masks = true; + carbon::Skeleton sk_ignored = compiled(sys, dense, f, masked, ignore); + if (sk_ignored.region_masks_honoured()) { + return fail("Options::ignore_region_masks did not disable masks"); + } + if (sk_ignored.edges() != sk_unmasked.edges() || + sk_ignored.export_launch_order() != order_unmasked) { + return fail("ignore_region_masks: schedule differs from the unmasked pipeline"); + } + + if (setenv("CARBON_IGNORE_REGION_MASKS", "1", 1) != 0) { + return fail("setenv failed"); + } + carbon::Skeleton sk_env = compiled(sys, dense, f, masked); + unsetenv("CARBON_IGNORE_REGION_MASKS"); + if (sk_env.region_masks_honoured() || sk_env.export_launch_order() != order_unmasked) { + return fail("CARBON_IGNORE_REGION_MASKS=1: schedule differs from the unmasked pipeline"); + } + + carbon::Skeleton sk_a = compiled(sys, dense, f, masked); + carbon::Skeleton sk_b = compiled(sys, dense, f, masked); + if (!sk_a.region_masks_honoured()) { + return fail("masks not honoured by default"); + } + if (sk_a.export_launch_order() != sk_b.export_launch_order()) { + return fail("masked schedule is not deterministic"); + } + if (sk_a.export_launch_order() == order_unmasked) { + return fail("masked schedule should differ from the unmasked one"); + } + + // Exporters annotate non-all masks only, and say when masks are ignored. + auto has = [](const std::string& text, const char* needle) { + return text.find(needle) != std::string::npos; + }; + const std::string list_masked = sk_a.export_kernel_list_dot("masked"); + const std::string list_unmasked = sk_unmasked.export_kernel_list_dot("unmasked"); + const std::string list_ignored = sk_ignored.export_kernel_list_dot("ignored"); + if (!has(list_masked, "region {1-2}") || !has(list_masked, "region {0}")) { + return fail("export_kernel_list_dot: missing region annotations:\n" + list_masked); + } + if (has(list_unmasked, "region {") || has(list_unmasked, "region_masks=ignored")) { + return fail("export_kernel_list_dot: unmasked pipeline must render without annotations"); + } + if (has(list_ignored, "region {") || !has(list_ignored, "region_masks=ignored")) { + return fail("export_kernel_list_dot: ignored masks must be reported, not annotated"); + } + const std::string dot_masked = sk_a.export_dot("masked"); + if (!has(dot_masked, "region {0}") || has(sk_unmasked.export_dot("unmasked"), "region {")) { + return fail("export_dot: tooltips must carry non-all masks only"); + } + return true; +} + +// ---------- F. numerics ---------- + +// Jacobi ping-pong where every half step writes the interior with a stencil and the walls +// with a Map BC, so the two kernels of each half step can run side by side. +auto +jacobi_with_bc(Geo geo) -> Builder { + return [geo](carbon::Dense& d, Fields& fl) { + std::vector ks; + ks.push_back(build_stencil(d, fl.u, fl.v, kInteriorMask, geo, "step_uv")); + ks.push_back(build_affine(d, fl.u, fl.v, kWallMask, 0.5F, 1.0F, geo, "bc_uv")); + ks.push_back(build_stencil(d, fl.v, fl.u, kInteriorMask, geo, "step_vu")); + ks.push_back(build_affine(d, fl.v, fl.u, kWallMask, 0.5F, 1.0F, geo, "bc_vu")); + return ks; + }; +} + +// Two masked stencils over the same input share one auto-halo. +auto +split_stencils(Geo geo) -> Builder { + return [geo](carbon::Dense& d, Fields& fl) { + std::vector ks; + ks.push_back(build_affine(d, fl.src, fl.dst, RegionMask::all(), 1.0F, 1.0F, geo, "bump")); + ks.push_back(build_stencil(d, fl.dst, fl.out, kLowerMask, geo, "smooth_lower")); + ks.push_back(build_stencil(d, fl.dst, fl.out, kUpperMask, geo, "smooth_upper")); + ks.push_back(build_affine(d, fl.dst, fl.out, kWallMask, 2.0F, 0.0F, geo, "bc")); + ks.push_back(build_affine(d, fl.out, fl.src, RegionMask::all(), 0.25F, 0.0F, geo, "back")); + return ks; + }; +} + +[[nodiscard]] auto +subtest_numerics(carbon::System& sys, + carbon::Dense& dense, + Geo geo) -> bool { + { + Fields f = make_fields(dense); + carbon::Skeleton sk = compiled(sys, dense, f, split_stencils(geo)); + size_t halos = 0; + for (const carbon::Kernel& k : sk.effective_kernels()) { + halos += k.kind() == carbon::KernelKind::Halo ? 1U : 0U; + } + // Effective order: bump, auto_halo_dst, smooth_lower, smooth_upper, bc, back. + if (halos != 1U || sk.edges()[2] != std::vector{5U}) { + return fail("split stencils: expected one shared halo and no edge between the stencils"); + } + } + + constexpr int kIters = 4; + const carbon::OverlapMode modes[] = {carbon::OverlapMode::None, carbon::OverlapMode::Standard, + carbon::OverlapMode::Extended, + carbon::OverlapMode::TwoWayExtended}; + const std::pair pipelines[] = { + {"writers_then_stencil", writers_then_stencil(geo)}, + {"stencil_plus_bc", stencil_plus_bc(geo)}, + {"jacobi_with_bc", jacobi_with_bc(geo)}, + {"split_stencils", split_stencils(geo)}, + }; + for (const auto& [name, build] : pipelines) { + for (const carbon::OverlapMode mode : modes) { + carbon::Skeleton::Options opts(mode); + const std::string tag = + std::string(name) + "/overlap=" + std::to_string(static_cast(mode)); + if (!run_and_compare(sys, dense, build, opts, kIters, tag)) { + return false; + } + } + carbon::Skeleton::Options capped; + capped.max_streams = 1U; + if (!run_and_compare(sys, dense, build, capped, kIters, std::string(name) + "/max1")) { + return false; + } + carbon::Skeleton::Options graph(carbon::OverlapMode::None, false, 0U, false, + /*cuda_graph=*/true); + if (!run_and_compare(sys, dense, build, graph, kIters, std::string(name) + "/graph")) { + return false; + } + } + return true; +} + +// A masked reduction over kLower runs beside a writer of kUpper and must see none of it. +[[nodiscard]] auto +subtest_masked_reduction(carbon::System& sys, + carbon::Dense& dense, + Geo geo) -> bool { + constexpr float kValue = 3.0F; + Field fld = dense.newField(carbon::MemorySide::HostDevice, "fld"); + Field one = dense.newField(carbon::MemorySide::HostDevice, "one"); + size_t lower_cells = 0; + for (size_t g = 0; g < dense.gpu_count(); ++g) { + const auto& span = dense.spans()[g]; + const auto haloed = span.haloed_extent(); + const int64_t pitch = span.xy_slab_elements(); + const int64_t halo_z = span.halo_z(); + const int64_t lim_z = span.logic_extent().z; + for (int64_t z = 0; z < haloed.z; ++z) { + for (int64_t y = 0; y < haloed.y; ++y) { + for (int64_t x = 0; x < haloed.x; ++x) { + const int64_t off = z * pitch + y * haloed.x + x; + fld.cpu_buffers()[g].data()[off] = kValue; + one.cpu_buffers()[g].data()[off] = 1.0F; + const bool owned = z >= halo_z && z < halo_z + lim_z; + const carbon::int64_3d gl{x, y, span.z_offset() + z}; + lower_cells += owned && geo.label(gl) == kLower ? 1U : 0U; + } + } + } + } + carbon::ReductionResult sum(sys); + carbon::Stream s = sys.stream(); + try { + carbon::Transfer(sys, fld.cpu_buffers(), fld.gpu_buffers())(s); + carbon::Transfer(sys, one.cpu_buffers(), one.gpu_buffers())(s); + s.wait(); + + for (const bool overlap : {false, true}) { + carbon::Skeleton sk(sys, s); + sk.add(build_affine(dense, one, fld, overlap ? kInteriorMask : kUpperMask, 100.0F, 0.0F, geo, + "writer")); + sk.add(build_masked_sum(dense, fld, kLowerMask, geo, sum)); + sk.compile(); + if (sk.edges() != (overlap ? Edges{{1U}, {}} : Edges{{}, {}})) { + return fail("masked reduction: wrong edges"); + } + if (overlap) { + continue; + } + if (sk.num_streams() != 2U) { + return fail("masked reduction: expected the reduction beside the writer"); + } + sk.run(); + sum.sync(s); + s.wait(); + } + } catch (const std::exception& e) { + return fail(std::string("masked reduction threw: ") + e.what()); + } + const float expected = kValue * static_cast(lower_cells); + if (sum.host_value() != expected) { + return fail("masked reduction: got " + std::to_string(sum.host_value()) + ", want " + + std::to_string(expected)); + } + return true; +} + +} // namespace + +auto +main() -> int { + carbon::init(); + if (carbon::device_count() <= 0) { + CARBON_LOG_ERROR("test_skeleton_region_mask: no CUDA devices visible"); + return EXIT_FAILURE; + } + + carbon::System sys(carbon::get_all_devices()); + const size_t n_gpus = sys.gpu_group().size(); + + carbon::Stencil stencil( + std::vector{ + {1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}, + /*remove_center=*/true); + const carbon::int64_3d global{8, 5, 4 * static_cast(n_gpus)}; + carbon::Dense dense(sys, global, std::move(stencil)); + const Geo geo{global.x, global.z}; + + const bool ok = subtest_structure(sys, dense, geo) && subtest_stencil(sys, dense, geo) && + subtest_loader(sys, dense) && subtest_empty_and_cap(sys, dense, geo) && + subtest_ignore_and_determinism(sys, dense, geo) && + subtest_numerics(sys, dense, geo) && subtest_masked_reduction(sys, dense, geo); + if (!ok) { + return EXIT_FAILURE; + } + CARBON_LOG_INFO("test_skeleton_region_mask: OK on {} GPU(s)", n_gpus); + return EXIT_SUCCESS; +} diff --git a/tests/test_skeleton_region_mask_dist.cu b/tests/test_skeleton_region_mask_dist.cu new file mode 100644 index 00000000..2546e795 --- /dev/null +++ b/tests/test_skeleton_region_mask_dist.cu @@ -0,0 +1,319 @@ +// MPI cross-rank Skeleton region masks. +// +// Every rank owns one z slab. The domain is labelled walls (x == 0 || x == nx - 1) and +// interior; each half step of a Jacobi ping-pong is an interior stencil plus a masked wall +// kernel writing the same field, so with masks honoured the two run side by side while the +// next stencil (and its cross-rank auto-halo) still waits on both. +// +// A. Masked pipeline under OverlapMode::None and ::Standard is bit-identical to the same +// pipeline with Options::ignore_region_masks, and every rank issues the same launch +// order (hash compared across ranks). +// B. compile() and the exporters stay rank-local: rank 0 alone exports a halo pipeline +// without blocking (the rank-consistency collective lives in run(), not compile()). +// C. A rank-dependent RegionMask makes the first run() throw std::logic_error on every +// rank instead of issuing NCCL collectives in different orders and deadlocking. +// +// Skipped (returns 0) when world_size < 2 or no GPUs are visible. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using Field = carbon::Dense::Field; +using carbon::RegionMask; + +constexpr int kCycles = 4; +const RegionMask kInterior = RegionMask::from_label(0); +const RegionMask kWalls = RegionMask::from_label(1); + +struct Geo { + int64_t nx; + + [[nodiscard]] CARBON_HD auto + label(const carbon::int64_3d& g) const -> std::uint8_t { + return (g.x == 0 || g.x == nx - 1) ? 1U : 0U; + } +}; + +auto +fail(const std::string& msg) -> bool { + CARBON_LOG_ERROR("test_skeleton_region_mask_dist: {}", msg); + return false; +} + +[[nodiscard]] auto +build_interior(carbon::Dense& dense, + Field& fin, + Field& fout, + Geo geo, + std::string name) -> carbon::Kernel { + return carbon::Kernel::compute( + dense, + [&fin, &fout, geo](carbon::KernelLoader& loader) { + loader.region(kInterior); + const auto in = loader.read_stencil(fin); + const auto out = loader.write(fout); + return [in, out, geo] CARBON_HOST_DEVICE(carbon::Dense::Span s, carbon::Dense::Idx idx) { + if (geo.label(s.global_location(idx)) != 0U) { + return; + } + float sum = 0.0F; + float n = 0.0F; + for (const carbon::NeighbourValue& nb : + {in.neighbour(s, idx, {1, 0, 0}, 0), in.neighbour(s, idx, {-1, 0, 0}, 0), + in.neighbour(s, idx, {0, 1, 0}, 0), in.neighbour(s, idx, {0, -1, 0}, 0), + in.neighbour(s, idx, {0, 0, 1}, 0), in.neighbour(s, idx, {0, 0, -1}, 0)}) { + if (nb.valid) { + sum += nb.value; + n += 1.0F; + } + } + out.write(s, idx, 0, sum / n); + }; + }, + std::move(name), + /*shared_mem=*/0U); +} + +[[nodiscard]] auto +build_walls(carbon::Dense& dense, + Field& fin, + Field& fout, + RegionMask mask, + Geo geo, + std::string name) -> carbon::Kernel { + return carbon::Kernel::compute( + dense, + [&fin, &fout, mask, geo](carbon::KernelLoader& loader) { + loader.region(mask); + const auto in = loader.read(fin); + const auto out = loader.write(fout); + return [in, out, geo] CARBON_HOST_DEVICE(carbon::Dense::Span s, carbon::Dense::Idx idx) { + if (geo.label(s.global_location(idx)) != 1U) { + return; + } + out.write(s, idx, 0, 0.5F * in.read(s, idx, 0) + 1.0F); + }; + }, + std::move(name), + /*shared_mem=*/0U); +} + +auto +add_pipeline(carbon::Skeleton& sk, + carbon::Dense& dense, + Field& u, + Field& v, + Geo geo, + RegionMask wall_mask = kWalls) -> void { + sk.add(build_interior(dense, u, v, geo, "interior_uv")); + sk.add(build_walls(dense, u, v, wall_mask, geo, "walls_v")); + sk.add(build_interior(dense, v, u, geo, "interior_vu")); + sk.add(build_walls(dense, v, u, wall_mask, geo, "walls_u")); +} + +auto +init_field(const carbon::Dense& dense, + Field& f, + float seed) -> void { + const auto& span = dense.spans()[0]; + const auto haloed = span.haloed_extent(); + const int64_t pitch = span.xy_slab_elements(); + float* h = f.cpu_buffers()[0].data(); + for (int64_t z = 0; z < haloed.z; ++z) { + for (int64_t y = 0; y < haloed.y; ++y) { + for (int64_t x = 0; x < haloed.x; ++x) { + h[z * pitch + y * haloed.x + x] = + seed + static_cast(x + y * 11 + (span.z_offset() + z) * 113); + } + } + } +} + +[[nodiscard]] auto +fnv1a(const std::string& s) -> std::uint64_t { + std::uint64_t h = 1469598103934665603ULL; + for (const char c : s) { + h ^= static_cast(c); + h *= 1099511628211ULL; + } + return h; +} + +// Runs the masked pipeline (honoured or ignored) and returns the owned cells of u. +[[nodiscard]] auto +run_masked(carbon::System& sys, + carbon::Dense& dense, + Geo geo, + carbon::Skeleton::Options opts, + std::vector& owned, + std::string& launch_order, + size_t& streams) -> bool { + auto u = dense.newField(carbon::MemorySide::HostDevice, "u"); + auto v = dense.newField(carbon::MemorySide::HostDevice, "v"); + init_field(dense, u, 0.0F); + init_field(dense, v, 5000.0F); + carbon::Stream stream = sys.stream(); + try { + carbon::Transfer(sys, u.cpu_buffers(), u.gpu_buffers())(stream); + carbon::Transfer(sys, v.cpu_buffers(), v.gpu_buffers())(stream); + stream.wait(); + + carbon::Skeleton sk(sys, stream, opts); + add_pipeline(sk, dense, u, v, geo); + for (int it = 0; it < kCycles; ++it) { + sk.run(); + } + sk.wait(); + launch_order = sk.export_launch_order(); + streams = sk.num_streams(); + + carbon::Transfer(sys, u.gpu_buffers(), u.cpu_buffers())(stream); + stream.wait(); + } catch (const std::exception& e) { + return fail(std::string("masked pipeline threw: ") + e.what()); + } + const auto& span = dense.spans()[0]; + const int64_t begin = span.halo_z() * span.xy_slab_elements(); + const int64_t end = begin + span.logic_extent().z * span.xy_slab_elements(); + const float* h = u.cpu_buffers()[0].data(); + owned.assign(h + begin, h + end); + return true; +} + +[[nodiscard]] auto +subtest_numerics(carbon::System& sys, + const carbon::Distributed& dist, + carbon::Dense& dense, + Geo geo) -> bool { + carbon::Skeleton::Options ignored; + ignored.ignore_region_masks = true; + std::vector ref; + std::string ref_order; + size_t ref_streams = 0; + if (!run_masked(sys, dense, geo, ignored, ref, ref_order, ref_streams)) { + return false; + } + for (const carbon::OverlapMode mode : + {carbon::OverlapMode::None, carbon::OverlapMode::Standard}) { + std::vector got; + std::string order; + size_t streams = 0; + if (!run_masked(sys, dense, geo, carbon::Skeleton::Options{mode}, got, order, streams)) { + return false; + } + const std::string tag = "overlap=" + std::to_string(static_cast(mode)); + if (mode == carbon::OverlapMode::None && streams < 2U) { + return fail(tag + ": expected the wall kernel on its own stream"); + } + if (got != ref) { + return fail(tag + ": masked result differs from the whole-field schedule"); + } + if (!dist.all_ranks_equal(fnv1a(order))) { + return fail(tag + ": ranks issued different launch orders:\n" + order); + } + } + return true; +} + +[[nodiscard]] auto +subtest_rank_local_export(carbon::System& sys, + const carbon::Distributed& dist, + carbon::Dense& dense, + Geo geo) -> bool { + auto u = dense.newField(carbon::MemorySide::Device, "u"); + auto v = dense.newField(carbon::MemorySide::Device, "v"); + carbon::Skeleton sk(sys); + add_pipeline(sk, dense, u, v, geo); + if (dist.world_rank() == 0) { + const std::string dot = sk.export_kernel_list_dot("rank0_only"); + if (dot.find("region {1}") == std::string::npos) { + return fail("rank-local export: missing region annotation"); + } + } + return true; +} + +[[nodiscard]] auto +subtest_rank_mismatch(carbon::System& sys, + const carbon::Distributed& dist, + carbon::Dense& dense, + Geo geo) -> bool { + auto u = dense.newField(carbon::MemorySide::Device, "u"); + auto v = dense.newField(carbon::MemorySide::Device, "v"); + carbon::Skeleton sk(sys); + // Same cells, different declaration on rank 1: a contract violation the check must catch. + add_pipeline(sk, dense, u, v, geo, dist.world_rank() == 1 ? RegionMask::bit(7) : kWalls); + bool threw = false; + try { + sk.run(); + sk.wait(); + } catch (const std::logic_error& e) { + threw = std::string(e.what()).find("ranks added different pipelines") != std::string::npos; + } + if (!dist.all_ranks_equal(threw ? 1U : 0U) || !threw) { + return fail("rank-dependent mask: expected std::logic_error on every rank"); + } + return true; +} + +} // namespace + +int +main() { + carbon::init(); + + auto distributed = std::make_shared(); + if (distributed->world_size() < 2) { + CARBON_LOG_INFO("test_skeleton_region_mask_dist: world_size={} < 2, skipping", + distributed->world_size()); + return EXIT_SUCCESS; + } + if (carbon::device_count() < 1) { + CARBON_LOG_INFO("test_skeleton_region_mask_dist: no GPU devices, skipping"); + return EXIT_SUCCESS; + } + + carbon::System sys(distributed); + carbon::Stencil stencil( + std::vector{ + {1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}, + /*remove_center=*/true); + const carbon::int64_3d global{8, 5, 4 * static_cast(distributed->world_size())}; + carbon::Dense dense(sys, global, std::move(stencil)); + const Geo geo{global.x}; + + const bool ok = subtest_numerics(sys, *distributed, dense, geo) && + subtest_rank_local_export(sys, *distributed, dense, geo) && + subtest_rank_mismatch(sys, *distributed, dense, geo); + // Agree on the verdict so a one-rank failure cannot leave the peer blocked or green. + const bool all_ok = distributed->all_ranks_equal(ok ? 1U : 0U) && ok; + if (!all_ok) { + return EXIT_FAILURE; + } + CARBON_LOG_INFO("test_skeleton_region_mask_dist: OK on rank {}/{}", distributed->world_rank(), + distributed->world_size()); + return EXIT_SUCCESS; +} diff --git a/tests/test_skeleton_scalar_pattern.cu b/tests/test_skeleton_scalar_pattern.cu index d36080af..ede76247 100644 --- a/tests/test_skeleton_scalar_pattern.cu +++ b/tests/test_skeleton_scalar_pattern.cu @@ -113,6 +113,9 @@ main() { carbon::Transfer(sys, f.cpu_buffers(), f.gpu_buffers())(up); up.wait(); sk.run(); + // run() is asynchronous and unordered with `up`: without this wait the upload below races + // the reduction still reading f, and the lag-1 slot can see 3.0 (192 instead of 128). + sk.wait(); f.fill_owned_host([](carbon::int64_3d, int) { return 3.0F; }); diff --git a/tests/test_sub_grid.cu b/tests/test_sub_grid.cu new file mode 100644 index 00000000..573aa0aa --- /dev/null +++ b/tests/test_sub_grid.cu @@ -0,0 +1,301 @@ +// SubGrid construction test (milestone 1: types, lane tables, fields). +// +// Builds SubGrids over a multi-GPU Dense with a radius-1 z stencil (so every slab has an +// Internal and a Boundary region) and checks, against a brute-force host selection: +// +// - Coverage: per GPU, the lanes are exactly the owned cells whose label bit is in the mask, +// each once; parent-Internal cells first, then parent-Boundary cells, each run in parent +// iteration order (strictly increasing storage offset). +// - Determinism: building the same SubGrid twice gives identical lane tables. +// - The general predicate constructor, an empty selection, and multi-bit masks. +// - Fields: fill_owned_host + device round trip, and host-side reads through S partitions +// and, via the derived Span / Idx, through a parent-field partition. +// - Type rules: S::Span / S::Idx derive from the parent's, S::Partition does not, and a +// parent Idx does not convert to an S Idx. + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +using S = carbon::SubGrid; + +static_assert(std::is_base_of_v); +static_assert(std::is_base_of_v); +static_assert(!std::is_base_of_v, + S::Partition>); +static_assert(std::is_convertible_v); +static_assert(std::is_convertible_v); +static_assert(!std::is_convertible_v); +static_assert(!std::is_convertible_v); +static_assert(std::is_trivially_copyable_v); +static_assert(std::is_trivially_copyable_v); + +constexpr std::uint8_t kFaceLabel = 1; +constexpr std::uint8_t kBallLabel = 2; + +// 1 on the domain faces, 2 inside a small ball, 0 elsewhere. +[[nodiscard]] auto +label_of(carbon::int64_3d g, + carbon::int64_3d ext) -> std::uint8_t { + if (g.x == 0 || g.y == 0 || g.z == 0 || g.x == ext.x - 1 || g.y == ext.y - 1 || + g.z == ext.z - 1) { + return kFaceLabel; + } + const int64_t dx = g.x - ext.x / 2; + const int64_t dy = g.y - ext.y / 2; + const int64_t dz = g.z - ext.z / 2; + if (dx * dx + dy * dy + dz * dz <= 9) { + return kBallLabel; + } + return 0; +} + +int g_failures = 0; + +auto +expect(bool ok, + const std::string& what) -> void { + if (!ok) { + ++g_failures; + if (g_failures <= 20) { + CARBON_LOG_ERROR("test_sub_grid: {}", what); + } + } +} + +struct Expected { + std::vector internal; + std::vector boundary; +}; + +// Brute force: owned cells of GPU g in storage order, split by owned-local z band. +template +[[nodiscard]] auto +expected_cells(const carbon::Dense& dense, + size_t g, + Pred&& selected) -> Expected { + const auto& span = dense.spans()[g]; + const int64_t h = span.halo_z(); + const int64_t lz = span.logic_extent().z; + const auto ext = span.haloed_extent(); + Expected out; + for (int64_t bz = h; bz < h + lz; ++bz) { + const int64_t local_z = bz - h; + const bool boundary = h > 0 && (local_z < h || local_z >= lz - h); + for (int64_t y = 0; y < ext.y; ++y) { + for (int64_t x = 0; x < ext.x; ++x) { + const carbon::int64_3d cell{x, y, bz}; + if (selected(span.global_location(carbon::Dense::Idx(cell)))) { + (boundary ? out.boundary : out.internal).push_back(cell); + } + } + } + } + return out; +} + +template +auto +check_lanes(const carbon::Dense& dense, + const S& sub, + Pred&& selected, + const std::string& tag) -> void { + expect(sub.gpu_count() == dense.gpu_count(), tag + ": gpu_count"); + for (size_t g = 0; g < sub.gpu_count(); ++g) { + const Expected want = expected_cells(dense, g, selected); + const auto ni = static_cast(want.internal.size()); + const auto nb = static_cast(want.boundary.size()); + expect(sub.internal_count(g) == ni, tag + ": internal_count gpu " + std::to_string(g) + + " got " + std::to_string(sub.internal_count(g)) + + " want " + std::to_string(ni)); + expect(sub.boundary_count(g) == nb, tag + ": boundary_count gpu " + std::to_string(g) + + " got " + std::to_string(sub.boundary_count(g)) + + " want " + std::to_string(nb)); + if (sub.internal_count(g) != ni || sub.boundary_count(g) != nb) { + continue; + } + const auto& lanes = sub.host_spans()[g].sub(); + expect(lanes.count() == ni + nb, tag + ": span count"); + expect(lanes.lane_offset(carbon::DataView::Internal) == 0, tag + ": internal offset"); + expect(lanes.lane_count(carbon::DataView::Internal) == ni, tag + ": internal lane_count"); + expect(lanes.lane_offset(carbon::DataView::Boundary) == ni, tag + ": boundary offset"); + expect(lanes.lane_count(carbon::DataView::Boundary) == nb, tag + ": boundary lane_count"); + expect(lanes.lane_count(carbon::DataView::Standard) == ni + nb, tag + ": standard lane_count"); + expect(sub.spans()[g].sub().count() == ni + nb, tag + ": device span count"); + for (int64_t lane = 0; lane < ni + nb; ++lane) { + const carbon::int64_3d want_cell = lane < ni ? want.internal[static_cast(lane)] + : want.boundary[static_cast(lane - ni)]; + expect(sub.parent_idx(g, lane).cell() == want_cell, + tag + ": gpu " + std::to_string(g) + " lane " + std::to_string(lane) + " cell"); + } + } +} + +auto +same_tables(const S& a, + const S& b) -> bool { + if (a.gpu_count() != b.gpu_count()) { + return false; + } + for (size_t g = 0; g < a.gpu_count(); ++g) { + if (a.count(g) != b.count(g) || a.internal_count(g) != b.internal_count(g)) { + return false; + } + for (int64_t lane = 0; lane < a.count(g); ++lane) { + if (a.parent_idx(g, lane).cell() != b.parent_idx(g, lane).cell()) { + return false; + } + } + } + return true; +} + +[[nodiscard]] auto +encode(carbon::int64_3d g, + int c) -> float { + return static_cast(c * 1000000 + g.z * 10000 + g.y * 100 + g.x); +} + +} // namespace + +int +main() { + carbon::init(); + if (carbon::device_count() < 1) { + CARBON_LOG_WARN("test_sub_grid: no devices, skipping"); + return 0; + } + + try { + carbon::System sys(carbon::get_all_devices()); + const size_t n_gpus = sys.gpu_group().size(); + carbon::Stencil stencil(std::vector{{0, 0, -1}, {0, 0, 1}}, + /*remove_center=*/true); + const carbon::int64_3d ext{12, 10, 8 * static_cast(n_gpus)}; + carbon::Dense dense(sys, ext, std::move(stencil)); + expect(dense.spans()[0].halo_z() == 1, "expected halo_z == 1"); + + auto labels = dense.newField(carbon::MemorySide::HostDevice, "labels"); + labels.fill_owned_host([&](carbon::int64_3d g, int) { + return label_of(g, ext); + }); + carbon::Stream stream = sys.stream(); + carbon::Transfer upload(sys, labels.cpu_buffers(), labels.gpu_buffers()); + upload(stream); + stream.wait(); + + // Faces only. + const S faces = dense.new_sub_grid(labels, carbon::RegionMask{kFaceLabel}, "faces"); + check_lanes( + dense, faces, + [&](carbon::int64_3d g) { + return label_of(g, ext) == kFaceLabel; + }, + "faces"); + expect(faces.name() == "faces", "faces name"); + expect(faces.mask() == carbon::RegionMask{kFaceLabel}, "faces mask"); + + // Determinism. + const S faces_again = dense.new_sub_grid(labels, carbon::RegionMask{kFaceLabel}); + expect(same_tables(faces, faces_again), "rebuilding the same SubGrid changed its lane table"); + expect(faces.uid() != faces_again.uid(), "two SubGrids share a uid"); + + // Multi-bit mask. + const S both = dense.new_sub_grid(labels, carbon::RegionMask{kFaceLabel, kBallLabel}); + check_lanes( + dense, both, + [&](carbon::int64_3d g) { + return label_of(g, ext) != 0; + }, + "both"); + + // General predicate constructor. + const S every_third = dense.new_sub_grid([](carbon::KernelLoader&) { + return [] CARBON_HD(const carbon::Dense::Span& s, const carbon::Dense::Idx& i) { + return s.global_location(i).x % 3 == 0; + }; + }); + check_lanes( + dense, every_third, + [](carbon::int64_3d g) { + return g.x % 3 == 0; + }, + "every_third"); + expect(every_third.mask().is_all(), "predicate SubGrid default mask is all"); + + // Empty selection. + const S empty = dense.new_sub_grid(labels, carbon::RegionMask{7}); + expect(empty.total_count() == 0, "empty selection total_count"); + auto empty_field = empty.newField(carbon::MemorySide::HostDevice, "empty"); + empty_field.fill_owned_host([](carbon::int64_3d, int) { + return 1.0F; + }); + expect(empty_field.partitions().size() == n_gpus, "empty field partitions"); + + // Fields: fill on host, round trip through the device, read back via partitions. + auto f = faces.newField(carbon::MemorySide::HostDevice, "f"); + expect(f.name() == "f", "field name"); + expect(f.partitions().size() == n_gpus && f.host_partitions().size() == n_gpus, + "field partition counts"); + for (size_t g = 0; g < n_gpus; ++g) { + expect(f.cpu_buffers()[g].size() == static_cast(faces.count(g)) * 2U, + "field buffer size gpu " + std::to_string(g)); + expect(f.partitions()[g].owner() == faces.uid(), "partition owner"); + } + f.fill_owned_host([](carbon::int64_3d g, int c) { + return encode(g, c); + }); + carbon::Transfer up(sys, f.cpu_buffers(), f.gpu_buffers()); + up(stream); + for (size_t g = 0; g < n_gpus; ++g) { + float* h = f.cpu_buffers()[g].data(); + for (size_t k = 0; k < f.cpu_buffers()[g].size(); ++k) { + h[k] = -1.0F; + } + } + carbon::Transfer down(sys, f.gpu_buffers(), f.cpu_buffers()); + down(stream); + stream.wait(); + + for (size_t g = 0; g < n_gpus; ++g) { + const S::Span& s = faces.host_spans()[g]; + const auto& fp = f.host_partitions()[g]; + const auto& lp = labels.host_partitions()[g]; + for (int64_t lane = 0; lane < faces.count(g); ++lane) { + const S::Idx i(faces.parent_idx(g, lane), lane); + const carbon::int64_3d global = s.global_location(i); + expect(global == faces.global_location(g, lane), "global_location"); + for (int c = 0; c < 2; ++c) { + expect(fp.read(s, i, c) == encode(global, c), + "field round trip gpu " + std::to_string(g) + " lane " + std::to_string(lane)); + } + expect(lp.read(s, i, 0) == kFaceLabel, "parent-field read through S span / idx"); + } + } + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_sub_grid: exception: {}", e.what()); + return 1; + } + + if (g_failures > 0) { + CARBON_LOG_ERROR("test_sub_grid: {} failure(s)", g_failures); + return 1; + } + CARBON_LOG_INFO("test_sub_grid: OK"); + return 0; +} diff --git a/tests/test_sub_grid_block.cu b/tests/test_sub_grid_block.cu new file mode 100644 index 00000000..1a0bc698 --- /dev/null +++ b/tests/test_sub_grid_block.cu @@ -0,0 +1,622 @@ +// SubGrid over a Block (block-sparse) parent. +// +// A multi-GPU Block over a ball (so many bricks are partially active) and a SubGrid of a few +// hundred scattered "marker" voxels: a hash selection plus the two voxel rows on either side +// of the 2-GPU slab cut. The selection is checked to reach brick faces, inactive neighbours +// and (on several GPUs) the slab cut. Every result is compared exactly against a host +// reference built from the Block's host bitmasks and origins: +// +// - Construction: label and predicate constructors give the same lanes, in the Block's +// storage order (Internal bricks, then Boundary bricks, voxels z-y-x). +// - Device kernel: parent read / write, SubGrid field read / write, and x/y neighbour reads +// of a parent field that cross brick faces. +// - Host kernel: global_location (origins) and the same x/y neighbour reads (connectivity and +// bitmask) through the host topology tables. +// - Reductions: Sum / Max / count, Internal + Boundary == Standard, BlockAtomic, host and +// universal, an empty SubGrid, tokens and the ownership throw. +// - Skeleton: a Block writer followed by a SubGrid compute and a SubGrid reduction that +// stencil-read the parent in all six directions (across the slab cut through HaloBlock), +// under every OverlapMode, with the OCC split present exactly when overlap is on. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using SB = carbon::detail::block::DefaultStaticBlock; +using B = carbon::Block; +using S = carbon::SubGrid; +using carbon::DataView; +using carbon::int64_3d; + +constexpr std::uint8_t kMark = 1; + +[[nodiscard]] CARBON_HD constexpr auto +id_of(int64_3d g) -> int64_t { + return (g.z * 128 + g.y) * 128 + g.x; +} + +/** Scattered markers plus two sparse rows on either side of the 2-GPU slab cut. */ +[[nodiscard]] CARBON_HD constexpr auto +marked(int64_3d g, + int64_t n) -> bool { + const auto h = (static_cast(g.x) * 73856093ULL) ^ + (static_cast(g.y) * 19349663ULL) ^ + (static_cast(g.z) * 83492791ULL); + if (h % 211ULL == 0ULL) { + return true; + } + const int64_t cut = n / 2; + return (g.z == cut || g.z == cut - 1) && (g.x * 3 + g.y) % 29 == 0; +} + +[[nodiscard]] auto +in_ball(int64_3d g, + int64_t n) -> bool { + const double c = static_cast(n - 1) * 0.5; + const double r = static_cast(n) * 0.45; + const double dx = static_cast(g.x) - c; + const double dy = static_cast(g.y) - c; + const double dz = static_cast(g.z) - c; + return dx * dx + dy * dy + dz * dz <= r * r; +} + +[[nodiscard]] auto +active(int64_3d g, + int64_t n) -> bool { + return g.x >= 0 && g.y >= 0 && g.z >= 0 && g.x < n && g.y < n && g.z < n && in_ball(g, n); +} + +template +[[nodiscard]] CARBON_HD auto +xy_sum(const P& p, + const SpanT& s, + const IdxT& i) -> int64_t { + const auto xp = p.neighbour(s, i, carbon::int8_3d{1, 0, 0}, 0); + const auto xm = p.neighbour(s, i, carbon::int8_3d{-1, 0, 0}, 0); + const auto yp = p.neighbour(s, i, carbon::int8_3d{0, 1, 0}, 0); + const auto ym = p.neighbour(s, i, carbon::int8_3d{0, -1, 0}, 0); + return (xp.valid ? xp.value : 0) + (xm.valid ? xm.value : 0) + (yp.valid ? yp.value : 0) + + (ym.valid ? ym.value : 0); +} + +template +[[nodiscard]] CARBON_HD auto +six_sum(const P& p, + const SpanT& s, + const IdxT& i) -> int64_t { + const auto zp = p.neighbour(s, i, carbon::int8_3d{0, 0, 1}, 0); + const auto zm = p.neighbour(s, i, carbon::int8_3d{0, 0, -1}, 0); + return xy_sum(p, s, i) + (zp.valid ? zp.value : 0) + (zm.valid ? zm.value : 0); +} + +/** Host reference: sum of @p offset + id over the active neighbours of @p g in @p dirs . */ +[[nodiscard]] auto +ref_sum(int64_3d g, + int64_t n, + bool with_z, + int64_t offset) -> int64_t { + std::vector dirs{{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}}; + if (with_z) { + dirs.push_back({0, 0, 1}); + dirs.push_back({0, 0, -1}); + } + int64_t acc = 0; + for (const int64_3d d : dirs) { + const int64_3d h{g.x + d.x, g.y + d.y, g.z + d.z}; + if (active(h, n)) { + acc += id_of(h) + offset; + } + } + return acc; +} + +int g_failures = 0; + +auto +expect(bool ok, + const std::string& what) -> void { + if (!ok) { + ++g_failures; + if (g_failures <= 20) { + CARBON_LOG_ERROR("test_sub_grid_block: {}", what); + } + } +} + +template +auto +expect_throws(Fn&& fn, + const std::string& what) -> void { + try { + fn(); + } catch (const std::invalid_argument&) { + return; + } + expect(false, what + ": expected std::invalid_argument"); +} + +template +[[nodiscard]] auto +read_back(carbon::ReductionResult& r, + carbon::Stream& stream, + DataView view = DataView::Standard) -> T { + r.sync(stream); + stream.wait(); + return r.host_value(view); +} + +template +auto +to_device(carbon::System& sys, + Field& f, + carbon::Stream& stream) -> void { + carbon::Transfer(sys, f.cpu_buffers(), f.gpu_buffers())(stream); + stream.wait(); +} + +template +auto +to_host(carbon::System& sys, + Field& f, + carbon::Stream& stream) -> void { + carbon::Transfer(sys, f.gpu_buffers(), f.cpu_buffers())(stream); + stream.wait(); +} + +/** A selected voxel as the host reference sees it. */ +struct Cell { + int64_3d global{}; + B::Idx idx{}; +}; + +/** Zeroes every storage slot (owned and ghost) of a Block field on the device. */ +template +auto +zero_block_field(carbon::System& sys, + const B& block, + B::Field& f, + carbon::Stream& stream) -> void { + for (size_t g = 0; g < block.gpu_count(); ++g) { + const size_t n = static_cast(block.storage_block_count(g)) * SB::VoxelCount; + if (n != 0U) { + sys.async_memset(f.gpu_buffers()[g], 0, n * sizeof(T), stream); + } + } + stream.wait(); +} + +} // namespace + +int +main() { + carbon::init(); + if (carbon::device_count() < 1) { + CARBON_LOG_WARN("test_sub_grid_block: no devices, skipping"); + return 0; + } + + try { + carbon::System sys(carbon::get_all_devices()); + const size_t n_gpus = sys.gpu_group().size(); + const int64_t n = std::max(64, SB::MemZ * static_cast(n_gpus)); + const B block( + sys, int64_3d{n, n, n}, + [n](const int64_3d& g) { + return in_ball(g, n); + }, + "ball"); + carbon::Stream stream = sys.stream(); + + // ---- Host reference: selected voxels per GPU in Block storage order ------------------- + std::vector> want(n_gpus); + std::vector want_internal(n_gpus, 0); + int64_t brick_face_lanes = 0; + int64_t inactive_neighbour_lanes = 0; + int64_t slab_cut_lanes = 0; + for (size_t g = 0; g < n_gpus; ++g) { + const uint32_t n_internal = block.n_internal_blocks(g); + for (uint32_t b = 0; b < block.block_count(g); ++b) { + const auto& bm = block.host_bitmasks(g)[b]; + const carbon::int32_3d o = block.host_origins(g)[b]; + for (int z = 0; z < SB::MemZ; ++z) { + for (int y = 0; y < SB::MemY; ++y) { + for (int x = 0; x < SB::MemX; ++x) { + const int64_3d gc{o.x + x, o.y + y, o.z + z}; + if (!bm.is_active(x, y, z) || !marked(gc, n)) { + continue; + } + want[g].push_back({gc, B::Idx{b, static_cast(x), static_cast(y), + static_cast(z)}}); + want_internal[g] += b < n_internal ? 1 : 0; + brick_face_lanes += (x == 0 || y == 0 || z == 0 || x == SB::MemX - 1 || + y == SB::MemY - 1 || z == SB::MemZ - 1) + ? 1 + : 0; + inactive_neighbour_lanes += + (!active({gc.x + 1, gc.y, gc.z}, n) || !active({gc.x - 1, gc.y, gc.z}, n) || + !active({gc.x, gc.y + 1, gc.z}, n) || !active({gc.x, gc.y - 1, gc.z}, n)) + ? 1 + : 0; + slab_cut_lanes += (gc.z == n / 2 || gc.z == n / 2 - 1) ? 1 : 0; + } + } + } + } + } + int64_t want_total = 0; + for (const auto& w : want) { + want_total += static_cast(w.size()); + } + CARBON_LOG_INFO( + "test_sub_grid_block: {}^3 ball on {} GPU(s), {} blocks, {} active voxels; " + "{} selected ({} on brick faces, {} next to an inactive voxel, {} on the " + "slab-cut rows)", + n, n_gpus, block.block_count(), block.active_voxel_count(), want_total, brick_face_lanes, + inactive_neighbour_lanes, slab_cut_lanes); + expect(brick_face_lanes > 0, "selection reaches brick faces"); + expect(inactive_neighbour_lanes > 0, "selection reaches inactive neighbours"); + expect(slab_cut_lanes > 0, "selection reaches the slab cut rows"); + + // ---- Construction ----------------------------------------------------------------------- + auto labels = block.newField(carbon::MemorySide::Device, "labels"); + carbon::Kernel::compute( + block, + [labels, n](carbon::KernelLoader& L) { + auto out = L.write(labels); + return [=] CARBON_HD(const B::Span& s, const B::Idx& i) { + out.write(s, i, 0, marked(s.global_location(i), n) ? kMark : std::uint8_t{0}); + }; + }, + "label") + .launch(stream); + stream.wait(); + + const S marks = block.new_sub_grid(labels, carbon::RegionMask{kMark}, "marks"); + const S marks_pred = block.new_sub_grid( + [n](carbon::KernelLoader&) { + return [n] CARBON_HD(const B::Span& s, const B::Idx& i) -> bool { + return marked(s.global_location(i), n); + }; + }, + carbon::RegionMask{kMark}, "marks_pred"); + + expect(marks.gpu_count() == n_gpus, "gpu_count"); + expect(marks.total_count() > 0, "non-empty selection"); + for (size_t g = 0; g < n_gpus; ++g) { + expect(marks.count(g) == static_cast(want[g].size()), + "count on gpu " + std::to_string(g)); + expect(marks.internal_count(g) == want_internal[g], + "internal_count on gpu " + std::to_string(g)); + expect(marks_pred.count(g) == marks.count(g), "predicate constructor count"); + for (int64_t lane = 0; lane < std::min(marks.count(g), want[g].size()); ++lane) { + const Cell& c = want[g][static_cast(lane)]; + const B::Idx& p = marks.parent_idx(g, lane); + expect(p.block_idx() == c.idx.block_idx() && p.intra() == c.idx.intra(), + "lane order on gpu " + std::to_string(g)); + expect(marks.global_location(g, lane) == c.global, "global_location"); + if (lane < marks_pred.count(g)) { + const B::Idx& q = marks_pred.parent_idx(g, lane); + expect(q.block_idx() == p.block_idx() && q.intra() == p.intra(), + "label and predicate constructors agree"); + } + } + } + expect(n_gpus == 1 || marks.boundary_count(0) > 0, "boundary lanes on a multi-GPU slab"); + expect(marks.internal_count(0) > 0, "internal lanes"); + + // ---- Device kernel ---------------------------------------------------------------------- + auto u = block.newField(carbon::MemorySide::HostDevice, "u"); + zero_block_field(sys, block, u, stream); + carbon::Kernel::compute( + block, + [u](carbon::KernelLoader& L) { + auto p = L.write(u); + return [=] CARBON_HD(const B::Span& s, const B::Idx& i) { + p.write(s, i, 0, id_of(s.global_location(i))); + }; + }, + "init_u") + .launch(stream); + to_host(sys, u, stream); + + auto out = block.newField(carbon::MemorySide::Device, "out"); + zero_block_field(sys, block, out, stream); + auto q = marks.newField(carbon::MemorySide::HostDevice, "q"); + q.fill_owned_host([](int64_3d g, int) { + return g.x + 2 * g.y; + }); + to_device(sys, q, stream); + auto nxy = marks.newField(carbon::MemorySide::HostDevice, "nxy"); + + const carbon::Kernel k_dev = marks.make_kernel( + [u, out, q, nxy](carbon::KernelLoader& L) { + auto uG = L.read_stencil(u); + auto oG = L.write(out); + auto qS = L.read_write(q); + auto nS = L.write(nxy); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) { + oG.write(s, i, 0, 2 * uG.read(s, i, 0) + qS.read(s, i, 0)); + qS.write(s, i, 0, qS.read(s, i, 0) + 1); + nS.write(s, i, 0, xy_sum(uG, s, i)); + }; + }, + "s_device"); + k_dev.launch(stream); + stream.wait(); + auto out_host = block.download_to_host(out, stream); + stream.wait(); + to_host(sys, q, stream); + to_host(sys, nxy, stream); + for (size_t g = 0; g < n_gpus; ++g) { + const B::Span& span = block.span(g); + int64_t touched = 0; + for (uint32_t b = 0; b < block.block_count(g); ++b) { + const auto& bm = block.host_bitmasks(g)[b]; + const carbon::int32_3d o = block.host_origins(g)[b]; + for (int z = 0; z < SB::MemZ; ++z) { + for (int y = 0; y < SB::MemY; ++y) { + for (int x = 0; x < SB::MemX; ++x) { + if (!bm.is_active(x, y, z)) { + continue; + } + const int64_3d gc{o.x + x, o.y + y, o.z + z}; + const B::Idx idx{b, static_cast(x), static_cast(y), + static_cast(z)}; + const int64_t got = out_host[g].data()[span.linear_offset(idx, 1, 0)]; + const int64_t want_out = marked(gc, n) ? 2 * id_of(gc) + gc.x + 2 * gc.y : 0; + touched += got != 0 ? 1 : 0; + expect(got == want_out, "device kernel parent write at " + std::to_string(gc.x) + + "," + std::to_string(gc.y) + "," + std::to_string(gc.z)); + } + } + } + } + expect(touched == marks.count(g), "device kernel writes exactly the selected voxels"); + for (int64_t lane = 0; lane < marks.count(g); ++lane) { + const int64_3d gc = want[g][static_cast(lane)].global; + expect(q.cpu_buffers()[g].data()[lane] == gc.x + 2 * gc.y + 1, "SubGrid field write"); + expect(nxy.cpu_buffers()[g].data()[lane] == ref_sum(gc, n, false, 0), + "device x/y neighbour sum across bricks"); + } + } + + // ---- Host kernel ------------------------------------------------------------------------ + auto hloc = marks.newField(carbon::MemorySide::HostDevice, "hloc"); + auto hnxy = marks.newField(carbon::MemorySide::HostDevice, "hnxy"); + const carbon::Kernel k_host = marks.make_host_kernel( + [u, hloc, hnxy](carbon::KernelLoader& L) { + auto uG = L.read_stencil(u); + auto lS = L.write(hloc); + auto nS = L.write(hnxy); + return [=](const S::Span& s, const S::Idx& i) { + lS.write(s, i, 0, id_of(s.global_location(i))); + nS.write(s, i, 0, xy_sum(uG, s, i)); + }; + }, + "s_host"); + expect(k_host.kind() == carbon::KernelKind::ComputeHost, "host kernel kind"); + k_host.launch(stream); + for (size_t g = 0; g < n_gpus; ++g) { + for (int64_t lane = 0; lane < marks.count(g); ++lane) { + const int64_3d gc = want[g][static_cast(lane)].global; + expect(hloc.cpu_buffers()[g].data()[lane] == id_of(gc), "host global_location"); + expect(hnxy.cpu_buffers()[g].data()[lane] == ref_sum(gc, n, false, 0), + "host x/y neighbour sum across bricks"); + } + } + + // ---- Reductions ------------------------------------------------------------------------- + int64_t want_sum = 0; + int64_t want_internal_sum = 0; + int64_t want_max = std::numeric_limits::lowest(); + for (size_t g = 0; g < n_gpus; ++g) { + for (int64_t lane = 0; lane < marks.count(g); ++lane) { + const int64_3d gc = want[g][static_cast(lane)].global; + want_sum += id_of(gc); + want_internal_sum += lane < want_internal[g] ? id_of(gc) : 0; + want_max = std::max(want_max, gc.x + 2 * gc.y + 1); + } + } + auto sum_u = [u](carbon::KernelLoader& L) { + auto p = L.read(u); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) -> int64_t { + return p.read(s, i, 0); + }; + }; + auto sum_u_host = [u](carbon::KernelLoader& L) { + auto p = L.read(u); + return [=](const S::Span& s, const S::Idx& i) -> int64_t { + return p.read(s, i, 0); + }; + }; + + carbon::ReductionResult r_sum(sys); + const carbon::Kernel k_sum = marks.make_reduce_kernel(sum_u, r_sum); + k_sum.launch(stream); + expect(read_back(r_sum, stream) == want_sum, "device Sum of a parent field"); + k_sum.launch(stream, DataView::Internal); + k_sum.launch(stream, DataView::Boundary); + const int64_t got_internal = read_back(r_sum, stream, DataView::Internal); + const int64_t got_boundary = r_sum.host_value(DataView::Boundary); + expect(got_internal == want_internal_sum, "Internal-view sum"); + expect(got_internal + got_boundary == want_sum, "Internal + Boundary == Standard"); + + carbon::ReductionResult r_max(sys); + marks + .make_reduce_kernel( + [q](carbon::KernelLoader& L) { + auto p = L.read(q); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) -> int64_t { + return p.read(s, i, 0); + }; + }, + r_max, carbon::reduce::Max{}) + .launch(stream); + expect(read_back(r_max, stream) == want_max, "device Max of a SubGrid field"); + + carbon::ReductionResult r_count(sys); + marks + .make_reduce_kernel( + [](carbon::KernelLoader&) { + return [] CARBON_HD(const S::Span&, const S::Idx&) -> int64_t { + return 1; + }; + }, + r_count) + .launch(stream); + expect(read_back(r_count, stream) == marks.total_count(), "lane count"); + + carbon::ReductionResult r_atomic(sys); + carbon::reduce::ReduceOptions atomic; + atomic.finalize = carbon::reduce::ReduceFinalize::BlockAtomic; + marks.make_reduce_kernel(sum_u, r_atomic, {}, 0U, atomic).launch(stream); + expect(read_back(r_atomic, stream) == want_sum, "BlockAtomic Sum"); + + carbon::ReductionResult r_host(sys); + marks.make_host_reduce_kernel(sum_u_host, r_host).launch(stream); + expect(read_back(r_host, stream) == want_sum, "host Sum"); + + carbon::ReductionResult r_uni_dev(sys); + carbon::ReductionResult r_uni_host(sys); + marks.make_universal_reduce_kernel(sum_u, r_uni_dev).launch(stream); + marks.make_universal_reduce_kernel(sum_u, r_uni_host).launch_on_host(stream); + expect(read_back(r_uni_dev, stream) == want_sum, "universal reduce, device launch"); + expect(read_back(r_uni_host, stream) == want_sum, "universal reduce, host launch"); + + for (const carbon::AccessToken& t : k_sum.impl()->tokens()) { + if (t.resource == carbon::ResourceKind::Field) { + expect(t.mask == marks.mask(), "reduce field token carries the SubGrid mask"); + } + } + + const S empty = block.new_sub_grid(labels, carbon::RegionMask{9}, "empty"); + expect(empty.total_count() == 0, "empty selection"); + carbon::ReductionResult r_empty_sum(sys); + carbon::ReductionResult r_empty_max(sys); + empty.make_reduce_kernel(sum_u, r_empty_sum).launch(stream); + empty.make_reduce_kernel(sum_u, r_empty_max, carbon::reduce::Max{}) + .launch(stream); + expect(read_back(r_empty_sum, stream) == 0, "empty SubGrid Sum is 0"); + expect(read_back(r_empty_max, stream) == std::numeric_limits::lowest(), + "empty SubGrid Max is the identity"); + + auto pred_field = marks_pred.newField(carbon::MemorySide::Device, "pred_field"); + expect_throws( + [&]() { + (void)marks.make_kernel([pred_field](carbon::KernelLoader& L) { + auto p = L.write(pred_field); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) { + p.write(s, i, 0, 1); + }; + }); + }, + "loading another SubGrid's field"); + + // ---- Skeleton: stencil reads of the parent across the slab cut -------------------------- + constexpr int kIters = 3; + int64_t want_six_total = 0; + for (size_t g = 0; g < n_gpus; ++g) { + for (const Cell& c : want[g]) { + want_six_total += ref_sum(c.global, n, true, kIters); + } + } + for (const carbon::OverlapMode mode : + {carbon::OverlapMode::None, carbon::OverlapMode::Standard, carbon::OverlapMode::Extended, + carbon::OverlapMode::TwoWayExtended}) { + const std::string tag = "skeleton overlap=" + std::to_string(static_cast(mode)); + auto v = block.newField(carbon::MemorySide::Device, "v"); + zero_block_field(sys, block, v, stream); + carbon::Kernel::compute( + block, + [v](carbon::KernelLoader& L) { + auto p = L.write(v); + return [=] CARBON_HD(const B::Span& s, const B::Idx& i) { + p.write(s, i, 0, id_of(s.global_location(i))); + }; + }, + "init_v") + .launch(stream); + stream.wait(); + auto six = marks.newField(carbon::MemorySide::HostDevice, "six"); + carbon::ReductionResult r_six(sys); + + carbon::Skeleton sk(sys, carbon::Skeleton::Options(mode)); + sk.add(carbon::Kernel::compute( + block, + [v](carbon::KernelLoader& L) { + auto p = L.read_write(v); + return [=] CARBON_HD(const B::Span& s, const B::Idx& i) { + p.write(s, i, 0, p.read(s, i, 0) + 1); + }; + }, + "bump")); + sk.add(carbon::Kernel::compute( + marks, + [v, six](carbon::KernelLoader& L) { + auto p = L.read_stencil(v); + auto o = L.write(six); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) { + o.write(s, i, 0, six_sum(p, s, i)); + }; + }, + "s_nsum")); + sk.add(carbon::Kernel::reduce( + marks, + [v](carbon::KernelLoader& L) { + auto p = L.read_stencil(v); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) -> int64_t { + return six_sum(p, s, i); + }; + }, + r_six, carbon::reduce::Sum{}, "s_rsum")); + sk.compile(); + const std::string order = sk.export_launch_order(); + for (int it = 0; it < kIters; ++it) { + sk.run(); + } + sk.wait(); + + expect(read_back(r_six, stream) == want_six_total, tag + ": reduction value"); + to_host(sys, six, stream); + int64_t bad = 0; + for (size_t g = 0; g < n_gpus; ++g) { + for (int64_t lane = 0; lane < marks.count(g); ++lane) { + const int64_3d gc = want[g][static_cast(lane)].global; + bad += six.cpu_buffers()[g].data()[lane] != ref_sum(gc, n, true, kIters) ? 1 : 0; + } + } + expect(bad == 0, tag + ": " + std::to_string(bad) + " lanes with a wrong 6-neighbour sum"); + const auto has = [&order](const char* what) { + return order.find(what) != std::string::npos; + }; + const bool split = has("s_nsum [compute/internal]") && has("s_nsum [compute/boundary]") && + has("s_rsum [reduction/internal]") && has("s_rsum [reduction/boundary]"); + expect(split == (mode != carbon::OverlapMode::None), + tag + ": OCC split of the SubGrid kernels\n" + order); + } + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_sub_grid_block: exception: {}", e.what()); + return 1; + } + + if (g_failures > 0) { + CARBON_LOG_ERROR("test_sub_grid_block: {} failure(s)", g_failures); + return 1; + } + CARBON_LOG_INFO("test_sub_grid_block: OK"); + return 0; +} diff --git a/tests/test_sub_grid_jacobi_axpy.cu b/tests/test_sub_grid_jacobi_axpy.cu new file mode 100644 index 00000000..47aab994 --- /dev/null +++ b/tests/test_sub_grid_jacobi_axpy.cu @@ -0,0 +1,811 @@ +// A Jacobi step followed by an AXPY, with B and C in parallel, on Dense and Block parents. +// +// Every iteration computes, in int64 so any scheduling or indexing error is an exact mismatch, +// +// u_out = (sum of the 6 neighbours of u_in) / 6 + src on C +// u_out = (u_in + sum of its valid neighbours) / (1 + n_valid) + src on B +// y = 3 u_out + y everywhere +// +// where B is the set of voxels missing at least one face neighbour (domain face, or an +// inactive voxel of the Block ball) and C is every other active voxel. src = (x + 2y + 3z) % 5 +// keeps the field from flattening. u ping-pongs between u_a and u_b, and y accumulates every +// iteration's u, so a wrong value in any of the kIters iterations reaches the final check. +// +// Labels: kB = 1 on B, kC = 2 on C. Each parent grid runs the pipeline in these variants, +// kIters iterations each, then compares u_a and y with a host reference on every active voxel: +// +// no_s one parent Jacobi kernel that branches on neighbour validity (None, Standard) +// bc_parent B as a SubGrid + C as a masked parent kernel (region kC) under every OverlapMode +// bc_sub B and C as two SubGrids with complementary masks under every OverlapMode +// +// B and C write disjoint regions of u_out, so the Skeleton must not order them and must put +// them on different streams. With OCC on, each Jacobi step has exactly two [compute/internal] +// launches and two [compute/boundary] launches (b_X and c_X); the AXPYs stay whole. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using carbon::Dense; +using carbon::int64_3d; +using carbon::OverlapMode; +using carbon::RegionMask; +using SB = carbon::detail::block::DefaultStaticBlock; +using BlockGrid = carbon::Block; + +constexpr int kIters = 100; +static_assert(kIters % 2 == 0, + "kIters must be even so the result ends in u_a"); + +constexpr std::uint8_t kB = 1; +constexpr std::uint8_t kC = 2; +constexpr int64_t kAxpyA = 3; +constexpr int64_t kInactive = std::numeric_limits::min(); + +/** Domain box, optionally restricted to a ball (integer test, identical on host and device). */ +struct Geometry { + int64_3d ext{}; + bool ball = false; + + [[nodiscard]] CARBON_HD auto + active(int64_3d g) const -> bool { + if (g.x < 0 || g.y < 0 || g.z < 0 || g.x >= ext.x || g.y >= ext.y || g.z >= ext.z) { + return false; + } + if (!ball) { + return true; + } + // |2g - (n - 1)|^2 <= (0.9 n)^2, i.e. radius 0.45 n around the centre. + const int64_t dx = 2 * g.x - (ext.x - 1); + const int64_t dy = 2 * g.y - (ext.y - 1); + const int64_t dz = 2 * g.z - (ext.z - 1); + return 100 * (dx * dx + dy * dy + dz * dz) <= 81 * ext.x * ext.x; + } + + /** True when at least one face neighbour of @p g is missing: that voxel is in B. */ + [[nodiscard]] CARBON_HD auto + in_B(int64_3d g) const -> bool { + return !active({g.x + 1, g.y, g.z}) || !active({g.x - 1, g.y, g.z}) || + !active({g.x, g.y + 1, g.z}) || !active({g.x, g.y - 1, g.z}) || + !active({g.x, g.y, g.z + 1}) || !active({g.x, g.y, g.z - 1}); + } +}; + +[[nodiscard]] CARBON_HD constexpr auto +init_u(int64_3d g) -> int64_t { + return (7 * g.x + 3 * g.y + 5 * g.z) % 97 + 1; +} + +[[nodiscard]] CARBON_HD constexpr auto +init_y(int64_3d g) -> int64_t { + return g.x + g.y + g.z; +} + +[[nodiscard]] CARBON_HD constexpr auto +src(int64_3d g) -> int64_t { + return (g.x + 2 * g.y + 3 * g.z) % 5; +} + +struct NeighbourSum { + int64_t sum = 0; + int64_t count = 0; +}; + +template +[[nodiscard]] CARBON_HD auto +neighbour_sum(const P& p, + const SpanT& s, + const IdxT& i) -> NeighbourSum { + NeighbourSum r{}; + const auto add = [&r](const carbon::NeighbourValue& n) { + if (n.valid) { + r.sum += n.value; + ++r.count; + } + }; + add(p.neighbour(s, i, carbon::int8_3d{1, 0, 0}, 0)); + add(p.neighbour(s, i, carbon::int8_3d{-1, 0, 0}, 0)); + add(p.neighbour(s, i, carbon::int8_3d{0, 1, 0}, 0)); + add(p.neighbour(s, i, carbon::int8_3d{0, -1, 0}, 0)); + add(p.neighbour(s, i, carbon::int8_3d{0, 0, 1}, 0)); + add(p.neighbour(s, i, carbon::int8_3d{0, 0, -1}, 0)); + return r; +} + +[[nodiscard]] CARBON_HD constexpr auto +c_rule(NeighbourSum n) -> int64_t { + return n.sum / 6; +} + +[[nodiscard]] CARBON_HD constexpr auto +b_rule(int64_t self, + NeighbourSum n) -> int64_t { + return (self + n.sum) / (1 + n.count); +} + +int g_failures = 0; + +auto +expect(bool ok, + const std::string& what) -> void { + if (!ok) { + ++g_failures; + if (g_failures <= 20) { + CARBON_LOG_ERROR("test_sub_grid_jacobi_axpy: {}", what); + } + } +} + +// ---- Parent-specific pieces: field side, storage zeroing, owned-voxel walk, readback ---------- + +[[nodiscard]] auto +field_side(const Dense&) -> carbon::MemorySide { + return carbon::MemorySide::HostDevice; +} + +[[nodiscard]] auto +field_side(const BlockGrid&) -> carbon::MemorySide { + return carbon::MemorySide::Device; +} + +auto +zero_storage(carbon::System&, + const Dense&, + Dense::Field&, + carbon::Stream&) -> void {} + +auto +zero_storage(carbon::System& sys, + const BlockGrid& block, + BlockGrid::Field& f, + carbon::Stream& stream) -> void { + for (size_t g = 0; g < block.gpu_count(); ++g) { + const size_t n = static_cast(block.storage_block_count(g)) * SB::VoxelCount; + if (n != 0U) { + sys.async_memset(f.gpu_buffers()[g], 0, n * sizeof(int64_t), stream); + } + } + stream.wait(); +} + +/** Calls @p fn(global, offset) for every owned voxel of GPU @p g ; offset indexes host_values. */ +template +auto +for_each_owned(const Dense& dense, + size_t g, + Fn&& fn) -> void { + const Dense::Span& span = dense.spans()[g]; + const int64_t h = span.halo_z(); + const int64_3d ext = span.haloed_extent(); + for (int64_t z = h; z < h + span.logic_extent().z; ++z) { + for (int64_t y = 0; y < ext.y; ++y) { + for (int64_t x = 0; x < ext.x; ++x) { + const Dense::Idx idx(int64_3d{x, y, z}); + fn(span.global_location(idx), static_cast(span.linear_offset(idx))); + } + } + } +} + +template +auto +for_each_owned(const BlockGrid& block, + size_t g, + Fn&& fn) -> void { + const BlockGrid::Span& span = block.span(g); + for (uint32_t b = 0; b < block.block_count(g); ++b) { + const auto& bm = block.host_bitmasks(g)[b]; + const carbon::int32_3d o = block.host_origins(g)[b]; + for (int z = 0; z < SB::MemZ; ++z) { + for (int y = 0; y < SB::MemY; ++y) { + for (int x = 0; x < SB::MemX; ++x) { + if (!bm.is_active(x, y, z)) { + continue; + } + const BlockGrid::Idx idx{b, static_cast(x), static_cast(y), + static_cast(z)}; + fn(int64_3d{o.x + x, o.y + y, o.z + z}, + static_cast(span.linear_offset(idx, 1, 0))); + } + } + } + } +} + +[[nodiscard]] auto +host_values(carbon::System& sys, + const Dense&, + Dense::Field& f, + carbon::Stream& stream) -> std::vector> { + carbon::Transfer(sys, f.gpu_buffers(), f.cpu_buffers())(stream); + stream.wait(); + std::vector> out; + for (size_t g = 0; g < f.cpu_buffers().size(); ++g) { + const auto& buf = f.cpu_buffers()[g]; + out.emplace_back(buf.data(), buf.data() + buf.size()); + } + return out; +} + +[[nodiscard]] auto +host_values(carbon::System&, + const BlockGrid& block, + BlockGrid::Field& f, + carbon::Stream& stream) -> std::vector> { + const auto bufs = block.download_to_host(f, stream); + stream.wait(); + std::vector> out; + for (const auto& buf : bufs) { + out.emplace_back(buf.data(), buf.data() + buf.size()); + } + return out; +} + +// ---- Host reference ---------------------------------------------------------------------------- + +struct Reference { + std::vector u; + std::vector y; +}; + +[[nodiscard]] auto +linear(const Geometry& geo, + int64_3d g) -> size_t { + return static_cast((g.z * geo.ext.y + g.y) * geo.ext.x + g.x); +} + +[[nodiscard]] auto +reference(const Geometry& geo) -> Reference { + const size_t total = static_cast(geo.ext.x * geo.ext.y * geo.ext.z); + std::vector u(total, kInactive); + std::vector next(total, kInactive); + std::vector y(total, kInactive); + std::vector cells; + for (int64_t z = 0; z < geo.ext.z; ++z) { + for (int64_t yy = 0; yy < geo.ext.y; ++yy) { + for (int64_t x = 0; x < geo.ext.x; ++x) { + const int64_3d g{x, yy, z}; + if (geo.active(g)) { + cells.push_back(g); + u[linear(geo, g)] = init_u(g); + y[linear(geo, g)] = init_y(g); + } + } + } + } + const int64_3d dirs[6] = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}; + for (int it = 0; it < kIters; ++it) { + for (const int64_3d g : cells) { + NeighbourSum n{}; + for (const int64_3d d : dirs) { + const int64_3d h{g.x + d.x, g.y + d.y, g.z + d.z}; + if (geo.active(h)) { + n.sum += u[linear(geo, h)]; + ++n.count; + } + } + const int64_t self = u[linear(geo, g)]; + next[linear(geo, g)] = (n.count == 6 ? c_rule(n) : b_rule(self, n)) + src(g); + } + for (const int64_3d g : cells) { + y[linear(geo, g)] += kAxpyA * next[linear(geo, g)]; + } + std::swap(u, next); + } + return {std::move(u), std::move(y)}; +} + +// ---- Kernels ----------------------------------------------------------------------------------- + +template +using F = typename G::template Field; + +template +struct Fields { + F u_a; + F u_b; + F y; +}; + +template +[[nodiscard]] auto +make_fields(carbon::System& sys, + const G& grid, + carbon::Stream& stream) -> Fields { + Fields f{grid.template newField(field_side(grid), "u_a"), + grid.template newField(field_side(grid), "u_b"), + grid.template newField(field_side(grid), "y")}; + zero_storage(sys, grid, f.u_a, stream); + zero_storage(sys, grid, f.u_b, stream); + zero_storage(sys, grid, f.y, stream); + carbon::Kernel::compute( + grid, + [u_a = f.u_a, u_b = f.u_b, y = f.y](carbon::KernelLoader& L) { + auto pa = L.write(u_a); + auto pb = L.write(u_b); + auto py = L.write(y); + return [=] CARBON_HD(const typename G::Span& s, const typename G::Idx& i) { + const int64_3d g = s.global_location(i); + pa.write(s, i, 0, init_u(g)); + pb.write(s, i, 0, int64_t{0}); + py.write(s, i, 0, init_y(g)); + }; + }, + "init") + .launch(stream); + stream.wait(); + return f; +} + +// Without B/C: one kernel over every active voxel, branching on neighbour validity. +template +[[nodiscard]] auto +jacobi_full(const G& grid, + const F& in, + const F& out, + const std::string& name) -> carbon::Kernel { + return carbon::Kernel::compute( + grid, + [in, out](carbon::KernelLoader& L) { + auto pin = L.read_stencil(in); + auto pout = L.write(out); + return [=] CARBON_HD(const typename G::Span& s, const typename G::Idx& i) { + const NeighbourSum n = neighbour_sum(pin, s, i); + const int64_t v = n.count == 6 ? c_rule(n) : b_rule(pin.read(s, i, 0), n); + pout.write(s, i, 0, v + src(s.global_location(i))); + }; + }, + name); +} + +// C as a masked parent kernel: region kC, skips B voxels, interior (c) rule. +template +[[nodiscard]] auto +jacobi_c_parent(const G& grid, + const F& in, + const typename G::template Field& labels, + const F& out, + const std::string& name) -> carbon::Kernel { + return carbon::Kernel::compute( + grid, + [in, labels, out](carbon::KernelLoader& L) { + L.region(RegionMask{kC}); + auto lab = L.read(labels, RegionMask::all()); + auto pin = L.read_stencil(in); + auto pout = L.write(out); + return [=] CARBON_HD(const typename G::Span& s, const typename G::Idx& i) { + if (lab.read(s, i, 0) != kC) { + return; + } + pout.write(s, i, 0, c_rule(neighbour_sum(pin, s, i)) + src(s.global_location(i))); + }; + }, + name); +} + +/** SubGrid Jacobi: @p use_b_rule selects the B rule; otherwise the C rule. */ +template +[[nodiscard]] auto +jacobi_sub(const carbon::SubGrid& sub, + const F& in, + const F& out, + bool use_b_rule, + const std::string& name) -> carbon::Kernel { + using S = carbon::SubGrid; + return carbon::Kernel::compute( + sub, + [in, out, use_b_rule](carbon::KernelLoader& L) { + auto pin = L.read_stencil(in); + auto pout = L.write(out); + return [=] CARBON_HD(const typename S::Span& s, const typename S::Idx& i) { + const NeighbourSum n = neighbour_sum(pin, s, i); + const int64_t v = use_b_rule ? b_rule(pin.read(s, i, 0), n) : c_rule(n); + pout.write(s, i, 0, v + src(s.global_location(i))); + }; + }, + name); +} + +template +[[nodiscard]] auto +axpy(const G& grid, + const F& u, + const F& y, + const std::string& name) -> carbon::Kernel { + return carbon::Kernel::compute( + grid, + [u, y](carbon::KernelLoader& L) { + auto pu = L.read(u); + auto py = L.read_write(y); + return [=] CARBON_HD(const typename G::Span& s, const typename G::Idx& i) { + py.write(s, i, 0, kAxpyA * pu.read(s, i, 0) + py.read(s, i, 0)); + }; + }, + name); +} + +// ---- Launch-order helpers ---------------------------------------------------------------------- + +struct Launch { + size_t stream = 0; + std::string label; +}; + +/** Parse lines of the form " N stream K launch LABEL". */ +[[nodiscard]] auto +parse_launches(const std::string& order) -> std::vector { + std::vector out; + std::istringstream is(order); + std::string line; + while (std::getline(is, line)) { + const auto launch_pos = line.find(" launch "); + if (launch_pos == std::string::npos) { + continue; + } + const auto stream_pos = line.find("stream "); + if (stream_pos == std::string::npos) { + continue; + } + Launch L{}; + L.stream = static_cast(std::stoul(line.substr(stream_pos + 7))); + L.label = line.substr(launch_pos + 10); + out.push_back(std::move(L)); + } + return out; +} + +[[nodiscard]] auto +find_effective(const carbon::Skeleton& sk, + size_t user_idx) -> size_t { + const auto& to_user = sk.effective_to_user(); + for (size_t e = 0; e < to_user.size(); ++e) { + if (to_user[e] == user_idx) { + return e; + } + } + return carbon::Skeleton::kNoKernel; +} + +auto +expect_no_edge(const carbon::Skeleton& sk, + size_t user_a, + size_t user_b, + const std::string& tag) -> void { + const size_t e_a = find_effective(sk, user_a); + const size_t e_b = find_effective(sk, user_b); + expect(e_a != carbon::Skeleton::kNoKernel && e_b != carbon::Skeleton::kNoKernel, + tag + ": kernels not found in the effective list"); + if (e_a == carbon::Skeleton::kNoKernel || e_b == carbon::Skeleton::kNoKernel) { + return; + } + const auto has = [](const std::vector& succ, size_t target) { + return std::find(succ.begin(), succ.end(), target) != succ.end(); + }; + expect(!has(sk.edges()[e_a], e_b) && !has(sk.edges()[e_b], e_a), + tag + ": B and C write disjoint regions but are ordered"); +} + +[[nodiscard]] auto +matching(const std::vector& launches, + const std::string& label) -> std::vector { + std::vector out; + for (const Launch& L : launches) { + if (L.label == label) { + out.push_back(&L); + } + } + return out; +} + +auto +expect_bc_schedule(const std::vector& launches, + OverlapMode mode, + const std::string& step, // "ab" or "ba" + const std::string& tag) -> void { + // Unsplit launches are labelled "... [compute/standard]"; OCC halves use + // [compute/internal] / [compute/boundary]. + const std::string b = "b_" + step; + const std::string c = "c_" + step; + const auto b_std = matching(launches, b + " [compute/standard]"); + const auto c_std = matching(launches, c + " [compute/standard]"); + const auto b_i = matching(launches, b + " [compute/internal]"); + const auto b_bnd = matching(launches, b + " [compute/boundary]"); + const auto c_i = matching(launches, c + " [compute/internal]"); + const auto c_bnd = matching(launches, c + " [compute/boundary]"); + + if (mode == OverlapMode::None) { + expect(b_std.size() == 1 && c_std.size() == 1 && b_i.empty() && b_bnd.empty() && c_i.empty() && + c_bnd.empty(), + tag + " step " + step + ": None should launch each of b/c once as [compute/standard]"); + if (b_std.size() == 1 && c_std.size() == 1) { + expect(b_std[0]->stream != c_std[0]->stream, + tag + " step " + step + ": b and c must run on different streams under None"); + } + return; + } + + expect(b_std.empty() && c_std.empty(), + tag + " step " + step + ": OCC must not leave a [compute/standard] b/c launch"); + expect(b_i.size() == 1 && b_bnd.size() == 1 && c_i.size() == 1 && c_bnd.size() == 1, + tag + " step " + step + ": OCC needs exactly 2 internal + 2 boundary (b and c); got b_i=" + + std::to_string(b_i.size()) + " b_bnd=" + std::to_string(b_bnd.size()) + + " c_i=" + std::to_string(c_i.size()) + " c_bnd=" + std::to_string(c_bnd.size())); + if (b_i.size() == 1 && c_i.size() == 1) { + expect(b_i[0]->stream != c_i[0]->stream, + tag + " step " + step + ": the two internal halves must be on different streams"); + } + // The Skeleton currently places both boundary halves on the halo stream after the halo + // finishes; that still gives exactly two boundary launches per step. +} + +auto +expect_axpy_shape(const std::vector& launches, + OverlapMode mode, + const std::string& tag) -> void { + const auto a_std = matching(launches, "axpy_b [compute/standard]"); + const auto b_std = matching(launches, "axpy_a [compute/standard]"); + const auto a_i = matching(launches, "axpy_b [compute/internal]"); + const auto a_b = matching(launches, "axpy_b [compute/boundary]"); + const auto b_i = matching(launches, "axpy_a [compute/internal]"); + const auto b_bnd = matching(launches, "axpy_a [compute/boundary]"); + if (mode == OverlapMode::TwoWayExtended) { + // TwoWayExtended also OCC-splits the Map consumer that follows the stencil writers. + expect(a_std.empty() && b_std.empty() && a_i.size() == 1 && a_b.size() == 1 && + b_i.size() == 1 && b_bnd.size() == 1, + tag + ": TwoWayExtended should OCC-split both AXPYs"); + } else { + expect(a_std.size() == 1 && b_std.size() == 1 && a_i.empty() && a_b.empty() && b_i.empty() && + b_bnd.empty(), + tag + ": AXPY must stay a single [compute/standard] launch outside TwoWayExtended"); + } +} + +// ---- Driver ------------------------------------------------------------------------------------ + +template +auto +compare(carbon::System& sys, + const G& grid, + const Geometry& geo, + F& field, + const std::vector& want, + carbon::Stream& stream, + const std::string& tag) -> void { + const auto got = host_values(sys, grid, field, stream); + int64_t bad = 0; + int64_t checked = 0; + std::string first; + for (size_t g = 0; g < grid.gpu_count(); ++g) { + for_each_owned(grid, g, [&](int64_3d gc, size_t off) { + const int64_t w = want[linear(geo, gc)]; + const int64_t v = got[g][off]; + ++checked; + if (v != w) { + if (bad == 0) { + first = " (first at " + std::to_string(gc.x) + "," + std::to_string(gc.y) + "," + + std::to_string(gc.z) + ": got " + std::to_string(v) + ", want " + + std::to_string(w) + ")"; + } + ++bad; + } + }); + } + expect(checked > 0, tag + ": no voxels checked"); + expect(bad == 0, tag + ": field '" + field.name() + "' differs in " + std::to_string(bad) + + " of " + std::to_string(checked) + " voxels" + first); +} + +enum class BcForm : unsigned char { + None, + ParentC, + SubC +}; + +template +auto +run_grid(carbon::System& sys, + const G& grid, + const Geometry& geo, + const std::string& grid_tag) -> void { + using S = carbon::SubGrid; + carbon::Stream stream = sys.stream(); + + const Reference ref = reference(geo); + std::set distinct; + for (const int64_t v : ref.u) { + if (v != kInactive) { + distinct.insert(v); + } + } + expect(distinct.size() > 10, grid_tag + ": the reference u flattened to " + + std::to_string(distinct.size()) + " distinct values"); + + auto labels = grid.template newField(carbon::MemorySide::Device, "labels"); + carbon::Kernel::compute( + grid, + [labels, geo](carbon::KernelLoader& L) { + auto out = L.write(labels); + return [=] CARBON_HD(const typename G::Span& s, const typename G::Idx& i) { + out.write(s, i, 0, geo.in_B(s.global_location(i)) ? kB : kC); + }; + }, + "labels") + .launch(stream); + stream.wait(); + const S sub_b = grid.new_sub_grid(labels, RegionMask{kB}, "B"); + const S sub_c = grid.new_sub_grid(labels, RegionMask{kC}, "C"); + + int64_t owned_total = 0; + for (size_t g = 0; g < grid.gpu_count(); ++g) { + int64_t want_b = 0; + int64_t want_owned = 0; + for_each_owned(grid, g, [&](int64_3d gc, size_t) { + ++want_owned; + int64_t valid = 0; + for (const int64_3d d : {int64_3d{1, 0, 0}, int64_3d{-1, 0, 0}, int64_3d{0, 1, 0}, + int64_3d{0, -1, 0}, int64_3d{0, 0, 1}, int64_3d{0, 0, -1}}) { + valid += geo.active({gc.x + d.x, gc.y + d.y, gc.z + d.z}) ? 1 : 0; + } + want_b += valid < 6 ? 1 : 0; + }); + owned_total += want_owned; + expect(sub_b.count(g) == want_b, grid_tag + ": B.count on gpu " + std::to_string(g) + " is " + + std::to_string(sub_b.count(g)) + ", want " + + std::to_string(want_b)); + expect(sub_b.count(g) + sub_c.count(g) == want_owned, + grid_tag + ": B.count + C.count must equal owned voxels on gpu " + std::to_string(g)); + expect(sub_b.internal_count(g) <= sub_b.count(g), grid_tag + ": B.internal_count"); + } + expect(sub_b.total_count() > 0, grid_tag + ": empty B"); + expect(sub_c.total_count() > 0, grid_tag + ": empty C"); + CARBON_LOG_INFO( + "test_sub_grid_jacobi_axpy: {} on {} GPU(s): {} active voxels, {} in B, {} in C " + "({} distinct reference values after {} iterations)", + grid_tag, grid.gpu_count(), owned_total, sub_b.total_count(), sub_c.total_count(), + distinct.size(), kIters); + + struct Variant { + std::string name; + BcForm form; + OverlapMode mode; + }; + const std::vector variants{ + {"no_s", BcForm::None, OverlapMode::None}, + {"no_s/occ=standard", BcForm::None, OverlapMode::Standard}, + {"bc_parent", BcForm::ParentC, OverlapMode::None}, + {"bc_parent/occ=standard", BcForm::ParentC, OverlapMode::Standard}, + {"bc_parent/occ=extended", BcForm::ParentC, OverlapMode::Extended}, + {"bc_parent/occ=two_way_extended", BcForm::ParentC, OverlapMode::TwoWayExtended}, + {"bc_sub", BcForm::SubC, OverlapMode::None}, + {"bc_sub/occ=standard", BcForm::SubC, OverlapMode::Standard}, + {"bc_sub/occ=extended", BcForm::SubC, OverlapMode::Extended}, + {"bc_sub/occ=two_way_extended", BcForm::SubC, OverlapMode::TwoWayExtended}, + }; + + for (const Variant& var : variants) { + const std::string tag = grid_tag + " " + var.name; + Fields f = make_fields(sys, grid, stream); + std::string order; + try { + carbon::Skeleton sk(sys, carbon::Skeleton::Options(var.mode)); + if (var.form == BcForm::None) { + sk.add(jacobi_full(grid, f.u_a, f.u_b, "jacobi_ab")); + sk.add(axpy(grid, f.u_b, f.y, "axpy_b")); + sk.add(jacobi_full(grid, f.u_b, f.u_a, "jacobi_ba")); + sk.add(axpy(grid, f.u_a, f.y, "axpy_a")); + } else if (var.form == BcForm::ParentC) { + // User indices: 0=b_ab, 1=c_ab, 2=axpy_b, 3=b_ba, 4=c_ba, 5=axpy_a + sk.add(jacobi_sub(sub_b, f.u_a, f.u_b, /*use_b_rule=*/true, "b_ab")); + sk.add(jacobi_c_parent(grid, f.u_a, labels, f.u_b, "c_ab")); + sk.add(axpy(grid, f.u_b, f.y, "axpy_b")); + sk.add(jacobi_sub(sub_b, f.u_b, f.u_a, /*use_b_rule=*/true, "b_ba")); + sk.add(jacobi_c_parent(grid, f.u_b, labels, f.u_a, "c_ba")); + sk.add(axpy(grid, f.u_a, f.y, "axpy_a")); + } else { + sk.add(jacobi_sub(sub_b, f.u_a, f.u_b, /*use_b_rule=*/true, "b_ab")); + sk.add(jacobi_sub(sub_c, f.u_a, f.u_b, /*use_b_rule=*/false, "c_ab")); + sk.add(axpy(grid, f.u_b, f.y, "axpy_b")); + sk.add(jacobi_sub(sub_b, f.u_b, f.u_a, /*use_b_rule=*/true, "b_ba")); + sk.add(jacobi_sub(sub_c, f.u_b, f.u_a, /*use_b_rule=*/false, "c_ba")); + sk.add(axpy(grid, f.u_a, f.y, "axpy_a")); + } + sk.compile(); + order = sk.export_launch_order(); + const std::vector launches = parse_launches(order); + + if (var.form != BcForm::None) { + expect_no_edge(sk, 0, 1, tag + " ab"); + expect_no_edge(sk, 3, 4, tag + " ba"); + expect_bc_schedule(launches, var.mode, "ab", tag); + expect_bc_schedule(launches, var.mode, "ba", tag); + expect_axpy_shape(launches, var.mode, tag); + } else if (var.mode != OverlapMode::None) { + expect(std::any_of(launches.begin(), launches.end(), + [](const Launch& L) { + return L.label == "jacobi_ab [compute/internal]"; + }) && + std::any_of(launches.begin(), launches.end(), + [](const Launch& L) { + return L.label == "jacobi_ab [compute/boundary]"; + }), + tag + ": jacobi_ab should be OCC-split\n" + order); + } + + for (int cycle = 0; cycle < kIters / 2; ++cycle) { + sk.run(); + } + sk.wait(); + } catch (const std::exception& e) { + expect(false, tag + ": threw: " + e.what()); + continue; + } + + compare(sys, grid, geo, f.u_a, ref.u, stream, tag); + compare(sys, grid, geo, f.y, ref.y, stream, tag); + } +} + +} // namespace + +int +main() { + carbon::init(); + if (carbon::device_count() < 1) { + CARBON_LOG_WARN("test_sub_grid_jacobi_axpy: no devices, skipping"); + return 0; + } + + try { + carbon::System sys(carbon::get_all_devices()); + const auto n_gpus = static_cast(sys.gpu_group().size()); + + { + const Geometry geo{int64_3d{24, 20, 8 * n_gpus}, false}; + carbon::Stencil stencil( + std::vector{ + {1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}, + /*remove_center=*/true); + const Dense dense(sys, geo.ext, std::move(stencil)); + run_grid(sys, dense, geo, "dense"); + } + { + const int64_t n = std::max(64, SB::MemZ * n_gpus); + const Geometry geo{int64_3d{n, n, n}, true}; + const BlockGrid block( + sys, geo.ext, + [geo](const int64_3d& g) { + return geo.active(g); + }, + "ball"); + run_grid(sys, block, geo, "block"); + } + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_sub_grid_jacobi_axpy: exception: {}", e.what()); + return 1; + } + + if (g_failures > 0) { + CARBON_LOG_ERROR("test_sub_grid_jacobi_axpy: {} failure(s)", g_failures); + return 1; + } + CARBON_LOG_INFO("test_sub_grid_jacobi_axpy: OK"); + return 0; +} diff --git a/tests/test_sub_grid_kernel.cu b/tests/test_sub_grid_kernel.cu new file mode 100644 index 00000000..2ea738c6 --- /dev/null +++ b/tests/test_sub_grid_kernel.cu @@ -0,0 +1,329 @@ +// SubGrid kernel test (milestone 2: S.make_kernel / S.make_host_kernel). +// +// Over a multi-GPU Dense with a radius-1 z stencil and a "domain faces" SubGrid S: +// +// - Map: an S kernel reads a parent field through the S span / idx and writes an S field. +// - Views: Internal + Boundary launches touch every lane exactly once; Internal alone touches +// exactly the first internal_count lanes. +// - Scatter: an S kernel writes a parent field only at the selected cells. +// - Stencil on a parent field: after the parent halo, an S kernel reads z neighbours through +// read_stencil and matches a host reference, including across GPU slabs. +// - Host kernel: make_host_kernel gives the same result as the device kernel. +// - Tokens: Map accesses carry the SubGrid mask, stencil reads stay all ones. +// - Ownership: loading another SubGrid's field, or an S field from a Dense kernel, throws. +// - An empty SubGrid launches as a no-op. + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +using S = carbon::SubGrid; +using carbon::DataView; + +constexpr std::uint8_t kFace = 1; +constexpr std::uint8_t kBall = 2; + +[[nodiscard]] auto +label_of(carbon::int64_3d g, + carbon::int64_3d ext) -> std::uint8_t { + if (g.x == 0 || g.y == 0 || g.z == 0 || g.x == ext.x - 1 || g.y == ext.y - 1 || + g.z == ext.z - 1) { + return kFace; + } + const int64_t dx = g.x - ext.x / 2; + const int64_t dy = g.y - ext.y / 2; + const int64_t dz = g.z - ext.z / 2; + return dx * dx + dy * dy + dz * dz <= 9 ? kBall : std::uint8_t{0}; +} + +[[nodiscard]] auto +value_of(carbon::int64_3d g) -> float { + return static_cast(g.z * 10000 + g.y * 100 + g.x); +} + +int g_failures = 0; + +auto +expect(bool ok, + const std::string& what) -> void { + if (!ok) { + ++g_failures; + if (g_failures <= 20) { + CARBON_LOG_ERROR("test_sub_grid_kernel: {}", what); + } + } +} + +template +auto +download(carbon::System& sys, + Field& f, + carbon::Stream& stream) -> void { + carbon::Transfer d(sys, f.gpu_buffers(), f.cpu_buffers()); + d(stream); + stream.wait(); +} + +template +auto +upload(carbon::System& sys, + Field& f, + carbon::Stream& stream) -> void { + carbon::Transfer u(sys, f.cpu_buffers(), f.gpu_buffers()); + u(stream); + stream.wait(); +} + +template +auto +expect_throws(Fn&& fn, + const std::string& what) -> void { + try { + fn(); + } catch (const std::invalid_argument&) { + return; + } + expect(false, what + ": expected std::invalid_argument"); +} + +} // namespace + +int +main() { + carbon::init(); + if (carbon::device_count() < 1) { + CARBON_LOG_WARN("test_sub_grid_kernel: no devices, skipping"); + return 0; + } + + try { + carbon::System sys(carbon::get_all_devices()); + const size_t n_gpus = sys.gpu_group().size(); + carbon::Stencil stencil(std::vector{{0, 0, -1}, {0, 0, 1}}, + /*remove_center=*/true); + const carbon::int64_3d ext{12, 10, 8 * static_cast(n_gpus)}; + carbon::Dense dense(sys, ext, std::move(stencil)); + carbon::Stream stream = sys.stream(); + + auto labels = dense.newField(carbon::MemorySide::HostDevice, "labels"); + labels.fill_owned_host([&](carbon::int64_3d g, int) { + return label_of(g, ext); + }); + upload(sys, labels, stream); + + auto u = dense.newField(carbon::MemorySide::HostDevice, "u"); + u.fill_owned_host([](carbon::int64_3d g, int) { + return value_of(g); + }); + upload(sys, u, stream); + + const S faces = dense.new_sub_grid(labels, carbon::RegionMask{kFace}, "faces"); + + // ---- Map: parent read -> S write -------------------------------------------------- + auto twice = faces.newField(carbon::MemorySide::HostDevice, "twice"); + const carbon::Kernel map_k = faces.make_kernel( + [u, twice](carbon::KernelLoader& L) { + auto uG = L.read(u); + auto uS = L.write(twice); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) { + uS.write(s, i, 0, 2.0F * uG.read(s, i, 0)); + }; + }, + "map"); + expect(map_k.kind() == carbon::KernelKind::Compute, "map kernel kind"); + expect(map_k.name() == "map", "map kernel name"); + map_k.launch(stream); + stream.wait(); + download(sys, twice, stream); + for (size_t g = 0; g < n_gpus; ++g) { + for (int64_t lane = 0; lane < faces.count(g); ++lane) { + const float want = 2.0F * value_of(faces.global_location(g, lane)); + expect(twice.cpu_buffers()[g].data()[lane] == want, + "map gpu " + std::to_string(g) + " lane " + std::to_string(lane)); + } + } + + // Tokens: Map accesses carry the SubGrid mask. + for (const carbon::AccessToken& t : map_k.impl()->tokens()) { + expect(t.mask == faces.mask(), "map token '" + t.field_name + "' mask is the SubGrid mask"); + } + + // ---- Views: Internal + Boundary == Standard, each lane once ------------------------- + auto hits = faces.newField(carbon::MemorySide::HostDevice, "hits"); + const carbon::Kernel inc_k = faces.make_kernel([hits](carbon::KernelLoader& L) { + auto h = L.read_write(hits); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) { + h.write(s, i, 0, h.read(s, i, 0) + 1); + }; + }); + auto zero_hits = [&]() { + hits.fill_owned_host([](carbon::int64_3d, int) { + return 0; + }); + upload(sys, hits, stream); + }; + zero_hits(); + inc_k.launch(stream, DataView::Internal); + inc_k.launch(stream, DataView::Boundary); + stream.wait(); + download(sys, hits, stream); + for (size_t g = 0; g < n_gpus; ++g) { + for (int64_t lane = 0; lane < faces.count(g); ++lane) { + expect(hits.cpu_buffers()[g].data()[lane] == 1, "internal+boundary hits lane once"); + } + } + zero_hits(); + inc_k.launch(stream, DataView::Internal); + stream.wait(); + download(sys, hits, stream); + for (size_t g = 0; g < n_gpus; ++g) { + expect(faces.internal_count(g) > 0 && faces.boundary_count(g) > 0, + "test geometry has both internal and boundary lanes"); + for (int64_t lane = 0; lane < faces.count(g); ++lane) { + const int want = lane < faces.internal_count(g) ? 1 : 0; + expect(hits.cpu_buffers()[g].data()[lane] == want, "internal-only launch lane set"); + } + } + + // ---- Scatter: S kernel writes a parent field at the selected cells only ------------- + auto marks = dense.newField(carbon::MemorySide::HostDevice, "marks"); + marks.fill_owned_host([](carbon::int64_3d, int) { + return 0; + }); + upload(sys, marks, stream); + faces + .make_kernel([marks](carbon::KernelLoader& L) { + auto m = L.write(marks); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) { + m.write(s, i, 0, 7); + }; + }) + .launch(stream); + stream.wait(); + download(sys, marks, stream); + for (size_t g = 0; g < n_gpus; ++g) { + const auto& span = dense.spans()[g]; + const auto& mp = marks.host_partitions()[g]; + const int64_t h = span.halo_z(); + for (int64_t z = h; z < h + span.logic_extent().z; ++z) { + for (int64_t y = 0; y < ext.y; ++y) { + for (int64_t x = 0; x < ext.x; ++x) { + const carbon::Dense::Idx idx(carbon::int64_3d{x, y, z}); + const int want = label_of(span.global_location(idx), ext) == kFace ? 7 : 0; + expect(mp.read(span, idx, 0) == want, "scatter to parent field"); + } + } + } + } + + // ---- Stencil on a parent field (through the parent halo) ---------------------------- + auto zsum = faces.newField(carbon::MemorySide::HostDevice, "zsum"); + u.make_halo_kernel("halo_u").launch(stream); + const carbon::Kernel stencil_k = faces.make_kernel([u, zsum](carbon::KernelLoader& L) { + auto uG = L.read_stencil(u); + auto out = L.write(zsum); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) { + const auto up = uG.neighbour(s, i, carbon::int8_3d{0, 0, 1}, 0); + const auto dn = uG.neighbour(s, i, carbon::int8_3d{0, 0, -1}, 0); + out.write(s, i, 0, (up.valid ? up.value : 0.0F) + (dn.valid ? dn.value : 0.0F)); + }; + }); + bool saw_stencil = false; + for (const carbon::AccessToken& t : stencil_k.impl()->tokens()) { + if (t.pattern == carbon::AccessPattern::Stencil) { + saw_stencil = true; + expect(t.mask.is_all(), "stencil token keeps the all-ones mask"); + } + } + expect(saw_stencil, "stencil kernel recorded a stencil token"); + stencil_k.launch(stream); + stream.wait(); + download(sys, zsum, stream); + for (size_t g = 0; g < n_gpus; ++g) { + for (int64_t lane = 0; lane < faces.count(g); ++lane) { + const carbon::int64_3d c = faces.global_location(g, lane); + float want = 0.0F; + if (c.z + 1 < ext.z) { + want += value_of({c.x, c.y, c.z + 1}); + } + if (c.z > 0) { + want += value_of({c.x, c.y, c.z - 1}); + } + expect(zsum.cpu_buffers()[g].data()[lane] == want, + "parent stencil gpu " + std::to_string(g) + " lane " + std::to_string(lane)); + } + } + + // ---- Host kernel ---------------------------------------------------------------------- + auto twice_host = faces.newField(carbon::MemorySide::HostDevice, "twice_host"); + const carbon::Kernel host_k = faces.make_host_kernel([u, twice_host](carbon::KernelLoader& L) { + auto uG = L.read(u); + auto uS = L.write(twice_host); + return [=](const S::Span& s, const S::Idx& i) { + uS.write(s, i, 0, 2.0F * uG.read(s, i, 0)); + }; + }); + expect(host_k.kind() == carbon::KernelKind::ComputeHost, "host kernel kind"); + host_k.launch(stream); + for (size_t g = 0; g < n_gpus; ++g) { + for (int64_t lane = 0; lane < faces.count(g); ++lane) { + expect(twice_host.cpu_buffers()[g].data()[lane] == twice.cpu_buffers()[g].data()[lane], + "host kernel matches device kernel"); + } + } + + // ---- Ownership ----------------------------------------------------------------------- + const S ball = dense.new_sub_grid(labels, carbon::RegionMask{kBall}, "ball"); + auto ball_field = ball.newField(carbon::MemorySide::Device, "ball_field"); + expect_throws( + [&]() { + (void)faces.make_kernel([ball_field](carbon::KernelLoader& L) { + auto b = L.read(ball_field); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) { + (void)b.read(s, i, 0); + }; + }); + }, + "loading another SubGrid's field"); + expect_throws( + [&]() { + (void)dense.make_kernel([ball_field](carbon::KernelLoader& L) { + (void)L.read(ball_field); + return [] CARBON_HD(const carbon::Dense::Span&, const carbon::Dense::Idx&) { + }; + }); + }, + "loading a SubGrid field from a Dense kernel"); + + // ---- Empty SubGrid ------------------------------------------------------------------- + const S empty = dense.new_sub_grid(labels, carbon::RegionMask{9}); + auto empty_field = empty.newField(carbon::MemorySide::Device, "empty_field"); + const carbon::Kernel empty_k = empty.make_kernel([empty_field](carbon::KernelLoader& L) { + auto e = L.write(empty_field); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) { + e.write(s, i, 0, 1.0F); + }; + }); + for (const DataView v : {DataView::Standard, DataView::Internal, DataView::Boundary}) { + empty_k.launch(stream, v); + } + stream.wait(); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_sub_grid_kernel: exception: {}", e.what()); + return 1; + } + + if (g_failures > 0) { + CARBON_LOG_ERROR("test_sub_grid_kernel: {} failure(s)", g_failures); + return 1; + } + CARBON_LOG_INFO("test_sub_grid_kernel: OK"); + return 0; +} diff --git a/tests/test_sub_grid_reduce.cu b/tests/test_sub_grid_reduce.cu new file mode 100644 index 00000000..2d2f9b23 --- /dev/null +++ b/tests/test_sub_grid_reduce.cu @@ -0,0 +1,350 @@ +// SubGrid reductions. +// +// Over a multi-GPU Dense with a radius-1 z stencil and a "domain faces" SubGrid, every +// result is compared exactly (integer values) against a host reference over the selection: +// +// - Sum of a parent field, Max of a SubGrid field, and a lane count, on the device. +// - Views: the Internal and Boundary results add up to the Standard one. +// - ReduceFinalize::BlockAtomic, the host reduction, and the universal reduction (device and +// host launches) agree with the default device reduction. +// - Tokens: Map reads carry the SubGrid mask. +// - Errors: loading another SubGrid's field and ReduceOptions::stage1_threads throw. +// - An empty SubGrid reduces to the operator's identity. +// - Skeleton: a reduction that stencil-reads a parent field after a Dense writer is +// OCC-split (Internal / Boundary partials + merge) and gives the reference value under +// every OverlapMode. + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using S = carbon::SubGrid; +using carbon::DataView; +using carbon::Dense; + +constexpr std::uint8_t kFace = 1; +constexpr std::uint8_t kBall = 2; + +[[nodiscard]] auto +label_of(carbon::int64_3d g, + carbon::int64_3d ext) -> std::uint8_t { + if (g.x == 0 || g.y == 0 || g.z == 0 || g.x == ext.x - 1 || g.y == ext.y - 1 || + g.z == ext.z - 1) { + return kFace; + } + const int64_t dx = g.x - ext.x / 2; + const int64_t dy = g.y - ext.y / 2; + const int64_t dz = g.z - ext.z / 2; + return dx * dx + dy * dy + dz * dz <= 9 ? kBall : std::uint8_t{0}; +} + +[[nodiscard]] auto +id_of(carbon::int64_3d g) -> int64_t { + return g.z * 10000 + g.y * 100 + g.x; +} + +int g_failures = 0; + +auto +expect(bool ok, + const std::string& what) -> void { + if (!ok) { + ++g_failures; + if (g_failures <= 20) { + CARBON_LOG_ERROR("test_sub_grid_reduce: {}", what); + } + } +} + +template +auto +upload(carbon::System& sys, + Field& f, + carbon::Stream& stream) -> void { + carbon::Transfer(sys, f.cpu_buffers(), f.gpu_buffers())(stream); + stream.wait(); +} + +template +auto +expect_throws(Fn&& fn, + const std::string& what) -> void { + try { + fn(); + } catch (const std::invalid_argument&) { + return; + } + expect(false, what + ": expected std::invalid_argument"); +} + +template +[[nodiscard]] auto +read_back(carbon::ReductionResult& r, + carbon::Stream& stream, + DataView view = DataView::Standard) -> T { + r.sync(stream); + stream.wait(); + return r.host_value(view); +} + +} // namespace + +int +main() { + carbon::init(); + if (carbon::device_count() < 1) { + CARBON_LOG_WARN("test_sub_grid_reduce: no devices, skipping"); + return 0; + } + + try { + carbon::System sys(carbon::get_all_devices()); + const size_t n_gpus = sys.gpu_group().size(); + carbon::Stencil stencil(std::vector{{0, 0, -1}, {0, 0, 1}}, + /*remove_center=*/true); + const carbon::int64_3d ext{12, 10, 8 * static_cast(n_gpus)}; + Dense dense(sys, ext, std::move(stencil)); + carbon::Stream stream = sys.stream(); + + auto labels = dense.newField(carbon::MemorySide::HostDevice, "labels"); + labels.fill_owned_host([&](carbon::int64_3d g, int) { + return label_of(g, ext); + }); + upload(sys, labels, stream); + auto ids = dense.newField(carbon::MemorySide::HostDevice, "ids"); + ids.fill_owned_host([](carbon::int64_3d g, int) { + return id_of(g); + }); + upload(sys, ids, stream); + + const S faces = dense.new_sub_grid(labels, carbon::RegionMask{kFace}, "faces"); + auto weight = faces.newField(carbon::MemorySide::HostDevice, "weight"); + weight.fill_owned_host([](carbon::int64_3d g, int) { + return (g.x * 7 + g.y * 13) % 101; + }); + upload(sys, weight, stream); + + // Host references, total and per view. + int64_t want_sum = 0; + int64_t want_max = std::numeric_limits::lowest(); + int64_t want_internal_sum = 0; + for (size_t g = 0; g < n_gpus; ++g) { + for (int64_t lane = 0; lane < faces.count(g); ++lane) { + const carbon::int64_3d c = faces.global_location(g, lane); + want_sum += id_of(c); + want_max = std::max(want_max, (c.x * 7 + c.y * 13) % 101); + if (lane < faces.internal_count(g)) { + want_internal_sum += id_of(c); + } + } + } + + auto sum_ids = [ids](carbon::KernelLoader& L) { + auto p = L.read(ids); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) -> int64_t { + return p.read(s, i, 0); + }; + }; + auto sum_ids_host = [ids](carbon::KernelLoader& L) { + auto p = L.read(ids); + return [=](const S::Span& s, const S::Idx& i) -> int64_t { + return p.read(s, i, 0); + }; + }; + + // ---- Device Sum, Max, count ------------------------------------------------------- + carbon::ReductionResult r_sum(sys); + const carbon::Kernel k_sum = faces.make_reduce_kernel(sum_ids, r_sum); + expect(k_sum.kind() == carbon::KernelKind::Reduction, "reduce kernel kind"); + k_sum.launch(stream); + expect(read_back(r_sum, stream) == want_sum, "device Sum of a parent field"); + + carbon::ReductionResult r_max(sys); + carbon::Kernel::reduce( + faces, + [weight](carbon::KernelLoader& L) { + auto w = L.read(weight); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) -> int64_t { + return w.read(s, i, 0); + }; + }, + r_max, carbon::reduce::Max{}, "max_weight") + .launch(stream); + expect(read_back(r_max, stream) == want_max, "device Max of a SubGrid field"); + + carbon::ReductionResult r_count(sys); + faces + .make_reduce_kernel( + [](carbon::KernelLoader&) { + return [] CARBON_HD(const S::Span&, const S::Idx&) -> int64_t { + return 1; + }; + }, + r_count) + .launch(stream); + expect(read_back(r_count, stream) == faces.total_count(), "lane count"); + + // ---- Views ---------------------------------------------------------------------------- + k_sum.launch(stream, DataView::Internal); + k_sum.launch(stream, DataView::Boundary); + const int64_t got_internal = read_back(r_sum, stream, DataView::Internal); + const int64_t got_boundary = r_sum.host_value(DataView::Boundary); + expect(faces.boundary_count(0) > 0, "test geometry has boundary lanes"); + expect(got_internal == want_internal_sum, "Internal-view sum"); + expect(got_internal + got_boundary == want_sum, "Internal + Boundary == Standard"); + + // ---- BlockAtomic, host, universal ----------------------------------------------------- + carbon::ReductionResult r_atomic(sys); + carbon::reduce::ReduceOptions atomic; + atomic.finalize = carbon::reduce::ReduceFinalize::BlockAtomic; + faces.make_reduce_kernel(sum_ids, r_atomic, {}, 0U, atomic).launch(stream); + expect(read_back(r_atomic, stream) == want_sum, "BlockAtomic Sum"); + + carbon::ReductionResult r_host(sys); + const carbon::Kernel k_host = faces.make_host_reduce_kernel(sum_ids_host, r_host); + expect(k_host.kind() == carbon::KernelKind::ReductionHost, "host reduce kind"); + k_host.launch(stream); + expect(read_back(r_host, stream) == want_sum, "host Sum"); + + carbon::ReductionResult r_uni_dev(sys); + carbon::ReductionResult r_uni_host(sys); + auto sum_ids_universal = [ids](carbon::KernelLoader& L) { + auto p = L.read(ids); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) -> int64_t { + return p.read(s, i, 0); + }; + }; + faces.make_universal_reduce_kernel(sum_ids_universal, r_uni_dev).launch(stream); + faces.make_universal_reduce_kernel(sum_ids_universal, r_uni_host) + .launch_on_host(stream); + expect(read_back(r_uni_dev, stream) == want_sum, "universal reduce, device launch"); + expect(read_back(r_uni_host, stream) == want_sum, "universal reduce, host launch"); + + // ---- Tokens ----------------------------------------------------------------------------- + for (const carbon::AccessToken& t : k_sum.impl()->tokens()) { + if (t.resource == carbon::ResourceKind::Field) { + expect(t.mask == faces.mask(), "reduce field token carries the SubGrid mask"); + } + } + + // ---- Errors ----------------------------------------------------------------------------- + const S ball = dense.new_sub_grid(labels, carbon::RegionMask{kBall}, "ball"); + auto ball_field = ball.newField(carbon::MemorySide::Device, "ball_field"); + carbon::ReductionResult r_err(sys); + expect_throws( + [&]() { + (void)faces.make_reduce_kernel( + [ball_field](carbon::KernelLoader& L) { + auto b = L.read(ball_field); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) -> int64_t { + return b.read(s, i, 0); + }; + }, + r_err); + }, + "reducing another SubGrid's field"); + carbon::reduce::ReduceOptions threads; + threads.stage1_threads = 128U; + expect_throws( + [&]() { + (void)faces.make_reduce_kernel(sum_ids, r_err, {}, 0U, threads); + }, + "ReduceOptions::stage1_threads"); + + // ---- Empty SubGrid ---------------------------------------------------------------------- + const S empty = dense.new_sub_grid(labels, carbon::RegionMask{9}); + carbon::ReductionResult r_empty_sum(sys); + carbon::ReductionResult r_empty_max(sys); + empty.make_reduce_kernel(sum_ids, r_empty_sum).launch(stream); + empty + .make_reduce_kernel( + [ids](carbon::KernelLoader& L) { + auto p = L.read(ids); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) -> int64_t { + return p.read(s, i, 0); + }; + }, + r_empty_max, carbon::reduce::Max{}) + .launch(stream); + expect(read_back(r_empty_sum, stream) == 0, "empty SubGrid Sum is 0"); + expect(read_back(r_empty_max, stream) == std::numeric_limits::lowest(), + "empty SubGrid Max is the identity"); + + // ---- Skeleton: OCC-split reduction over a stencil read ---------------------------------- + constexpr int kIters = 3; + // After kIters bumps every cell holds id + kIters; the reduction sums z neighbours. + int64_t want_zsum = 0; + for (size_t g = 0; g < n_gpus; ++g) { + for (int64_t lane = 0; lane < faces.count(g); ++lane) { + const carbon::int64_3d c = faces.global_location(g, lane); + if (c.z + 1 < ext.z) { + want_zsum += id_of({c.x, c.y, c.z + 1}) + kIters; + } + if (c.z > 0) { + want_zsum += id_of({c.x, c.y, c.z - 1}) + kIters; + } + } + } + for (const carbon::OverlapMode mode : + {carbon::OverlapMode::None, carbon::OverlapMode::Standard, carbon::OverlapMode::Extended, + carbon::OverlapMode::TwoWayExtended}) { + const std::string tag = "skeleton overlap=" + std::to_string(static_cast(mode)); + auto u = dense.newField(carbon::MemorySide::HostDevice, "u"); + u.fill_owned_host([](carbon::int64_3d g, int) { + return id_of(g); + }); + upload(sys, u, stream); + carbon::ReductionResult r_z(sys); + carbon::Skeleton sk(sys, carbon::Skeleton::Options(mode)); + sk.add(carbon::Kernel::compute( + dense, + [u](carbon::KernelLoader& L) { + auto p = L.read_write(u); + return [=] CARBON_HD(const Dense::Span& s, const Dense::Idx& i) { + p.write(s, i, 0, p.read(s, i, 0) + 1); + }; + }, + "bump")); + sk.add(carbon::Kernel::reduce( + faces, + [u](carbon::KernelLoader& L) { + auto p = L.read_stencil(u); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) -> int64_t { + const auto up = p.neighbour(s, i, carbon::int8_3d{0, 0, 1}, 0); + const auto dn = p.neighbour(s, i, carbon::int8_3d{0, 0, -1}, 0); + return (up.valid ? up.value : 0) + (dn.valid ? dn.value : 0); + }; + }, + r_z, carbon::reduce::Sum{}, "s_zsum")); + sk.compile(); + const std::string order = sk.export_launch_order(); + for (int it = 0; it < kIters; ++it) { + sk.run(); + } + sk.wait(); + expect(read_back(r_z, stream) == want_zsum, tag + ": reduction value"); + const bool split = order.find("s_zsum [reduction/internal]") != std::string::npos && + order.find("s_zsum [reduction/boundary]") != std::string::npos; + expect(split == (mode != carbon::OverlapMode::None), + tag + ": OCC split of the SubGrid reduction\n" + order); + } + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_sub_grid_reduce: exception: {}", e.what()); + return 1; + } + + if (g_failures > 0) { + CARBON_LOG_ERROR("test_sub_grid_reduce: {} failure(s)", g_failures); + return 1; + } + CARBON_LOG_INFO("test_sub_grid_reduce: OK"); + return 0; +} diff --git a/tests/test_sub_grid_skeleton.cu b/tests/test_sub_grid_skeleton.cu new file mode 100644 index 00000000..2fa95dd0 --- /dev/null +++ b/tests/test_sub_grid_skeleton.cu @@ -0,0 +1,429 @@ +// SubGrid kernels under the Skeleton (milestone 3). +// +// Over a multi-GPU Dense with a radius-1 z stencil and a "domain faces" SubGrid: +// +// A. A pipeline mixing parent and SubGrid kernels - +// bump (Dense, Map) u = 0.5 u + 1 +// s_smooth (S, stencil on u) acc += u(z-1) + u(z+1) [S field] +// s_scatter (S, Map) v = 0.25 acc at the S cells [parent field] +// d_stencil (Dense, stencil) w = v + v(z+1) - v(z-1) +// back (Dense, Map) u += 0.001 w +// is run for a few iterations under every OverlapMode, with a CUDA graph, and with +// region masks ignored, and every field must match a hand-sequenced single-stream run +// with explicit halos bit for bit. Standard OCC must split s_smooth (an S kernel that +// stencil-reads a parent field after its halo); Extended OCC must also split s_scatter, +// the S kernel producing d_stencil's stencil input. +// B. Two SubGrids with disjoint masks writing the same parent field get no edge and run on +// different streams; with masks ignored they are ordered. Both write their cells. + +#include + +#include +#include +#include +#include +#include + +namespace { + +using S = carbon::SubGrid; +using carbon::Dense; + +constexpr std::uint8_t kFace = 1; +constexpr std::uint8_t kBall = 2; +constexpr int kIters = 3; + +[[nodiscard]] auto +label_of(carbon::int64_3d g, + carbon::int64_3d ext) -> std::uint8_t { + if (g.x == 0 || g.y == 0 || g.z == 0 || g.x == ext.x - 1 || g.y == ext.y - 1 || + g.z == ext.z - 1) { + return kFace; + } + const int64_t dx = g.x - ext.x / 2; + const int64_t dy = g.y - ext.y / 2; + const int64_t dz = g.z - ext.z / 2; + return dx * dx + dy * dy + dz * dz <= 9 ? kBall : std::uint8_t{0}; +} + +int g_failures = 0; + +auto +expect(bool ok, + const std::string& what) -> void { + if (!ok) { + ++g_failures; + if (g_failures <= 20) { + CARBON_LOG_ERROR("test_sub_grid_skeleton: {}", what); + } + } +} + +template +auto +transfer(carbon::System& sys, + Field& f, + carbon::Stream& stream, + bool to_device) -> void { + using T = typename Field::value_type; + if (to_device) { + carbon::Transfer(sys, f.cpu_buffers(), f.gpu_buffers())(stream); + } else { + carbon::Transfer(sys, f.gpu_buffers(), f.cpu_buffers())(stream); + } + stream.wait(); +} + +struct Fields { + Dense::Field u; + Dense::Field v; + Dense::Field w; + S::Field acc; +}; + +[[nodiscard]] auto +make_fields(carbon::System& sys, + const Dense& dense, + const S& sub, + carbon::Stream& stream) -> Fields { + Fields f{dense.newField(carbon::MemorySide::HostDevice, "u"), + dense.newField(carbon::MemorySide::HostDevice, "v"), + dense.newField(carbon::MemorySide::HostDevice, "w"), + sub.newField(carbon::MemorySide::HostDevice, "acc")}; + f.u.fill_owned_host([](carbon::int64_3d g, int) { + return static_cast((g.x * 7 + g.y * 3 + g.z * 5) % 17) * 0.125F; + }); + f.v.fill_owned_host([](carbon::int64_3d g, int) { + return static_cast(g.z) * 0.5F; + }); + f.w.fill_owned_host([](carbon::int64_3d, int) { + return 0.0F; + }); + f.acc.fill_owned_host([](carbon::int64_3d g, int) { + return static_cast(g.x) * 0.25F; + }); + transfer(sys, f.u, stream, true); + transfer(sys, f.v, stream, true); + transfer(sys, f.w, stream, true); + transfer(sys, f.acc, stream, true); + return f; +} + +[[nodiscard]] CARBON_HD inline auto +or_zero(carbon::NeighbourValue n) -> float { + return n.valid ? n.value : 0.0F; +} + +// User kernels of pipeline A, in program order. +[[nodiscard]] auto +pipeline(const Dense& dense, + const S& sub, + const Fields& f) -> std::vector { + std::vector ks; + ks.push_back(carbon::Kernel::compute( + dense, + [u = f.u](carbon::KernelLoader& L) { + auto pu = L.read_write(u); + return [=] CARBON_HD(const Dense::Span& s, const Dense::Idx& i) { + pu.write(s, i, 0, 0.5F * pu.read(s, i, 0) + 1.0F); + }; + }, + "bump")); + ks.push_back(carbon::Kernel::compute( + sub, + [u = f.u, acc = f.acc](carbon::KernelLoader& L) { + auto pu = L.read_stencil(u); + auto pa = L.read_write(acc); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) { + const float up = or_zero(pu.neighbour(s, i, carbon::int8_3d{0, 0, 1}, 0)); + const float dn = or_zero(pu.neighbour(s, i, carbon::int8_3d{0, 0, -1}, 0)); + pa.write(s, i, 0, pa.read(s, i, 0) + up + dn); + }; + }, + "s_smooth")); + ks.push_back(sub.make_kernel( + [acc = f.acc, v = f.v](carbon::KernelLoader& L) { + auto pa = L.read(acc); + auto pv = L.write(v); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) { + pv.write(s, i, 0, 0.25F * pa.read(s, i, 0)); + }; + }, + "s_scatter")); + ks.push_back(carbon::Kernel::compute( + dense, + [v = f.v, w = f.w](carbon::KernelLoader& L) { + auto pv = L.read_stencil(v); + auto pw = L.write(w); + return [=] CARBON_HD(const Dense::Span& s, const Dense::Idx& i) { + const float up = or_zero(pv.neighbour(s, i, carbon::int8_3d{0, 0, 1}, 0)); + const float dn = or_zero(pv.neighbour(s, i, carbon::int8_3d{0, 0, -1}, 0)); + pw.write(s, i, 0, pv.read(s, i, 0) + up - dn); + }; + }, + "d_stencil")); + ks.push_back(carbon::Kernel::compute( + dense, + [u = f.u, w = f.w](carbon::KernelLoader& L) { + auto pw = L.read(w); + auto pu = L.read_write(u); + return [=] CARBON_HD(const Dense::Span& s, const Dense::Idx& i) { + pu.write(s, i, 0, pu.read(s, i, 0) + 0.001F * pw.read(s, i, 0)); + }; + }, + "back")); + return ks; +} + +// Single stream, program order, halos placed by hand. +auto +run_reference(const Dense& dense, + const S& sub, + Fields& f, + carbon::Stream& stream) -> void { + const std::vector ks = pipeline(dense, sub, f); + const carbon::Kernel halo_u = f.u.make_halo_kernel("halo_u"); + const carbon::Kernel halo_v = f.v.make_halo_kernel("halo_v"); + for (int it = 0; it < kIters; ++it) { + ks[0].launch(stream); + halo_u.launch(stream); + ks[1].launch(stream); + ks[2].launch(stream); + halo_v.launch(stream); + ks[3].launch(stream); + ks[4].launch(stream); + } + stream.wait(); +} + +auto +compare_owned(const Dense& dense, + const Dense::Field& a, + const Dense::Field& b, + const std::string& tag) -> void { + for (size_t g = 0; g < dense.gpu_count(); ++g) { + const auto& span = dense.spans()[g]; + const auto& pa = a.host_partitions()[g]; + const auto& pb = b.host_partitions()[g]; + const int64_t h = span.halo_z(); + const carbon::int64_3d ext = span.haloed_extent(); + int64_t bad = 0; + for (int64_t z = h; z < h + span.logic_extent().z; ++z) { + for (int64_t y = 0; y < ext.y; ++y) { + for (int64_t x = 0; x < ext.x; ++x) { + const Dense::Idx idx(carbon::int64_3d{x, y, z}); + bad += pa.read(span, idx, 0) != pb.read(span, idx, 0) ? 1 : 0; + } + } + } + expect(bad == 0, tag + ": field '" + a.name() + "' differs on gpu " + std::to_string(g) + + " in " + std::to_string(bad) + " cell(s)"); + } +} + +auto +compare_sub(const S::Field& a, + const S::Field& b, + const std::string& tag) -> void { + for (size_t g = 0; g < a.cpu_buffers().size(); ++g) { + int64_t bad = 0; + for (size_t k = 0; k < a.cpu_buffers()[g].size(); ++k) { + bad += a.cpu_buffers()[g].data()[k] != b.cpu_buffers()[g].data()[k] ? 1 : 0; + } + expect(bad == 0, tag + ": SubGrid field differs on gpu " + std::to_string(g) + " in " + + std::to_string(bad) + " lane(s)"); + } +} + +[[nodiscard]] auto +contains(const std::string& text, + const std::string& needle) -> bool { + return text.find(needle) != std::string::npos; +} + +auto +subtest_pipeline(carbon::System& sys, + const Dense& dense, + const S& sub) -> void { + carbon::Stream stream = sys.stream(); + Fields ref = make_fields(sys, dense, sub, stream); + run_reference(dense, sub, ref, stream); + transfer(sys, ref.u, stream, false); + transfer(sys, ref.v, stream, false); + transfer(sys, ref.w, stream, false); + transfer(sys, ref.acc, stream, false); + + struct Case { + std::string tag; + carbon::Skeleton::Options opts; + }; + std::vector cases; + for (const carbon::OverlapMode mode : + {carbon::OverlapMode::None, carbon::OverlapMode::Standard, carbon::OverlapMode::Extended, + carbon::OverlapMode::TwoWayExtended}) { + cases.push_back( + {"overlap=" + std::to_string(static_cast(mode)), carbon::Skeleton::Options(mode)}); + } + cases.push_back({"graph", carbon::Skeleton::Options(carbon::OverlapMode::None, false, 0U, false, + /*cuda_graph=*/true)}); + carbon::Skeleton::Options ignored(carbon::OverlapMode::Standard); + ignored.ignore_region_masks = true; + cases.push_back({"standard/ignore_region_masks", ignored}); + + for (const Case& c : cases) { + Fields f = make_fields(sys, dense, sub, stream); + std::string order; + try { + carbon::Skeleton sk(sys, c.opts); + for (carbon::Kernel& k : pipeline(dense, sub, f)) { + sk.add(std::move(k)); + } + sk.compile(); + order = sk.export_launch_order(); + for (int it = 0; it < kIters; ++it) { + sk.run(); + } + sk.wait(); + } catch (const std::exception& e) { + expect(false, c.tag + ": threw: " + e.what()); + continue; + } + transfer(sys, f.u, stream, false); + transfer(sys, f.v, stream, false); + transfer(sys, f.w, stream, false); + transfer(sys, f.acc, stream, false); + compare_owned(dense, f.u, ref.u, c.tag); + compare_owned(dense, f.v, ref.v, c.tag); + compare_owned(dense, f.w, ref.w, c.tag); + compare_sub(f.acc, ref.acc, c.tag); + + const bool split_smooth = contains(order, "s_smooth [compute/internal]") && + contains(order, "s_smooth [compute/boundary]"); + const bool split_scatter = contains(order, "s_scatter [compute/internal]") && + contains(order, "s_scatter [compute/boundary]"); + const carbon::OverlapMode mode = c.opts.overlap_mode; + if (mode == carbon::OverlapMode::None) { + expect(!split_smooth && !split_scatter, c.tag + ": no kernel should be split\n" + order); + } else { + expect(split_smooth, c.tag + ": s_smooth should be OCC-split\n" + order); + } + if (mode == carbon::OverlapMode::Extended || mode == carbon::OverlapMode::TwoWayExtended) { + expect(split_scatter, c.tag + ": s_scatter should be split by Extended OCC\n" + order); + } + } +} + +auto +subtest_disjoint(carbon::System& sys, + const Dense& dense, + const S& faces, + const S& ball) -> void { + carbon::Stream stream = sys.stream(); + auto v = dense.newField(carbon::MemorySide::HostDevice, "v_marks"); + + auto marker = [&v](const S& sub, int value, const char* name) { + return sub.make_kernel( + [v, value](carbon::KernelLoader& L) { + auto pv = L.write(v); + return [=] CARBON_HD(const S::Span& s, const S::Idx& i) { + pv.write(s, i, 0, value); + }; + }, + name); + }; + + for (const bool ignore : {false, true}) { + v.fill_owned_host([](carbon::int64_3d, int) { + return -1; + }); + transfer(sys, v, stream, true); + carbon::Skeleton::Options opts; + opts.ignore_region_masks = ignore; + const std::string tag = ignore ? "disjoint/ignored" : "disjoint"; + try { + carbon::Skeleton sk(sys, opts); + sk.add(marker(faces, 1, "faces_mark")); + sk.add(marker(ball, 2, "ball_mark")); + sk.compile(); + using Edges = std::vector>; + if (ignore) { + expect(sk.edges() == Edges{{1U}, {}}, tag + ": unmasked writers must be ordered"); + } else { + expect(sk.edges() == Edges{{}, {}}, tag + ": disjoint SubGrids must not be ordered"); + expect(sk.kernel_streams()[0] != sk.kernel_streams()[1], + tag + ": disjoint SubGrids should run on different streams"); + } + sk.run(); + sk.wait(); + } catch (const std::exception& e) { + expect(false, tag + ": threw: " + e.what()); + continue; + } + transfer(sys, v, stream, false); + const carbon::int64_3d ext = dense.global_extent(); + for (size_t g = 0; g < dense.gpu_count(); ++g) { + const auto& span = dense.spans()[g]; + const auto& pv = v.host_partitions()[g]; + const int64_t h = span.halo_z(); + int64_t bad = 0; + for (int64_t z = h; z < h + span.logic_extent().z; ++z) { + for (int64_t y = 0; y < ext.y; ++y) { + for (int64_t x = 0; x < ext.x; ++x) { + const Dense::Idx idx(carbon::int64_3d{x, y, z}); + const std::uint8_t label = label_of(span.global_location(idx), ext); + const int want = label == kFace ? 1 : (label == kBall ? 2 : -1); + bad += pv.read(span, idx, 0) != want ? 1 : 0; + } + } + } + expect(bad == 0, tag + ": wrong marks on gpu " + std::to_string(g)); + } + } +} + +} // namespace + +int +main() { + carbon::init(); + if (carbon::device_count() < 1) { + CARBON_LOG_WARN("test_sub_grid_skeleton: no devices, skipping"); + return 0; + } + + try { + carbon::System sys(carbon::get_all_devices()); + const size_t n_gpus = sys.gpu_group().size(); + carbon::Stencil stencil(std::vector{{0, 0, -1}, {0, 0, 1}}, + /*remove_center=*/true); + const carbon::int64_3d ext{12, 10, 8 * static_cast(n_gpus)}; + Dense dense(sys, ext, std::move(stencil)); + carbon::Stream stream = sys.stream(); + + auto labels = dense.newField(carbon::MemorySide::HostDevice, "labels"); + labels.fill_owned_host([&](carbon::int64_3d g, int) { + return label_of(g, ext); + }); + transfer(sys, labels, stream, true); + + const S faces = dense.new_sub_grid(labels, carbon::RegionMask{kFace}, "faces"); + const S ball = dense.new_sub_grid(labels, carbon::RegionMask{kBall}, "ball"); + + subtest_pipeline(sys, dense, faces); + subtest_disjoint(sys, dense, faces, ball); + } catch (const std::exception& e) { + CARBON_LOG_ERROR("test_sub_grid_skeleton: exception: {}", e.what()); + return 1; + } + + if (g_failures > 0) { + CARBON_LOG_ERROR("test_sub_grid_skeleton: {} failure(s)", g_failures); + return 1; + } + CARBON_LOG_INFO("test_sub_grid_skeleton: OK"); + return 0; +}