Skip to content

Unify atomic and two-phase reduction - #9349

Merged
bernhardmgruber merged 13 commits into
NVIDIA:mainfrom
bernhardmgruber:unify_atomic_reduce
Jul 1, 2026
Merged

bernhardmgruber merged 13 commits into
NVIDIA:mainfrom
bernhardmgruber:unify_atomic_reduce

Conversation

@bernhardmgruber

@bernhardmgruber bernhardmgruber commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

This PR tries to unify the atomic/non-deterministic and two-phase reduction dispatches and kernels. The goal is simplification and elimination of redundancy. But I am not sure the code is actually more readable, not sure. @NaderAlAwar also agrees the direction is good.

  • From @NaderAlAwar: How does this affect user defined tuning policies, when the user sets the determinism level? For example, the user can set determinism to not guaranteed, but then disable atomics? Semantically that is fine, but it could be confusing. Or the user could enable atomics but select run to run determinism. We can static_assert fail those cases if the input dtype is floating point I guess.

@copy-pr-bot

copy-pr-bot Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@cccl-authenticator-app cccl-authenticator-app Bot moved this from Todo to In Progress in CCCL Jun 9, 2026
Comment thread c/parallel/include/cccl/c/reduce.h Resolved
@bernhardmgruber
bernhardmgruber marked this pull request as ready for review June 14, 2026 20:38
@bernhardmgruber
bernhardmgruber requested review from a team as code owners June 14, 2026 20:38
@cccl-authenticator-app cccl-authenticator-app Bot moved this from In Progress to In Review in CCCL Jun 14, 2026
@bernhardmgruber
bernhardmgruber marked this pull request as draft June 14, 2026 20:39
@cccl-authenticator-app cccl-authenticator-app Bot moved this from In Review to In Progress in CCCL Jun 14, 2026
@coderabbitai

coderabbitai Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR unifies reduce’s deterministic and nondeterministic paths under a shared StableReductionOrder flag across tuning, dispatch, kernel generation, public API wiring, JIT compilation, tests, and benchmark policy selection.

Changes

Unify nondeterministic reduce under StableReductionOrder

Layer / File(s) Summary
Policy selector and tuning updates
cub/cub/device/dispatch/tuning/tuning_reduce.cuh, cub/test/catch2_test_device_reduce_env.cu, cub/benchmarks/bench/reduce/nondeterministic.cu
policy_selector adds stable_reduction_order and get_two_phase_tuning, operator() delegates to that helper, and policy_selector_from_types gains StableReductionOrder. The nondeterministic tuning header is removed. Device reduce tuning tests drop nondeterministic tuning candidates and update expected kernel-selection environments. The benchmark policy selector now returns the unified reduce_policy shape.
Multi-block reduce kernel split by StableReductionOrder
cub/cub/device/dispatch/kernels/kernel_reduce.cuh
DeviceReduceKernel gains StableReductionOrder and switches between stable per-block output and non-stable atomic accumulation. The nondeterministic atomic kernel is removed, the tuning include is dropped, and the single-tile AgentReducePolicy template arguments are fixed to 0, 0.
Dispatch path unified around StableReductionOrder
cub/cub/device/dispatch/dispatch_reduce.cuh
DeviceReduceKernelSource gains StableReductionOrder, conditional output typing, and InitSize(). The regular-size helper adds pointer unwrapping, output initialization, stable versus non-stable launch handling, and conditional second-stage execution. dispatch gains StableReductionOrder, routes through compute-cap dispatch, and skips temp-storage setup for the non-stable or single-tile cases.
DeviceReduce selects the unified dispatch variants
cub/cub/device/device_reduce.cuh
DeviceReduce include dependencies change to use the unified dispatch headers. The __not_guaranteed path switches to detail::reduce::dispatch with StableReductionOrder=false, and the other determinism branch uses policy_selector_from_types with StableReductionOrder=true.
C parallel reduce build and load wiring updated
c/parallel/src/reduce.cu, c/parallel/include/cccl/c/reduce.h, c/parallel/test/test_reduce.cpp
Kernel-name generation now takes explicit init_t and StableReductionOrder, the compile step builds one unified policy selector, drops nondeterministic kernel compilation and naming, allocates runtime_policy as a policy_selector, and simplifies load and cleanup. The nondeterministic entry point now dispatches through detail::reduce::dispatch<void, false>. The build-result struct and test expectations drop the removed runtime-policy-size and nondeterministic-name assertions.
Unified dispatch exercised in reduce tests
cub/test/catch2_test_device_reduce_nondeterministic.cu, cub/test/catch2_test_device_reduce_env.cu
The nondeterministic reduce test includes the unified dispatch header and calls reduce::dispatch<use_default, false> for both sizing and execution. Environment tests update expected DeviceReduceKernel instantiations for stable and non-stable paths and remove NondeterministicDeviceReduceAtomicKernel expectations.

