Skip to content

Design the API surface of the CUB tuning API #7671

Closed

Description

@bernhardmgruber

Before we make any tuning API features public we should carefully review all CUB algorithm's policies, their names and data members. The main goal is consistency, good user experience, and allowing future evolution (e.g. instead of a bool use_warpspeed_scan we should rather store an enum that can be extended by more algorithms in the future).

Here is a list of all current tuning policies and there data members: https://docs.google.com/spreadsheets/d/1EUdwvmv2n7-WRp30-lt7CQxyu8r6atdfJJx3O6Pf1Ag

We should carefully review how API entry points, dispatch functions and kernels relate to their tuning policies. We may want to split some tuning policies. For example, tuning policies for segmented algorithms should probably be separate from those for device-wide single problem algorithms, since they use different API entry points, dispatches, and often kernels. We should also review how a single API entrypoint should handle multiple policies in the background (e.g. rfa, non-deterministic, and ordinary DeviceReduce have different tuning policies but the same API entrypoint).

Furthermore, tuning policies may be specified not only at the CUB API but also for APIs in Thrust or libcu++, so we should have an idea how they can be used across our entire libraries.

We must have a complete picture about the API surface before going public with any tuning APIs.

There is now a section "Public API exposure" in the tuning design document: https://docs.google.com/document/d/1KtrSsMk2LAXSB5cdAUnmn3BMow5y6B8BhC5-XVA434g

Current design direction and guidelines for the exposure:

  1. Tuning policies remain in their tuning headers and are named cub::AlgorithmXYZPolicy. E.g. cub::TransformPolicy.
  2. Any nested types needed by the public exposure also become public. E.g. cub::ScanPolicy makes cub::ScanLookbackPolicy, and transitively cub::LookbackDelayPolicy public.
  3. Tuning policies are spelled in CamelCase with members in snake_case, just like anything else in CUB's public API
  4. The default policy selectors in the tuning headers will remain internal. There are ideas on how to expose this functionality in the future.
  5. Document the tuning policy to use at the struct DeviceAlgorithm level, including an API example. We discussed having a per-overload alias, e.g. struct DeviceScan { ... using InclusiveScanInitPolicy = cub::ScanPolicy; ... } for the cub::DeviceScan::InclusiveScanInit function, but most device layer structs use only one or two policies, so it seems too redundant. Plus, we can easily add this later.
  6. The API example should show how the public CUB API is called with a user defined policy selector.