Suggested reviewers

  • davebayer

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 33959b11-5fd6-48e6-b8ca-66c2bf741cb7

📥 Commits

Reviewing files that changed from the base of the PR and between f5606f1 and fa08256.

📒 Files selected for processing (9)
  • c/parallel/include/cccl/c/reduce.h
  • c/parallel/src/reduce.cu
  • cub/cub/device/device_reduce.cuh
  • cub/cub/device/dispatch/dispatch_reduce.cuh
  • cub/cub/device/dispatch/dispatch_reduce_nondeterministic.cuh
  • cub/cub/device/dispatch/kernels/kernel_reduce.cuh
  • cub/cub/device/dispatch/tuning/tuning_reduce.cuh
  • cub/cub/device/dispatch/tuning/tuning_reduce_nondeterministic.cuh
  • cub/test/catch2_test_device_reduce_nondeterministic.cu
💤 Files with no reviewable changes (2)
  • cub/cub/device/dispatch/dispatch_reduce_nondeterministic.cuh
  • cub/cub/device/dispatch/tuning/tuning_reduce_nondeterministic.cuh

Comment on lines +102 to +105
CUB_RUNTIME_FUNCTION static constexpr size_t InitSize()
{
return sizeof(InitValueT);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

important: InitSize() is now used to zero the atomic output buffer, but it returns sizeof(InitValueT). Valid not_guaranteed calls can still have an init type narrower than AccumT/the output element type, and then only the low bytes of d_out[0] get cleared before the fetch_add path runs. That makes the reduction accumulate onto garbage. This needs to use the accumulator/output element size instead.

Comment on lines +689 to +691
if constexpr (UseAtomics)
{
reduce_grid_size = ::cuda::std::max(1, reduce_grid_size);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

suggestion: ::cuda::std::max was added here without a direct <cuda/std/algorithm> include. That currently relies on transitive headers and makes this header fragile.
As per coding guidelines, files must include all headers related to the symbols that they are using; no transitive header inclusions are allowed.

Source: Coding guidelines

@github-actions

This comment has been minimized.

@bernhardmgruber
bernhardmgruber marked this pull request as ready for review June 17, 2026 21:49
@cccl-authenticator-app cccl-authenticator-app Bot moved this from In Progress to In Review in CCCL Jun 17, 2026
@bernhardmgruber

Copy link
Copy Markdown
Contributor Author

the user can set determinism to not guaranteed, but then disable atomics? Semantically that is fine, but it could be confusing.

I think this is fine and no action is required. The user asks for no guarantees and gets them by accident. This is fine.

the user could enable atomics but select run to run determinism. We can static_assert fail those cases if the input dtype is floating point I guess.

Yes. I added the static assertions.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (2)
cub/cub/device/dispatch/dispatch_reduce.cuh (2)

101-105: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

important: InitSize() returns sizeof(InitValueT), but line 655 uses it to memset d_out[0] which holds AccumT. When sizeof(InitValueT) < sizeof(AccumT) (e.g., int init with double accumulator), only partial bytes are cleared, leaving garbage in the high bytes before atomic adds accumulate onto it.

Return sizeof(AccumT) or use a dedicated output-element size.


686-692: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

suggestion: ::cuda::std::max is used but <cuda/std/algorithm> is not directly included. This relies on transitive inclusion which the coding guidelines prohibit.

Source: Coding guidelines

🧹 Nitpick comments (3)
cub/cub/device/dispatch/kernels/kernel_reduce.cuh (1)

188-196: 💤 Low value

suggestion: The AgentReducePolicy<0, 0, ...> instantiation passes zeros for threads and items. This works because NoScaling receives the actual values and AgentReduce reads them from the scaling policy. However, passing explicit zeros is confusing since AgentReducePolicy::BLOCK_THREADS and ITEMS_PER_THREAD will be 0. Consider adding a brief comment explaining that the actual values come from NoScaling.

cub/cub/device/dispatch/dispatch_reduce.cuh (2)

629-629: 💤 Low value

suggestion: sm_count and sm_occupancy are initialized to 0 then immediately assigned. Per coding guidelines, prefer const with direct initialization or restructure to avoid mutable temporaries.

-  int sm_count = 0;
-  if (const auto error = CubDebug(launcher_factory.MultiProcessorCount(sm_count)))
+  int sm_count_tmp = 0;
+  if (const auto error = CubDebug(launcher_factory.MultiProcessorCount(sm_count_tmp)))
   {
     return error;
   }
+  const int sm_count = sm_count_tmp;

Also applies to: 637-637

Source: Coding guidelines


594-602: 💤 Low value

suggestion: get_device_ptr casts and dereferences a void* as void**. This works for the intended use case but is fragile. Consider a template or documenting the strict aliasing implications.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 280d0787-db37-4886-b24b-def7cfdc318d

📥 Commits

Reviewing files that changed from the base of the PR and between fa08256 and 494ffff.

📒 Files selected for processing (9)
  • c/parallel/include/cccl/c/reduce.h
  • c/parallel/src/reduce.cu
  • cub/cub/device/device_reduce.cuh
  • cub/cub/device/dispatch/dispatch_reduce.cuh
  • cub/cub/device/dispatch/dispatch_reduce_nondeterministic.cuh
  • cub/cub/device/dispatch/kernels/kernel_reduce.cuh
  • cub/cub/device/dispatch/tuning/tuning_reduce.cuh
  • cub/cub/device/dispatch/tuning/tuning_reduce_nondeterministic.cuh
  • cub/test/catch2_test_device_reduce_nondeterministic.cu
💤 Files with no reviewable changes (2)
  • cub/cub/device/dispatch/tuning/tuning_reduce_nondeterministic.cuh
  • cub/cub/device/dispatch/dispatch_reduce_nondeterministic.cuh
✅ Files skipped from review due to trivial changes (1)
  • c/parallel/include/cccl/c/reduce.h
🚧 Files skipped from review as they are similar to previous changes (3)
  • cub/test/catch2_test_device_reduce_nondeterministic.cu
  • cub/cub/device/device_reduce.cuh
  • c/parallel/src/reduce.cu

@github-actions

This comment has been minimized.

@NaderAlAwar NaderAlAwar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: cub/benchmarks/bench/reduce/nondeterministic.cu:23 still refers to the deleted cub::detail::reduce_nondeterministic namespace

Comment thread c/parallel/src/reduce.cu Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
c/parallel/src/reduce.cu (1)

153-168: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

important: validate build before any compile work.

Line 153 accepts a public C API output pointer, but the function later writes through build without checking for null. Match load, cleanup, and link_ltoir by returning CUDA_ERROR_INVALID_VALUE.

 try
 {
+  if (build == nullptr)
+  {
+    return CUDA_ERROR_INVALID_VALUE;
+  }
+
   if (determinism == CCCL_NOT_GUARANTEED && (op.type != CCCL_PLUS || output_it.type != CCCL_POINTER))

As per path instructions, c/**/* reviews focus on C API/ABI stability and error/status handling.

Source: Path instructions

🧹 Nitpick comments (1)
cub/cub/device/dispatch/kernels/kernel_reduce.cuh (1)

166-166: 📐 Maintainability & Code Quality | 🔵 Trivial

suggestion: track or resolve this TODO with the exact nvc++ failure mode. As written, the workaround is hard to validate or remove later. I can help draft a focused regression check or tracking issue.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 814d75af-10cc-4066-93b9-6a32fd7c9c94

📥 Commits

Reviewing files that changed from the base of the PR and between 51bfd8e and 0cf95f2.

📒 Files selected for processing (11)
  • c/parallel/include/cccl/c/reduce.h
  • c/parallel/src/reduce.cu
  • c/parallel/test/test_reduce.cpp
  • cub/cub/device/device_reduce.cuh
  • cub/cub/device/dispatch/dispatch_reduce.cuh
  • cub/cub/device/dispatch/dispatch_reduce_nondeterministic.cuh
  • cub/cub/device/dispatch/kernels/kernel_reduce.cuh
  • cub/cub/device/dispatch/tuning/tuning_reduce.cuh
  • cub/cub/device/dispatch/tuning/tuning_reduce_nondeterministic.cuh
  • cub/test/catch2_test_device_reduce_env.cu
  • cub/test/catch2_test_device_reduce_nondeterministic.cu
💤 Files with no reviewable changes (2)
  • cub/cub/device/dispatch/tuning/tuning_reduce_nondeterministic.cuh
  • cub/cub/device/dispatch/dispatch_reduce_nondeterministic.cuh
🚧 Files skipped from review as they are similar to previous changes (5)
  • cub/test/catch2_test_device_reduce_nondeterministic.cu
  • cub/cub/device/device_reduce.cuh
  • cub/cub/device/dispatch/tuning/tuning_reduce.cuh
  • cub/cub/device/dispatch/dispatch_reduce.cuh
  • cub/test/catch2_test_device_reduce_env.cu

Comment thread c/parallel/src/reduce.cu Resolved
@github-actions

This comment has been minimized.

@bernhardmgruber bernhardmgruber mentioned this pull request Jun 30, 2026
2 tasks done
Comment on lines +883 to +888
// Return if the caller is simply requesting the size of the storage allocation
if (d_temp_storage == nullptr)
{
temp_storage_bytes = 1;
return cudaSuccess;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe we can factor that out of the if

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had this initially and then MSVC complained because you can't put a constexpr bool inside an expression of a runtime if, since in some cases that is always true or false, and MSVC will recommend to use if constexpr instead ;)

@github-actions

This comment has been minimized.

Comment thread c/parallel/src/reduce.cu

std::unique_ptr<char[]> payload(static_cast<char*>(build_ptr->payload));
std::free(build_ptr->runtime_policy);
delete static_cast<cub::detail::reduce::policy_selector*>(build_ptr->runtime_policy);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: since this was allocated with std::malloc, isn't it preferable to use std::free?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's allocated with:

auto policy_ptr = std::make_unique<cub::detail::reduce::policy_selector>(policy_sel);

which uses new. Should be fine.

@github-actions

Copy link
Copy Markdown
Contributor

🥳 CI Workflow Results

🟩 Finished in 1h 13m: Pass: 100%/291 | Total: 3d 03h | Max: 1h 05m | Hits: 99%/199557

See results here.

@bernhardmgruber
bernhardmgruber merged commit 5ddd2d4 into NVIDIA:main Jul 1, 2026
310 of 311 checks passed
@bernhardmgruber
bernhardmgruber deleted the unify_atomic_reduce branch July 1, 2026 07:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

3 participants