Activity

  1. bernhardmgruber commented on May 5, 2026

    @bernhardmgruber
    ContributorAuthor

    I think we need to essentially solve how the public tuning API for DeviceReduce will look like: #7577. That is, how policy selectors interplay with requirements at the public API that change the underlying dispatch/kernel/algorithm.

  2. bernhardmgruber commented on May 7, 2026

    @bernhardmgruber
    ContributorAuthor

    Based on the following PRs:

    which serve as examples, here is my current design proposal (summarized by claude based on the above PRs):

    Summary and open questions

    All four PRs make CUB's internal tuning policies public so users can customize algorithm behavior per compute capability. The mechanism is:

    1. A policy struct (in the cub namespace) holds tuning knobs (threads per block, items per thread, algorithm choice, etc.)
    2. Users write a policy selector — a callable taking cuda::compute_capability and returning the policy struct
    3. The selector is passed via cuda::execution::tune(selector) as an environment to the existing DeviceXxx API methods

    New public entities for cub::DeviceMergeSort

    Entity Data Members
    cub::MergeSortPolicy threads_per_block, items_per_thread, load_algorithm, load_modifier, store_algorithm

    Example:

    struct PolicySelector
    {
      __host__ __device__ constexpr auto operator()(cuda::compute_capability cc) const -> cub::MergeSortPolicy
      {
        return {.threads_per_block = 256,
                .items_per_thread  = cc > cuda::compute_capability{9, 0} ? 17 : 14,
                .load_algorithm    = cub::BLOCK_LOAD_DIRECT,
                .load_modifier     = cub::LOAD_DEFAULT,
                .store_algorithm   = cub::BLOCK_STORE_DIRECT};
      }
    };
    
      auto d_keys   = thrust::device_vector<int>{8, 6, 7, 5, 3, 0, 9};
      auto d_values = thrust::device_vector<int>{0, 1, 2, 3, 4, 5, 6};
    
      const auto error = cub::DeviceMergeSort::SortPairs(
        d_keys.data(), d_values.data(), d_keys.size(), cuda::std::less{}, cuda::execution::tune(PolicySelector{}));
      if (error != cudaSuccess)
      {
        std::cerr << "cub::DeviceMergeSort::SortPairs failed with status: " << error << '\n';
      }
    • Should we rename cuda::execution::tune to cuda::execution::tune_with? @gevtushenko: no
    • Are we happy with the name cub::MergeSortPolicy? Is it clear that this belongs to cub::DeviceMergeSort algorithms? It was previously suggested to nest the policies into cub::DeviceMergeSort::Policy, but this is not possible, since the definitions for the policy are needed far before struct DeviceMergeSort is defined.

    New public entities for cub::DeviceTransform

    Entity Enumerators / Data Members
    cub::TransformAlgorithm prefetch, vectorized, ldgsts, ublkcp
    cub::TransformPrefetchPolicy threads_per_block, items_per_thread_no_input, min_items_per_thread, max_items_per_thread, prefetch_byte_stride, unroll_factor
    cub::TransformVectorizedPolicy threads_per_block, items_per_thread, vec_size
    cub::TransformAsyncCopyPolicy threads_per_block, min_items_per_thread, max_items_per_thread, unroll_factor
    cub::TransformPolicy min_bytes_in_flight, algorithm (TransformAlgorithm), prefetch (TransformPrefetchPolicy), vectorized (TransformVectorizedPolicy), async_copy (TransformAsyncCopyPolicy)
    • Should we split the TransformAsyncCopyPolicy into two, one for ldgsts and one for ublkcp? Then they could evolve independently

    New public entities for cub::DeviceScan

    Entity Enumerators / Data Members
    cub::LookbackDelayAlgorithm no_delay, fixed_delay, exponential_backoff, exponential_backoff_jitter, exponential_backoff_jitter_window, exponential_backon_jitter_window, exponential_backon_jitter, exponential_backon, reduce_by_key
    cub::LookbackDelayPolicy kind (LookbackDelayAlgorithm), delay, l2_write_latency
    cub::ScanAlgorithm lookback, warpspeed
    cub::ScanLookbackPolicy threads_per_block, items_per_thread, load_algorithm, load_modifier, store_algorithm, scan_algorithm, delay_constructor (LookbackDelayPolicy)
    cub::ScanWarpspeedPolicy num_reduce_and_scan_warps, look_ahead_items_per_thread, items_per_thread
    cub::ScanPolicy algorithm (ScanAlgorithm), lookback (ScanLookbackPolicy), warpspeed (ScanWarpspeedPolicy)
    • Are we happy with the names for the LookbackDelayPolicy and LookbackDelayAlgorithm?
    • There is a LookbackDelayAlgorithm::reduce_by_key. Should we keep that internal by renaming it to __reduce_by_key? Answer: yes
    • Are we happy with the names and order of members in ScanWarpspeedPolicy?

    New public entities for cub::DeviceReduce

    Entity Data Members
    cub::ReducePassPolicy threads_per_block, items_per_thread, vec_size, block_algorithm, load_modifier
    cub::ReducePolicy multi_tile (ReducePassPolicy), single_tile (ReducePassPolicy)
    cub::ReduceDeterministicPassPolicy threads_per_block, items_per_thread, block_algorithm
    cub::ReduceDeterministicPolicy multi_tile (ReduceDeterministicPassPolicy), single_tile (ReduceDeterministicPassPolicy)
    cub::ReduceNondeterministicPolicy multi_tile (ReducePassPolicy)
    • Are we fine with the name of ReducePassPolicy?
    • Should we duplicate the type ReducePassPolicy for the multi and single tile pass, so they could evolve independently? In both cases, they use the same backend AgentReduce so there is currently no need for it
    • Should ReduceNondeterministicPolicy just contain the members of ReducePassPolicy directly instead of a single data member?

    Example with multiple policy selectors:

    struct MyReducePolicySelector
    {
      __host__ __device__ constexpr auto operator()(cuda::compute_capability cc) const -> cub::ReducePolicy
      {
        auto agent = cub::ReducePassPolicy{
          .threads_per_block = 256,
          .items_per_thread  = cc > cuda::compute_capability{9, 0} ? 20 : 16,
          .vec_size          = 4,
          .block_algorithm   = cub::BLOCK_REDUCE_WARP_REDUCTIONS,
          .load_modifier     = cub::LOAD_LDG};
        return {.multi_tile = agent, .single_tile = agent};
      }
    };
    
    struct MyNondeterministicPolicySelector
    {
      __host__ __device__ constexpr auto operator()(cuda::compute_capability) const -> cub::ReduceNondeterministicPolicy
      {
        return {.multi_tile = cub::ReducePassPolicy{
                  .threads_per_block = 256,
                  .items_per_thread  = 16,
                  .vec_size          = 4,
                  .block_algorithm   = cub::BLOCK_REDUCE_WARP_REDUCTIONS_NONDETERMINISTIC,
                  .load_modifier     = cub::LOAD_LDG}};
      }
    };
    
    struct MyDeterministicPolicySelector
    {
      __host__ __device__ constexpr auto operator()(cuda::compute_capability) const -> cub::ReduceDeterministicPolicy
      {
        auto pass = cub::ReduceDeterministicPassPolicy{
          .threads_per_block = 256, .items_per_thread = 16, .block_algorithm = cub::BLOCK_REDUCE_RAKING};
        return {.multi_tile = pass, .single_tile = pass};
      }
    };
    ...
    
      auto input  = thrust::device_vector<float>{1.0f, 2.0f, 3.0f, 4.0f, 5.0f};
      auto output = thrust::device_vector<float>(1);
    
      auto env = cuda::std::execution::env{
        cuda::execution::require(determinism), // non-fixed determinism
        cuda::execution::tune(
          MyReducePolicySelector{}, MyDeterministicPolicySelector{}, MyNondeterministicPolicySelector{})};
    
      const auto error = cub::DeviceReduce::Sum(input.begin(), output.begin(), input.size(), env);
    • Are we happy with the choice that a single public CUB API requires multiple policy selectors if it can dispatch to multiple backend algorithms? For comparison, DeviceTransform also has multiple backend algorithms but they are all contained in a single TransformPolicy because the choice of algorithm is a tuning value and not up to the user. For DeviceRadixSort there is also a scan pass involved which is just a data member in the RadixSortPolicy.

    Inconvenience/Pitfall: When the user requests a gpu_to_gpu deterministic reduction and passes a policy selector generating a ReduceDeterministicPolicy, but passes a buffer of non-FP types, the CUB device layer falls back to run_to_run determinism internally since that also gives a GPU to GPU deterministic result, however, the ReduceDeterministicPolicy will then be ignored in this case and a the ordinary ReducePolicy is queried from the env. This may be surprising.

    • Should we delay exposing the [non-]deterministic policies for now?
  3. bernhardmgruber commented on May 11, 2026

    @bernhardmgruber
    ContributorAuthor

    We discussed the state of the tuning API design briefly during the Monday Code Review Hour and here are some notes:

    • We will not ship any public exposure with CCCL 3.4, sadly. We think the design is not fully ready.
    • Some naming improvements, mostly around tuning policy data members, were suggested. Should be easy to address once we find consensus. Answer this can and should be handled for each algorithm specifically while reviewing the PR.
    • Better support for unrolling should be a high focus. I demonstrated how this looks in DeviceTransform with int unroll_factor and a for loop with runtime trip count. It was argued that it will likely look differently in DeviceMergeSort where we have multiple loops with static trip count. It was suggested that a bool unroll could be enough, but we should do the test and implement it. Resolution: Expose unrolling control in cub::DeviceMergeSort to tuning #9052
    • We need to properly test whether tuning policies are extensible. That is, whether we can add new data members to the end of a tuning policy while users rely on designate initializers or aggregate initialization to construct a policy (now with less arguments than the policy has members). In C++17 and higher standards. Answer: This works as demonstrated by Control unrolling in cub::DeviceMerge[Sort] via tuning  #9181, where the merge[sort] policies where extended by a new data member with a default value. Unit tests were not modified (using those policies) and compiled without warnings.
    • Can we provide default values for tuning policy members at the end that the user does not specify? Answer: yes, tested in Control unrolling in cub::DeviceMerge[Sort] via tuning  #9181
    • Should we provide defaults for all values? Answer: we can, but it's hard to say what a good default value is independent of the GPU's compute capability that it will be used on. So while it's technically solvable, I don't see a user benefit. I will defer this, since we can always add default values later.
    • Can we validate the tuning values better? Like, whether a block size is between [1;1024]. Answer: yes and it's mostly already done. I tried adding a validate_policy(const transform_policy& active_policy) for DeviceTransform and had it populated by claude. I initially wanted to validate on the host, but there we ideally keep the tuning policy a runtime value to save compilation time. Validating in device code is fine as well. However, DeviceTransform already has several validations in place, like whether the vector size is a power of two, so why should we move away or duplicate these conditions to the start of the kernel away from the code that relies on those conditions. When removing all conditions checked later in the kernel, there is actually nothing remaining that should be checked early. Arguable the block size could be validated, but that will just give a clear error message when launching the kernel at runtime. So I am included to not any additional validation.
    • We should not need to provide multiple policy selectors to DeviceReduce::Sum and rather use a struct with appropriate sub members, like DeviceTransform. There is not actually a difference between the two cases (as I tried to argue). Resolution: moved to the specific PR.
    • The policy selector names in the examples should be better (not MyReducePolicySelector). Answer: will be done at the PRs.
  4. bernhardmgruber commented on Jun 2, 2026

    @bernhardmgruber
    ContributorAuthor

    I discussed the state of this work with @gevtushenko yesterday and we concluded that there no fundamental blockers anymore with the current design (tuning polices are extensible without errors/warnings on the user side). #9052 shows that controlling unrolling via tuning is possible, but we do not need to ship it at the same time as the public DeviceMerge[Sort] tunings. For DeviceReduce we can just offer a product type containing the policies for the various backend algorithms. Therefore, any remaining problem can be discussed at the respective PR. Those should be mostly naming discussions now.

  5. moved this from Todo to In Progress in CCCLon Jun 9, 2026
  6. bernhardmgruber commented on Jun 30, 2026

    @bernhardmgruber
    ContributorAuthor

    I sent a bunch of refactorings for DeviceReduce and only a single policy is needed now. This removes the complexity of exposing tuning for DeviceReduce and there are no more open questions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

  • Status
    In Progress

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions